Files
aaredb/testfunctions.ipynb
T
GotthardG 248085b3c4 Update dependencies and improve Python path handling
Updated several frontend dependencies including MUI packages and added new ones like `@mui/x-charts`. Adjusted the Python path setup in the CI configuration to correctly point to the `aaredb` backend, ensuring accurate module resolution.
2025-03-19 12:04:50 +01:00

58 KiB

In [1]:
import json

#from nbclient.client import timestamp

import backend.aareDBclient as aareDBclient
from aareDBclient.rest import ApiException
from pprint import pprint

from app.schemas import characterizationParameters, ResultCreate

#from app.data.data import sample

#from aareDBclient import SamplesApi, ShipmentsApi, PucksApi
#from aareDBclient.models import SampleEventCreate, SetTellPosition
#from examples.examples import api_response

print(aareDBclient.__version__)

configuration = aareDBclient.Configuration(
    #host = "https://mx-aare-test.psi.ch:1492"
    host = "https://127.0.0.1:8000"
)

print(configuration.host)

configuration.verify_ssl = False  # Disable SSL verification
#print(dir(SamplesApi))
0.1.0a26
https://127.0.0.1:8000
In [ ]:
## Fetch all Shipments, list corresponding dewars and pucks

from datetime import date, datetime
from aareDBclient import ShipmentsApi, SamplesApi, GridScanParamers
from aareDBclient.models import Shipment

with aareDBclient.ApiClient(configuration) as api_client:
    api_instance = aareDBclient.ShipmentsApi(api_client)

    try:
        # Fetch all shipments
        all_shipments_response = api_instance.fetch_shipments_shipments_get()

        # Print shipment names and their associated puck names
        for shipment in all_shipments_response:
            print(f"Shipment ID: {shipment.id}, Shipment Name: {shipment.shipment_name}")
            if hasattr(shipment, 'dewars') and shipment.dewars:  # Ensure 'dewars' exists
                for dewar in shipment.dewars:
                    print(f"  Dewar ID: {dewar.id}, Dewar Name: {dewar.dewar_name}, Dewar Unique ID: {dewar.unique_id}  ")

                    if hasattr(dewar, 'pucks') and dewar.pucks:  # Ensure 'pucks' exists
                        for puck in dewar.pucks:
                            print(f"    Puck ID: {puck.id},  Puck Name: {puck.puck_name}")
                    else:
                        print("    No pucks found in this dewar.")
            else:
                print("    No dewars found in this shipment.")

    except ApiException as e:
        print(f"Exception when calling ShipmentsApi->fetch_shipments_shipments_get: {e}")
In [43]:
from datetime import date
from aareDBclient import LogisticsApi
from aareDBclient.models import LogisticsEventCreate  # Import required model

