{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e29b9d8c-73af-40d6-9cf4-a35af00e8f5a",
   "metadata": {},
   "source": [
    "# Focusing notebook\n",
    "Results in focused beam on the camera. \n",
    "Important: make sure the rotation of the camera is correct, check by either moving the camera or steering the beam"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f2d90bd7-468f-4df5-b094-3ed94b78d586",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-05-01 at 15:26:19 | INFO | Loading started.\n",
      "2025-05-01 at 15:26:19 | WARNING | Cannot write log file to snapshots.\n",
      "2025-05-01 at 15:26:19 | WARNING | [Errno 13] Permission denied: '/sf/cristallina/applications/beamline/snapshots/slic_logs/cristallina.log'\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/gfa/.mounts/sf_cristallina/applications/slic/cristallina\n",
      "\u001b]0;⊚slic\u0007could not set up DBusNotify: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.Notifications was not provided by any .service files\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-05-01 at 15:26:21 | WARNING | No transmission value reported from SARFE10-OATT053\n",
      "2025-05-01 at 15:26:21 | WARNING | No transmission value reported from SAROP31-OATA150\n",
      "2025-05-01 at 15:26:22 | INFO | Using undulator (Aramis) offset to PSSS energy of 0 eV.\n",
      "2025-05-01 at 15:26:22 | INFO | Photon energy offsets: PSSS -8 eV , DCCM -12 eV, undulator -16 eV.\n",
      "2025-05-01 at 15:26:22 | WARNING | Error: Could not connect to dilution fridge. name 'Dilution' is not defined\n",
      "2025-05-01 at 15:26:22 | INFO | Connected to stand server\n",
      "2025-05-01 at 15:26:22 | WARNING | Cannot write log file to pgroup p22259.\n",
      "2025-05-01 at 15:26:22 | INFO | Using CristallinaQ setup for detectors.\n",
      "2025-05-01 at 15:26:22 | INFO | Running at cristallina with pgroup p22259. Experiment type: Q.\n",
      "2025-05-01 at 15:26:22 | INFO | Loading finished.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SAT functions\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "sys.path.append('/sf/cristallina/applications/slic/cristallina/crq_exp/')\n",
    "from tqdm.notebook import tqdm\n",
    "\n",
    "%cd /sf/cristallina/applications/slic/cristallina\n",
    "%run /sf/cristallina/applications/slic/cristallina/cristallina.py"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "23e77708-0432-4f51-84ea-f63cd750339c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "%matplotlib widget\n",
    "import threading\n",
    "from queue import Queue\n",
    "from beamline.kb_focusing import kbV_focusing_acquire, kbH_focusing_acquire, kb_focusing_acquire, ReadData, plotdata"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bca9418a-81bb-4f13-bb73-e375759210f1",
   "metadata": {},
   "source": [
    "## Horizontal focus first"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc79a8c1-2132-49b4-8d5e-a1867518e0f4",
   "metadata": {},
   "source": [
    "Mesurement is run in a thread, if you want to stop the measurement, stop with **stop_measurement.set()**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ca5de5cc-64a2-459e-b11b-212a60361788",
   "metadata": {},
   "outputs": [],
   "source": [
    "stop_measurement=threading.Event()\n",
    "intermediate_results = []\n",
    "out_fpath = Queue()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "8c23f850-01af-42b9-99c5-26b8ecf58720",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-05-01 at 15:26:23 | INFO | BU/BD sent to start\n",
      "2025-05-01 at 15:26:26 | INFO | BU to start:  1.000\n",
      "2025-05-01 at 15:26:26 | INFO | BD to start:  0.800\n",
      "2025-05-01 at 15:26:26 | INFO | \n",
      "2025-05-01 at 15:26:36 | INFO |       BU / BD positions =  1.300 /  1.100\n",
      "2025-05-01 at 15:26:38 | INFO |         Aperture position = -0.300; Beam position = 1353.178\n",
      "2025-05-01 at 15:26:41 | INFO |         Aperture position =  0.000; Beam position = 1361.812\n",
      "2025-05-01 at 15:26:44 | INFO |         Aperture position =  0.300; Beam position = 1354.503\n",
      "2025-05-01 at 15:27:00 | INFO |       BU / BD positions =  1.300 /  1.600\n",
      "2025-05-01 at 15:27:01 | INFO |         Aperture position = -0.300; Beam position = 1354.479\n",
      "2025-05-01 at 15:27:04 | INFO |         Aperture position =  0.000; Beam position = 1359.144\n",
      "2025-05-01 at 15:27:08 | INFO |         Aperture position =  0.300; Beam position = 1354.953\n",
      "2025-05-01 at 15:27:23 | INFO |       BU / BD positions =  1.300 /  2.100\n",
      "2025-05-01 at 15:27:24 | INFO |         Aperture position = -0.300; Beam position = 1365.956\n",
      "2025-05-01 at 15:27:28 | INFO |         Aperture position =  0.000; Beam position = 1359.836\n",
      "2025-05-01 at 15:27:31 | INFO |         Aperture position =  0.300; Beam position = 1357.322\n",
      "2025-05-01 at 15:28:01 | INFO | \n",
      "2025-05-01 at 15:28:01 | INFO | BD to start:  0.800\n",
      "2025-05-01 at 15:28:02 | INFO | \n",
      "2025-05-01 at 15:28:18 | INFO |       BU / BD positions =  1.800 /  1.100\n",
      "2025-05-01 at 15:28:20 | INFO |         Aperture position = -0.300; Beam position = 1354.185\n",
      "2025-05-01 at 15:28:23 | INFO |         Aperture position =  0.000; Beam position = 1366.677\n",
      "2025-05-01 at 15:28:26 | INFO |         Aperture position =  0.300; Beam position = 1357.578\n",
      "2025-05-01 at 15:28:42 | INFO |       BU / BD positions =  1.800 /  1.600\n",
      "2025-05-01 at 15:28:43 | INFO |         Aperture position = -0.300; Beam position = 1346.070\n",
      "2025-05-01 at 15:28:46 | INFO |         Aperture position =  0.000; Beam position = 1360.324\n",
      "2025-05-01 at 15:28:50 | INFO |         Aperture position =  0.300; Beam position = 1367.877\n",
      "2025-05-01 at 15:29:05 | INFO |       BU / BD positions =  1.800 /  2.100\n",
      "2025-05-01 at 15:29:06 | INFO |         Aperture position = -0.300; Beam position = 1359.428\n",
      "2025-05-01 at 15:29:10 | INFO |         Aperture position =  0.000; Beam position = 1355.008\n",
      "2025-05-01 at 15:29:13 | INFO |         Aperture position =  0.300; Beam position = 1354.985\n",
      "2025-05-01 at 15:29:43 | INFO | \n",
      "2025-05-01 at 15:29:43 | INFO | BD to start:  0.800\n",
      "2025-05-01 at 15:29:44 | INFO | \n",
      "2025-05-01 at 15:30:00 | INFO |       BU / BD positions =  2.300 /  1.100\n",
      "2025-05-01 at 15:30:01 | INFO |         Aperture position = -0.300; Beam position = 1359.718\n",
      "2025-05-01 at 15:30:05 | INFO |         Aperture position =  0.000; Beam position = 1356.016\n",
      "2025-05-01 at 15:30:08 | INFO |         Aperture position =  0.300; Beam position = 1366.954\n",
      "2025-05-01 at 15:30:23 | INFO |       BU / BD positions =  2.300 /  1.600\n",
      "2025-05-01 at 15:30:25 | INFO |         Aperture position = -0.300; Beam position = 1363.036\n",
      "2025-05-01 at 15:30:28 | INFO |         Aperture position =  0.000; Beam position = 1357.821\n",
      "2025-05-01 at 15:30:31 | INFO |         Aperture position =  0.300; Beam position = 1365.960\n",
      "2025-05-01 at 15:30:47 | INFO |       BU / BD positions =  2.300 /  2.100\n",
      "2025-05-01 at 15:30:48 | INFO |         Aperture position = -0.300; Beam position = 1356.810\n",
      "2025-05-01 at 15:30:52 | INFO |         Aperture position =  0.000; Beam position = 1361.337\n",
      "2025-05-01 at 15:30:55 | INFO |         Aperture position =  0.300; Beam position = 1366.168\n",
      "2025-05-01 at 15:31:25 | INFO | \n",
      "2025-05-01 at 15:31:25 | INFO | BD to start:  0.800\n",
      "2025-05-01 at 15:31:26 | INFO | BU to start:  1.000\n",
      "2025-05-01 at 15:31:26 | INFO | Data saved to: /sf/cristallina/applications/beamline/snapshots/KBs/2025-05-01/C_2025-05-01T15:26_horizontal.dat\n",
      "2025-05-01 at 15:31:26 | INFO | Done\n"
     ]
    }
   ],
   "source": [
    "thr=threading.Thread( target=kbH_focusing_acquire,\n",
    "                      args=(intermediate_results,stop_measurement,out_fpath),\n",
    "                      kwargs={\n",
    "    'bender_ds_center': 1.6,\n",
    "    'bender_us_center': 1.8, \n",
    "    'bender_us_span'  : 0.5,\n",
    "    'bender_ds_span'  : 0.5,\n",
    "    'bender_npoints'  : 3,\n",
    "    'bender_us_start' : None,\n",
    "    'bender_ds_start' : None,\n",
    "    'aperture_center' : 0,\n",
    "    'aperture_span'   : 0.3,\n",
    "    'aperture_npoints': 3,\n",
    "    'aperture_narrow_dimension' : 0.15,\n",
    "    'aperture_wide_dimension'   : 2,\n",
    "    'n_pulses'        : 1,\n",
    "    'camera_name'     : 'SARES30-CAMS156-XE',\n",
    "})\n",
    "thr.start()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "5199c607-403a-49a8-81de-2b93afd6aecd",
   "metadata": {},
   "outputs": [],
   "source": [
    "#stop_measurement.set()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4d3f2aae-5b5e-42fa-9609-fb0e2d72f2ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load and plot intermediate data\n",
    "d_intermediate = ReadData(intermediate_results)\n",
    "intermediate_results\n",
    "\n",
    "plotdata(d_intermediate,Plot3D=True,PlotContour=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "d2dc1063-8834-425a-9f98-1c309310ecbb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "open file: /sf/cristallina/applications/beamline/snapshots/KBs/2025-05-01/C_2025-05-01T15:26_horizontal.json\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "821f71abad3e4290a77dbd7613616194",
       "version_major": 2,
       "version_minor": 0
      },
      "image/png": "[encoded data, 380844 characters]",
      "text/html": [
       "\n",
       "            <div style=\"display: inline-block;\">\n",
       "                <div class=\"jupyter-widgets widget-label\" style=\"text-align: center;\">\n",
       "                    3D\n",
       "                </div>\n",
       "                <img src='data:image/png;base64,[encoded data, 380844 characters]' width=1000.0/>\n",
       "            </div>\n",
       "        "
      ],
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load and plot the final data and save the png\n",
    "saved_file_path = out_fpath.get()\n",
    "saved_file_path_json = str( saved_file_path.with_suffix(\".json\") )\n",
    "d_done = ReadData( saved_file_path_json  )\n",
    "\n",
    "plotdata(d_done,Plot3D=True,PlotContour=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "645d681e-47eb-444b-b855-0bf2e3fa809f",
   "metadata": {},
   "source": [
    "## Vertical focus second"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "41022aad-a704-4303-ab72-287e362ca632",
   "metadata": {},
   "source": [
    "Mesurement is run in a thread, if you want to stop the measurement, stop with **stop_measurement.set()**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "44c26899-f728-4f4a-b3a6-b0484977710c",
   "metadata": {},
   "outputs": [],
   "source": [
    "stop_measurement=threading.Event()\n",
    "intermediate_results = []\n",
    "out_fpath = Queue()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "09c7ba7e-b086-43c3-a4bf-11e1224c3ca7",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-05-01 at 15:10:17 | INFO | BU/BD sent to start\n",
      "2025-05-01 at 15:10:20 | INFO | BU to start:  0.690\n",
      "2025-05-01 at 15:10:20 | INFO | BD to start:  0.750\n",
      "2025-05-01 at 15:10:20 | INFO | \n",
      "2025-05-01 at 15:10:30 | INFO |       BU / BD positions =  0.990 /  1.050\n",
      "2025-05-01 at 15:10:32 | INFO |         Aperture position = -0.300; Beam position = -456.282\n",
      "2025-05-01 at 15:10:35 | INFO |         Aperture position =  0.000; Beam position = -465.272\n",
      "2025-05-01 at 15:10:38 | INFO |         Aperture position =  0.300; Beam position = -423.303\n",
      "2025-05-01 at 15:10:54 | INFO |       BU / BD positions =  0.990 /  1.550\n",
      "2025-05-01 at 15:10:55 | INFO |         Aperture position = -0.300; Beam position = -490.987\n",
      "2025-05-01 at 15:10:58 | INFO |         Aperture position =  0.000; Beam position = -461.135\n",
      "2025-05-01 at 15:11:02 | INFO |         Aperture position =  0.300; Beam position = -494.880\n",
      "2025-05-01 at 15:11:17 | INFO |       BU / BD positions =  0.990 /  2.050\n",
      "2025-05-01 at 15:11:18 | INFO |         Aperture position = -0.300; Beam position = -443.729\n",
      "2025-05-01 at 15:11:22 | INFO |         Aperture position =  0.000; Beam position = -459.953\n"
     ]
    }
   ],
   "source": [
    "thr=threading.Thread( target=kbV_focusing_acquire,\n",
    "                      args=(intermediate_results,stop_measurement,out_fpath),\n",
    "                      kwargs={\n",
    "    'bender_ds_center': 1.55,\n",
    "    'bender_us_center': 1.49, \n",
    "    'bender_us_span'  : 0.5,\n",
    "    'bender_ds_span'  : 0.5,\n",
    "    'bender_npoints'  : 3,\n",
    "    'bender_us_start' : None,\n",
    "    'bender_ds_start' : None,\n",
    "    'aperture_center' : 0,\n",
    "    'aperture_span'   : 0.3,\n",
    "    'aperture_npoints': 3,\n",
    "    'aperture_narrow_dimension' : 0.15,\n",
    "    'aperture_wide_dimension'   : 2,\n",
    "    'n_pulses'        : 1,\n",
    "    'camera_name'     : 'SARES30-CAMS156-XE',\n",
    "})\n",
    "thr.start()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "35ca791b-7969-467d-8c81-678fdd76551e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#stop_measurement.set()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "2bfe7a86-fea0-4193-87c6-f09221e84971",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1f889e9155254781a7a3b220d2458ced",
       "version_major": 2,
       "version_minor": 0
      },
      "image/png": "[encoded data, 362576 characters]",
      "text/html": [
       "\n",
       "            <div style=\"display: inline-block;\">\n",
       "                <div class=\"jupyter-widgets widget-label\" style=\"text-align: center;\">\n",
       "                    3D\n",
       "                </div>\n",
       "                <img src='data:image/png;base64,[encoded data, 362576 characters]' width=1000.0/>\n",
       "            </div>\n",
       "        "
      ],
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load and plot intermediate data\n",
    "d_intermediate = ReadData(intermediate_results)\n",
    "intermediate_results\n",
    "\n",
    "plotdata(d_intermediate,Plot3D=True,PlotContour=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "0bd3688d-ff19-4a2e-be3f-b245913d1d04",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "open file: /sf/cristallina/applications/beamline/snapshots/KBs/2025-05-01/C_2025-05-01T15:10_vertical.json\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1f889e9155254781a7a3b220d2458ced",
       "version_major": 2,
       "version_minor": 0
      },
      "image/png": "[encoded data, 381672 characters]",
      "text/html": [
       "\n",
       "            <div style=\"display: inline-block;\">\n",
       "                <div class=\"jupyter-widgets widget-label\" style=\"text-align: center;\">\n",
       "                    3D\n",
       "                </div>\n",
       "                <img src='data:image/png;base64,[encoded data, 381672 characters]' width=1000.0/>\n",
       "            </div>\n",
       "        "
      ],
      "text/plain": [
       "Canvas(toolbar=Toolbar(toolitems=[('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous …"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# Load and plot the final data and save the png\n",
    "saved_file_path = out_fpath.get()\n",
    "saved_file_path_json = str( saved_file_path.with_suffix(\".json\") )\n",
    "d_done = ReadData( saved_file_path_json  )\n",
    "\n",
    "plotdata(d_done,Plot3D=True,PlotContour=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37b92a9f-aa38-4189-bbb0-33706d4a4714",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3bb53703-fa4d-4c6b-8b39-0d5e30c49cf5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ab08b768-a3f4-460e-93d6-ce69c18053c3",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c095962-7fd3-41da-ba3f-b557425d2834",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3372eda2-26a8-4e91-8a93-1d35ab5d7731",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "66bf3825-5846-4d32-b270-92152afd517e",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fcf9297-0bdc-41aa-8eb3-b744ece51ddd",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c7356fe9-5cd2-4b33-8f21-ced957027cb1",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "849991a3-1885-482c-ba6f-456644f19846",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5ab11d0f-7bb9-4353-8b56-555644acfbe5",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20b8bb41-6ce2-4f86-8234-93f8042047fc",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "adb163e3-902e-47a8-a72a-9eb41503dc0d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91c4191c-50e5-42a7-a55f-3b06b464fe50",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:it-slic-crq]",
   "language": "python",
   "name": "conda-env-it-slic-crq-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
