Skip to content
This repository was archived by the owner on May 7, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"diffcalc_api.server:app",
"--reload"
],
"jinja": true,
"justMyCode": true
},
{
"name": "Debug Unit Test",
"type": "python",
Expand Down
14 changes: 14 additions & 0 deletions src/diffcalc_api/errors/ub.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class ErrorCodes(ErrorCodesBase):
INVALID_PROPERTY = 400
NO_TAG_OR_IDX_PROVIDED = 400
BOTH_TAG_OR_IDX_PROVIDED = 400
NO_UB_MATRIX_ERROR = 400


responses = {code: ALL_RESPONSES[code] for code in np.unique(ErrorCodes.all_codes())}
Expand Down Expand Up @@ -91,3 +92,16 @@ def __init__(self):
"""Set detail and status code."""
self.detail = f"invalid property. Choose one of: {VECTOR_PROPERTIES}"
self.status_code = ErrorCodes.INVALID_PROPERTY


class NoUbMatrixError(DiffcalcAPIException):
"""When there is no U/UB matrix, some commands in diffcalc-core fail."""

def __init__(self):
"""Set detail and status code."""
self.detail = (
"It seems like there is no UB matrix for this record. Please "
+ "try again after setting the UB matrix, either by calculating the UB from"
+ " existing reflections/orientations or setting it explicitly."
)
self.status_code = ErrorCodes.NO_UB_MATRIX_ERROR
11 changes: 10 additions & 1 deletion src/diffcalc_api/models/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from pydantic import BaseModel

from diffcalc_api.models.ub import HklModel
from diffcalc_api.models.ub import HklModel, MiscutModel


class InfoResponse(BaseModel):
Expand Down Expand Up @@ -54,3 +54,12 @@ class MillerIndicesResponse(BaseModel):
"""

payload: HklModel


class MiscutResponse(BaseModel):
"""Response for any operation returning miscuts.

Only used for endpoints in ub routes.
"""

payload: MiscutModel
10 changes: 10 additions & 0 deletions src/diffcalc_api/models/ub.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,13 @@ def select_idx_or_tag_str(idx: Optional[int], tag: Optional[str]) -> str:
Return a string for diffcalc_api.models.response.InfoResponse endpoint responses.
"""
return f"index {idx}" if idx is not None else f"tag {tag}"


class MiscutModel(BaseModel):
"""Describe a miscut.

Miscut requires a rotation axis definition, and an angle from this rotation axis.
"""

angle: float
rotation_axis: XyzModel
37 changes: 0 additions & 37 deletions src/diffcalc_api/routes/hkl.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
from diffcalc_api.errors.hkl import InvalidSolutionBoundsError
from diffcalc_api.models.hkl import SolutionConstraints
from diffcalc_api.models.response import (
ArrayResponse,
DiffractorAnglesResponse,
MillerIndicesResponse,
ScanResponse,
Expand All @@ -19,42 +18,6 @@
router = APIRouter(prefix="/hkl", tags=["hkl"])


@router.get("/{name}/UB", response_model=ArrayResponse)
async def calculate_ub(
name: str,
tag1: Optional[str] = Query(default=None, example="refl1"),
idx1: Optional[int] = Query(default=None),
tag2: Optional[str] = Query(default=None, example="plane"),
idx2: Optional[int] = Query(default=None),
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Calculate the UB matrix.

Args:
name: the name of the hkl object to access within the store
store: accessor to the hkl object.
collection: collection within which the hkl object resides.
tag1: the tag of the first reference object.
idx1: the index of the first reference object.
tag2: the tag of the second reference object.
idx2: the index of the second reference object.

For each reference object, only a tag or index needs to be given. If none are
provided, diffcalc-core tries to work it out from the available reference
objects.

Returns:
ArrayResponse object containing a list of angles, combined together into one
dictionary.

"""
content = await service.calculate_ub(
name, store, collection, tag1, idx1, tag2, idx2
)
return ArrayResponse(payload=content)


@router.get("/{name}/position/lab", response_model=DiffractorAnglesResponse)
async def lab_position_from_miller_indices(
name: str,
Expand Down
174 changes: 172 additions & 2 deletions src/diffcalc_api/routes/ub.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Endpoints relating to the management of setting up the UB calculation."""

from typing import Optional
from typing import List, Optional

from fastapi import APIRouter, Body, Depends, Query

Expand All @@ -12,14 +12,22 @@
NoTagOrIdxProvidedError,
)
from diffcalc_api.examples import ub as examples
from diffcalc_api.models.response import InfoResponse, StringResponse
from diffcalc_api.models.response import (
ArrayResponse,
InfoResponse,
MiscutResponse,
StringResponse,
)
from diffcalc_api.models.ub import (
AddOrientationParams,
AddReflectionParams,
EditOrientationParams,
EditReflectionParams,
HklModel,
MiscutModel,
PositionModel,
SetLatticeParams,
XyzModel,
select_idx_or_tag_str,
)
from diffcalc_api.services import ub as service
Expand Down Expand Up @@ -269,6 +277,168 @@ async def set_lattice(
)


@router.put("/{name}/miscut", response_model=InfoResponse)
async def set_miscut(
name: str,
rot_axis: XyzModel = Body(...),
angle: float = Query(...),
add_miscut: bool = Query(default=False),
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Find the U matrix using a miscut axis/angle, and set this as the new U matrix.

Args:
name: the name of the hkl object to access within the store
rot_axis: the rotational axis of the miscut
angle: the miscut angle
add_miscut: boolean determining extra processing on U matrix before it is set
store: accessor to the hkl object
collection: collection within which the hkl object resides
"""
await service.set_miscut(name, rot_axis, angle, add_miscut, store, collection)
return InfoResponse(
message=(
"Miscut has been set using the provided rotation axis and angle of the "
+ f"miscut for crystal {name} of collection {collection}."
)
)


@router.get("/{name}/miscut", response_model=MiscutResponse)
async def get_miscut(
name: str,
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Get the rotation axis and angle of the miscut, using current UB matrix.

Args:
name: the name of the hkl object to access within the store
store: accessor to the hkl object
collection: collection within which the hkl object resides

Returns:
miscut angle and miscut axis as a list.
"""
angle, axis = await service.get_miscut(name, store, collection)
return MiscutResponse(
payload=MiscutModel(
angle=angle, rotation_axis=XyzModel(x=axis[0], y=axis[1], z=axis[2])
)
)


@router.get("/{name}/miscut/hkl", response_model=MiscutResponse)
async def get_miscut_from_hkl(
name: str,
hkl: HklModel = Depends(),
pos: PositionModel = Depends(),
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Get the rotation axis and angle of the miscut using a single reflection.

Args:
name: the name of the hkl object to access within the store
hkl: hkl of the reflection
pos: position of the reflection
store: accessor to the hkl object
collection: collection within which the hkl object resides

Returns:
miscut angle and miscut axis as a tuple.
"""
angle, axis = await service.get_miscut_from_hkl(name, hkl, pos, store, collection)
return MiscutResponse(
payload=MiscutModel(
angle=angle, rotation_axis=XyzModel(x=axis[0], y=axis[1], z=axis[2])
)
)


@router.get("/{name}/ub", response_model=ArrayResponse)
async def calculate_ub(
name: str,
tag1: Optional[str] = Query(default=None, example="refl1"),
idx1: Optional[int] = Query(default=None),
tag2: Optional[str] = Query(default=None, example="plane"),
idx2: Optional[int] = Query(default=None),
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Calculate the UB matrix.

Args:
name: the name of the hkl object to access within the store
store: accessor to the hkl object.
collection: collection within which the hkl object resides.
tag1: the tag of the first reference object.
idx1: the index of the first reference object.
tag2: the tag of the second reference object.
idx2: the index of the second reference object.

For each reference object, only a tag or index needs to be given. If none are
provided, diffcalc-core tries to work it out from the available reference
objects.

Returns:
ArrayResponse object containing a list of angles, combined together into one
dictionary.

"""
content = await service.calculate_ub(
name, store, collection, tag1, idx1, tag2, idx2
)
return ArrayResponse(payload=content)


@router.put("/{name}/ub", response_model=InfoResponse)
async def set_ub(
name: str,
ub_matrix: List[List[float]] = Body(
..., example=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
),
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Manually set the UB matrix.

Args:
name: the name of the hkl object to access within the store
u_matrix: 3d array containing the UB matrix
store: accessor to the hkl object.
collection: collection within which the hkl object resides.
"""
await service.set_u(name, ub_matrix, store, collection)
return InfoResponse(
payload=f"UB matrix set for crystal {name} of collection {collection}"
)


@router.put("/{name}/u", response_model=InfoResponse)
async def set_u(
name: str,
u_matrix: List[List[float]] = Body(
..., example=[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
),
store: HklCalcStore = Depends(get_store),
collection: Optional[str] = Query(default=None, example="B07"),
):
"""Manually set the U matrix.

Args:
name: the name of the hkl object to access within the store
u_matrix: 3d array containing the U matrix
store: accessor to the hkl object.
collection: collection within which the hkl object resides.
"""
await service.set_u(name, u_matrix, store, collection)
return InfoResponse(
payload=f"U matrix set for crystal {name} of collection {collection}"
)


@router.put("/{name}/{property}", response_model=InfoResponse)
async def modify_property(
name: str,
Expand Down
41 changes: 1 addition & 40 deletions src/diffcalc_api/services/hkl.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Defines business logic for handling requests from hkl endpoints."""

from itertools import product
from typing import Dict, List, Optional, Tuple, Union
from typing import Dict, List, Optional, Tuple

import numpy as np
from diffcalc.hkl.geometry import Position
Expand Down Expand Up @@ -265,42 +265,3 @@ def combine_lab_position_results(
result.append({**physical_angles.asdict, **virtual_angles})

return result


async def calculate_ub(
name: str,
store: HklCalcStore,
collection: Optional[str],
tag1: Optional[str],
idx1: Optional[int],
tag2: Optional[str],
idx2: Optional[int],
) -> List[List[float]]:
"""Calculate the UB matrix.

Args:
name: the name of the hkl object to access within the store
store: accessor to the hkl object.
collection: collection within which the hkl object resides.
tag1: the tag of the first reference object.
idx1: the index of the first reference object.
tag2: the tag of the second reference object.
idx2: the index of the second reference object.

For each reference object, only a tag or index needs to be given. If none are
provided, diffcalc-core tries to work it out from the available reference
objects.

Returns:
a list of angles, combined together into one dictionary.

"""
hklcalc = await store.load(name, collection)

first_retrieve: Optional[Union[str, int]] = tag1 if tag1 else idx1
second_retrieve: Optional[Union[str, int]] = tag2 if tag2 else idx2

hklcalc.ubcalc.calc_ub(first_retrieve, second_retrieve)

await store.save(name, hklcalc, collection)
return np.round(hklcalc.ubcalc.UB, 6).tolist()
Loading