with aareDBclient.ApiClient(configuration) as api_client:
    api_instance = aareDBclient.LogisticsApi(api_client)

    try:
        # Create payload using the required model
        logistics_event_create = LogisticsEventCreate(
            dewar_qr_code='923db239427869be',
            location_qr_code='A2-X06SA',
            transaction_type='incoming',
            timestamp=date.today()  # Adjust if the API expects datetime
        )

        # Pass the payload to the API function
        api_response = api_instance.scan_dewar_logistics_dewar_scan_post(
            logistics_event_create=logistics_event_create  # Pass as an object
        )
        print("API Response:", api_response)

    except ApiException as e:
        print(f"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}")

    try:
        # Create payload using the required model
        logistics_event_create = LogisticsEventCreate(
            dewar_qr_code='923db239427869be',
            location_qr_code='A2-X06SA',
            transaction_type='refill',
            timestamp=date.today()  # Adjust if the API expects datetime
        )

        # Pass the payload to the API function
        api_response = api_instance.scan_dewar_logistics_dewar_scan_post(
            logistics_event_create=logistics_event_create  # Pass as an object
        )
        print("API Response:", api_response)

    except ApiException as e:
        print(f"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}")

    try:
        # Create payload using the required model
        logistics_event_create = LogisticsEventCreate(
            dewar_qr_code='923db239427869be',
            location_qr_code='X06DA-Beamline',
            transaction_type='beamline',
            timestamp=date.today()  # Adjust if the API expects datetime
        )

        # Pass the payload to the API function
        api_response = api_instance.scan_dewar_logistics_dewar_scan_post(
            logistics_event_create=logistics_event_create  # Pass as an object
        )
        print("API Response:", api_response)

    except ApiException as e:
        print(f"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[43], line 19
     15 try:
     16     with open(file_path, "rb") as file_data:
     17         # Use the low-level call_api method; note that the files parameter here is
     18         # a dictionary with key matching the FastAPI parameter name.
---> 19         response = api_client.call_api(
     20             f"/{sample_id}/upload_images",
     21             "POST",
     22             path_params={"sample_id": sample_id},
     23             files={"uploaded_file": (filename, file_data, mime_type)}
     24         )
     25     print("API Response:")
     26     print(response)

TypeError: ApiClient.call_api() got an unexpected keyword argument 'path_params'
In [2]:
# Get a list of pucks that are "at the beamline"

with aareDBclient.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = aareDBclient.PucksApi(api_client)
    get_pucks_at_beamline = aareDBclient.PucksApi(api_client)

    try:
        # Create Return Address
        api_response = api_instance.get_pucks_by_slot_pucks_slot_slot_identifier_get(slot_identifier='X06DA')
        print("The response of PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get:\n")
        pprint(api_response)

    except ApiException as e:
        print("Exception when calling PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get: %s\n" % e)
The response of PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get:

[PuckWithTellPosition(id=1, puck_name='PUCK-001', puck_type='Unipuck', puck_location_in_dewar=1, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position='A2'),
 PuckWithTellPosition(id=2, puck_name='PUCK002', puck_type='Unipuck', puck_location_in_dewar=2, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position='A1'),
 PuckWithTellPosition(id=3, puck_name='PUCK003', puck_type='Unipuck', puck_location_in_dewar=3, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position='F2'),
 PuckWithTellPosition(id=4, puck_name='PUCK004', puck_type='Unipuck', puck_location_in_dewar=4, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position=None),
 PuckWithTellPosition(id=5, puck_name='PUCK005', puck_type='Unipuck', puck_location_in_dewar=5, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position=None),
 PuckWithTellPosition(id=6, puck_name='PUCK006', puck_type='Unipuck', puck_location_in_dewar=6, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position='F1'),
 PuckWithTellPosition(id=7, puck_name='PUCK007', puck_type='Unipuck', puck_location_in_dewar=7, dewar_id=1, dewar_name='Dewar One', pgroup='p20001', samples=None, tell_position=None)]
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
In [78]:
from aareDBclient import SetTellPosition, SetTellPositionRequest

with aareDBclient.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = aareDBclient.PucksApi(api_client)

    # Payload with SetTellPosition objects
    payload = SetTellPositionRequest(
        tell="X06DA",
        #pucks=[
        #    SetTellPosition(puck_name='PSIMX074', segment='B', puck_in_segment=1),
        #    SetTellPosition(puck_name='PSIMX080', segment='B', puck_in_segment=2),
        #    SetTellPosition(puck_name='PSIMX081', segment='C', puck_in_segment=3),
        #    SetTellPosition(puck_name='PSIMX084', segment='C', puck_in_segment=4),
        #    SetTellPosition(puck_name='PSIMX104', segment='E', puck_in_segment=5),
        #    SetTellPosition(puck_name='PSIMX107', segment='E', puck_in_segment=1),
        #    SetTellPosition(puck_name='PSIMX117', segment='F', puck_in_segment=2),
        #]
        #pucks=[
        #    SetTellPosition(puck_name='PSIMX074', segment='F', puck_in_segment=1),
        #    SetTellPosition(puck_name='PSIMX080', segment='F', puck_in_segment=2),
        #    SetTellPosition(puck_name='PSIMX107', segment='A', puck_in_segment=1),
        #    SetTellPosition(puck_name='PSIMX117', segment='A', puck_in_segment=2),
        #]
        pucks=[
            SetTellPosition(puck_name='PUCK006', segment='F', puck_in_segment=1),
            SetTellPosition(puck_name='PUCK003', segment='F', puck_in_segment=2),
            SetTellPosition(puck_name='PUCK002', segment='A', puck_in_segment=1),
            SetTellPosition(puck_name='PUCK001', segment='A', puck_in_segment=2),
        ]
        #pucks = []
    )

    # Call the PUT method to update the tell_position
    try:
        api_response = api_instance.set_tell_positions_pucks_set_tell_positions_put(
            set_tell_position_request=payload
        )  # Pass the entire payload as a single parameter

        print("The response of PucksApi->pucks_puck_id_tell_position_put:\n")
        pprint(api_response)

    except Exception as e:
        print(f"Exception when calling PucksApi: {e}")
The response of PucksApi->pucks_puck_id_tell_position_put:

[{'message': 'Tell position updated successfully.',
  'new_position': 'F1',
  'previous_position': None,
  'puck_name': 'PUCK006',
  'status': 'updated',
  'tell': 'X06DA'},
 {'message': 'Tell position updated successfully.',
  'new_position': 'F2',
  'previous_position': None,
  'puck_name': 'PUCK003',
  'status': 'updated',
  'tell': 'X06DA'},
 {'message': 'Tell position updated successfully.',
  'new_position': 'A1',
  'previous_position': None,
  'puck_name': 'PUCK002',
  'status': 'updated',
  'tell': 'X06DA'},
 {'message': 'Tell position updated successfully.',
  'new_position': 'A2',
  'previous_position': None,
  'puck_name': 'PUCK001',
  'status': 'updated',
  'tell': 'X06DA'}]
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
In [2]:
# Get puck_id puck_name sample_id sample_name of pucks in the tell

with aareDBclient.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = aareDBclient.PucksApi(api_client)

    # GET request: Fetch all pucks in the tell
    try:
        # Call the API method to fetch pucks
        all_pucks_response = api_instance.get_pucks_with_tell_position_pucks_with_tell_position_get(tell='X06DA')

        # Debug response structure by printing it in JSON format
        formatted_response = json.dumps(
            [p.to_dict() for p in all_pucks_response],  # Assuming the API response can be converted to dicts
            indent=4  # Use indentation for readability
        )
        #print("The response of PucksApi->get_all_pucks_in_tell (formatted):\n")
        #print(formatted_response)

        # Iterate through each puck and print information
        for p in all_pucks_response:
            print(f"Puck ID: {p.id}, Puck Name: {p.puck_name}")

            ## Check if the puck has any samples
            if hasattr(p, 'samples') and p.samples:  # Ensure 'samples' attribute exists and is not empty
                for sample in p.samples:
                    print(f"  Sample ID: {sample.id}, Sample Name: {sample.sample_name}, Position: {sample.position}, Mount count: {sample.mount_count}")
            else:
                print("  No samples found in this puck.")

    except ApiException as e:
        print("Exception when calling PucksApi->get_all_pucks_in_tell: %s\n" % e)
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
In [2]:
sample_id = 247
In [5]:
from aareDBclient import SampleEventCreate

# Create an event for a sample

with aareDBclient.ApiClient(configuration) as api_client:
    # Instance of the API client
    api_instance = aareDBclient.SamplesApi(api_client)
    #sample_id=293
    try:
        # Define the payload with only `event_type`
        sample_event_create = SampleEventCreate(
            sample_id=sample_id,
            event_type="Centering"  # Valid event type
            #event_type="Collecting"  # Valid event type
        )

        # Debug the payload before sending
        print("Payload being sent to API:")
        print(sample_event_create.json())  # Ensure it matches `SampleEventCreate`

        # Call the API
        api_response = api_instance.create_sample_event_samples_samples_sample_id_events_post(
            sample_id=sample_id,  # Ensure this matches a valid sample ID in the database
            sample_event_create=sample_event_create
        )

        print("API response:")
        #pprint(api_response)

        for p in api_response:
            print(p)

    except ApiException as e:
        print("Exception when calling post_sample_event:")
        print(f"Status Code: {e.status}")
        if e.body:
            print(f"Error Details: {e.body}")
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): 127.0.0.1:8000
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
DEBUG:urllib3.connectionpool:https://127.0.0.1:8000 "POST /samples/samples/247/events HTTP/1.1" 200 405
Payload being sent to API:
{"event_type":"Centering"}
API response:
('id', 247)
('sample_name', 'Sample247')
('position', 16)
('puck_id', 30)
('crystalname', None)
('proteinname', None)
('positioninpuck', None)
('priority', None)
('comments', None)
('data_collection_parameters', None)
('events', [SampleEventResponse(event_type='Mounting', id=482, sample_id=247, timestamp=datetime.datetime(2025, 3, 13, 13, 39)), SampleEventResponse(event_type='Centering', id=483, sample_id=247, timestamp=datetime.datetime(2025, 3, 14, 20, 35, 49))])
('mount_count', 0)
('unmount_count', 0)
In [ ]:
### not working
with aareDBclient.ApiClient(configuration) as api_client:
    # Create an instance of the Samples API class
    api_instance = aareDBclient.SamplesApi(api_client)

    try:
        # Get the last sample event
        last_event_response = api_instance.get_last_sample_event_samples_samples_sample_id_events_last_get(27)
        print("The response of get_last_sample_event:\n")
        pprint(last_event_response)

    except ApiException as e:
        print("Exception when calling get_last_sample_event: %s\n" % e)
