{
 "cells": [
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:24:28.514707Z",
     "start_time": "2025-05-05T13:24:27.932416Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import json\n",
    "import requests\n",
    "#from nbclient.client import timestamp\n",
    "\n",
    "import backend.aareDBclient as aareDBclient\n",
    "from aareDBclient.rest import ApiException\n",
    "from pprint import pprint\n",
    "\n",
    "from app.schemas import characterizationParameters, ResultCreate, BeamtimeCreate\n",
    "\n",
    "#from app.data.data import sample\n",
    "\n",
    "#from aareDBclient import SamplesApi, ShipmentsApi, PucksApi\n",
    "#from aareDBclient.models import SampleEventCreate, SetTellPosition\n",
    "#from examples.examples import api_response\n",
    "\n",
    "print(aareDBclient.__version__)\n",
    "\n",
    "configuration = aareDBclient.Configuration(\n",
    "    #host = \"https://mx-aare-test.psi.ch:1492\"\n",
    "    host = \"https://localhost:8000\"\n",
    ")\n",
    "\n",
    "# 1. Get the token\n",
    "login_resp = requests.post(\n",
    "    \"https://localhost:8000/auth/token/login\",\n",
    "    data={\"username\": \"testuser\", \"password\": \"testpass\"},\n",
    "    verify=False  # Only for self-signed/dev certs!\n",
    ")\n",
    "\n",
    "token = login_resp.json()[\"access_token\"]\n",
    "\n",
    "print(configuration.host)\n",
    "\n",
    "configuration.verify_ssl = False  # Disable SSL verification\n",
    "#print(dir(SamplesApi))"
   ],
   "id": "3b7c27697a4d5c83",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"POST /auth/token/login HTTP/1.1\" 200 233\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.1.1a2\n",
      "https://localhost:8000\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": [
    "## Fetch all Shipments, list corresponding dewars and pucks\n",
    "\n",
    "from datetime import date, datetime\n",
    "from aareDBclient import ShipmentsApi, SamplesApi, GridScanParamers\n",
    "from aareDBclient.models import Shipment\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    api_instance = aareDBclient.ShipmentsApi(api_client)\n",
    "\n",
    "    try:\n",
    "        # Fetch all shipments\n",
    "        all_shipments_response = api_instance.fetch_shipments_shipments_get()\n",
    "\n",
    "        # Print shipment names and their associated puck names\n",
    "        for shipment in all_shipments_response:\n",
    "            print(f\"Shipment ID: {shipment.id}, Shipment Name: {shipment.shipment_name}\")\n",
    "            if hasattr(shipment, 'dewars') and shipment.dewars:  # Ensure 'dewars' exists\n",
    "                for dewar in shipment.dewars:\n",
    "                    print(f\"  Dewar ID: {dewar.id}, Dewar Name: {dewar.dewar_name}, Dewar Unique ID: {dewar.unique_id}  \")\n",
    "\n",
    "                    if hasattr(dewar, 'pucks') and dewar.pucks:  # Ensure 'pucks' exists\n",
    "                        for puck in dewar.pucks:\n",
    "                            print(f\"    Puck ID: {puck.id},  Puck Name: {puck.puck_name}\")\n",
    "                    else:\n",
    "                        print(\"    No pucks found in this dewar.\")\n",
    "            else:\n",
    "                print(\"    No dewars found in this shipment.\")\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(f\"Exception when calling ShipmentsApi->fetch_shipments_shipments_get: {e}\")\n"
   ],
   "id": "4955b858f2cef93e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-02-25T15:47:34.956061Z",
     "start_time": "2025-02-25T15:47:34.941372Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from datetime import date\n",
    "from aareDBclient import LogisticsApi\n",
    "from aareDBclient.models import LogisticsEventCreate  # Import required model\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    api_instance = aareDBclient.LogisticsApi(api_client)\n",
    "\n",
    "    try:\n",
    "        # Create payload using the required model\n",
    "        logistics_event_create = LogisticsEventCreate(\n",
    "            dewar_qr_code='923db239427869be',\n",
    "            location_qr_code='A2-X06SA',\n",
    "            transaction_type='incoming',\n",
    "            timestamp=date.today()  # Adjust if the API expects datetime\n",
    "        )\n",
    "\n",
    "        # Pass the payload to the API function\n",
    "        api_response = api_instance.scan_dewar_logistics_dewar_scan_post(\n",
    "            logistics_event_create=logistics_event_create  # Pass as an object\n",
    "        )\n",
    "        print(\"API Response:\", api_response)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(f\"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}\")\n",
    "\n",
    "    try:\n",
    "        # Create payload using the required model\n",
    "        logistics_event_create = LogisticsEventCreate(\n",
    "            dewar_qr_code='923db239427869be',\n",
    "            location_qr_code='A2-X06SA',\n",
    "            transaction_type='refill',\n",
    "            timestamp=date.today()  # Adjust if the API expects datetime\n",
    "        )\n",
    "\n",
    "        # Pass the payload to the API function\n",
    "        api_response = api_instance.scan_dewar_logistics_dewar_scan_post(\n",
    "            logistics_event_create=logistics_event_create  # Pass as an object\n",
    "        )\n",
    "        print(\"API Response:\", api_response)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(f\"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}\")\n",
    "\n",
    "    try:\n",
    "        # Create payload using the required model\n",
    "        logistics_event_create = LogisticsEventCreate(\n",
    "            dewar_qr_code='923db239427869be',\n",
    "            location_qr_code='X06DA-Beamline',\n",
    "            transaction_type='beamline',\n",
    "            timestamp=date.today()  # Adjust if the API expects datetime\n",
    "        )\n",
    "\n",
    "        # Pass the payload to the API function\n",
    "        api_response = api_instance.scan_dewar_logistics_dewar_scan_post(\n",
    "            logistics_event_create=logistics_event_create  # Pass as an object\n",
    "        )\n",
    "        print(\"API Response:\", api_response)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(f\"Exception when calling LogisticsApi->scan_dewar_logistics_dewar_scan_post: {e}\")\n"
   ],
   "id": "8fd3638bffaecd23",
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "ApiClient.call_api() got an unexpected keyword argument 'path_params'",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[43], line 19\u001B[0m\n\u001B[1;32m     15\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m     16\u001B[0m     \u001B[38;5;28;01mwith\u001B[39;00m \u001B[38;5;28mopen\u001B[39m(file_path, \u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mrb\u001B[39m\u001B[38;5;124m\"\u001B[39m) \u001B[38;5;28;01mas\u001B[39;00m file_data:\n\u001B[1;32m     17\u001B[0m         \u001B[38;5;66;03m# Use the low-level call_api method; note that the files parameter here is\u001B[39;00m\n\u001B[1;32m     18\u001B[0m         \u001B[38;5;66;03m# a dictionary with key matching the FastAPI parameter name.\u001B[39;00m\n\u001B[0;32m---> 19\u001B[0m         response \u001B[38;5;241m=\u001B[39m \u001B[43mapi_client\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mcall_api\u001B[49m\u001B[43m(\u001B[49m\n\u001B[1;32m     20\u001B[0m \u001B[43m            \u001B[49m\u001B[38;5;124;43mf\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43m/\u001B[39;49m\u001B[38;5;132;43;01m{\u001B[39;49;00m\u001B[43msample_id\u001B[49m\u001B[38;5;132;43;01m}\u001B[39;49;00m\u001B[38;5;124;43m/upload_images\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\n\u001B[1;32m     21\u001B[0m \u001B[43m            \u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43mPOST\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m,\u001B[49m\n\u001B[1;32m     22\u001B[0m \u001B[43m            \u001B[49m\u001B[43mpath_params\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43m{\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43msample_id\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m:\u001B[49m\u001B[43m \u001B[49m\u001B[43msample_id\u001B[49m\u001B[43m}\u001B[49m\u001B[43m,\u001B[49m\n\u001B[1;32m     23\u001B[0m \u001B[43m            \u001B[49m\u001B[43mfiles\u001B[49m\u001B[38;5;241;43m=\u001B[39;49m\u001B[43m{\u001B[49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[38;5;124;43muploaded_file\u001B[39;49m\u001B[38;5;124;43m\"\u001B[39;49m\u001B[43m:\u001B[49m\u001B[43m \u001B[49m\u001B[43m(\u001B[49m\u001B[43mfilename\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mfile_data\u001B[49m\u001B[43m,\u001B[49m\u001B[43m \u001B[49m\u001B[43mmime_type\u001B[49m\u001B[43m)\u001B[49m\u001B[43m}\u001B[49m\n\u001B[1;32m     24\u001B[0m \u001B[43m        \u001B[49m\u001B[43m)\u001B[49m\n\u001B[1;32m     25\u001B[0m     \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mAPI Response:\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m     26\u001B[0m     \u001B[38;5;28mprint\u001B[39m(response)\n",
      "\u001B[0;31mTypeError\u001B[0m: ApiClient.call_api() got an unexpected keyword argument 'path_params'"
     ]
    }
   ],
   "execution_count": 43
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-28T14:36:56.694422Z",
     "start_time": "2025-04-28T14:36:56.656426Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Get a list of pucks that are \"at the beamline\"\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    # Create an instance of the API class\n",
    "    api_instance = aareDBclient.PucksApi(api_client)\n",
    "    get_pucks_at_beamline = aareDBclient.PucksApi(api_client)\n",
    "\n",
    "    try:\n",
    "        # Create Return Address\n",
    "        api_response = api_instance.get_pucks_by_slot_pucks_slot_slot_identifier_get(slot_identifier='X06DA')\n",
    "        print(\"The response of PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get:\\n\")\n",
    "        pprint(api_response)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(\"Exception when calling PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get: %s\\n\" % e)"
   ],
   "id": "9cf3457093751b61",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/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 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"GET /pucks/slot/X06DA HTTP/1.1\" 200 693\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The response of PucksApi->get_pucks_by_slot_pucks_slot_slot_identifier_get:\n",
      "\n",
      "[PuckWithTellPosition(id=27, puck_name='PKK004', puck_type='Unipuck', puck_location_in_dewar=4, dewar_id=5, dewar_name='Dewar Five', pgroup='p20003', samples=None, tell_position=None),\n",
      " PuckWithTellPosition(id=28, puck_name='PKK005', puck_type='Unipuck', puck_location_in_dewar=5, dewar_id=5, dewar_name='Dewar Five', pgroup='p20003', samples=None, tell_position=None),\n",
      " PuckWithTellPosition(id=29, puck_name='PKK006', puck_type='Unipuck', puck_location_in_dewar=6, dewar_id=5, dewar_name='Dewar Five', pgroup='p20003', samples=None, tell_position=None),\n",
      " PuckWithTellPosition(id=30, puck_name='PKK007', puck_type='Unipuck', puck_location_in_dewar=7, dewar_id=5, dewar_name='Dewar Five', pgroup='p20003', samples=None, tell_position=None)]\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-28T14:37:09.989924Z",
     "start_time": "2025-04-28T14:37:09.960196Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from aareDBclient import SetTellPosition, SetTellPositionRequest\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    # Create an instance of the API class\n",
    "    api_instance = aareDBclient.PucksApi(api_client)\n",
    "\n",
    "    # Payload with SetTellPosition objects\n",
    "    payload = SetTellPositionRequest(\n",
    "        tell=\"X06DA\",\n",
    "        #pucks=[\n",
    "        #    SetTellPosition(puck_name='PSIMX074', segment='B', puck_in_segment=1),\n",
    "        #    SetTellPosition(puck_name='PSIMX080', segment='B', puck_in_segment=2),\n",
    "        #    SetTellPosition(puck_name='PSIMX081', segment='C', puck_in_segment=3),\n",
    "        #    SetTellPosition(puck_name='PSIMX084', segment='C', puck_in_segment=4),\n",
    "        #    SetTellPosition(puck_name='PSIMX104', segment='E', puck_in_segment=5),\n",
    "        #    SetTellPosition(puck_name='PSIMX107', segment='E', puck_in_segment=1),\n",
    "        #    SetTellPosition(puck_name='PSIMX117', segment='F', puck_in_segment=2),\n",
    "        #]\n",
    "        #pucks=[\n",
    "        #    SetTellPosition(puck_name='PSIMX074', segment='F', puck_in_segment=1),\n",
    "        #    SetTellPosition(puck_name='PSIMX080', segment='F', puck_in_segment=2),\n",
    "        #    SetTellPosition(puck_name='PSIMX107', segment='A', puck_in_segment=1),\n",
    "        #    SetTellPosition(puck_name='PSIMX117', segment='A', puck_in_segment=2),\n",
    "        #]\n",
    "        pucks=[\n",
    "            SetTellPosition(puck_name='PKK006', segment='F', puck_in_segment=1),\n",
    "            SetTellPosition(puck_name='PKK005', segment='F', puck_in_segment=2),\n",
    "            SetTellPosition(puck_name='PKK007', segment='A', puck_in_segment=1),\n",
    "            SetTellPosition(puck_name='PKK004', segment='A', puck_in_segment=2),\n",
    "        ]\n",
    "        #pucks = []\n",
    "    )\n",
    "\n",
    "    # Call the PUT method to update the tell_position\n",
    "    try:\n",
    "        api_response = api_instance.set_tell_positions_pucks_set_tell_positions_put(\n",
    "            set_tell_position_request=payload\n",
    "        )  # Pass the entire payload as a single parameter\n",
    "\n",
    "        print(\"The response of PucksApi->pucks_puck_id_tell_position_put:\\n\")\n",
    "        pprint(api_response)\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Exception when calling PucksApi: {e}\")\n"
   ],
   "id": "37e3eac6760150ee",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/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 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"PUT /pucks/set-tell-positions HTTP/1.1\" 200 601\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The response of PucksApi->pucks_puck_id_tell_position_put:\n",
      "\n",
      "[{'message': 'Tell position updated successfully.',\n",
      "  'new_position': 'F1',\n",
      "  'previous_position': None,\n",
      "  'puck_name': 'PKK006',\n",
      "  'status': 'updated',\n",
      "  'tell': 'X06DA'},\n",
      " {'message': 'Tell position updated successfully.',\n",
      "  'new_position': 'F2',\n",
      "  'previous_position': None,\n",
      "  'puck_name': 'PKK005',\n",
      "  'status': 'updated',\n",
      "  'tell': 'X06DA'},\n",
      " {'message': 'Tell position updated successfully.',\n",
      "  'new_position': 'A1',\n",
      "  'previous_position': None,\n",
      "  'puck_name': 'PKK007',\n",
      "  'status': 'updated',\n",
      "  'tell': 'X06DA'},\n",
      " {'message': 'Tell position updated successfully.',\n",
      "  'new_position': 'A2',\n",
      "  'previous_position': None,\n",
      "  'puck_name': 'PKK004',\n",
      "  'status': 'updated',\n",
      "  'tell': 'X06DA'}]\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-28T14:37:23.148869Z",
     "start_time": "2025-04-28T14:37:23.115094Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Get puck_id puck_name sample_id sample_name of pucks in the tell\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    # Create an instance of the API class\n",
    "    api_instance = aareDBclient.PucksApi(api_client)\n",
    "\n",
    "    # GET request: Fetch all pucks in the tell\n",
    "    try:\n",
    "        # Call the API method to fetch pucks\n",
    "        all_pucks_response = api_instance.get_pucks_with_tell_position_pucks_with_tell_position_get(tell='X06DA')\n",
    "\n",
    "        # Debug response structure by printing it in JSON format\n",
    "        formatted_response = json.dumps(\n",
    "            [p.to_dict() for p in all_pucks_response],  # Assuming the API response can be converted to dicts\n",
    "            indent=4  # Use indentation for readability\n",
    "        )\n",
    "        #print(\"The response of PucksApi->get_all_pucks_in_tell (formatted):\\n\")\n",
    "        #print(formatted_response)\n",
    "\n",
    "        # Iterate through each puck and print information\n",
    "        for p in all_pucks_response:\n",
    "            print(f\"Puck ID: {p.id}, Puck Name: {p.puck_name}\")\n",
    "\n",
    "            ## Check if the puck has any samples\n",
    "            if hasattr(p, 'samples') and p.samples:  # Ensure 'samples' attribute exists and is not empty\n",
    "                for sample in p.samples:\n",
    "                    print(f\"  Sample ID: {sample.id}, Sample Name: {sample.sample_name}, Position: {sample.position}, Mount count: {sample.mount_count}\")\n",
    "            else:\n",
    "                print(\"  No samples found in this puck.\")\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(\"Exception when calling PucksApi->get_all_pucks_in_tell: %s\\n\" % e)"
   ],
   "id": "51578d944878db6a",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/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 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"GET /pucks/with-tell-position?tell=X06DA HTTP/1.1\" 200 7592\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Puck ID: 29, Puck Name: PKK006\n",
      "  Sample ID: 268, Sample Name: Sample268, Position: 13, Mount count: 0\n",
      "  Sample ID: 265, Sample Name: Sample265, Position: 3, Mount count: 0\n",
      "  Sample ID: 266, Sample Name: Sample266, Position: 4, Mount count: 0\n",
      "  Sample ID: 269, Sample Name: Sample269, Position: 16, Mount count: 0\n",
      "  Sample ID: 267, Sample Name: Sample267, Position: 6, Mount count: 0\n",
      "Puck ID: 30, Puck Name: PKK007\n",
      "  Sample ID: 276, Sample Name: Sample276, Position: 15, Mount count: 0\n",
      "  Sample ID: 270, Sample Name: Sample270, Position: 1, Mount count: 0\n",
      "  Sample ID: 274, Sample Name: Sample274, Position: 6, Mount count: 0\n",
      "  Sample ID: 277, Sample Name: Sample277, Position: 16, Mount count: 0\n",
      "  Sample ID: 273, Sample Name: Sample273, Position: 5, Mount count: 0\n",
      "  Sample ID: 271, Sample Name: Sample271, Position: 2, Mount count: 0\n",
      "  Sample ID: 275, Sample Name: Sample275, Position: 7, Mount count: 0\n",
      "  Sample ID: 272, Sample Name: Sample272, Position: 4, Mount count: 0\n",
      "Puck ID: 28, Puck Name: PKK005\n",
      "  Sample ID: 264, Sample Name: Sample264, Position: 11, Mount count: 0\n",
      "  Sample ID: 261, Sample Name: Sample261, Position: 6, Mount count: 0\n",
      "  Sample ID: 262, Sample Name: Sample262, Position: 7, Mount count: 0\n",
      "  Sample ID: 260, Sample Name: Sample260, Position: 5, Mount count: 0\n",
      "  Sample ID: 263, Sample Name: Sample263, Position: 9, Mount count: 0\n",
      "Puck ID: 27, Puck Name: PKK004\n",
      "  Sample ID: 251, Sample Name: Sample251, Position: 3, Mount count: 0\n",
      "  Sample ID: 253, Sample Name: Sample253, Position: 7, Mount count: 0\n",
      "  Sample ID: 252, Sample Name: Sample252, Position: 4, Mount count: 0\n",
      "  Sample ID: 255, Sample Name: Sample255, Position: 9, Mount count: 0\n",
      "  Sample ID: 250, Sample Name: Sample250, Position: 2, Mount count: 0\n",
      "  Sample ID: 254, Sample Name: Sample254, Position: 8, Mount count: 0\n",
      "  Sample ID: 258, Sample Name: Sample258, Position: 14, Mount count: 0\n",
      "  Sample ID: 256, Sample Name: Sample256, Position: 12, Mount count: 0\n",
      "  Sample ID: 249, Sample Name: Sample249, Position: 1, Mount count: 0\n",
      "  Sample ID: 257, Sample Name: Sample257, Position: 13, Mount count: 0\n",
      "  Sample ID: 259, Sample Name: Sample259, Position: 16, Mount count: 0\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:31:12.902282Z",
     "start_time": "2025-05-05T13:31:12.900432Z"
    }
   },
   "cell_type": "code",
   "source": "sample_id = 277",
   "id": "54d4d46ca558e7b9",
   "outputs": [],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:31:16.752616Z",
     "start_time": "2025-05-05T13:31:16.720296Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from aareDBclient import SampleEventCreate\n",
    "\n",
    "# Create an event for a sample\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    # Instance of the API client\n",
    "    api_instance = aareDBclient.SamplesApi(api_client)\n",
    "    #sample_id=293\n",
    "    try:\n",
    "        # Define the payload with only `event_type`\n",
    "        sample_event_create = SampleEventCreate(\n",
    "            sample_id=sample_id,\n",
    "            #event_type=\"Centering\"  # Valid event type\n",
    "            event_type=\"Collecting\"  # Valid event type\n",
    "        )\n",
    "\n",
    "        # Debug the payload before sending\n",
    "        print(\"Payload being sent to API:\")\n",
    "        print(sample_event_create.json())  # Ensure it matches `SampleEventCreate`\n",
    "\n",
    "        # Call the API\n",
    "        api_response = api_instance.create_sample_event_samples_samples_sample_id_events_post(\n",
    "            sample_id=sample_id,  # Ensure this matches a valid sample ID in the database\n",
    "            sample_event_create=sample_event_create\n",
    "        )\n",
    "\n",
    "        print(\"API response:\")\n",
    "        #pprint(api_response)\n",
    "\n",
    "        for p in api_response:\n",
    "            print(p)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(\"Exception when calling post_sample_event:\")\n",
    "        print(f\"Status Code: {e.status}\")\n",
    "        if e.body:\n",
    "            print(f\"Error Details: {e.body}\")\n"
   ],
   "id": "4a0665f92756b486",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"POST /samples/samples/277/events HTTP/1.1\" 200 413\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Payload being sent to API:\n",
      "{\"event_type\":\"Collecting\"}\n",
      "API response:\n",
      "('id', 277)\n",
      "('sample_name', 'Sample277')\n",
      "('position', 15)\n",
      "('puck_id', 30)\n",
      "('crystalname', None)\n",
      "('proteinname', None)\n",
      "('positioninpuck', None)\n",
      "('priority', None)\n",
      "('comments', None)\n",
      "('data_collection_parameters', None)\n",
      "('events', [SampleEventResponse(event_type='Mounting', id=533, sample_id=277, timestamp=datetime.datetime(2025, 5, 4, 14, 9)), SampleEventResponse(event_type='Collecting', id=534, sample_id=277, timestamp=datetime.datetime(2025, 5, 5, 13, 31, 16, 741949))])\n",
      "('mount_count', 0)\n",
      "('unmount_count', 0)\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-04-29T14:27:46.730515Z",
     "start_time": "2025-04-29T14:27:46.622922Z"
    }
   },
   "cell_type": "code",
   "source": [
    "### not working\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    # Create an instance of the Samples API class\n",
    "    api_instance = aareDBclient.SamplesApi(api_client)\n",
    "\n",
    "    try:\n",
    "        # Get the last sample event\n",
    "        last_event_response = api_instance.get_last_sample_event_samples_samples_sample_id_events_last_get(27)\n",
    "        print(\"The response of get_last_sample_event:\\n\")\n",
    "        pprint(last_event_response)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(\"Exception when calling get_last_sample_event: %s\\n\" % e)\n"
   ],
   "id": "f1d171700d6cf7fe",
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'SamplesApi' object has no attribute 'get_last_sample_event_samples_samples_sample_id_events_last_get'",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[48], line 8\u001B[0m\n\u001B[1;32m      4\u001B[0m api_instance \u001B[38;5;241m=\u001B[39m aareDBclient\u001B[38;5;241m.\u001B[39mSamplesApi(api_client)\n\u001B[1;32m      6\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m      7\u001B[0m     \u001B[38;5;66;03m# Get the last sample event\u001B[39;00m\n\u001B[0;32m----> 8\u001B[0m     last_event_response \u001B[38;5;241m=\u001B[39m \u001B[43mapi_instance\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mget_last_sample_event_samples_samples_sample_id_events_last_get\u001B[49m(\u001B[38;5;241m27\u001B[39m)\n\u001B[1;32m      9\u001B[0m     \u001B[38;5;28mprint\u001B[39m(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mThe response of get_last_sample_event:\u001B[39m\u001B[38;5;130;01m\\n\u001B[39;00m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m     10\u001B[0m     pprint(last_event_response)\n",
      "\u001B[0;31mAttributeError\u001B[0m: 'SamplesApi' object has no attribute 'get_last_sample_event_samples_samples_sample_id_events_last_get'"
     ]
    }
   ],
   "execution_count": 48
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:31:21.833174Z",
     "start_time": "2025-05-05T13:31:21.791711Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# Post multiple images to the sample database\n",
    "\n",
    "import os\n",
    "import mimetypes\n",
    "import requests\n",
    "\n",
    "# List of file paths to the images you want to upload\n",
    "#file_paths = [\n",
    "#    \"backend/tests/sample_image/0_200.jpg\",\n",
    "#    \"backend/tests/sample_image/90_200.jpg\",\n",
    "#    \"backend/tests/sample_image/0_700.jpg\",\n",
    "#    \"backend/tests/sample_image/90_700.jpg\",\n",
    "#]\n",
    "\n",
    "#file_paths = [\"backend/tests/sample_image/mount.jpeg.jpg\"]\n",
    "\n",
    "#file_paths = [\n",
    "#    \"backend/tests/sample_image/bb_raster_90.jpg\"\n",
    "#]\n",
    "\n",
    "file_paths = [\"backend/tests/sample_image/after_dc.jpeg.jpg\"]\n",
    "\n",
    "\n",
    "\n",
    "# Base URL for the upload endpoint\n",
    "url = f\"https://127.0.0.1:8000/samples/{sample_id}/upload-images\"\n",
    "\n",
    "# Iterate through each file and upload it\n",
    "for file_path in file_paths:\n",
    "    # Determine file name and MIME type\n",
    "    filename = os.path.basename(file_path)\n",
    "    mime_type, _ = mimetypes.guess_type(file_path)\n",
    "    if mime_type is None:\n",
    "        mime_type = \"application/octet-stream\"\n",
    "\n",
    "    # Open the file for uploading\n",
    "    with open(file_path, \"rb\") as file_data:\n",
    "        files = {\n",
    "            # Use key \"uploaded_file\" as required by your API\n",
    "            \"uploaded_file\": (filename, file_data, mime_type)\n",
    "        }\n",
    "        headers = {\n",
    "            \"accept\": \"application/json\"\n",
    "        }\n",
    "\n",
    "        # Send the POST request\n",
    "        print(f\"Uploading {filename}...\")\n",
    "        response = requests.post(url, headers=headers, files=files, verify=False)\n",
    "\n",
    "        # Check the API response\n",
    "        print(f\"API Response for {filename}:\")\n",
    "        print(response.status_code)\n",
    "        try:\n",
    "            print(response.json())\n",
    "        except Exception:\n",
    "            print(response.text)\n"
   ],
   "id": "11f62976d2e7d9b1",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): 127.0.0.1:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: 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\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://127.0.0.1:8000 \"POST /samples/277/upload-images HTTP/1.1\" 200 205\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Uploading after_dc.jpeg.jpg...\n",
      "API Response for after_dc.jpeg.jpg:\n",
      "200\n",
      "{'pgroup': 'p20003', 'sample_id': 277, 'sample_event_id': 534, 'filepath': 'images/p20003/2025-05-05/Dewar Five/PKK007/15/Collecting_2025-05-05_13-31-16/after_dc.jpeg.jpg', 'status': 'active', 'comment': None, 'id': 1}\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "help(api_instance.upload_sample_images_samples_samples_sample_id_upload_images_post)",
   "id": "cb1b99e6327fff84"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:34:32.164108Z",
     "start_time": "2025-05-05T13:34:32.130230Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# post experiment results to sample database\n",
    "\n",
    "from aareDBclient.models import (\n",
    "    ExperimentParametersCreate,\n",
    "    RotationParameters,\n",
    "    BeamlineParameters,\n",
    "    GridScanParamers,\n",
    "    Detector\n",
    ")\n",
    "\n",
    "\n",
    "# Build the nested parameters\n",
    "rotation = RotationParameters(\n",
    "    omegaStart_deg=0.0,\n",
    "    omegaStep=0.2,\n",
    "    phi=10.0,\n",
    "    chi=0.0,\n",
    "    numberOfImages=1800,\n",
    "    exposureTime_s=0.01\n",
    ")\n",
    "\n",
    "#characterization = characterizationParameters(\n",
    "#    omegaStart_deg=0.0,\n",
    "#    omegaStep=90.0,\n",
    "#    oscillation_deg=1.0,\n",
    "#    phi=10.0,\n",
    "#    chi=0.0,\n",
    "#    numberOfImages=4,\n",
    "#    exposureTime_s=0.02\n",
    "#)\n",
    "\n",
    "#gridscan = GridScanParamers(\n",
    "#    xStart=90.0,\n",
    "#    xStep=0.1,\n",
    "#    yStart=0.0,\n",
    "#    yStep= 0.1,\n",
    "#    zStart=0.0,\n",
    "#    zStep=0.0,\n",
    "#    numberOfImages=4600,\n",
    "#    exposureTime_s=0.001\n",
    "#)\n",
    "\n",
    "# If your client code requires you to build a detector model,\n",
    "# you can either use a Detector model or pass a dictionary.\n",
    "# Here we pass a dictionary.\n",
    "detector_data = Detector(\n",
    "    manufacturer=\"DECTRIS\",\n",
    "    model=\"PILATUS4 2M\",\n",
    "    type=\"photon-counting\",\n",
    "    serialNumber=\"16684dscsd668468\",\n",
    "    detectorDistance_mm=232.0,\n",
    "    beamCenterX_px=768.0,\n",
    "    beamCenterY_px=857.0,\n",
    "    pixelSizeX_um=150.0,\n",
    "    pixelSizeY_um=150.0,\n",
    ")\n",
    "\n",
    "beamline_params = BeamlineParameters(\n",
    "    synchrotron=\"Swiss Light Source\",\n",
    "    beamline=\"PXIII\",\n",
    "    detector=detector_data,\n",
    "    wavelength=1.033,\n",
    "    ringCurrent_A=0.4,\n",
    "    ringMode=\"Machine Development\",\n",
    "    monochromator=\"Si111\",\n",
    "    transmission=10.00,\n",
    "    focusingOptic=\"Kirkpatrick-Baez\",\n",
    "    beamlineFluxAtSample_ph_s=0,\n",
    "    beamSizeWidth=30.0,\n",
    "    beamSizeHeight=30.0,\n",
    "    #characterization=characterization\n",
    "    rotation=rotation  # Optional nested parameter\n",
    "    #gridScan=gridscan\n",
    "    # gridScan and jet are optional and can be added similarly\n",
    ")\n",
    "\n",
    "# Prepare the experiment parameters payload.\n",
    "# Note that the run_number will be set on the server side, so you can leave\n",
    "# it out or set it to a dummy value if your client model requires it.\n",
    "experiment_params_payload = ExperimentParametersCreate(\n",
    "    # run_number can be omitted/ignored if computed on the server\n",
    "    type=\"standard\",\n",
    "    beamline_parameters=beamline_params,\n",
    "    sample_id=sample_id  # change sample_id to an existing sample in your database\n",
    ")\n",
    "\n",
    "# Now, use the API instance to send the POST request\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    api_instance = aareDBclient.SamplesApi(api_client)\n",
    "\n",
    "    try:\n",
    "        # Call the endpoint. The endpoint path expects the sample_id.\n",
    "        api_response = api_instance.create_experiment_parameters_for_sample(\n",
    "    sample_id=experiment_params_payload.sample_id,\n",
    "    experiment_parameters_create=experiment_params_payload\n",
    ")\n",
    "\n",
    "        print(\"API Response:\")\n",
    "        print(api_response)\n",
    "    except ApiException as e:\n",
    "        print(\"Exception when calling ExperimentParametersApi->create_experiment_parameters_for_sample:\")\n",
    "        print(e)\n"
   ],
   "id": "421ba0710f29a5fa",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"POST /samples/samples/277/experiment_parameters HTTP/1.1\" 200 904\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "API Response:\n",
      "run_number=2 type='standard' 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=232.0, beam_center_x_px=768.0, beam_center_y_px=857.0, pixel_size_x_um=150.0, pixel_size_y_um=150.0), wavelength=1.033, ring_current_a=0.4, ring_mode='Machine Development', undulator=None, undulatorgap_mm=None, monochromator='Si111', transmission=10.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.2, chi=0.0, phi=10.0, number_of_images=1800, exposure_time_s=0.01), grid_scan=None, jet=None, cryojet_temperature_k=None, humidifier_temperature_k=None, humidifier_humidity=None) dataset=None sample_id=277 id=2\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:34:49.891432Z",
     "start_time": "2025-05-05T13:34:49.872697Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from datetime import datetime\n",
    "\n",
    "sample_id = sample_id\n",
    "run_id = 2\n",
    "\n",
    "def test_mark_run_written(sample_id, run_id, configuration):\n",
    "    # Prepare your dataset dict as required by your API (.dict() results if using Pydantic model)\n",
    "    dataset_payload = {\n",
    "        \"filepath\": \"/das/work/p11/p11206/raw_data/vincent/20250415_6D_SLS2_1st_data/20250415_fullbeam_dtz220_Lyso102_again_360deg\",\n",
    "        \"status\": \"written\",\n",
    "        \"written_at\": datetime.now().isoformat()\n",
    "    }\n",
    "\n",
    "    # The API method and argument names may differ if autogenerated — adjust accordingly\n",
    "    with aareDBclient.ApiClient(configuration) as api_client:\n",
    "        api_instance = aareDBclient.SamplesApi(api_client)\n",
    "        try:\n",
    "            api_response = api_instance.update_dataset_for_experiment_run(\n",
    "                sample_id=sample_id, run_id=run_id, datasets=dataset_payload\n",
    "            )\n",
    "            print(\"Dataset updated successfully:\")\n",
    "            print(api_response)\n",
    "        except ApiException as e:\n",
    "            print(f\"API call failed: {e}\")\n",
    "\n",
    "# Usage example (replace with your actual IDs and configuration):\n",
    "test_mark_run_written(sample_id, run_id, configuration)"
   ],
   "id": "77793ecd843c1ef3",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"PATCH /samples/update-dataset/277/2 HTTP/1.1\" 200 1085\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Dataset updated successfully:\n",
      "run_number=2 type='standard' 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=232.0, beam_center_x_px=768.0, beam_center_y_px=857.0, pixel_size_x_um=150.0, pixel_size_y_um=150.0), wavelength=1.033, ring_current_a=0.4, ring_mode='Machine Development', undulator=None, undulatorgap_mm=None, monochromator='Si111', transmission=10.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.2, chi=0.0, phi=10.0, number_of_images=1800, exposure_time_s=0.01), grid_scan=None, jet=None, cryojet_temperature_k=None, humidifier_temperature_k=None, humidifier_humidity=None) dataset=Datasets(filepath='/das/work/p11/p11206/raw_data/vincent/20250415_6D_SLS2_1st_data/20250415_fullbeam_dtz220_Lyso102_again_360deg', status='written', written_at=datetime.datetime(2025, 5, 5, 15, 34, 49, 874526)) sample_id=277 id=2\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T14:38:32.418132Z",
     "start_time": "2025-05-05T14:38:32.370685Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from app.schemas import CurvePoint\n",
    "# %%\n",
    "from app.schemas import ResultCreate, Results\n",
    "from pprint import pprint\n",
    "import random\n",
    "import math\n",
    "import aareDBclient\n",
    "from aareDBclient.rest import ApiException\n",
    "\n",
    "# Your actual sample and experiment IDs\n",
    "sample_id = sample_id  # Replace with valid IDs\n",
    "status = \"successful\"\n",
    "run_id = 2  # Replace with valid run_id\n",
    "\n",
    "# Function to generate list of CurvePoint (resolution, value pairs)\n",
    "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):\n",
    "    resolutions = sorted([round(random.uniform(min_res, max_res), decimals) for _ in range(length)], reverse=True)  # Reverse order\n",
    "\n",
    "    curve = []\n",
    "    for res in resolutions:\n",
    "        # Exponential-like decay: Higher resolution (small number) -> value ~1, Lower resolution (big number) -> value ~0\n",
    "        decay_factor = (res - max_res) / (min_res - max_res)  # Normalize res to [0,1]\n",
    "        value = max_value - ( math.exp(- 20 * decay_factor ) ) # Exponential decay\n",
    "\n",
    "        # Add small random noise for realism\n",
    "        noise_value = random.uniform(-noise, noise)\n",
    "        value = min(max(value + noise_value, min_value), max_value)  # Clamp between min_value and max_value\n",
    "\n",
    "        curve.append(CurvePoint(resolution=res, value=round(value, decimals)))\n",
    "\n",
    "    return curve\n",
    "\n",
    "# Create random Results payload\n",
    "results_data = Results(\n",
    "    pipeline=\"autoproc\",\n",
    "    status=status,\n",
    "    resolution=round(random.uniform(1.0, 4.0), 2),\n",
    "    unit_cell=f\"{random.uniform(20, 120):.2f}, {random.uniform(20, 120):.2f}, \"\n",
    "              f\"{random.uniform(20, 120):.2f}, {random.uniform(60, 120):.2f}, \"\n",
    "              f\"{random.uniform(60, 120):.2f}, {random.uniform(60, 120):.2f}\",\n",
    "    spacegroup=random.choice(['P212121', 'C2', 'P1', 'P21', 'P21212', 'P41212']),\n",
    "    rmerge=round(random.uniform(0.02, 0.10), 3),\n",
    "    rmeas=round(random.uniform(0.02, 0.15), 3),\n",
    "    isig=round(random.uniform(1.0, 30.0), 2),\n",
    "    cc=logarithmic_decay_curve(100),  # List of CurvePoint for CC curve\n",
    "    cchalf=logarithmic_decay_curve(100),  # List of CurvePoint for CC(1/2) curve\n",
    "    completeness=round(random.uniform(85.0, 100.0), 2),\n",
    "    multiplicity=round(random.uniform(1.0, 10.0), 2),\n",
    "    nobs=random.randint(10000, 500000),\n",
    "    total_refl=random.randint(5000, 250000),\n",
    "    unique_refl=random.randint(5000, 100000),\n",
    "    comments=\"Random auto-generated test entry\"\n",
    ")\n",
    "\n",
    "payload = ResultCreate(sample_id=sample_id, run_id=run_id, result=results_data, status=status)\n",
    "\n",
    "# correct serialization, passing exact required dict structure\n",
    "payload_dict = {\n",
    "    \"sample_id\": sample_id,\n",
    "    \"run_id\": run_id,\n",
    "    \"status\": status,\n",
    "    \"result\": results_data.model_dump(),\n",
    "}\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    api_instance = aareDBclient.SamplesApi(api_client)\n",
    "\n",
    "    try:\n",
    "        api_response = api_instance.create_result(\n",
    "            result_create=payload_dict\n",
    "        )\n",
    "\n",
    "        print(\"API call successful:\")\n",
    "        pprint(api_response)\n",
    "\n",
    "    except ApiException as e:\n",
    "        print(f\"API call failed: {e}\")\n"
   ],
   "id": "3e3974d5df795c32",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"POST /samples/processing-results HTTP/1.1\" 200 7213\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "API call successful:\n",
      "ResultResponse(id=5, status='successful', sample_id=277, run_id=2, result=Results(pipeline='autoproc', resolution=1.4, unit_cell='108.05, 108.47, 84.95, 78.67, 102.50, 78.68', spacegroup='P1', rmerge=0.033, rmeas=0.049, isig=3.77, cc=[CurvePoint(resolution=3.982, value=0.995), CurvePoint(resolution=3.944, value=0.998), CurvePoint(resolution=3.937, value=0.996), CurvePoint(resolution=3.87, value=0.999), CurvePoint(resolution=3.85, value=1.0), CurvePoint(resolution=3.841, value=1.0), CurvePoint(resolution=3.827, value=1.0), CurvePoint(resolution=3.775, value=1.0), CurvePoint(resolution=3.719, value=0.996), CurvePoint(resolution=3.718, value=0.998), CurvePoint(resolution=3.711, value=1.0), CurvePoint(resolution=3.688, value=0.998), CurvePoint(resolution=3.684, value=0.997), CurvePoint(resolution=3.679, value=0.998), CurvePoint(resolution=3.53, value=1.0), CurvePoint(resolution=3.518, value=0.999), CurvePoint(resolution=3.493, value=0.997), CurvePoint(resolution=3.456, value=1.0), CurvePoint(resolution=3.443, value=0.998), CurvePoint(resolution=3.416, value=1.0), CurvePoint(resolution=3.368, value=1.0), CurvePoint(resolution=3.334, value=1.0), CurvePoint(resolution=3.32, value=1.0), CurvePoint(resolution=3.287, value=1.0), CurvePoint(resolution=3.278, value=0.995), CurvePoint(resolution=3.26, value=0.999), CurvePoint(resolution=3.247, value=1.0), CurvePoint(resolution=3.225, value=0.995), CurvePoint(resolution=3.173, value=0.996), CurvePoint(resolution=3.17, value=0.998), CurvePoint(resolution=3.155, value=1.0), CurvePoint(resolution=3.019, value=1.0), CurvePoint(resolution=3.007, value=0.997), CurvePoint(resolution=3.005, value=1.0), CurvePoint(resolution=2.962, value=0.999), CurvePoint(resolution=2.954, value=1.0), CurvePoint(resolution=2.939, value=1.0), CurvePoint(resolution=2.935, value=1.0), CurvePoint(resolution=2.935, value=1.0), CurvePoint(resolution=2.93, value=1.0), CurvePoint(resolution=2.903, value=1.0), CurvePoint(resolution=2.889, value=0.997), CurvePoint(resolution=2.851, value=1.0), CurvePoint(resolution=2.721, value=1.0), CurvePoint(resolution=2.705, value=0.999), CurvePoint(resolution=2.671, value=0.997), CurvePoint(resolution=2.639, value=0.996), CurvePoint(resolution=2.536, value=1.0), CurvePoint(resolution=2.529, value=1.0), CurvePoint(resolution=2.509, value=1.0), CurvePoint(resolution=2.501, value=0.997), CurvePoint(resolution=2.485, value=0.998), CurvePoint(resolution=2.458, value=1.0), CurvePoint(resolution=2.454, value=1.0), CurvePoint(resolution=2.452, value=1.0), CurvePoint(resolution=2.438, value=0.998), CurvePoint(resolution=2.435, value=1.0), CurvePoint(resolution=2.402, value=1.0), CurvePoint(resolution=2.354, value=0.999), CurvePoint(resolution=2.345, value=1.0), CurvePoint(resolution=2.334, value=0.997), CurvePoint(resolution=2.331, value=1.0), CurvePoint(resolution=2.255, value=0.999), CurvePoint(resolution=2.229, value=1.0), CurvePoint(resolution=2.186, value=1.0), CurvePoint(resolution=2.128, value=1.0), CurvePoint(resolution=2.08, value=1.0), CurvePoint(resolution=2.004, value=0.999), CurvePoint(resolution=1.991, value=0.997), CurvePoint(resolution=1.981, value=0.997), CurvePoint(resolution=1.966, value=1.0), CurvePoint(resolution=1.951, value=0.996), CurvePoint(resolution=1.926, value=0.997), CurvePoint(resolution=1.915, value=0.996), CurvePoint(resolution=1.904, value=0.995), CurvePoint(resolution=1.889, value=0.994), CurvePoint(resolution=1.872, value=1.0), CurvePoint(resolution=1.825, value=0.995), CurvePoint(resolution=1.818, value=0.999), CurvePoint(resolution=1.811, value=0.991), CurvePoint(resolution=1.791, value=0.994), CurvePoint(resolution=1.722, value=0.992), CurvePoint(resolution=1.702, value=0.991), CurvePoint(resolution=1.696, value=0.993), CurvePoint(resolution=1.665, value=0.985), CurvePoint(resolution=1.648, value=0.987), CurvePoint(resolution=1.519, value=0.969), CurvePoint(resolution=1.467, value=0.954), CurvePoint(resolution=1.394, value=0.931), CurvePoint(resolution=1.365, value=0.914), CurvePoint(resolution=1.351, value=0.905), CurvePoint(resolution=1.338, value=0.895), CurvePoint(resolution=1.278, value=0.847), CurvePoint(resolution=1.233, value=0.79), CurvePoint(resolution=1.191, value=0.723), CurvePoint(resolution=1.187, value=0.715), CurvePoint(resolution=1.114, value=0.534), CurvePoint(resolution=1.107, value=0.514), CurvePoint(resolution=1.084, value=0.434), CurvePoint(resolution=1.038, value=0.229)], cchalf=[CurvePoint(resolution=3.994, value=0.999), CurvePoint(resolution=3.994, value=0.996), CurvePoint(resolution=3.986, value=1.0), CurvePoint(resolution=3.929, value=1.0), CurvePoint(resolution=3.926, value=1.0), CurvePoint(resolution=3.892, value=0.996), CurvePoint(resolution=3.797, value=1.0), CurvePoint(resolution=3.784, value=0.999), CurvePoint(resolution=3.7, value=0.998), CurvePoint(resolution=3.694, value=1.0), CurvePoint(resolution=3.66, value=0.998), CurvePoint(resolution=3.645, value=0.999), CurvePoint(resolution=3.601, value=1.0), CurvePoint(resolution=3.581, value=0.996), CurvePoint(resolution=3.555, value=1.0), CurvePoint(resolution=3.421, value=1.0), CurvePoint(resolution=3.421, value=1.0), CurvePoint(resolution=3.365, value=1.0), CurvePoint(resolution=3.339, value=0.999), CurvePoint(resolution=3.271, value=0.999), CurvePoint(resolution=3.261, value=1.0), CurvePoint(resolution=3.252, value=0.996), CurvePoint(resolution=3.22, value=0.995), CurvePoint(resolution=3.205, value=0.996), CurvePoint(resolution=3.179, value=0.999), CurvePoint(resolution=3.116, value=0.996), CurvePoint(resolution=3.073, value=0.998), CurvePoint(resolution=3.012, value=0.999), CurvePoint(resolution=2.999, value=0.999), CurvePoint(resolution=2.985, value=1.0), CurvePoint(resolution=2.98, value=1.0), CurvePoint(resolution=2.976, value=1.0), CurvePoint(resolution=2.927, value=0.996), CurvePoint(resolution=2.911, value=0.996), CurvePoint(resolution=2.855, value=1.0), CurvePoint(resolution=2.831, value=1.0), CurvePoint(resolution=2.827, value=1.0), CurvePoint(resolution=2.785, value=0.996), CurvePoint(resolution=2.778, value=0.999), CurvePoint(resolution=2.753, value=0.998), CurvePoint(resolution=2.716, value=1.0), CurvePoint(resolution=2.691, value=1.0), CurvePoint(resolution=2.677, value=0.995), CurvePoint(resolution=2.659, value=0.998), CurvePoint(resolution=2.646, value=1.0), CurvePoint(resolution=2.626, value=1.0), CurvePoint(resolution=2.532, value=0.996), CurvePoint(resolution=2.508, value=1.0), CurvePoint(resolution=2.507, value=0.999), CurvePoint(resolution=2.446, value=0.997), CurvePoint(resolution=2.439, value=0.997), CurvePoint(resolution=2.409, value=1.0), CurvePoint(resolution=2.404, value=0.995), CurvePoint(resolution=2.346, value=1.0), CurvePoint(resolution=2.332, value=1.0), CurvePoint(resolution=2.328, value=0.996), CurvePoint(resolution=2.309, value=0.996), CurvePoint(resolution=2.27, value=1.0), CurvePoint(resolution=2.193, value=0.997), CurvePoint(resolution=2.148, value=1.0), CurvePoint(resolution=2.143, value=1.0), CurvePoint(resolution=2.123, value=0.995), CurvePoint(resolution=2.109, value=1.0), CurvePoint(resolution=2.099, value=1.0), CurvePoint(resolution=2.051, value=1.0), CurvePoint(resolution=2.036, value=0.999), CurvePoint(resolution=2.035, value=0.995), CurvePoint(resolution=2.033, value=0.999), CurvePoint(resolution=1.996, value=1.0), CurvePoint(resolution=1.99, value=1.0), CurvePoint(resolution=1.988, value=1.0), CurvePoint(resolution=1.977, value=0.994), CurvePoint(resolution=1.934, value=0.997), CurvePoint(resolution=1.898, value=1.0), CurvePoint(resolution=1.856, value=0.994), CurvePoint(resolution=1.808, value=0.994), CurvePoint(resolution=1.755, value=0.993), CurvePoint(resolution=1.743, value=0.998), CurvePoint(resolution=1.735, value=0.991), CurvePoint(resolution=1.701, value=0.987), CurvePoint(resolution=1.687, value=0.992), CurvePoint(resolution=1.561, value=0.98), CurvePoint(resolution=1.538, value=0.975), CurvePoint(resolution=1.533, value=0.974), CurvePoint(resolution=1.456, value=0.956), CurvePoint(resolution=1.452, value=0.948), CurvePoint(resolution=1.419, value=0.938), CurvePoint(resolution=1.404, value=0.935), CurvePoint(resolution=1.371, value=0.919), CurvePoint(resolution=1.346, value=0.902), CurvePoint(resolution=1.315, value=0.876), CurvePoint(resolution=1.286, value=0.848), CurvePoint(resolution=1.266, value=0.833), CurvePoint(resolution=1.212, value=0.753), CurvePoint(resolution=1.21, value=0.75), CurvePoint(resolution=1.175, value=0.692), CurvePoint(resolution=1.172, value=0.678), CurvePoint(resolution=1.156, value=0.649), CurvePoint(resolution=1.147, value=0.625), CurvePoint(resolution=1.109, value=0.517)], completeness=97.29, multiplicity=5.3, nobs=189003, total_refl=140823, unique_refl=44561, comments='Random auto-generated test entry'))\n"
     ]
    }
   ],
   "execution_count": 27
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:24:47.091043Z",
     "start_time": "2025-05-05T13:24:47.082140Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# get experiment results to sample database\n",
    "\n",
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    # Create an instance of the API class\n",
    "    api_instance = aareDBclient.SamplesApi(api_client)\n",
    "\n",
    "    # GET request: Fetch all pucks in the tell\n",
    "    try:\n",
    "        # Call the API method to fetch pucks\n",
    "        all_results_response = api_instance.get_sample_results_samples_results_get(active_pgroup=\"p20003\")\n",
    "        pprint(all_results_response)\n",
    "        ## Debug response structure by printing it in JSON format\n",
    "        #formatted_response = json.dumps(\n",
    "        #    [p.to_dict() for p in all_results_response],  # Assuming the API response can be converted to dicts\n",
    "        #    indent=4  # Use indentation for readability\n",
    "        #)\n",
    "        #print(\"The response of PucksApi->get_all_pucks_in_tell (formatted):\\n\")\n",
    "        #print(formatted_response)\n",
    "\n",
    "        ## Iterate through each puck and print information\n",
    "        #for p in all_results_response:\n",
    "        #    print(f\"Puck ID: {p.id}, Puck Name: {p.puck_name}\")\n",
    "        #\n",
    "        #    ## Check if the puck has any samples\n",
    "        #    if hasattr(p, 'samples') and p.samples:  # Ensure 'samples' attribute exists and is not empty\n",
    "        #        for sample in p.samples:\n",
    "        #            print(f\"  Sample ID: {sample.id}, Sample Name: {sample.sample_name}, Position: {sample.position}, Mount count: {sample.mount_count}\")\n",
    "        #    else:\n",
    "        #        print(\"  No samples found in this puck.\")\n",
    "        #\n",
    "    except ApiException as e:\n",
    "        print(\"Exception when calling PucksApi->get_all_pucks_in_tell: %s\\n\" % e)"
   ],
   "id": "6079a4f10102e906",
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'SamplesApi' object has no attribute 'get_sample_results_samples_results_get'",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mAttributeError\u001B[0m                            Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[4], line 10\u001B[0m\n\u001B[1;32m      7\u001B[0m \u001B[38;5;66;03m# GET request: Fetch all pucks in the tell\u001B[39;00m\n\u001B[1;32m      8\u001B[0m \u001B[38;5;28;01mtry\u001B[39;00m:\n\u001B[1;32m      9\u001B[0m     \u001B[38;5;66;03m# Call the API method to fetch pucks\u001B[39;00m\n\u001B[0;32m---> 10\u001B[0m     all_results_response \u001B[38;5;241m=\u001B[39m \u001B[43mapi_instance\u001B[49m\u001B[38;5;241;43m.\u001B[39;49m\u001B[43mget_sample_results_samples_results_get\u001B[49m(active_pgroup\u001B[38;5;241m=\u001B[39m\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124mp20003\u001B[39m\u001B[38;5;124m\"\u001B[39m)\n\u001B[1;32m     11\u001B[0m     pprint(all_results_response)\n\u001B[1;32m     12\u001B[0m     \u001B[38;5;66;03m## Debug response structure by printing it in JSON format\u001B[39;00m\n\u001B[1;32m     13\u001B[0m     \u001B[38;5;66;03m#formatted_response = json.dumps(\u001B[39;00m\n\u001B[1;32m     14\u001B[0m     \u001B[38;5;66;03m#    [p.to_dict() for p in all_results_response],  # Assuming the API response can be converted to dicts\u001B[39;00m\n\u001B[0;32m   (...)\u001B[0m\n\u001B[1;32m     29\u001B[0m     \u001B[38;5;66;03m#        print(\"  No samples found in this puck.\")\u001B[39;00m\n\u001B[1;32m     30\u001B[0m     \u001B[38;5;66;03m#\u001B[39;00m\n",
      "\u001B[0;31mAttributeError\u001B[0m: 'SamplesApi' object has no attribute 'get_sample_results_samples_results_get'"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-05-05T13:39:17.528508Z",
     "start_time": "2025-05-05T13:39:17.496188Z"
    }
   },
   "cell_type": "code",
   "source": [
    "with aareDBclient.ApiClient(configuration) as api_client:\n",
    "    api_client.default_headers[\"Authorization\"] = f\"Bearer {token}\"\n",
    "    api_instance = aareDBclient.BeamtimesApi(api_client)\n",
    "\n",
    "\n",
    "    payload = BeamtimeCreate(\n",
    "        pgroups = \"p20003\",\n",
    "        shift = \"morning\",\n",
    "        beamtime_name = \"unscheduled beamtime\",\n",
    "        beamline = \"X06DA\",\n",
    "        start_date = \"2025-05-05\",\n",
    "        end_date = \"2025-05-05\",\n",
    "        status = \"unscheduled\",\n",
    "        comments = \"unscheduled beamtime created by test functions\",\n",
    "        proposal_id = 1,\n",
    "        local_contact_id= 1\n",
    "        )\n",
    "\n",
    "    try:\n",
    "        api_response = api_instance.create_beamtime_protected_beamtimes_post(payload.dict())\n",
    "        pprint(api_response)\n",
    "\n",
    "        print(\"The response of BeamtimesApi->beamtime_create:\\n\")\n",
    "        pprint(api_response)\n",
    "\n",
    "    except Exception as e:\n",
    "        print(f\"Exception when calling BeamtimesApi: {e}\")\n"
   ],
   "id": "deff7388a205e169",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): localhost:8000\n",
      "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'localhost'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings\n",
      "  warnings.warn(\n",
      "DEBUG:urllib3.connectionpool:https://localhost:8000 \"POST /protected/beamtimes/ HTTP/1.1\" 400 66\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Exception when calling BeamtimesApi: (400)\n",
      "Reason: Bad Request\n",
      "HTTP response headers: HTTPHeaderDict({'date': 'Mon, 05 May 2025 13:39:16 GMT', 'server': 'uvicorn', 'content-length': '66', 'content-type': 'application/json'})\n",
      "HTTP response body: {\"detail\":\"A beamtime for this pgroup/shift/date already exists.\"}\n",
      "\n"
     ]
    }
   ],
   "execution_count": 18
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
