{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# Silicon calibration for a single crystal on ID11 nscope\n", "\n", "Uses the older ImageD11 calibration fitting routines\n", "\n", "Last updated 22/02/2025 by @jadball"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/calibration/silicon_calib.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/calibration/silicon_calib.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "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\n", "\n", "# Experts : update these files for your detector if you need to\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", "detector = 'eiger'\n", "omegamotor = 'rot_center'\n", "dtymotor = 'dty'\n", "\n", "# Default segmentation options\n", "options = { 'cut' : 1, 'pixels_in_spot' : 3, 'howmany' : 100000 }\n", "\n", "# EXPERTS: These can be provided as papermill parameters. Users, leave these as None for now...\n", "dataroot = None\n", "analysisroot = None\n", "sample = None\n", "dataset = None\n", "\n", "econst = 12.398423 # energy conversion - don't change"]}, {"cell_type": "code", "execution_count": null, "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, "metadata": {}, "outputs": [], "source": ["# '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 NIST SRM SiO2 670c\n", "\n", "symmetry = \"cubic\"\n", "a_silicon = 5.43094\n", "energy = 43.5689 # your guess of the beam energy in keV"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["%matplotlib ipympl\n", "import pylab as pl\n", "import numpy as np\n", "import ImageD11.sinograms.dataset\n", "import ImageD11.sinograms.assemble_label\n", "import ImageD11.sinograms.properties\n", "import ImageD11.transformer\n", "import ImageD11.columnfile\n", "import ImageD11.unitcell\n", "import ImageD11.indexing\n", "import ImageD11.grain\n", "import ImageD11.nbGui.fit_geometry\n", "import ImageD11.nbGui.nb_utils as utils\n", "import silx.io\n", "from ImageD11.parameters import AnalysisSchema, parameters\n", "from ImageD11.nbGui import segmenter_gui"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["# Segment the single crystal data"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# Set up the file paths. Edit this if you are not at ESRF or not using the latest data policy.\n", "if dataroot is None:\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, "metadata": {}, "outputs": [], "source": ["# List the samples available:\n", "segmenter_gui.printsamples(dataroot)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# USER: Decide which sample\n", "if sample is None:\n", " sample = 'Si_cube'"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# List the datasets for that sample:\n", "segmenter_gui.printdatasets( dataroot, sample )"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# USER: Decide which dataset\n", "if dataset is None:\n", " dataset = \"rot\""]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# create ImageD11 dataset object\n", "dset = ImageD11.sinograms.dataset.DataSet(dataroot=dataroot,\n", " analysisroot=analysisroot,\n", " sample=sample,\n", " dset=dataset,\n", " detector=detector,\n", " omegamotor=omegamotor,\n", " dtymotor=dtymotor\n", " )\n", "dset.import_all() # Can use scans = [f'{scan}.1' for scan in range(1,102)] )\n", "dset.maskfile = maskfile\n", "dset.e2dxfile = e2dxfile\n", "dset.e2dyfile = e2dyfile\n", "dset.save()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["ui = segmenter_gui.SegmenterGui(dset, **options )"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["options = ui.getopts()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# create batch file to send to SLURM cluster\n", "sbat = ImageD11.sinograms.lima_segmenter.setup(dset.dsfile, **ui.getopts(), pythonpath=PYTHONPATH)\n", "if sbat is None:\n", " raise ValueError(\"This scan has already been segmented!\")\n", "print(sbat)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.slurm_submit_and_wait(sbat, 60)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# label sparse peaks\n", "\n", "ImageD11.sinograms.assemble_label.main(dset.dsfile)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# generate peaks table\n", "\n", "ImageD11.sinograms.properties.main(dset.dsfile, options={'algorithm': 'lmlabel', 'wtmax': 70000, 'save_overlaps': False})"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# View peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# Load some peaks for your silicon\n", "\n", "colf = dset.get_cf_2d()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# Remove any weak peaks / noise (average intensity > cutoff)\n", "cutoff = 10\n", "colf.filter(colf.sum_intensity / colf.Number_of_pixels > cutoff)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["f, a = pl.subplots(1,2,figsize=(12,6), constrained_layout=True)\n", "a[0].plot(colf.fc,colf.sum_intensity/colf.Number_of_pixels,'.',alpha=0.2)\n", "a[0].set(yscale='log',xlabel='pixel',ylabel='intensity')\n", "a[1].plot(colf.fc,colf.sc,'.')\n", "a[1].set(xlabel='pixel', ylabel='pixel');\n", "pl.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# set up our filenames\n", "\n", "flt_file = \"si.flt\"\n", "gve_file = \"si.gve\"\n", "new_flt_file = \"si.flt.new\"\n", "par_file_start = \"si_start.par\" # you can set this to an existing parameter file if you already ran the powder_calib.ipynb notebook\n", "par_file_powder = \"si_powder.par\"\n", "par_file_end = \"si_fit.par\"\n", "ubi_file = \"si.ubi\"\n", "map_file = \"si.map\""]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["colf.writefile(flt_file)"]}, {"cell_type": "code", "execution_count": null, "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, "metadata": {}, "outputs": [], "source": ["# guess the detector distance in um\n", "# you can also manually specify\n", "distance_guess = auto_guess_distance(dset.masterfile, dset.scans[-1]) # detector distance in um\n", "print(distance_guess)\n", "# distance_guess = 140000 # 140 mm"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["__Note: If you followed powder_calib.ipynb first, you should have a much better starting point than the below suggested parameter file.__\n", "\n", "__Currently the below cell is only set up for the Eiger__"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["if not os.path.exists(par_file_start):\n", " with open(par_file_start,\"w\") as pars:\n", " pars.write(f\"\"\"cell__a {a_silicon}\n", "cell__b {a_silicon}\n", "cell__c {a_silicon}\n", "cell_alpha 90.0\n", "cell_beta 90.0\n", "cell_gamma 90.0\n", "cell_lattice_[P,A,B,C,I,F,R] 227\n", "chi 0.0\n", "distance {distance_guess}\n", "fit_tolerance 0.05\n", "o11 -1\n", "o12 0\n", "o21 0\n", "o22 -1\n", "omegasign 1.0\n", "t_x 0\n", "t_y 0\n", "t_z 0\n", "tilt_x 0.0\n", "tilt_y 0.0\n", "tilt_z 0.0\n", "wavelength {econst/energy}\n", "wedge 0.0\n", "y_center 1062.0\n", "y_size 75.0\n", "z_center 1126.0\n", "z_size 75.0\"\"\")"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Initial fit of parameters with Si peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ui = ImageD11.nbGui.fit_geometry.FitGeom()\n", "ui.loadfiltered(flt_file)\n", "ui.loadfileparameters(par_file_start) #, phase_name='Si') # you must specify a phase name if you're using an existing json file\n", "ui.fitGui()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ui.saveparameters(par_file_powder)\n", "ui.savegv(gve_file)"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["# Indexing single crystal"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# Change log level to 1 to see what it did\n", "idx = ImageD11.indexing.index( ui.colfile, npk_tol=[( ui.colfile.nrows//2, 0.05),], log_level=3)\n", "print('UBIs found:')\n", "idx.ubis"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["idx.saveubis(ubi_file)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Refining indexed crystal UBI and translation with initial parameters"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["!makemap.py -f {flt_file} -u {ubi_file} -U {map_file} -p {par_file_powder} -l {symmetry} -s {symmetry} -t 0.05 --omega_slop={dset.ostep/2}\n", "!makemap.py -f {flt_file} -u {map_file} -U {map_file} -p {par_file_powder} -l {symmetry} -s {symmetry} -t 0.025 --omega_slop={dset.ostep/2}"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Fitting parameters with refined crystal UBI and translation"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# fix the wedge to zero\n", "!refine_em.py {new_flt_file} {map_file} {par_file_powder} --omega_slop={dset.ostep/2} -x wedge -l {symmetry}"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["# Refining indexed crystal UBI and translation with refined parameters"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# refine_em.py creates 0.par\n", "\n", "!cp 0.par {par_file_end}\n", "!makemap.py -f {flt_file} -u {map_file} -U {map_file} -p {par_file_end} -l {symmetry} -s {symmetry} -t 0.05 --omega_slop={dset.ostep/2}\n", "!makemap.py -f {flt_file} -u {map_file} -U {map_file} -p {par_file_end} -l {symmetry} -s {symmetry} -t 0.025 --omega_slop={dset.ostep/2}"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["# Re-fitting parameters with refined crystal UBI and translation"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["!refine_em.py {new_flt_file} {map_file} {par_file_end} --omega_slop={dset.ostep/2} -x wedge -l {symmetry}"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Final refinement of indexed crystal UBI and translation"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["!cp 0.par {par_file_end}\n", "!makemap.py -f {flt_file} -u {map_file} -U {map_file} -p {par_file_end} -s {symmetry} -t 0.025 --omega_slop={dset.ostep/2}"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Look at new parameters"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["!cat {par_file_end}"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["!ubi2cellpars.py {map_file}"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["g = ImageD11.grain.read_grain_file(map_file)[0]\n", "v = np.linalg.det(g.ubi)\n", "a_avg = pow(v ,1/3)\n", "\n", "deviatoric = g.eps_grain_matrix( [a_avg, a_avg, a_avg, 90, 90, 90] )\n", "print('deviatoric strains, should be zero, so an estimate of precision:\\n',deviatoric)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["wold = ui.parameterobj.get('wavelength')\n", "wnew = wold*a_silicon/a_avg\n", "print( 'Wavelength input',wold,'estimated from silicon',wnew)\n", "print( 'Energy input',econst/wold,'estimated from silicon',econst/wnew)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["__If `wnew` is significantly different from `wold`, we recommend that you update the wavelength in the initial parameter guess, then re-running the rest of the notebook.__"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Final parameter visualisation"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["newcolf = ImageD11.columnfile.columnfile(new_flt_file)\n", "newcolf.parameters.loadparameters(par_file_end)\n", "newcolf.updateGeometry()\n", "ucell = ImageD11.unitcell.unitcell.from_par_file(par_file_end)\n", "ucell.makerings(newcolf.ds.max())\n", "\n", "fig, ax = pl.subplots(constrained_layout=True, figsize=(10, 5))\n", "ax.vlines(np.degrees(2*np.arcsin(np.array(ucell.ringds) * newcolf.parameters.get('wavelength')/2)), -180, 180, color='orange', zorder=0)\n", "ax.scatter(newcolf.tth_per_grain, newcolf.eta_per_grain, s=2)\n", "ax.set_xlim(2,22)\n", "ax.set_xlabel('2-theta ($^{o}$)')\n", "ax.set_ylabel('$\\eta$ ($^{o}$)')\n", "pl.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["__Once you're happy with the parameters, run the below cell to create a parameters json file with a geometry.par in the current directory__"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# load in the final parameters\n", "final_pars = parameters.from_file(par_file_end)\n", "# set crystal translations to zero\n", "final_pars.set('t_x', 0.0)\n", "final_pars.set('t_y', 0.0)\n", "final_pars.set('t_z', 0.0)\n", "final_pars.set('phase_name', 'Si')\n", "# make new AnalysisSchema from these\n", "asc = AnalysisSchema.from_old_pars_object(final_pars)\n", "# save to disk\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": 4}