In [12]:
# Post multiple images to the sample database

import os
import mimetypes
import requests

# List of file paths to the images you want to upload
#file_paths = [
#    "backend/tests/sample_image/0_200.jpg",
#    "backend/tests/sample_image/90_200.jpg",
#    "backend/tests/sample_image/0_700.jpg",
#    "backend/tests/sample_image/90_700.jpg",
#]

#file_paths = ["backend/tests/sample_image/mount.jpeg.jpg"]

#file_paths = [
#    "backend/tests/sample_image/bb_raster_90.jpg"
#]

file_paths = ["backend/tests/sample_image/after_dc.jpeg.jpg"]



# Base URL for the upload endpoint
url = f"https://127.0.0.1:8000/samples/{sample_id}/upload-images"

# Iterate through each file and upload it
for file_path in file_paths:
    # Determine file name and MIME type
    filename = os.path.basename(file_path)
    mime_type, _ = mimetypes.guess_type(file_path)
    if mime_type is None:
        mime_type = "application/octet-stream"

    # Open the file for uploading
    with open(file_path, "rb") as file_data:
        files = {
            # Use key "uploaded_file" as required by your API
            "uploaded_file": (filename, file_data, mime_type)
        }
        headers = {
            "accept": "application/json"
        }

        # Send the POST request
        print(f"Uploading {filename}...")
        response = requests.post(url, headers=headers, files=files, verify=False)

        # Check the API response
        print(f"API Response for {filename}:")
        print(response.status_code)
        try:
            print(response.json())
        except Exception:
            print(response.text)
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): 127.0.0.1:8000
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
DEBUG:urllib3.connectionpool:https://127.0.0.1:8000 "POST /samples/247/upload-images HTTP/1.1" 200 205
Uploading after_dc.jpeg.jpg...
API Response for after_dc.jpeg.jpg:
200
{'pgroup': 'p20003', 'sample_id': 247, 'sample_event_id': 486, 'filepath': 'images/p20003/2025-03-14/Dewar Five/PKK007/16/Collecting_2025-03-14_20-54-48/after_dc.jpeg.jpg', 'status': 'active', 'comment': None, 'id': 8}
In [ ]:
help(api_instance.upload_sample_images_samples_samples_sample_id_upload_images_post)
In [11]:
# post experiment results to sample database

from aareDBclient.models import (
    ExperimentParametersCreate,
    RotationParameters,
    BeamlineParameters,
    GridScanParamers
)


