Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /DiamondLightSource_python-murfey /src /murfey /util /fib.py
| """ | |
| General functinos specific to the FIB workflow | |
| """ | |
| import math | |
| import xml.etree.ElementTree as ET | |
| from pathlib import Path | |
| from typing import Any | |
| try: | |
| import PIL.Image # Used by 'parse_image_metadata' on the server-side | |
| except ImportError: | |
| pass | |
| def number_from_name(name: str) -> int: | |
| """ | |
| In the AutoTEM and Maps workflows for the FIB, the sites and images are | |
| auto-incremented with parenthesised numbers (e.g. "Lamella (2)"), with | |
| the first site/image typically not having a number. | |
| For sites set up and acquired manually, they will be saved in folders | |
| labelled "Site #1", "Site #2", etc. | |
| This function extracts the number from the file name, and returns 1 if | |
| no such number is found. | |
| """ | |
| # Ensure only the stem is extracted for parsing | |
| stem = Path(name).stem | |
| # Handle naming pattern for sites acquired without autoTEM | |
| if "#" in stem: | |
| return int(stem.rpartition("#")[-1]) | |
| # Handle naming pattern for sites acquired with autoTEM | |
| if "(" in stem and stem.endswith(")"): | |
| return int(stem[stem.rfind("(") + 1 : -1]) | |
| # Names without '()' or '#' should return 1 | |
| return 1 | |
| def get_slot_number( | |
| x: float | None = None, | |
| y: float | None = None, | |
| # Angles are in degrees | |
| rotation: float | None = None, | |
| rotation_offset: float = -75, | |
| ): | |
| """ | |
| In the Aquilos, the stage position values corresponding to slots 1 and 2 are | |
| taken at a fixed stage rotation; at different stage rotation values, the x- | |
| and y- ranges corresponding to slots 1 and 2 will change. This function will | |
| rotate the provided stage values into the correct reference frame and return | |
| the slot number. | |
| """ | |
| if x is not None and y is not None and rotation is not None: | |
| # Rotate the xy-coordinates to reference frame | |
| theta = math.radians(rotation - rotation_offset) | |
| sin = math.sin(theta) | |
| cos = math.cos(theta) | |
| x_rot = (x * cos) - (y * sin) | |
| return 1 if x_rot < 0 else 2 | |
| return None | |
| def parse_image_metadata( | |
| file: Path, | |
| rotation_offset: float, | |
| ): | |
| """ | |
| Helper function that goes through a FIB image and extracts the metadata of | |
| interest from it. | |
| The metadata is stored in different formats (e.g. XML, INI, ...) under different | |
| keys, with these key names differing depending on the image file format. The | |
| metadata extraction logic can eventually be extended to thoroughly search the | |
| image's keys to look for metadata if the initial key fails. | |
| Currently, this function works for the following images generated by the | |
| AutoTEM and Maps software packages: | |
| 1. Electron snapshot TIFFs (Maps) | |
| 2. Lamella evaluation images (AutoTEM) | |
| """ | |
| # Open image and load metadata | |
| img = PIL.Image.open(file) | |
| metadata_format = "" | |
| match file.suffix: | |
| # For PNGs, metadata is stored under the 'text' attribute | |
| case ".png": | |
| tags = dict(img.text) | |
| # XML metadata is stored as a string under 'Metadata' | |
| if tag_contents := tags.get("Metadata"): | |
| metadata_format = "xml" | |
| else: | |
| raise ValueError( | |
| "Could not find metadata under the expected key 'Metadata'" | |
| ) | |
| # For TIFFs, it's stored under the 'tag_v2' attribute | |
| case ".tif" | ".tiff": | |
| tags = dict(img.tag_v2) | |
| # XML metadata is stored as a string under '34683' | |
| if tag_contents := tags.get(34683): | |
| metadata_format = "xml" | |
| else: | |
| raise ValueError( | |
| "Could not find metadata under the expected key '34683'" | |
| ) | |
| case _: | |
| raise NotImplementedError(f"Unsupported image type {file.suffix!r}") | |
| # Parse and extract metadata based on the known format | |
| extracted: dict[str, Any] = {} | |
| match metadata_format: | |
| case "xml": | |
| # XML metadata is written as a single string and needs to be parsed | |
| xml_metadata = ET.fromstring(tag_contents) | |
| # Extract key values from metadata | |
| extracted = { | |
| key: node.text | |
| if (node := xml_metadata.find(node_path)) is not None | |
| else None | |
| for key, node_path in ( | |
| ("voltage", ".//Optics/AccelerationVoltage"), | |
| ("shift_x", ".//Optics/BeamShift/X"), | |
| ("shift_y", ".//Optics/BeamShift/Y"), | |
| ("len_x", ".//Optics/ScanFieldOfView/X"), | |
| ("len_y", ".//Optics/ScanFieldOfView/Y"), | |
| ("pos_x", ".//StageSettings/StagePosition/X"), | |
| ("pos_y", ".//StageSettings/StagePosition/Y"), | |
| ("pos_z", ".//StageSettings/StagePosition/Z"), | |
| # Angles are in radians | |
| ("rotation", ".//StageSettings/StagePosition/Rotation"), | |
| ("tilt_alpha", ".//StageSettings/StagePosition/Tilt/Alpha"), | |
| ("tilt_beta", ".//StageSettings/StagePosition/Tilt/Beta"), | |
| ("pixels_x", ".//BinaryResult/ImageSize/X"), | |
| ("pixels_y", ".//BinaryResult/ImageSize/Y"), | |
| ("pixel_size_x", ".//BinaryResult/PixelSize/X"), | |
| ("pixel_size_y", ".//BinaryResult/PixelSize/Y"), | |
| ) | |
| } | |
| # Calculate the slot number | |
| extracted["slot_number"] = get_slot_number( | |
| x=float(extracted["pos_x"]), | |
| y=float(extracted["pos_y"]), | |
| rotation=math.degrees( | |
| float(extracted["rotation"]) | |
| ), # Convert to degrees | |
| rotation_offset=rotation_offset, | |
| ) | |
| case _: | |
| raise NotImplementedError( | |
| f"Unsupported metadata format {metadata_format!r}" | |
| ) | |
| return extracted | |
Xet Storage Details
- Size:
- 5.95 kB
- Xet hash:
- 52ff7023c612e9baa27d1cda6b9f6dbbb8581cc68fce37d1461a9525f4effbcb
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.