From 13f5ef08ecc6c6ed052e349ffc60725e820ae277 Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Wed, 13 Jul 2022 14:35:21 +0000 Subject: [PATCH 1/8] created folder to contain logic of handling API calls, to separate this from actual API calls in routes/ --- src/diffcalc_API/controllers/Constraints.py | 52 +++++ .../controllers/HklCalculation.py | 106 ++++++++++ src/diffcalc_API/controllers/UBCalculation.py | 147 ++++++++++++++ src/diffcalc_API/controllers/__init__.py | 3 + src/diffcalc_API/examples/UBCalculation.py | 37 ++++ src/diffcalc_API/examples/__init__.py | 3 + src/diffcalc_API/routes/Constraints.py | 29 +-- src/diffcalc_API/routes/HklCalculation.py | 76 ++----- src/diffcalc_API/routes/UBCalculation.py | 187 ++++++------------ src/diffcalc_API/server.py | 20 +- 10 files changed, 438 insertions(+), 222 deletions(-) create mode 100644 src/diffcalc_API/controllers/Constraints.py create mode 100644 src/diffcalc_API/controllers/HklCalculation.py create mode 100644 src/diffcalc_API/controllers/UBCalculation.py create mode 100644 src/diffcalc_API/controllers/__init__.py create mode 100644 src/diffcalc_API/examples/UBCalculation.py create mode 100644 src/diffcalc_API/examples/__init__.py diff --git a/src/diffcalc_API/controllers/Constraints.py b/src/diffcalc_API/controllers/Constraints.py new file mode 100644 index 0000000..eb9d167 --- /dev/null +++ b/src/diffcalc_API/controllers/Constraints.py @@ -0,0 +1,52 @@ +from pathlib import Path +from typing import Callable, Dict, Union + +from diffcalc.hkl.calc import HklCalculation +from diffcalc.hkl.constraints import Constraints + +from diffcalc_API.config import constraintsWithNoValue +from diffcalc_API.errors.Constraints import check_constraint_exists + + +def set_constraints( + name: str, + constraintDict: Dict[str, Union[float, bool]], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + booleanConstraints = set(constraintDict.keys()).intersection(constraintsWithNoValue) + for constraint in booleanConstraints: + constraintDict[constraint] = bool(constraintDict[constraint]) + + hklCalc.constraints = Constraints(constraintDict) + persist(hklCalc, name) + return + + +def remove_constraint( + name: str, + property: str, + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + check_constraint_exists(property) + setattr(hklCalc.constraints, property, None) + persist(hklCalc, name) + return + + +def set_constraint( + name: str, + property: str, + value: Union[float, bool], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + check_constraint_exists(property) + + if property in constraintsWithNoValue: + value = bool(value) + + setattr(hklCalc.constraints, property, value) + persist(hklCalc, name) + return diff --git a/src/diffcalc_API/controllers/HklCalculation.py b/src/diffcalc_API/controllers/HklCalculation.py new file mode 100644 index 0000000..e8aeb75 --- /dev/null +++ b/src/diffcalc_API/controllers/HklCalculation.py @@ -0,0 +1,106 @@ +from itertools import product +from typing import Dict, List, Tuple + +import numpy as np +from diffcalc.hkl.calc import HklCalculation +from diffcalc.hkl.geometry import Position + +from diffcalc_API.errors.HklCalculation import ( + check_valid_miller_indices, + check_valid_scan_bounds, +) + +positionType = Tuple[float, float, float] + + +def lab_position_from_miller_indices( + millerIndices: Tuple[float, float, float], + wavelength: float, + hklCalc: HklCalculation, +) -> List[Tuple[Position, Dict[str, float]]]: + check_valid_miller_indices(millerIndices) + allPositions = hklCalc.get_position(*millerIndices, wavelength) + + return combine_lab_position_results(allPositions) + + +def miller_indices_from_lab_position( + pos: Tuple[float, float, float, float, float, float], + wavelength: float, + hklCalc: HklCalculation, +): + hklPosition = hklCalc.get_hkl(Position(*pos), wavelength) + return tuple(np.round(hklPosition, 16)) + + +def scan_hkl( + start: positionType, + stop: positionType, + inc: positionType, + wavelength: float, + hklCalc: HklCalculation, +): + valueOfAxes = [ + generate_axis(start[i], stop[i], inc[i]) if inc[i] != 0 else [0] + for i in range(3) + ] + + results = {} + + for h, k, l in product(*valueOfAxes): + check_valid_miller_indices((h, k, l)) + allPositions = hklCalc.get_position(h, k, l, wavelength) + results[f"({h}, {k}, {l})"] = combine_lab_position_results(allPositions) + + return results + + +def scan_wavelength( + start: float, + stop: float, + inc: float, + hkl: positionType, + hklCalc: HklCalculation, +): + check_valid_scan_bounds(start, stop, inc) + wavelengths = np.arange(start, stop + inc, inc) + result = {} + + for wavelength in wavelengths: + allPositions = hklCalc.get_position(*hkl, wavelength) + result[f"{wavelength}"] = combine_lab_position_results(allPositions) + + return result + + +def scan_constraint( + constraint: str, + start: float, + stop: float, + inc: float, + hkl: positionType, + wavelength: float, + hklCalc: HklCalculation, +): + check_valid_scan_bounds(start, stop, inc) + result = {} + for value in np.arange(start, stop + inc, inc): + setattr(hklCalc, constraint, value) + allPositions = hklCalc.get_position(*hkl, wavelength) + result[f"{value}"] = combine_lab_position_results(allPositions) + + return result + + +def generate_axis(start: float, stop: float, inc: float): + check_valid_scan_bounds(start, stop, inc) + return np.arange(start, stop + inc, inc) + + +def combine_lab_position_results(positions: List[Tuple[Position, Dict[str, float]]]): + result = [] + + for position in positions: + result.append({**position[0].asdict, **position[1]}) + + return result diff --git a/src/diffcalc_API/controllers/UBCalculation.py b/src/diffcalc_API/controllers/UBCalculation.py new file mode 100644 index 0000000..071a64e --- /dev/null +++ b/src/diffcalc_API/controllers/UBCalculation.py @@ -0,0 +1,147 @@ +from pathlib import Path +from typing import Callable, Optional, Tuple, Union + +from diffcalc.hkl.calc import HklCalculation +from diffcalc.hkl.geometry import Position + +from diffcalc_API.errors.UBCalculation import ( + calculate_UB_matrix, + get_orientation, + get_reflection, +) +from diffcalc_API.models.UBCalculation import ( + addOrientationParams, + addReflectionParams, + editOrientationParams, + editReflectionParams, + setLatticeParams, +) + + +def add_reflection( + name: str, + params: addReflectionParams, + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + hklCalc.ubcalc.add_reflection( + params.hkl, + Position(*params.position), + params.energy, + params.tag, + ) + + persist(hklCalc, name) + return + + +def edit_reflection( + name: str, + params: editReflectionParams, + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + reflection = get_reflection(hklCalc, params.tagOrIdx) + + hklCalc.ubcalc.edit_reflection( + params.tagOrIdx, + params.hkl if params.hkl else (reflection.h, reflection.k, reflection.l), + Position(params.position) if params.position else reflection.pos, + params.energy if params.energy else reflection.energy, + params.tagOrIdx if isinstance(params.tagOrIdx, str) else None, + ) + persist(hklCalc, name) + return + + +def delete_reflection( + name: str, + tagOrIdx: Union[str, int], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + _ = get_reflection(hklCalc, tagOrIdx) + hklCalc.ubcalc.del_reflection(tagOrIdx) + persist(hklCalc, name) + return + + +def add_orientation( + name: str, + params: addOrientationParams, + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + position = Position(*params.position) if params.position else None + + hklCalc.ubcalc.add_orientation( + params.hkl, + params.xyz, + position, + params.tag, + ) + + persist(hklCalc, name) + return + + +def edit_orientation( + name: str, + params: editOrientationParams, + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + orientation = get_orientation(hklCalc, params.tagOrIdx) + + hklCalc.ubcalc.edit_orientation( + params.tagOrIdx, + params.hkl if params.hkl else (orientation.h, orientation.k, orientation.l), + params.xyz if params.xyz else (orientation.x, orientation.y, orientation.z), + Position(params.position) if params.position else orientation.pos, + params.tagOrIdx if isinstance(params.tagOrIdx, str) else None, + ) + persist(hklCalc, name) + return + + +def delete_orientation( + name: str, + tagOrIdx: Union[str, int], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + _ = get_orientation(hklCalc, tagOrIdx) + hklCalc.ubcalc.del_orientation(tagOrIdx) + persist(hklCalc, name) + + +def set_lattice( + name: str, + params: setLatticeParams, + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + hklCalc.ubcalc.set_lattice(name=name, **params.dict()) + persist(hklCalc, name) + + +def modify_property( + name: str, + property: str, + targetValue: Tuple[float, float, float], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + setattr(hklCalc.ubcalc, property, targetValue) + persist(hklCalc, name) + + +def calculate_UB( + name: str, + firstTag: Optional[Union[int, str]], + secondTag: Optional[Union[int, str]], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + calculate_UB_matrix(hklCalc, firstTag, secondTag) + persist(hklCalc, name) diff --git a/src/diffcalc_API/controllers/__init__.py b/src/diffcalc_API/controllers/__init__.py new file mode 100644 index 0000000..a879260 --- /dev/null +++ b/src/diffcalc_API/controllers/__init__.py @@ -0,0 +1,3 @@ +from diffcalc_API.controllers import Constraints, HklCalculation, UBCalculation + +__all__ = ["UBCalculation", "HklCalculation", "Constraints"] diff --git a/src/diffcalc_API/examples/UBCalculation.py b/src/diffcalc_API/examples/UBCalculation.py new file mode 100644 index 0000000..1835138 --- /dev/null +++ b/src/diffcalc_API/examples/UBCalculation.py @@ -0,0 +1,37 @@ +from diffcalc_API.models.UBCalculation import ( + addOrientationParams, + addReflectionParams, + editOrientationParams, + editReflectionParams, + setLatticeParams, +) + +addReflection: addReflectionParams = addReflectionParams( + **{ + "hkl": [0, 0, 1], + "position": [7.31, 0.0, 10.62, 0, 0.0, 0], + "energy": 12.39842, + "tag": "refl1", + } +) + +editReflection: editReflectionParams = editReflectionParams( + **{"energy": 12.45, "tagOrIdx": "refl1"} +) + +addOrientation: addOrientationParams = addOrientationParams( + **{ + "hkl": [0, 1, 0], + "xyz": [0, 1, 0], + "tag": "plane", + } +) + +editOrientation: editOrientationParams = editOrientationParams( + **{ + "hkl": (0, 1, 0), + "tagOrIdx": "plane", + } +) + +setLattice: setLatticeParams = setLatticeParams(**{"a": 4.913, "c": 5.405}) diff --git a/src/diffcalc_API/examples/__init__.py b/src/diffcalc_API/examples/__init__.py new file mode 100644 index 0000000..f18cbe3 --- /dev/null +++ b/src/diffcalc_API/examples/__init__.py @@ -0,0 +1,3 @@ +from diffcalc_API.examples import UBCalculation + +__all__ = ["UBCalculation"] diff --git a/src/diffcalc_API/routes/Constraints.py b/src/diffcalc_API/routes/Constraints.py index e2edf62..d5ad7d4 100644 --- a/src/diffcalc_API/routes/Constraints.py +++ b/src/diffcalc_API/routes/Constraints.py @@ -1,20 +1,15 @@ from pathlib import Path -from typing import Callable, Dict, Tuple, Union +from typing import Callable, Dict, Union from diffcalc.hkl.calc import HklCalculation -from diffcalc.hkl.constraints import Constraints from fastapi import APIRouter, Body, Depends -from diffcalc_API.config import constraintsWithNoValue -from diffcalc_API.errors.Constraints import check_constraint_exists +from diffcalc_API.controllers import Constraints as controller from diffcalc_API.fileHandling import supplyPersist, unpickleHkl router = APIRouter(prefix="/constraints", tags=["constraints"]) -singleConstraintType = Union[Tuple[str, float], str] - - @router.put("/{name}/set") async def set_constraints( name: str, @@ -24,16 +19,10 @@ async def set_constraints( hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - booleanConstraints = set(constraintDict.keys()).intersection(constraintsWithNoValue) - for constraint in booleanConstraints: - constraintDict[constraint] = bool(constraintDict[constraint]) - - hklCalc.constraints = Constraints(constraintDict) - persist(hklCalc, name) + controller.set_constraints(name, constraintDict, hklCalc, persist) return {"message": f"constraints updated (replaced) for crystal {name}"} -# is patch the correct choice here? What about delete instead? @router.patch("/{name}/unconstrain/{property}") async def remove_constraint( name: str, @@ -41,9 +30,7 @@ async def remove_constraint( hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - check_constraint_exists(property) - setattr(hklCalc.constraints, property, None) - persist(hklCalc, name) + controller.remove_constraint(name, property, hklCalc, persist) return { "message": ( @@ -61,13 +48,7 @@ async def set_constraint( hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - check_constraint_exists(property) - - if property in constraintsWithNoValue: - value = bool(value) - - setattr(hklCalc.constraints, property, value) - persist(hklCalc, name) + controller.set_constraint(name, property, value, hklCalc, persist) return { "message": ( diff --git a/src/diffcalc_API/routes/HklCalculation.py b/src/diffcalc_API/routes/HklCalculation.py index c8aeb50..0ce7a8e 100644 --- a/src/diffcalc_API/routes/HklCalculation.py +++ b/src/diffcalc_API/routes/HklCalculation.py @@ -1,18 +1,14 @@ -from itertools import product -from typing import Dict, List, Tuple, Union +from typing import Tuple, Union -import numpy as np from diffcalc.hkl.calc import HklCalculation -from diffcalc.hkl.geometry import Position from fastapi import APIRouter, Depends, Query -from diffcalc_API.errors.HklCalculation import ( - check_valid_miller_indices, - check_valid_scan_bounds, -) +from diffcalc_API.controllers import HklCalculation as controller from diffcalc_API.fileHandling import unpickleHkl -router = APIRouter(prefix="/calculate", tags=["hkl"]) +router = APIRouter( + prefix="/calculate", tags=["hkl"], dependencies=[Depends(unpickleHkl)] +) singleConstraintType = Union[Tuple[str, float], str] @@ -26,10 +22,11 @@ async def lab_position_from_miller_indices( wavelength: float = Query(..., example=1.0), hklCalc: HklCalculation = Depends(unpickleHkl), ): - check_valid_miller_indices(millerIndices) - allPositions = hklCalc.get_position(*millerIndices, wavelength) + positions = controller.lab_position_from_miller_indices( + millerIndices, wavelength, hklCalc + ) - return {"payload": combine_lab_position_results(allPositions)} + return {"payload": positions} @router.get("/{name}/position/hkl") @@ -41,13 +38,8 @@ async def miller_indices_from_lab_position( wavelength: float = Query(..., example=1.0), hklCalc: HklCalculation = Depends(unpickleHkl), ): - hklPosition = hklCalc.get_hkl(Position(*pos), wavelength) - return {"payload": tuple(np.round(hklPosition, 16))} - - -def generate_axis(start: float, stop: float, inc: float): - check_valid_scan_bounds(start, stop, inc) - return np.arange(start, stop + inc, inc) + hkl = controller.miller_indices_from_lab_position(pos, wavelength, hklCalc) + return {"payload": hkl} @router.get("/{name}/scan/hkl") @@ -59,19 +51,8 @@ async def scan_hkl( wavelength: float = Query(..., example=1), hklCalc: HklCalculation = Depends(unpickleHkl), ): - valueOfAxes = [ - generate_axis(start[i], stop[i], inc[i]) if inc[i] != 0 else [0] - for i in range(3) - ] - - results = {} - - for h, k, l in product(*valueOfAxes): - check_valid_miller_indices((h, k, l)) - allPositions = hklCalc.get_position(h, k, l, wavelength) - results[f"({h}, {k}, {l})"] = combine_lab_position_results(allPositions) - - return {"payload": results} + scanResults = controller.scan_hkl(start, stop, inc, wavelength, hklCalc) + return {"payload": scanResults} @router.get("/{name}/scan/wavelength") @@ -83,15 +64,8 @@ async def scan_wavelength( hkl: positionType = Query(..., example=(1, 0, 1)), hklCalc: HklCalculation = Depends(unpickleHkl), ): - check_valid_scan_bounds(start, stop, inc) - wavelengths = np.arange(start, stop + inc, inc) - result = {} - - for wavelength in wavelengths: - allPositions = hklCalc.get_position(*hkl, wavelength) - result[f"{wavelength}"] = combine_lab_position_results(allPositions) - - return {"payload": result} + scanResults = controller.scan_wavelength(start, stop, inc, hkl, hklCalc) + return {"payload": scanResults} @router.get("/{name}/scan/{constraint}") @@ -105,20 +79,8 @@ async def scan_constraint( wavelength: float = Query(..., example=1.0), hklCalc: HklCalculation = Depends(unpickleHkl), ): - check_valid_scan_bounds(start, stop, inc) - result = {} - for value in np.arange(start, stop + inc, inc): - setattr(hklCalc, constraint, value) - allPositions = hklCalc.get_position(*hkl, wavelength) - result[f"{value}"] = combine_lab_position_results(allPositions) - - return {"payload": result} - - -def combine_lab_position_results(positions: List[Tuple[Position, Dict[str, float]]]): - result = [] - - for position in positions: - result.append({**position[0].asdict, **position[1]}) + scanResults = controller.scan_constraint( + constraint, start, stop, inc, hkl, wavelength, hklCalc + ) - return result + return {"payload": scanResults} diff --git a/src/diffcalc_API/routes/UBCalculation.py b/src/diffcalc_API/routes/UBCalculation.py index 7be25a4..1b076dc 100644 --- a/src/diffcalc_API/routes/UBCalculation.py +++ b/src/diffcalc_API/routes/UBCalculation.py @@ -4,16 +4,14 @@ import numpy as np from diffcalc.hkl.calc import HklCalculation -from diffcalc.hkl.geometry import Position from fastapi import APIRouter, Body, Depends, Query +from diffcalc_API.controllers import UBCalculation as controller from diffcalc_API.errors.UBCalculation import ( - calculate_UB_matrix, check_params_not_empty, check_property_is_valid, - get_orientation, - get_reflection, ) +from diffcalc_API.examples import UBCalculation as examples from diffcalc_API.fileHandling import supplyPersist, unpickleHkl from diffcalc_API.models.UBCalculation import ( addOrientationParams, @@ -23,192 +21,121 @@ setLatticeParams, ) -router = APIRouter(prefix="/ub", tags=["ub"]) - - -@router.get("/") -async def read_main(): - return {"msg": "Hello World"} +router = APIRouter( + prefix="/ub", + tags=["ub"], + dependencies=[Depends(unpickleHkl), Depends(supplyPersist)], +) @router.put("/{name}/reflection") async def add_reflection( name: str, - params: addReflectionParams = Body( - ..., - example={ - "hkl": [0, 0, 1], - "position": [7.31, 0.0, 10.62, 0, 0.0, 0], - "energy": 12.39842, - "tag": "refl1", - }, - ), + params: addReflectionParams = Body(..., example=examples.addReflection), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - hklCalc.ubcalc.add_reflection( - params.hkl, - Position(*params.position), - params.energy, - params.tag, - ) - - persist(hklCalc, name) + controller.add_reflection(name, params, hklCalc, persist) return {"message": f"added reflection for UB Calculation of crystal {name}"} -@router.put("/{name}/orientation") -async def add_orientation( +@router.patch("/{name}/reflection") +async def edit_reflection( name: str, - params: addOrientationParams = Body( - ..., - example={ - "hkl": [0, 1, 0], - "xyz": [0, 1, 0], - "tag": "plane", - }, - ), + params: editReflectionParams = Body(..., example=examples.editReflection), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - position = Position(*params.position) if params.position else None - - hklCalc.ubcalc.add_orientation( - params.hkl, - params.xyz, - position, - params.tag, - ) - - persist(hklCalc, name) - return {"message": f"added orientation for UB Calculation of crystal {name}"} + controller.edit_reflection(name, params, hklCalc, persist) + return { + "message": ( + f"reflection with tag/index {params.tagOrIdx} edited to: " + f"{hklCalc.ubcalc.get_reflection(params.tagOrIdx)}." + ) + } -@router.patch("/{name}/lattice") -async def set_lattice( +@router.delete("/{name}/reflection") +async def delete_reflection( name: str, - params: setLatticeParams = Body(example={"a": 4.913, "c": 5.405}), + tagOrIdx: Union[str, int] = Body(..., example="refl1"), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), - _=Depends(check_params_not_empty), ): - hklCalc.ubcalc.set_lattice(name=name, **params.dict()) - persist(hklCalc, name) - return {"message": f"lattice set for UB calculation of crystal {name}"} + controller.delete_reflection(name, tagOrIdx, hklCalc, persist) + return {"message": f"reflection with tag/index {tagOrIdx} deleted."} -@router.patch("/{name}/reflection") -async def edit_reflection( +@router.put("/{name}/orientation") +async def add_orientation( name: str, - params: editReflectionParams = Body( - ..., - example={ - "energy": 12.45, - "tagOrIdx": "refl1", - }, - ), + params: addOrientationParams = Body(..., example=examples.addOrientation), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - reflection = get_reflection(hklCalc, params.tagOrIdx) - - hklCalc.ubcalc.edit_reflection( - params.tagOrIdx, - params.hkl if params.hkl else (reflection.h, reflection.k, reflection.l), - Position(params.position) if params.position else reflection.pos, - params.energy if params.energy else reflection.energy, - params.tagOrIdx if isinstance(params.tagOrIdx, str) else None, - ) - persist(hklCalc, name) - return { - "message": ( - f"reflection edited to: {hklCalc.ubcalc.get_reflection(params.tagOrIdx)}." - ) - } + controller.add_orientation(name, params, hklCalc, persist) + return {"message": f"added orientation for UB Calculation of crystal {name}"} @router.patch("/{name}/orientation") async def edit_orientation( name: str, - params: editOrientationParams = Body( - ..., - example={ - "hkl": (0, 1, 0), - "tagOrIdx": "plane", - }, - ), + params: editOrientationParams = Body(..., example=examples.editOrientation), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - orientation = get_orientation(hklCalc, params.tagOrIdx) - - hklCalc.ubcalc.edit_orientation( - params.tagOrIdx, - params.hkl if params.hkl else (orientation.h, orientation.k, orientation.l), - params.xyz if params.xyz else (orientation.x, orientation.y, orientation.z), - Position(params.position) if params.position else orientation.pos, - params.tagOrIdx if isinstance(params.tagOrIdx, str) else None, - ) - persist(hklCalc, name) + controller.edit_orientation(name, params, hklCalc, persist) return { "message": ( - f"orientation edited to: {hklCalc.ubcalc.get_orientation(params.tagOrIdx)}." + f"orientation with tag/index {params.tagOrIdx} edited to: " + f"{hklCalc.ubcalc.get_orientation(params.tagOrIdx)}." ) } -@router.patch("/{name}/{property}") -async def modify_property( +@router.delete("/{name}/orientation") +async def delete_orientation( name: str, - property: str, - targetValue: Tuple[float, float, float] = Body(..., example=[1, 0, 0]), + tagOrIdx: Union[str, int] = Body(..., example="plane"), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), - _=Depends(check_property_is_valid), ): - setattr(hklCalc.ubcalc, property, targetValue) - persist(hklCalc, name) - - return {"message": f"{property} set for UB calculation of crystal {name}"} + controller.delete_orientation(name, tagOrIdx, hklCalc, persist) + return {"message": f"reflection with tag or index {tagOrIdx} deleted."} -@router.get("/{name}/UB") -async def calculate_UB( +@router.patch("/{name}/lattice") +async def set_lattice( name: str, - firstTag: Optional[Union[int, str]] = Query(default=None, example="refl1"), - secondTag: Optional[Union[int, str]] = Query(default=None, example="plane"), + params: setLatticeParams = Body(example=examples.setLattice), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), + _=Depends(check_params_not_empty), ): - calculate_UB_matrix(hklCalc, firstTag, secondTag) - - persist(hklCalc, name) - return json.dumps(np.round(hklCalc.ubcalc.UB, 6).tolist()) + controller.set_lattice(name, params, hklCalc, persist) + return {"message": f"lattice has been set for UB calculation of crystal {name}"} -@router.delete("/{name}/reflection") -async def delete_reflection( +@router.patch("/{name}/{property}") +async def modify_property( name: str, - tagOrIdx: Union[str, int] = Body(..., example="refl1"), + property: str, + targetValue: Tuple[float, float, float] = Body(..., example=[1, 0, 0]), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), + _=Depends(check_property_is_valid), ): - _ = get_reflection(hklCalc, tagOrIdx) - hklCalc.ubcalc.del_reflection(tagOrIdx) - persist(hklCalc, name) - - return {"message": f"reflection with tag or index {tagOrIdx} deleted."} + controller.modify_property(name, property, targetValue, hklCalc, persist) + return {"message": f"{property} has been set for UB calculation of crystal {name}"} -@router.delete("/{name}/orientation") -async def delete_orientation( +@router.get("/{name}/UB") +async def calculate_UB( name: str, - tagOrIdx: Union[str, int] = Body(..., example="plane"), + firstTag: Optional[Union[int, str]] = Query(default=None, example="refl1"), + secondTag: Optional[Union[int, str]] = Query(default=None, example="plane"), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - _ = get_orientation(hklCalc, tagOrIdx) - hklCalc.ubcalc.del_orientation(tagOrIdx) - persist(hklCalc, name) - - return {"message": f"reflection with tag or index {tagOrIdx} deleted."} + controller.calculate_UB(name, firstTag, secondTag, hklCalc, persist) + return json.dumps(np.round(hklCalc.ubcalc.UB, 6).tolist()) diff --git a/src/diffcalc_API/server.py b/src/diffcalc_API/server.py index 683cfb2..aaf51a4 100644 --- a/src/diffcalc_API/server.py +++ b/src/diffcalc_API/server.py @@ -1,19 +1,19 @@ from diffcalc.util import DiffcalcException from fastapi import FastAPI, Request, responses -from diffcalc_API import errorDefinitions, errors +from diffcalc_API import errorDefinitions +from diffcalc_API.errors.Constraints import responses as responsesConstraints +from diffcalc_API.errors.HklCalculation import responses as responsesHkl +from diffcalc_API.errors.UBCalculation import responses as responsesUb from diffcalc_API.fileHandling import createPickle, deletePickle from . import routes app = FastAPI(responses=errorDefinitions.responses) -app.include_router( - routes.UBCalculation.router, responses=errors.UBCalculation.responses -) -app.include_router(routes.Constraints.router, responses=errors.Constraints.responses) -app.include_router( - routes.HklCalculation.router, responses=errors.HklCalculation.responses -) + +app.include_router(routes.UBCalculation.router, responses=responsesUb) +app.include_router(routes.Constraints.router, responses=responsesConstraints) +app.include_router(routes.HklCalculation.router, responses=responsesHkl) ####################################################################################### # Middleware for Exceptions # @@ -38,6 +38,7 @@ async def http_exception_handler( ) +@app.middleware("http") async def server_exceptions_middleware(request: Request, call_next): try: return await call_next(request) @@ -50,9 +51,6 @@ async def server_exceptions_middleware(request: Request, call_next): ) -app.middleware("http")(server_exceptions_middleware) - - ####################################################################################### # Global Routes # ####################################################################################### From 8d479ac0e268864a3f25692c779c82ad828402a4 Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Thu, 14 Jul 2022 09:43:43 +0000 Subject: [PATCH 2/8] changed controllers to services, in line with common API terms (as controllers/routes are too similar) --- dump.rdb | Bin 0 -> 107 bytes src/diffcalc_API/controllers/__init__.py | 3 --- src/diffcalc_API/routes/Constraints.py | 8 +++---- src/diffcalc_API/routes/HklCalculation.py | 12 +++++------ src/diffcalc_API/routes/UBCalculation.py | 20 +++++++++--------- .../{controllers => services}/Constraints.py | 0 .../HklCalculation.py | 0 .../UBCalculation.py | 0 src/diffcalc_API/services/__init__.py | 3 +++ 9 files changed, 23 insertions(+), 23 deletions(-) create mode 100644 dump.rdb delete mode 100644 src/diffcalc_API/controllers/__init__.py rename src/diffcalc_API/{controllers => services}/Constraints.py (100%) rename src/diffcalc_API/{controllers => services}/HklCalculation.py (100%) rename src/diffcalc_API/{controllers => services}/UBCalculation.py (100%) create mode 100644 src/diffcalc_API/services/__init__.py diff --git a/dump.rdb b/dump.rdb new file mode 100644 index 0000000000000000000000000000000000000000..167a55dbc0bc43f1a49fdb1fc91d0508c8605672 GIT binary patch literal 107 zcmWG?b@2=~Ffg$E#aWb^l3A=H&s-48Iu}7}zrNO0rWc52XC(o%BsT IUMp|{0F Date: Thu, 14 Jul 2022 09:44:52 +0000 Subject: [PATCH 3/8] made a type definition follow correct naming convention --- src/diffcalc_API/services/HklCalculation.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/diffcalc_API/services/HklCalculation.py b/src/diffcalc_API/services/HklCalculation.py index e8aeb75..d2d2d7b 100644 --- a/src/diffcalc_API/services/HklCalculation.py +++ b/src/diffcalc_API/services/HklCalculation.py @@ -10,7 +10,7 @@ check_valid_scan_bounds, ) -positionType = Tuple[float, float, float] +PositionType = Tuple[float, float, float] def lab_position_from_miller_indices( @@ -34,9 +34,9 @@ def miller_indices_from_lab_position( def scan_hkl( - start: positionType, - stop: positionType, - inc: positionType, + start: PositionType, + stop: PositionType, + inc: PositionType, wavelength: float, hklCalc: HklCalculation, ): @@ -59,7 +59,7 @@ def scan_wavelength( start: float, stop: float, inc: float, - hkl: positionType, + hkl: PositionType, hklCalc: HklCalculation, ): check_valid_scan_bounds(start, stop, inc) @@ -78,7 +78,7 @@ def scan_constraint( start: float, stop: float, inc: float, - hkl: positionType, + hkl: PositionType, wavelength: float, hklCalc: HklCalculation, ): From 66932aa4670b772bab776e012956446d522354d2 Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Thu, 14 Jul 2022 10:16:12 +0000 Subject: [PATCH 4/8] modified to be able to merge --- src/diffcalc_API/errors/HklCalculation.py | 19 ++++++++++++++++- src/diffcalc_API/errors/UBCalculation.py | 18 +--------------- src/diffcalc_API/routes/Constraints.py | 9 +++++++- src/diffcalc_API/routes/HklCalculation.py | 22 +++++++++++++++++--- src/diffcalc_API/routes/UBCalculation.py | 23 +++++++-------------- src/diffcalc_API/services/HklCalculation.py | 15 +++++++++++++- src/diffcalc_API/services/UBCalculation.py | 19 ++--------------- tests/test_hklcalc.py | 21 +++++++++++++++++++ tests/test_ubcalc.py | 20 ------------------ 9 files changed, 90 insertions(+), 76 deletions(-) diff --git a/src/diffcalc_API/errors/HklCalculation.py b/src/diffcalc_API/errors/HklCalculation.py index 5dd33f4..177fe66 100644 --- a/src/diffcalc_API/errors/HklCalculation.py +++ b/src/diffcalc_API/errors/HklCalculation.py @@ -1,6 +1,7 @@ -from typing import Tuple +from typing import Optional, Tuple, Union import numpy as np +from diffcalc.hkl.calc import HklCalculation from diffcalc_API.errorDefinitions import DiffcalcAPIException, ErrorCodes, allResponses @@ -8,6 +9,7 @@ class codes(ErrorCodes): check_valid_miller_indices = 400 check_valid_scan_bounds = 400 + calculate_UB_matrix = 400 responses = {code: allResponses[code] for code in np.unique(codes().all_codes())} @@ -32,3 +34,18 @@ def check_valid_scan_bounds(start: float, stop: float, inc: float): ), ) return + + +def calculate_UB_matrix( + hkl: HklCalculation, + firstTag: Optional[Union[int, str]], + secondTag: Optional[Union[int, str]], +) -> None: + try: + hkl.ubcalc.calc_ub(firstTag, secondTag) + except Exception as e: + raise DiffcalcAPIException( + status_code=codes.calculate_UB_matrix, + detail=f"Error calculating UB matrix: {e.__str__()}", + ) + return diff --git a/src/diffcalc_API/errors/UBCalculation.py b/src/diffcalc_API/errors/UBCalculation.py index c23ec99..2ec5860 100644 --- a/src/diffcalc_API/errors/UBCalculation.py +++ b/src/diffcalc_API/errors/UBCalculation.py @@ -1,4 +1,4 @@ -from typing import Optional, Union +from typing import Union import numpy as np from diffcalc.hkl.calc import HklCalculation @@ -14,7 +14,6 @@ class codes(ErrorCodes): get_reflection = 403 get_orientation = 403 check_property_is_valid = 400 - calculate_UB_matrix = 400 responses = {code: allResponses[code] for code in np.unique(codes().all_codes())} @@ -68,18 +67,3 @@ def check_property_is_valid(property: str) -> None: detail=f"invalid property. Choose one of: {VectorProperties}", ) return - - -def calculate_UB_matrix( - hkl: HklCalculation, - firstTag: Optional[Union[int, str]], - secondTag: Optional[Union[int, str]], -) -> None: - try: - hkl.ubcalc.calc_ub(firstTag, secondTag) - except Exception as e: - raise DiffcalcAPIException( - status_code=codes.calculate_UB_matrix, - detail=f"Error calculating UB matrix: {e.__str__()}", - ) - return diff --git a/src/diffcalc_API/routes/Constraints.py b/src/diffcalc_API/routes/Constraints.py index 777a73c..fa95477 100644 --- a/src/diffcalc_API/routes/Constraints.py +++ b/src/diffcalc_API/routes/Constraints.py @@ -2,7 +2,7 @@ from typing import Callable, Dict, Union from diffcalc.hkl.calc import HklCalculation -from fastapi import APIRouter, Body, Depends +from fastapi import APIRouter, Body, Depends, Response from diffcalc_API.fileHandling import supplyPersist, unpickleHkl from diffcalc_API.services import Constraints as service @@ -10,6 +10,13 @@ router = APIRouter(prefix="/constraints", tags=["constraints"]) +@router.get("/{name}") +async def get_constraints_status( + name: str, hklCalc: HklCalculation = Depends(unpickleHkl) +): + return Response(content=str(hklCalc.constraints), media_type="application/text") + + @router.put("/{name}/set") async def set_constraints( name: str, diff --git a/src/diffcalc_API/routes/HklCalculation.py b/src/diffcalc_API/routes/HklCalculation.py index 074601a..2162f0b 100644 --- a/src/diffcalc_API/routes/HklCalculation.py +++ b/src/diffcalc_API/routes/HklCalculation.py @@ -1,9 +1,11 @@ -from typing import Tuple, Union +from pathlib import Path +from typing import Callable, Optional, Tuple, Union +import numpy as np from diffcalc.hkl.calc import HklCalculation -from fastapi import APIRouter, Depends, Query +from fastapi import APIRouter, Depends, Query, Response -from diffcalc_API.fileHandling import unpickleHkl +from diffcalc_API.fileHandling import supplyPersist, unpickleHkl from diffcalc_API.services import HklCalculation as service router = APIRouter( @@ -15,6 +17,20 @@ positionType = Tuple[float, float, float] +@router.get("/{name}/UB") +async def calculate_UB( + name: str, + firstTag: Optional[Union[int, str]] = Query(default=None, example="refl1"), + secondTag: Optional[Union[int, str]] = Query(default=None, example="plane"), + hklCalc: HklCalculation = Depends(unpickleHkl), + persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), +): + service.calculate_UB(name, firstTag, secondTag, hklCalc, persist) + return Response( + content=str(np.round(hklCalc.ubcalc.UB, 6)), media_type="application/text" + ) + + @router.get("/{name}/position/lab") async def lab_position_from_miller_indices( name: str, diff --git a/src/diffcalc_API/routes/UBCalculation.py b/src/diffcalc_API/routes/UBCalculation.py index f70683a..0a9fe6b 100644 --- a/src/diffcalc_API/routes/UBCalculation.py +++ b/src/diffcalc_API/routes/UBCalculation.py @@ -1,10 +1,8 @@ -import json from pathlib import Path -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Tuple, Union -import numpy as np from diffcalc.hkl.calc import HklCalculation -from fastapi import APIRouter, Body, Depends, Query +from fastapi import APIRouter, Body, Depends, Response from diffcalc_API.errors.UBCalculation import ( check_params_not_empty, @@ -28,6 +26,11 @@ ) +@router.get("/{name}") +async def get_UB_status(name: str, hklCalc: HklCalculation = Depends(unpickleHkl)): + return Response(content=str(hklCalc.ubcalc), media_type="application/text") + + @router.put("/{name}/reflection") async def add_reflection( name: str, @@ -127,15 +130,3 @@ async def modify_property( ): service.modify_property(name, property, targetValue, hklCalc, persist) return {"message": f"{property} has been set for UB calculation of crystal {name}"} - - -@router.get("/{name}/UB") -async def calculate_UB( - name: str, - firstTag: Optional[Union[int, str]] = Query(default=None, example="refl1"), - secondTag: Optional[Union[int, str]] = Query(default=None, example="plane"), - hklCalc: HklCalculation = Depends(unpickleHkl), - persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), -): - service.calculate_UB(name, firstTag, secondTag, hklCalc, persist) - return json.dumps(np.round(hklCalc.ubcalc.UB, 6).tolist()) diff --git a/src/diffcalc_API/services/HklCalculation.py b/src/diffcalc_API/services/HklCalculation.py index d2d2d7b..37ac648 100644 --- a/src/diffcalc_API/services/HklCalculation.py +++ b/src/diffcalc_API/services/HklCalculation.py @@ -1,11 +1,13 @@ from itertools import product -from typing import Dict, List, Tuple +from pathlib import Path +from typing import Callable, Dict, List, Optional, Tuple, Union import numpy as np from diffcalc.hkl.calc import HklCalculation from diffcalc.hkl.geometry import Position from diffcalc_API.errors.HklCalculation import ( + calculate_UB_matrix, check_valid_miller_indices, check_valid_scan_bounds, ) @@ -104,3 +106,14 @@ def combine_lab_position_results(positions: List[Tuple[Position, Dict[str, float result.append({**position[0].asdict, **position[1]}) return result + + +def calculate_UB( + name: str, + firstTag: Optional[Union[int, str]], + secondTag: Optional[Union[int, str]], + hklCalc: HklCalculation, + persist: Callable[[HklCalculation, str], Path], +): + calculate_UB_matrix(hklCalc, firstTag, secondTag) + persist(hklCalc, name) diff --git a/src/diffcalc_API/services/UBCalculation.py b/src/diffcalc_API/services/UBCalculation.py index 071a64e..f0ca2ca 100644 --- a/src/diffcalc_API/services/UBCalculation.py +++ b/src/diffcalc_API/services/UBCalculation.py @@ -1,14 +1,10 @@ from pathlib import Path -from typing import Callable, Optional, Tuple, Union +from typing import Callable, Tuple, Union from diffcalc.hkl.calc import HklCalculation from diffcalc.hkl.geometry import Position -from diffcalc_API.errors.UBCalculation import ( - calculate_UB_matrix, - get_orientation, - get_reflection, -) +from diffcalc_API.errors.UBCalculation import get_orientation, get_reflection from diffcalc_API.models.UBCalculation import ( addOrientationParams, addReflectionParams, @@ -134,14 +130,3 @@ def modify_property( ): setattr(hklCalc.ubcalc, property, targetValue) persist(hklCalc, name) - - -def calculate_UB( - name: str, - firstTag: Optional[Union[int, str]], - secondTag: Optional[Union[int, str]], - hklCalc: HklCalculation, - persist: Callable[[HklCalculation, str], Path], -): - calculate_UB_matrix(hklCalc, firstTag, secondTag) - persist(hklCalc, name) diff --git a/tests/test_hklcalc.py b/tests/test_hklcalc.py index 13fee59..7448174 100644 --- a/tests/test_hklcalc.py +++ b/tests/test_hklcalc.py @@ -142,3 +142,24 @@ def test_invalid_scans(client: TestClient): ) assert invalidWavelengthScan.status_code == codes.check_valid_scan_bounds + + +def test_calculate_UB(client: TestClient): + response = client.get( + "/calculate/test/UB", params={"firstTag": "refl1", "secondTag": "plane"} + ) + expected_UB = ( + "[[ 1.27889 -0. 0. ], [-0. 1.278111 0.04057 ]," + " [-0. -0.044633 1.161768]]" + ) + + assert response.status_code == 200 + assert response.text.replace("\n", ", ") == expected_UB + + +def test_calculate_UB_fails_when_incorrect_tags(client: TestClient): + response = client.get( + "/calculate/test/UB", params={"firstTag": "one", "secondTag": "two"} + ) + + assert response.status_code == codes.calculate_UB_matrix diff --git a/tests/test_ubcalc.py b/tests/test_ubcalc.py index d64cda7..a9e0b24 100644 --- a/tests/test_ubcalc.py +++ b/tests/test_ubcalc.py @@ -1,4 +1,3 @@ -import ast from pathlib import Path import numpy as np @@ -202,22 +201,3 @@ def test_modify_non_existent_property(client: TestClient): json=[0, 0, 1], ) assert response.status_code == codes.check_property_is_valid - - -def test_calculate_UB(client: TestClient): - dummyHkl.ubcalc.add_reflection([0, 0, 1], Position(7, 0, 10, 0, 0, 0), 12, "foo") - dummyHkl.ubcalc.add_orientation([0, 1, 0], [0, 1, 0], None, "bar") - dummyHkl.ubcalc.set_lattice(name="test", a=2) - - response = client.get("/ub/test/UB", params={"firstTag": "foo", "secondTag": "bar"}) - - expected_UB = [[3.141593, 0, 0], [0, 3.139679, 0.10964], [-0, -0.10964, 3.139679]] - - assert response.status_code == 200 - assert ast.literal_eval(response._content.decode().replace('"', "")) == expected_UB - - -def test_calculate_UB_fails_when_incorrect_tags(client: TestClient): - response = client.get("/ub/test/UB", params={"firstTag": "one", "secondTag": "two"}) - - assert response.status_code == codes.calculate_UB_matrix From f73bd35f6758fc53d229b93355c8b5c38107fd4c Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Thu, 14 Jul 2022 10:31:04 +0000 Subject: [PATCH 5/8] added deleteParams to enable easier merge with master --- src/diffcalc_API/models/UBCalculation.py | 4 ++++ src/diffcalc_API/routes/UBCalculation.py | 15 ++++++++------- tests/test_ubcalc.py | 8 ++++---- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/src/diffcalc_API/models/UBCalculation.py b/src/diffcalc_API/models/UBCalculation.py index 4e17582..5d83a86 100644 --- a/src/diffcalc_API/models/UBCalculation.py +++ b/src/diffcalc_API/models/UBCalculation.py @@ -41,3 +41,7 @@ class editOrientationParams(BaseModel): xyz: Optional[Tuple[float, float, float]] = None position: Optional[Tuple[float, float, float, float, float, float]] = None tagOrIdx: Union[int, str] + + +class deleteParams(BaseModel): + tagOrIdx: Union[int, str] diff --git a/src/diffcalc_API/routes/UBCalculation.py b/src/diffcalc_API/routes/UBCalculation.py index 0a9fe6b..765a0e8 100644 --- a/src/diffcalc_API/routes/UBCalculation.py +++ b/src/diffcalc_API/routes/UBCalculation.py @@ -1,5 +1,5 @@ from pathlib import Path -from typing import Callable, Tuple, Union +from typing import Callable, Tuple from diffcalc.hkl.calc import HklCalculation from fastapi import APIRouter, Body, Depends, Response @@ -13,6 +13,7 @@ from diffcalc_API.models.UBCalculation import ( addOrientationParams, addReflectionParams, + deleteParams, editOrientationParams, editReflectionParams, setLatticeParams, @@ -61,12 +62,12 @@ async def edit_reflection( @router.delete("/{name}/reflection") async def delete_reflection( name: str, - tagOrIdx: Union[str, int] = Body(..., example="refl1"), + params: deleteParams = Body(..., example={"tagOrIdx": "refl1"}), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - service.delete_reflection(name, tagOrIdx, hklCalc, persist) - return {"message": f"reflection with tag/index {tagOrIdx} deleted."} + service.delete_reflection(name, params.tagOrIdx, hklCalc, persist) + return {"message": f"reflection with tag/index {params.tagOrIdx} deleted."} @router.put("/{name}/orientation") @@ -99,12 +100,12 @@ async def edit_orientation( @router.delete("/{name}/orientation") async def delete_orientation( name: str, - tagOrIdx: Union[str, int] = Body(..., example="plane"), + params: deleteParams = Body(..., example={"tagOrIdx": "plane"}), hklCalc: HklCalculation = Depends(unpickleHkl), persist: Callable[[HklCalculation, str], Path] = Depends(supplyPersist), ): - service.delete_orientation(name, tagOrIdx, hklCalc, persist) - return {"message": f"reflection with tag or index {tagOrIdx} deleted."} + service.delete_orientation(name, params.tagOrIdx, hklCalc, persist) + return {"message": f"reflection with tag or index {params.tagOrIdx} deleted."} @router.patch("/{name}/lattice") diff --git a/tests/test_ubcalc.py b/tests/test_ubcalc.py index a9e0b24..aff4b7d 100644 --- a/tests/test_ubcalc.py +++ b/tests/test_ubcalc.py @@ -67,7 +67,7 @@ def test_edit_reflection(client: TestClient): def test_delete_reflection(client: TestClient): dummyHkl.ubcalc.add_reflection([0, 0, 1], Position(7, 0, 10, 0, 0, 0), 12, "foo") - response = client.delete("/ub/test/reflection", json="foo") + response = client.delete("/ub/test/reflection", json={"tagOrIdx": "foo"}) assert response.status_code == 200 with pytest.raises(Exception): @@ -86,7 +86,7 @@ def test_edit_or_delete_reflection_fails_for_non_existing_reflection( ) deleteResponse = client.delete( "/ub/test/reflection", - json="foo", + json={"tagOrIdx": "foo"}, ) assert editResponse.status_code == codes.get_reflection @@ -133,7 +133,7 @@ def test_delete_orientation(client: TestClient): dummyHkl.ubcalc.add_orientation([0, 0, 1], [0, 0, 1], None, "bar") response = client.delete( "/ub/test/orientation", - json="bar", + json={"tagOrIdx": "bar"}, ) assert response.status_code == 200 @@ -153,7 +153,7 @@ def test_edit_or_delete_orientation_fails_for_non_existing_orientation( ) deleteResponse = client.delete( "/ub/test/orientation", - json="bar", + json={"tagOrIdx": "bar"}, ) assert editResponse.status_code == codes.get_orientation From 87d379de715c9cd844f6f6f1edefc5fa6fb2d3dd Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Thu, 14 Jul 2022 10:32:48 +0000 Subject: [PATCH 6/8] changed to using str( instead of __str__ for easier merge --- src/diffcalc_API/errors/HklCalculation.py | 2 +- src/diffcalc_API/server.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/diffcalc_API/errors/HklCalculation.py b/src/diffcalc_API/errors/HklCalculation.py index 177fe66..bc3d37c 100644 --- a/src/diffcalc_API/errors/HklCalculation.py +++ b/src/diffcalc_API/errors/HklCalculation.py @@ -46,6 +46,6 @@ def calculate_UB_matrix( except Exception as e: raise DiffcalcAPIException( status_code=codes.calculate_UB_matrix, - detail=f"Error calculating UB matrix: {e.__str__()}", + detail=f"Error calculating UB matrix: {str(e)}", ) return diff --git a/src/diffcalc_API/server.py b/src/diffcalc_API/server.py index aaf51a4..b38ba0a 100644 --- a/src/diffcalc_API/server.py +++ b/src/diffcalc_API/server.py @@ -24,7 +24,7 @@ async def diffcalc_exception_handler(request: Request, exc: DiffcalcException): return responses.JSONResponse( status_code=400, - content={"message": exc.__str__(), "type": str(type(exc))}, + content={"message": str(exc), "type": str(type(exc))}, ) @@ -47,7 +47,7 @@ async def server_exceptions_middleware(request: Request, call_next): return responses.JSONResponse( status_code=500, - content={"message": e.__str__(), "type": str(type(e))}, + content={"message": str(e), "type": str(type(e))}, ) From acf8f2550cbaf0eb0cb85b23814cd05b9eb44ad9 Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Thu, 14 Jul 2022 10:57:46 +0000 Subject: [PATCH 7/8] modified files to pass flake/isort/mypy tests --- src/diffcalc_API/routes/Constraints.py | 7 ------- src/diffcalc_API/routes/HklCalculation.py | 1 - src/diffcalc_API/routes/UBCalculation.py | 1 - 3 files changed, 9 deletions(-) diff --git a/src/diffcalc_API/routes/Constraints.py b/src/diffcalc_API/routes/Constraints.py index 725a9de..fa95477 100644 --- a/src/diffcalc_API/routes/Constraints.py +++ b/src/diffcalc_API/routes/Constraints.py @@ -10,13 +10,6 @@ router = APIRouter(prefix="/constraints", tags=["constraints"]) -@router.get("/{name}") -async def get_constraints_status( - name: str, hklCalc: HklCalculation = Depends(unpickleHkl) -): - return Response(content=str(hklCalc.constraints), media_type="application/text") - - @router.get("/{name}") async def get_constraints_status( name: str, hklCalc: HklCalculation = Depends(unpickleHkl) diff --git a/src/diffcalc_API/routes/HklCalculation.py b/src/diffcalc_API/routes/HklCalculation.py index 43da91e..e857774 100644 --- a/src/diffcalc_API/routes/HklCalculation.py +++ b/src/diffcalc_API/routes/HklCalculation.py @@ -9,7 +9,6 @@ from diffcalc_API.fileHandling import supplyPersist, unpickleHkl from diffcalc_API.services import HklCalculation as service - router = APIRouter( prefix="/calculate", tags=["hkl"], dependencies=[Depends(unpickleHkl)] ) diff --git a/src/diffcalc_API/routes/UBCalculation.py b/src/diffcalc_API/routes/UBCalculation.py index fbf22b5..765a0e8 100644 --- a/src/diffcalc_API/routes/UBCalculation.py +++ b/src/diffcalc_API/routes/UBCalculation.py @@ -43,7 +43,6 @@ async def add_reflection( return {"message": f"added reflection for UB Calculation of crystal {name}"} - @router.patch("/{name}/reflection") async def edit_reflection( name: str, From 8b2cc169e27a9097ffde9b8e7fcc56055f61f1a0 Mon Sep 17 00:00:00 2001 From: Rose Yemelyanova Date: Thu, 14 Jul 2022 11:00:35 +0000 Subject: [PATCH 8/8] modified file to pass black check --- src/diffcalc_API/routes/HklCalculation.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/diffcalc_API/routes/HklCalculation.py b/src/diffcalc_API/routes/HklCalculation.py index e857774..2162f0b 100644 --- a/src/diffcalc_API/routes/HklCalculation.py +++ b/src/diffcalc_API/routes/HklCalculation.py @@ -1,4 +1,3 @@ - from pathlib import Path from typing import Callable, Optional, Tuple, Union