# Build the nested parameters
rotation = RotationParameters(
    omegaStart_deg=0.0,
    omegaStep=0.1,
    phi=10.0,
    chi=0.0,
    numberOfImages=3600,
    exposureTime_s=0.02
)

#characterization = characterizationParameters(
#    omegaStart_deg=0.0,
#    omegaStep=90.0,
#    oscillation_deg=1.0,
#    phi=10.0,
#    chi=0.0,
#    numberOfImages=4,
#    exposureTime_s=0.02
#)

#gridscan = GridScanParamers(
#    xStart=90.0,
#    xStep=0.1,
#    yStart=0.0,
#    yStep= 0.1,
#    zStart=0.0,
#    zStep=0.0,
#    numberOfImages=4600,
#    exposureTime_s=0.001
#)

# If your client code requires you to build a detector model,
# you can either use a Detector model or pass a dictionary.
# Here we pass a dictionary.
detector_data = {
    "manufacturer": "DECTRIS",
    "model": "PILATUS4 2M",
    "type": "photon-counting",
    "serialNumber": "16684dscsd668468",
    "detectorDistance_mm": 95.0,
    "beamCenterX_px": 512.0,
    "beamCenterY_px": 512.0,
    "pixelSizeX_um": 150.0,
    "pixelSizeY_um": 150.0,
}

beamline_params = BeamlineParameters(
    synchrotron="Swiss Light Source",
    beamline="PXIII",
    detector=detector_data,
    wavelength=1.0,
    ringCurrent_A=0.0,
    ringMode="Machine Down",
    monochromator="Si111",
    transmission=1.00,
    focusingOptic="Kirkpatrick-Baez",
    beamlineFluxAtSample_ph_s=0,
    beamSizeWidth=30.0,
    beamSizeHeight=30.0,
    #characterization=characterization
    rotation=rotation  # Optional nested parameter
    #gridScan=gridscan
    # gridScan and jet are optional and can be added similarly
)

# Prepare the experiment parameters payload.
# Note that the run_number will be set on the server side, so you can leave
# it out or set it to a dummy value if your client model requires it.
experiment_params_payload = ExperimentParametersCreate(
    # run_number can be omitted/ignored if computed on the server
    beamline_parameters=beamline_params,
    sample_id=sample_id  # change sample_id to an existing sample in your database
)

# Now, use the API instance to send the POST request
with aareDBclient.ApiClient(configuration) as api_client:
    api_instance = aareDBclient.SamplesApi(api_client)

    try:
        # Call the endpoint. The endpoint path expects the sample_id.
        api_response = api_instance.create_experiment_parameters_for_sample(
    sample_id=experiment_params_payload.sample_id,
    experiment_parameters_create=experiment_params_payload
)

        print("API Response:")
        print(api_response)
    except ApiException as e:
        print("Exception when calling ExperimentParametersApi->create_experiment_parameters_for_sample:")
        print(e)
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): 127.0.0.1:8000
/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
DEBUG:urllib3.connectionpool:https://127.0.0.1:8000 "POST /samples/samples/247/experiment_parameters HTTP/1.1" 200 860
API Response:
run_number=3 beamline_parameters=BeamlineParameters(synchrotron='Swiss Light Source', beamline='PXIII', detector=Detector(manufacturer='DECTRIS', model='PILATUS4 2M', type='photon-counting', serial_number='16684dscsd668468', detector_distance_mm=95.0, beam_center_x_px=512.0, beam_center_y_px=512.0, pixel_size_x_um=150.0, pixel_size_y_um=150.0), wavelength=1.0, ring_current_a=0.0, ring_mode='Machine Down', undulator=None, undulatorgap_mm=None, monochromator='Si111', transmission=1.0, focusing_optic='Kirkpatrick-Baez', beamline_flux_at_sample_ph_s=0.0, beam_size_width=30.0, beam_size_height=30.0, characterization=None, rotation=RotationParameters(omega_start_deg=0.0, omega_step=0.1, chi=0.0, phi=10.0, number_of_images=3600, exposure_time_s=0.02), grid_scan=None, jet=None, cryojet_temperature_k=None, humidifier_temperature_k=None, humidifier_humidity=None) sample_id=247 id=3
In [36]:
from app.schemas import CurvePoint
# %%
from app.schemas import ResultCreate, Results
from pprint import pprint
import random
import math
import aareDBclient
from aareDBclient.rest import ApiException

# Your actual sample and experiment IDs
sample_id = sample_id  # Replace with valid IDs
run_id = 1  # Replace with valid run_id

# Function to generate list of CurvePoint (resolution, value pairs)
def logarithmic_decay_curve(length, min_res=4.0, max_res=1.0, max_value=1.0, min_value=0.0, noise=0.005, decimals=3):
    resolutions = sorted([round(random.uniform(min_res, max_res), decimals) for _ in range(length)], reverse=True)  # Reverse order

    curve = []
    for res in resolutions:
        # Exponential-like decay: Higher resolution (small number) -> value ~1, Lower resolution (big number) -> value ~0
        decay_factor = (res - max_res) / (min_res - max_res)  # Normalize res to [0,1]
        value = max_value - ( math.exp(- 20 * decay_factor ) ) # Exponential decay

        # Add small random noise for realism
        noise_value = random.uniform(-noise, noise)
        value = min(max(value + noise_value, min_value), max_value)  # Clamp between min_value and max_value

        curve.append(CurvePoint(resolution=res, value=round(value, decimals)))

    return curve

