{"cells": [{"cell_type": "markdown", "id": "bd148401-0fc3-480c-b62e-bce5edc7183d", "metadata": {}, "source": ["# Fit the far-field diffraction geometry using a powder calibrant with dx dy spatial files"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/calibration/powder_calib.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/calibration/powder_calib.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "id": "1fbe01a0-bff9-48e5-8c09-c57ba21f139c", "metadata": {}, "outputs": [], "source": ["# python environment stuff\n", "IMAGED11_PATH = None # means do not use git, otherwise \"ImageD11\" or \"ImageD11_version_xx\", etc\n", "CHECKOUT_PATH = None # None means guess, or you can specify a folder for the checkout"]}, {"cell_type": "code", "execution_count": null, "id": "b412178d-bd79-4967-9d30-8be4c273f58d", "metadata": {}, "outputs": [], "source": ["if IMAGED11_PATH is not None:\n", " exec(open('/data/id11/nanoscope/install_ImageD11_from_git.py').read())\n", " PYTHONPATH=setup_ImageD11_from_git(CHECKOUT_PATH, IMAGED11_PATH)\n", "else:\n", " import site\n", " PYTHONPATH = site.getsitepackages()[0]\n", " print(PYTHONPATH)"]}, {"cell_type": "code", "execution_count": null, "id": "5c11df2b-ed9b-47b3-8166-e8f92fe42449", "metadata": {"tags": []}, "outputs": [], "source": ["import copy\n", "import silx.io\n", "import scipy.ndimage\n", "import numpy as np\n", "import fabio\n", "import matplotlib.pyplot as plt\n", "import h5py\n", "import matplotlib\n", "import ImageD11.columnfile\n", "import ImageD11.unitcell\n", "import ImageD11.transformer\n", "import ImageD11.frelon_peaksearch\n", "from ImageD11 import parameters\n", "from ImageD11.cImageD11 import s_1, s_I, s_sI, s_fI\n", "from ImageD11.nbGui import segmenter_gui\n", "from ImageD11.nbGui import fit_geometry\n", "from ImageD11.parameters import AnalysisSchema, parameters\n", "%matplotlib ipympl"]}, {"cell_type": "code", "execution_count": null, "id": "388f0e0c-a13a-4a6d-9601-1af79ba47550", "metadata": {}, "outputs": [], "source": ["# Set up the file paths. Edit this if you are not at ESRF or not using the latest data policy.\n", "dataroot, analysisroot = segmenter_gui.guess_ESRF_paths() \n", "\n", "if len(dataroot)==0:\n", " print(\"Please fix in the dataroot and analysisroot folder names above!!\")\n", " \n", "print('dataroot =',repr(dataroot))\n", "print('analysisroot =',repr(analysisroot))"]}, {"cell_type": "code", "execution_count": null, "id": "0c414a6f-8782-48a0-80dd-3d30879d3a93", "metadata": {}, "outputs": [], "source": ["# List the samples available:\n", "segmenter_gui.printsamples(dataroot)"]}, {"cell_type": "code", "execution_count": null, "id": "3e25f1a9-86ca-4e07-889f-a31e47a2660b", "metadata": {}, "outputs": [], "source": ["# USER: Decide which sample\n", "sample = 'CeO2'"]}, {"cell_type": "code", "execution_count": null, "id": "f1720b7d-c065-4df4-a3d3-2974a5a6659a", "metadata": {}, "outputs": [], "source": ["# List the datasets for that sample:\n", "segmenter_gui.printdatasets( dataroot, sample )"]}, {"cell_type": "code", "execution_count": null, "id": "66ee1f9f-eaa2-4417-99f5-f55cf40d2194", "metadata": {}, "outputs": [], "source": ["# USER: Decide which dataset\n", "dataset = \"rot\""]}, {"cell_type": "code", "execution_count": null, "id": "7f9ac02f-3380-4d3f-b5e3-7df8d2e25f05", "metadata": {"tags": []}, "outputs": [], "source": ["# USER: which detector are you using?\n", "detector = 'frelon3'"]}, {"cell_type": "code", "execution_count": null, "id": "28228c64-f8ab-44fb-b071-ba42f32589b0", "metadata": {"tags": []}, "outputs": [], "source": ["# USER: Which scan is the calibration?\n", "scan = '1.1'"]}, {"cell_type": "code", "execution_count": null, "id": "e32fccc1-2162-4cf8-9751-f5945a5bc11d", "metadata": {"tags": []}, "outputs": [], "source": ["ds = ImageD11.sinograms.dataset.DataSet(dataroot=dataroot,\n", " analysisroot=analysisroot,\n", " sample=sample,\n", " dset=dataset,\n", " detector=detector)\n", "\n", "frames = silx.io.get_data( f\"silx:{ds.masterfile}::{scan}/measurement/{ds.detector}\")\n", "print(frames.shape)"]}, {"cell_type": "code", "execution_count": null, "id": "dc56ea91-4d31-4d6b-8ef9-5e484bc0a9d1", "metadata": {"tags": []}, "outputs": [], "source": ["# now specify where the dark scan is\n", "# if we didn't collect one, change the below to False\n", "\n", "have_dark_scan = False\n", "\n", "if have_dark_scan:\n", " \n", " dark_sample = 'CeO2'\n", " dark_dataset = \"dark\"\n", " dark_scan = '1.1'\n", " \n", " ds_dark = ImageD11.sinograms.dataset.DataSet(dataroot=dataroot,\n", " analysisroot=analysisroot,\n", " sample=dark_sample,\n", " dset=dark_dataset,\n", " detector=detector)\n", "\n", " dark = silx.io.get_data(f\"silx:{ds_dark.masterfile}::{dark_scan}/measurement/{ds_dark.detector}\" )[:].mean(axis=0, dtype=np.float32)\n", " print(dark.shape)"]}, {"cell_type": "code", "execution_count": null, "id": "5a40d445-7bc8-49ca-b114-80e57a68dcfa", "metadata": {"tags": []}, "outputs": [], "source": ["# Try to determine which spatial calibration files to use depending on the detector\n", "\n", "if 'frelon' in detector:\n", " serial = silx.io.get_data( f\"silx:{ds.masterfile}::{scan}/instrument/{detector}/camera_settings/camera_serial\" )\n", " o11 = '1'\n", " print(\"Detector serial\", serial )\n", " if serial == \"21\":\n", " flat = silx.io.get_data( f\"fabio:/data/id11/3dxrd/inhouse/Frelon21/F21_flat_july18.edf\" )\n", " e2dxfile = \"/data/id11/3dxrd/inhouse/Frelon21/F21dxnew.edf\"\n", " e2dyfile = \"/data/id11/3dxrd/inhouse/Frelon21/F21dynew.edf\"\n", " maskfile = \"/data/id11/3dxrd/inhouse/Frelon21/F21_flat_Oct2016.msk\"\n", " pixelsize = float(fabio.open(e2dxfile).header['PSize_1'].split()[0])*1e6 # microns\n", "\n", " elif serial == \"36\": \n", " flat = silx.io.get_data( f\"fabio:/data/id11/3dxrd/inhouse/Frelon36/F36_Nov2023.edf\" )\n", " flat = flat / flat[500:-500, 500:-500].mean()\n", " e2dxfile = \"/data/id11/3dxrd/inhouse/Frelon36/f36dx.edf\"\n", " e2dyfile = \"/data/id11/3dxrd/inhouse/Frelon36/f36dy.edf\"\n", " maskfile = \"/data/id11/3dxrd/inhouse/Frelon36/frelon36_mask_20240117.edf\"\n", " pixelsize = float(fabio.open(e2dxfile).header['PSize_1'].split()[0])*1e6 # microns\n", "\n", " elif serial == \"29\":\n", " flat = silx.io.get_data( f\"fabio:/data/id11/3dxrd/inhouse/Frelon4M/c29_Agfilt_flat-dark.edf\" )\n", " e2dxfile = \"/data/id11/3dxrd/inhouse/Frelon4M/F4M_EO_dx.edf\"\n", " e2dyfile = \"/data/id11/3dxrd/inhouse/Frelon4M/F4M_EO_dy.edf\"\n", " maskfile = \"/data/id11/3dxrd/inhouse/Frelon4M/c29_Agfilt_flat-dark-mask.edf\"\n", " pixelsize = float(fabio.open(e2dxfile).header['PSize_1'].split()[0])*1e6 # microns\n", " else:\n", " print('Not sure what Frelon your detector is! You should manually provide the flat field, e2dxfile, e2dyfile, pixelsize, maskfile')\n", " print('Pixel size', pixelsize )\n", " print( \"Average flat, should be close to 1 : \",flat[100:-100, 100:-100].mean() )\n", " \n", " if have_dark_scan:\n", " cor = ( frames - dark[ None, :, :] ).mean( axis = 0, dtype = np.float32 ) / flat\n", " else:\n", " cor = frames.mean( axis = 0, dtype = np.float32 ) / flat\n", " \n", "elif 'eiger' in detector: # eiger\n", " cor = frames.mean( axis = 0, dtype = np.float32 )\n", " o11 = '-1'\n", " maskfile = \"/data/id11/nanoscope/Eiger/eiger_mask_E-08-0144_20250819.edf\"\n", " e2dxfile = \"/data/id11/nanoscope/Eiger/e2dx_20250819.edf\"\n", " e2dyfile = \"/data/id11/nanoscope/Eiger/e2dy_20250819.edf\"\n", " pixelsize = float(silx.io.get_data(f\"silx:{ds.masterfile}::{scan}/instrument/{ds.detector}/x_pixel_size\" )) * 1e6 # microns\n", "else:\n", " print('Unknown detector! Must manually specify')"]}, {"cell_type": "code", "execution_count": null, "id": "49341b2b-b7dc-4b15-968e-469e0130a1ca", "metadata": {"tags": []}, "outputs": [], "source": ["def guess_median_bg( img, size=91 ):\n", " m0 = scipy.ndimage.median_filter( cor, (size,1))\n", " m1 = scipy.ndimage.median_filter( cor, (1,size))\n", " bg = np.where(m0 lowcut ) )\n", "\n", "bg = guess_median_bg( cor )\n", "\n", "signal = ((cor - bg )*mask).clip(0,None)"]}, {"cell_type": "code", "execution_count": null, "id": "a91deedf-4f61-401b-adef-f9e32d82bbcb", "metadata": {"tags": []}, "outputs": [], "source": ["f,(a,b) = plt.subplots( 2, 2, figsize=(8, 6), constrained_layout=True )\n", "f.colorbar( a[1].imshow( cor * mask, norm='log', vmin=0.5, vmax=500, interpolation='nearest' ) )\n", "f.colorbar( b[1].imshow( signal, norm='log', vmin=0.5, vmax=500, interpolation='nearest' ) )\n", "a[1].set_title('Correction')\n", "a[0].plot( (cor * mask)[ 1024, : ] )\n", "a[0].plot( (cor * mask)[ :, 1024 ] )\n", "a[0].set(xlabel='pixel', ylabel='intensity')\n", "b[0].plot( signal[ 1024, : ] )\n", "b[0].plot( signal[ :, 1024 ] )\n", "b[1].set_title('Signal to peaksearch')\n", "b[0].set(xlabel='pixel', ylabel='intensity', ylim=(0, None) )\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "8bf70797-1bd2-42af-b1c4-337b08b3cc6f", "metadata": {"tags": []}, "outputs": [], "source": ["# Old way, using command line:\n", "# !powderimagetopeaks.py CeO2_for_S5_blue_rot_clean.edf CeO2_for_S5_blue_rot_clean0000.edf CeO2_for_S5_blue_rot_clean0001.edf 1024 1024\n", "def powderimagetopeaks( img, ci = 1024, cj = 1024 ):\n", " # cuts into 1 degree bins\n", " si, sj = img.shape\n", " i, j = np.mgrid[0:si,0:sj]\n", " phi = np.arctan2( i - ci, j - cj ) * 361 / np.pi\n", " return (phi%2).astype(int) == 0"]}, {"cell_type": "code", "execution_count": null, "id": "21201753-7e66-4cf5-ade9-78021460eabf", "metadata": {"tags": []}, "outputs": [], "source": ["peak_mask = powderimagetopeaks(signal)\n", "\n", "worker = ImageD11.frelon_peaksearch.worker(None, None)\n", "worker.threshold = 0\n", "\n", "pks = np.concatenate( (\n", " worker.peaksearch( signal * peak_mask ), # even degrees\n", " worker.peaksearch( signal * (1-peak_mask)), # odd degrees\n", " ), axis = 0 )\n", "print(f'Found {pks.shape[0]} peaks')"]}, {"cell_type": "code", "execution_count": null, "id": "29f1bca0-3896-432e-b421-f9fcebd9708e", "metadata": {"tags": []}, "outputs": [], "source": ["colfile = ImageD11.columnfile.colfile_from_dict( {\n", " \"s_raw\" : pks[ :, s_sI ] / pks[ :, s_I ],\n", " \"f_raw\" : pks[ :, s_fI ] / pks[ :, s_I ],\n", " \"Number_of_pixels\" : pks[ :, s_1 ], \n", " \"sum_intensity\" : pks[ :, s_I ],\n", " \"omega\" : np.zeros( len(pks), float ),\n", "} )"]}, {"cell_type": "code", "execution_count": null, "id": "0363424c-a306-41ae-af0c-821b058b7a44", "metadata": {"tags": []}, "outputs": [], "source": ["f, a = plt.subplots(1,2, figsize=(8,5), constrained_layout=True)\n", "a[0].plot( colfile.f_raw, colfile.s_raw, \".\", ms = 1)\n", "a[0].set( ylabel=\"detector slow direction\", xlabel=\"detector fast direction\", aspect='equal')\n", "a[1].plot( colfile.Number_of_pixels, colfile.sum_intensity, \".\", ms =1 )\n", "a[1].set( xlabel=\"Number of pixels\", ylabel=\"sum intensity\", yscale='log', xscale='log')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "id": "234b7390-8007-4cd5-87cd-3dda68305a23", "metadata": {"tags": []}, "outputs": [], "source": ["colfile = ImageD11.blobcorrector.eiger_spatial( e2dxfile, e2dyfile )(colfile)"]}, {"cell_type": "code", "execution_count": null, "id": "ff605eec-589d-4f53-b4cc-621a626836f0", "metadata": {"tags": []}, "outputs": [], "source": ["def auto_guess_distance(masterfile, scan):\n", " \"\"\"\n", " Automatically guess the distance from the masterfile\n", " \"\"\"\n", " possible_distance_motors = ['ffdtx1', 'frelx']\n", " distance_um = None\n", " for mot in possible_distance_motors:\n", " try:\n", " distance_um = float(silx.io.get_data(f\"silx:{masterfile}::{scan}/instrument/positioners/{mot}\" )) * 1e3 # microns\n", " except ValueError:\n", " continue\n", " if distance_um is None:\n", " raise ValueError(\"Couldn't find distance!\")\n", " \n", " return distance_um"]}, {"cell_type": "code", "execution_count": null, "id": "df82ca77-40c2-4aab-8dc9-632a14815420", "metadata": {"tags": []}, "outputs": [], "source": ["# guess the detector distance in um\n", "# you can also manually specify\n", "distance_guess = auto_guess_distance(ds.masterfile, scan) # detector distance in um\n", "\n", "# 'Ag': 25.514, 'Sn': 29.2001, 'Nd': 43.5689, 'Gd': 50.2391, 'Hf': 65.3508, 'W' : 69.525, 'Pt': 78.3948, 'Pb': 88.0045\n", "# here enter the lattice parameters and spacegroup of the calibrant\n", "# at ID11 we use CeO2 674b\n", "\n", "a_calibrant = 5.4115260\n", "spacegroup_calibrant = 225\n", "econst = 12.398423 # energy conversion - don't change\n", "energy = 43.5689 # the energy in keV"]}, {"cell_type": "code", "execution_count": null, "id": "64349042-2503-4663-a0b7-416135bf2255", "metadata": {"tags": []}, "outputs": [], "source": ["# get initial parameters\n", "\n", "trans = ImageD11.transformer.transformer()\n", "initial_parameters = trans.parameterobj\n", "initial_parameters.set('cell__a', a_calibrant)\n", "initial_parameters.set('cell__b', a_calibrant)\n", "initial_parameters.set('cell__c', a_calibrant)\n", "initial_parameters.set('cell_lattice_[P,A,B,C,I,F,R]', spacegroup_calibrant)\n", "initial_parameters.set('distance', distance_guess)\n", "initial_parameters.set('o11', int(o11))\n", "initial_parameters.set('wavelength', econst/energy)\n", "initial_parameters.set('y_size', pixelsize)\n", "initial_parameters.set('z_size', pixelsize)\n", "\n", "initial_parameters.get_parameters()"]}, {"cell_type": "code", "execution_count": null, "id": "36f69f3b-3d6a-4b20-8ae4-8c9a3f686773", "metadata": {"tags": []}, "outputs": [], "source": ["ui = ImageD11.nbGui.fit_geometry.FitGeom( )\n", "ui.setfiltered(colfile)\n", "ui.parameterobj = copy.deepcopy(initial_parameters)\n", "ui.fitGui()"]}, {"cell_type": "code", "execution_count": null, "id": "67ab3776-062f-429f-91e7-879610243db0", "metadata": {"tags": []}, "outputs": [], "source": ["# now save the parameter file to disk\n", "\n", "final_par_file = 'powder_pars.par'\n", "ui.saveparameters(final_par_file)"]}, {"cell_type": "markdown", "id": "6e36fe07-ac6b-4447-ac77-08eb09921dcb", "metadata": {}, "source": ["__We can now make a new-style parameter file, with Si added as a phase, for the single-crystal calibration notebooks.__"]}, {"cell_type": "code", "execution_count": null, "id": "f3e92ebd-6d28-40d1-925f-195fe659a8b0", "metadata": {}, "outputs": [], "source": ["asc = AnalysisSchema.from_old_pars_file(final_par_file)\n", "si_ucell = ImageD11.unitcell.unitcell([5.43094, 5.43094, 5.43094, 90.0, 90.0, 90.0], 227)\n", "asc.add_phase_from_unitcell(phase_name='Si', unitcell=si_ucell)\n", "asc.save('pars.json')"]}], "metadata": {"kernelspec": {"display_name": "Python 3 (main)", "language": "python", "name": "python3"}, "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.12.9"}, "widgets": {"application/vnd.jupyter.widget-state+json": {"state": {}, "version_major": 2, "version_minor": 0}}}, "nbformat": 4, "nbformat_minor": 5}