# Create random Results payload
results_data = Results(
    pipeline="autoproc",
    resolution=round(random.uniform(1.0, 4.0), 2),
    unit_cell=f"{random.uniform(20, 120):.2f}, {random.uniform(20, 120):.2f}, "
              f"{random.uniform(20, 120):.2f}, {random.uniform(60, 120):.2f}, "
              f"{random.uniform(60, 120):.2f}, {random.uniform(60, 120):.2f}",
    spacegroup=random.choice(['P212121', 'C2', 'P1', 'P21', 'P21212', 'P41212']),
    rmerge=round(random.uniform(0.02, 0.10), 3),
    rmeas=round(random.uniform(0.02, 0.15), 3),
    isig=round(random.uniform(1.0, 30.0), 2),
    cc=logarithmic_decay_curve(100),  # List of CurvePoint for CC curve
    cchalf=logarithmic_decay_curve(100),  # List of CurvePoint for CC(1/2) curve
    completeness=round(random.uniform(85.0, 100.0), 2),
    multiplicity=round(random.uniform(1.0, 10.0), 2),
    nobs=random.randint(10000, 500000),
    total_refl=random.randint(5000, 250000),
    unique_refl=random.randint(5000, 100000),
    comments="Random auto-generated test entry"
)

payload = ResultCreate(sample_id=sample_id, run_id=run_id, result=results_data)

# correct serialization, passing exact required dict structure
payload_dict = {
    "sample_id": sample_id,
    "run_id": run_id,
    "result": results_data.model_dump(),
}

with aareDBclient.ApiClient(configuration) as api_client:
    api_instance = aareDBclient.SamplesApi(api_client)

    try:
        api_response = api_instance.create_result(
            result_create=payload_dict
        )

        print("API call successful:")
        pprint(api_response)

    except ApiException as e:
        print(f"API call failed: {e}")
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): 127.0.0.1:8000
/Users/gotthardg/PycharmProjects/aaredb/.venv/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
DEBUG:urllib3.connectionpool:https://127.0.0.1:8000 "POST /samples/processing-results HTTP/1.1" 200 7218
API call successful:
ResultResponse(id=36, sample_id=247, run_id=1, result=Results(pipeline='autoproc', resolution=1.81, unit_cell='56.82, 75.31, 82.06, 91.76, 79.97, 79.75', spacegroup='P1', rmerge=0.097, rmeas=0.122, isig=13.86, cc=[CurvePoint(resolution=3.979, value=1.0), CurvePoint(resolution=3.964, value=0.997), CurvePoint(resolution=3.879, value=1.0), CurvePoint(resolution=3.814, value=0.999), CurvePoint(resolution=3.787, value=0.997), CurvePoint(resolution=3.767, value=1.0), CurvePoint(resolution=3.706, value=0.998), CurvePoint(resolution=3.68, value=1.0), CurvePoint(resolution=3.678, value=0.998), CurvePoint(resolution=3.677, value=0.998), CurvePoint(resolution=3.627, value=1.0), CurvePoint(resolution=3.619, value=1.0), CurvePoint(resolution=3.614, value=1.0), CurvePoint(resolution=3.598, value=0.998), CurvePoint(resolution=3.568, value=1.0), CurvePoint(resolution=3.477, value=0.999), CurvePoint(resolution=3.46, value=1.0), CurvePoint(resolution=3.44, value=1.0), CurvePoint(resolution=3.414, value=0.999), CurvePoint(resolution=3.341, value=0.997), CurvePoint(resolution=3.315, value=0.998), CurvePoint(resolution=3.258, value=0.995), CurvePoint(resolution=3.204, value=0.997), CurvePoint(resolution=3.182, value=0.996), CurvePoint(resolution=3.168, value=0.997), CurvePoint(resolution=3.07, value=0.997), CurvePoint(resolution=3.044, value=1.0), CurvePoint(resolution=3.037, value=0.999), CurvePoint(resolution=3.037, value=0.997), CurvePoint(resolution=3.024, value=0.996), CurvePoint(resolution=3.014, value=0.996), CurvePoint(resolution=3.009, value=0.998), CurvePoint(resolution=2.882, value=0.998), CurvePoint(resolution=2.798, value=0.997), CurvePoint(resolution=2.728, value=1.0), CurvePoint(resolution=2.722, value=0.998), CurvePoint(resolution=2.713, value=0.996), CurvePoint(resolution=2.712, value=1.0), CurvePoint(resolution=2.703, value=1.0), CurvePoint(resolution=2.587, value=0.998), CurvePoint(resolution=2.586, value=0.996), CurvePoint(resolution=2.57, value=0.996), CurvePoint(resolution=2.553, value=1.0), CurvePoint(resolution=2.539, value=0.999), CurvePoint(resolution=2.493, value=0.997), CurvePoint(resolution=2.483, value=0.998), CurvePoint(resolution=2.454, value=0.997), CurvePoint(resolution=2.435, value=1.0), CurvePoint(resolution=2.431, value=0.998), CurvePoint(resolution=2.418, value=1.0), CurvePoint(resolution=2.396, value=0.995), CurvePoint(resolution=2.36, value=1.0), CurvePoint(resolution=2.332, value=0.996), CurvePoint(resolution=2.323, value=0.998), CurvePoint(resolution=2.299, value=0.998), CurvePoint(resolution=2.294, value=1.0), CurvePoint(resolution=2.271, value=0.999), CurvePoint(resolution=2.267, value=1.0), CurvePoint(resolution=2.234, value=0.998), CurvePoint(resolution=2.216, value=1.0), CurvePoint(resolution=2.108, value=1.0), CurvePoint(resolution=2.028, value=0.994), CurvePoint(resolution=2.012, value=0.996), CurvePoint(resolution=2.007, value=0.996), CurvePoint(resolution=1.964, value=0.996), CurvePoint(resolution=1.92, value=1.0), CurvePoint(resolution=1.883, value=0.995), CurvePoint(resolution=1.824, value=0.996), CurvePoint(resolution=1.818, value=0.993), CurvePoint(resolution=1.817, value=0.993), CurvePoint(resolution=1.812, value=0.991), CurvePoint(resolution=1.769, value=0.99), CurvePoint(resolution=1.743, value=0.988), CurvePoint(resolution=1.732, value=0.992), CurvePoint(resolution=1.729, value=0.995), CurvePoint(resolution=1.689, value=0.993), CurvePoint(resolution=1.658, value=0.988), CurvePoint(resolution=1.654, value=0.984), CurvePoint(resolution=1.634, value=0.987), CurvePoint(resolution=1.608, value=0.984), CurvePoint(resolution=1.586, value=0.975), CurvePoint(resolution=1.559, value=0.974), CurvePoint(resolution=1.512, value=0.971), CurvePoint(resolution=1.485, value=0.965), CurvePoint(resolution=1.482, value=0.964), CurvePoint(resolution=1.479, value=0.963), CurvePoint(resolution=1.477, value=0.962), CurvePoint(resolution=1.434, value=0.948), CurvePoint(resolution=1.43, value=0.942), CurvePoint(resolution=1.401, value=0.931), CurvePoint(resolution=1.373, value=0.922), CurvePoint(resolution=1.333, value=0.889), CurvePoint(resolution=1.305, value=0.873), CurvePoint(resolution=1.253, value=0.814), CurvePoint(resolution=1.252, value=0.81), CurvePoint(resolution=1.216, value=0.765), CurvePoint(resolution=1.041, value=0.235), CurvePoint(resolution=1.04, value=0.23), CurvePoint(resolution=1.033, value=0.197), CurvePoint(resolution=1.015, value=0.096)], cchalf=[CurvePoint(resolution=3.985, value=1.0), CurvePoint(resolution=3.984, value=1.0), CurvePoint(resolution=3.974, value=1.0), CurvePoint(resolution=3.934, value=1.0), CurvePoint(resolution=3.895, value=0.998), CurvePoint(resolution=3.884, value=0.998), CurvePoint(resolution=3.833, value=0.996), CurvePoint(resolution=3.817, value=0.997), CurvePoint(resolution=3.794, value=0.995), CurvePoint(resolution=3.783, value=1.0), CurvePoint(resolution=3.782, value=1.0), CurvePoint(resolution=3.728, value=0.996), CurvePoint(resolution=3.728, value=0.999), CurvePoint(resolution=3.685, value=0.999), CurvePoint(resolution=3.637, value=1.0), CurvePoint(resolution=3.607, value=0.999), CurvePoint(resolution=3.606, value=1.0), CurvePoint(resolution=3.599, value=1.0), CurvePoint(resolution=3.549, value=0.995), CurvePoint(resolution=3.543, value=1.0), CurvePoint(resolution=3.464, value=1.0), CurvePoint(resolution=3.34, value=0.998), CurvePoint(resolution=3.295, value=1.0), CurvePoint(resolution=3.257, value=0.999), CurvePoint(resolution=3.254, value=1.0), CurvePoint(resolution=3.251, value=1.0), CurvePoint(resolution=3.251, value=1.0), CurvePoint(resolution=3.228, value=1.0), CurvePoint(resolution=3.227, value=1.0), CurvePoint(resolution=3.226, value=1.0), CurvePoint(resolution=3.184, value=0.995), CurvePoint(resolution=3.173, value=0.997), CurvePoint(resolution=3.08, value=1.0), CurvePoint(resolution=3.062, value=1.0), CurvePoint(resolution=3.04, value=1.0), CurvePoint(resolution=3.013, value=1.0), CurvePoint(resolution=2.965, value=1.0), CurvePoint(resolution=2.913, value=0.998), CurvePoint(resolution=2.876, value=1.0), CurvePoint(resolution=2.866, value=0.998), CurvePoint(resolution=2.849, value=1.0), CurvePoint(resolution=2.839, value=0.998), CurvePoint(resolution=2.816, value=1.0), CurvePoint(resolution=2.773, value=1.0), CurvePoint(resolution=2.747, value=0.995), CurvePoint(resolution=2.737, value=1.0), CurvePoint(resolution=2.733, value=0.998), CurvePoint(resolution=2.723, value=1.0), CurvePoint(resolution=2.713, value=1.0), CurvePoint(resolution=2.626, value=0.997), CurvePoint(resolution=2.583, value=0.996), CurvePoint(resolution=2.501, value=1.0), CurvePoint(resolution=2.493, value=1.0), CurvePoint(resolution=2.411, value=0.998), CurvePoint(resolution=2.31, value=1.0), CurvePoint(resolution=2.287, value=0.997), CurvePoint(resolution=2.246, value=0.995), CurvePoint(resolution=2.233, value=1.0), CurvePoint(resolution=2.191, value=0.998), CurvePoint(resolution=2.167, value=0.995), CurvePoint(resolution=2.149, value=0.996), CurvePoint(resolution=2.127, value=1.0), CurvePoint(resolution=2.114, value=1.0), CurvePoint(resolution=2.046, value=1.0), CurvePoint(resolution=2.004, value=0.996), CurvePoint(resolution=1.987, value=0.995), CurvePoint(resolution=1.908, value=0.993), CurvePoint(resolution=1.899, value=1.0), CurvePoint(resolution=1.856, value=0.995), CurvePoint(resolution=1.822, value=0.993), CurvePoint(resolution=1.812, value=0.997), CurvePoint(resolution=1.802, value=0.992), CurvePoint(resolution=1.796, value=0.995), CurvePoint(resolution=1.773, value=0.996), CurvePoint(resolution=1.767, value=0.991), CurvePoint(resolution=1.76, value=0.989), CurvePoint(resolution=1.742, value=0.991), CurvePoint(resolution=1.725, value=0.996), CurvePoint(resolution=1.723, value=0.995), CurvePoint(resolution=1.718, value=0.987), CurvePoint(resolution=1.687, value=0.989), CurvePoint(resolution=1.639, value=0.984), CurvePoint(resolution=1.598, value=0.982), CurvePoint(resolution=1.592, value=0.985), CurvePoint(resolution=1.494, value=0.963), CurvePoint(resolution=1.475, value=0.961), CurvePoint(resolution=1.449, value=0.954), CurvePoint(resolution=1.427, value=0.946), CurvePoint(resolution=1.402, value=0.929), CurvePoint(resolution=1.377, value=0.918), CurvePoint(resolution=1.324, value=0.889), CurvePoint(resolution=1.296, value=0.859), CurvePoint(resolution=1.253, value=0.814), CurvePoint(resolution=1.227, value=0.784), CurvePoint(resolution=1.225, value=0.773), CurvePoint(resolution=1.146, value=0.619), CurvePoint(resolution=1.118, value=0.547), CurvePoint(resolution=1.03, value=0.179), CurvePoint(resolution=1.013, value=0.087), CurvePoint(resolution=1.011, value=0.07)], completeness=86.92, multiplicity=5.46, nobs=48062, total_refl=73724, unique_refl=93185, comments='Random auto-generated test entry'))
In [6]:
# get experiment results to sample database

with aareDBclient.ApiClient(configuration) as api_client:
    # Create an instance of the API class
    api_instance = aareDBclient.SamplesApi(api_client)

    # GET request: Fetch all pucks in the tell
    try:
        # Call the API method to fetch pucks
        all_results_response = api_instance.get_sample_results_samples_results_get(active_pgroup="p20003")
        pprint(all_results_response)
        ## Debug response structure by printing it in JSON format
        #formatted_response = json.dumps(
        #    [p.to_dict() for p in all_results_response],  # Assuming the API response can be converted to dicts
        #    indent=4  # Use indentation for readability
        #)
        #print("The response of PucksApi->get_all_pucks_in_tell (formatted):\n")
        #print(formatted_response)

        ## Iterate through each puck and print information
        #for p in all_results_response:
        #    print(f"Puck ID: {p.id}, Puck Name: {p.puck_name}")
        #
        #    ## Check if the puck has any samples
        #    if hasattr(p, 'samples') and p.samples:  # Ensure 'samples' attribute exists and is not empty
        #        for sample in p.samples:
        #            print(f"  Sample ID: {sample.id}, Sample Name: {sample.sample_name}, Position: {sample.position}, Mount count: {sample.mount_count}")
        #    else:
        #        print("  No samples found in this puck.")
        #
    except ApiException as e:
        print("Exception when calling PucksApi->get_all_pucks_in_tell: %s\n" % e)
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): 127.0.0.1:8000
/Users/gotthardg/PycharmProjects/aaredb/.venv/lib/python3.12/site-packages/urllib3/connectionpool.py:1097: InsecureRequestWarning: Unverified HTTPS request is being made to host '127.0.0.1'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
  warnings.warn(
DEBUG:urllib3.connectionpool:https://127.0.0.1:8000 "GET /samples/results?active_pgroup=p20003 HTTP/1.1" 200 7927
[SampleResult(sample_id=215, sample_name='Sample215', puck_name='PKK004', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=216, sample_name='Sample216', puck_name='PKK004', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=217, sample_name='Sample217', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=218, sample_name='Sample218', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=219, sample_name='Sample219', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=220, sample_name='Sample220', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=221, sample_name='Sample221', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=222, sample_name='Sample222', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=223, sample_name='Sample223', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=224, sample_name='Sample224', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=225, sample_name='Sample225', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=226, sample_name='Sample226', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=227, sample_name='Sample227', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=228, sample_name='Sample228', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=229, sample_name='Sample229', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=230, sample_name='Sample230', puck_name='PKK005', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=231, sample_name='Sample231', puck_name='PKK006', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=232, sample_name='Sample232', puck_name='PKK006', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=233, sample_name='Sample233', puck_name='PKK006', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=234, sample_name='Sample234', puck_name='PKK006', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=235, sample_name='Sample235', puck_name='PKK006', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=236, sample_name='Sample236', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=237, sample_name='Sample237', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=238, sample_name='Sample238', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=239, sample_name='Sample239', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=240, sample_name='Sample240', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=241, sample_name='Sample241', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=242, sample_name='Sample242', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=243, sample_name='Sample243', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=244, sample_name='Sample244', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=245, sample_name='Sample245', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=246, sample_name='Sample246', puck_name='PKK007', dewar_name='Dewar Five', images=[], experiment_runs=[]),
 SampleResult(sample_id=247, sample_name='Sample247', puck_name='PKK007', dewar_name='Dewar Five', images=[ImageInfo(id=1, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Mounting_2025-03-13_13-39-00/mount.jpeg.jpg', comment=None, event_type='Mounting'), ImageInfo(id=2, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Centering_2025-03-14_20-35-49/0_200.jpg', comment=None, event_type='Centering'), ImageInfo(id=3, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Centering_2025-03-14_20-35-49/90_200.jpg', comment=None, event_type='Centering'), ImageInfo(id=4, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Centering_2025-03-14_20-35-49/0_700.jpg', comment=None, event_type='Centering'), ImageInfo(id=5, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Centering_2025-03-14_20-35-49/90_700.jpg', comment=None, event_type='Centering'), ImageInfo(id=6, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Collecting_2025-03-14_20-37-45/bb_raster_0.jpg', comment=None, event_type='Collecting'), ImageInfo(id=7, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Collecting_2025-03-14_20-54-05/bb_raster_90.jpg', comment=None, event_type='Collecting'), ImageInfo(id=8, filepath='images/p20003/2025-03-14/Dewar Five/PKK007/16/Collecting_2025-03-14_20-54-48/after_dc.jpeg.jpg', comment=None, event_type='Collecting')], experiment_runs=[ExperimentParametersRead(run_number=1, beamline_parameters=BeamlineParameters(synchrotron='Swiss Light Source', beamline='PXIII', detector=Detector(manufacturer='DECTRIS', model='PILATUS4 2M', type='photon-counting', serial_number='16684dscsd668468', detector_distance_mm=95.0, beam_center_x_px=512.0, beam_center_y_px=512.0, pixel_size_x_um=150.0, pixel_size_y_um=150.0), wavelength=1.0, ring_current_a=0.0, ring_mode='Machine Down', undulator=None, undulatorgap_mm=None, monochromator='Si111', transmission=1.0, focusing_optic='Kirkpatrick-Baez', beamline_flux_at_sample_ph_s=0.0, beam_size_width=30.0, beam_size_height=30.0, characterization=None, rotation=None, grid_scan=GridScanParamers(x_start=0.0, x_step=0.1, y_start=0.0, y_step=0.1, z_start=0.0, z_step=0.0, number_of_images=4600, exposure_time_s=0.001), jet=None, cryojet_temperature_k=None, humidifier_temperature_k=None, humidifier_humidity=None), sample_id=247, id=1), ExperimentParametersRead(run_number=2, beamline_parameters=BeamlineParameters(synchrotron='Swiss Light Source', beamline='PXIII', detector=Detector(manufacturer='DECTRIS', model='PILATUS4 2M', type='photon-counting', serial_number='16684dscsd668468', detector_distance_mm=95.0, beam_center_x_px=512.0, beam_center_y_px=512.0, pixel_size_x_um=150.0, pixel_size_y_um=150.0), wavelength=1.0, ring_current_a=0.0, ring_mode='Machine Down', undulator=None, undulatorgap_mm=None, monochromator='Si111', transmission=1.0, focusing_optic='Kirkpatrick-Baez', beamline_flux_at_sample_ph_s=0.0, beam_size_width=30.0, beam_size_height=30.0, characterization=None, rotation=None, grid_scan=GridScanParamers(x_start=90.0, x_step=0.1, y_start=0.0, y_step=0.1, z_start=0.0, z_step=0.0, number_of_images=4600, exposure_time_s=0.001), jet=None, cryojet_temperature_k=None, humidifier_temperature_k=None, humidifier_humidity=None), sample_id=247, id=2), ExperimentParametersRead(run_number=3, beamline_parameters=BeamlineParameters(synchrotron='Swiss Light Source', beamline='PXIII', detector=Detector(manufacturer='DECTRIS', model='PILATUS4 2M', type='photon-counting', serial_number='16684dscsd668468', detector_distance_mm=95.0, beam_center_x_px=512.0, beam_center_y_px=512.0, pixel_size_x_um=150.0, pixel_size_y_um=150.0), wavelength=1.0, ring_current_a=0.0, ring_mode='Machine Down', undulator=None, undulatorgap_mm=None, monochromator='Si111', transmission=1.0, focusing_optic='Kirkpatrick-Baez', beamline_flux_at_sample_ph_s=0.0, beam_size_width=30.0, beam_size_height=30.0, characterization=None, rotation=RotationParameters(omega_start_deg=0.0, omega_step=0.1, chi=0.0, phi=10.0, number_of_images=3600, exposure_time_s=0.02), grid_scan=None, jet=None, cryojet_temperature_k=None, humidifier_temperature_k=None, humidifier_humidity=None), sample_id=247, id=3)])]