{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# 3DXRD indexing notebook - Friedel pair method \n", "__Written by Haixing Fang, Jon Wright and James Ball__ \n", "__Date: 21/02/2025__"]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/TDXRD/1_index_friedel.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/TDXRD/1_index_friedel.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["import os\n", "\n", "os.environ['OMP_NUM_THREADS'] = '1'\n", "os.environ['OPENBLAS_NUM_THREADS'] = '1'\n", "os.environ['MKL_NUM_THREADS'] = '1'\n", "\n", "exec(open('/data/id11/nanoscope/install_ImageD11_from_git.py').read())"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": ["parameters"]}, "outputs": [], "source": ["# this cell is tagged with 'parameters'\n", "# to view the tag, select the cell, then find the settings gear icon (right or left sidebar) and look for Cell Tags\n", "\n", "# 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", "dset_path = ''\n", "\n", "phase_str = 'Fe'\n", "\n", "# path to parameters .json/.par\n", "parfile = ''\n", "\n", "# peak filtration options\n", "cf_strong_frac = 0.991\n", "cf_strong_dsmax = 1.01\n", "cf_strong_dstol = 0.01\n", "\n", "# friedel pair search options\n", "womega = 1.0\n", "weta = 1.0\n", "wtth = 1.5\n", "wI = 0.5\n", "\n", "# indexing options\n", "indexer_ds_tol = 0.003\n", "\n", "rings_for_gen = [1, 3]\n", "\n", "# now we want to decide which rings to score our found orientations against\n", "# generally we can just exclude dodgy rings (close to other phases, only a few peaks in etc)\n", "rings_for_scoring = [0, 1, 2, 3]\n", "\n", "# the sequence of hkl tolerances the indexer will iterate through\n", "hkl_tols_seq = [0.01, 0.02]\n", "# the sequence of minpks fractions the indexer will iterate through\n", "fracs = [0.9, 0.6]\n", "\n", "# the max number of UBIs we can find per pair of rings\n", "max_grains = 1000\n", "\n", "# makemap refinement options\n", "symmetry = \"cubic\"\n", "\n", "gridpars = {\n", " 'DSTOL' : 0.004,\n", " 'NUL' : True,\n", " 'FITPOS' : True,\n", " 'tolangle' : 0.25,\n", " 'toldist' : 100.,\n", " 'NTHREAD' : 1 ,\n", " 'NPKS': 25\n", "}\n", "\n", "absolute_minpks = 25"]}, {"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": {"tags": []}, "outputs": [], "source": ["import os\n", "import numpy as np\n", "import scipy.spatial\n", "from matplotlib import pyplot as plt\n", "\n", "import ImageD11.cImageD11\n", "import ImageD11.grain\n", "import ImageD11.indexing\n", "import ImageD11.columnfile\n", "import ImageD11.refinegrains\n", "import ImageD11.grid_index_parallel\n", "from ImageD11.sinograms import dataset\n", "from ImageD11.nbGui import nb_utils as utils\n", "from ImageD11.peakselect import select_ring_peaks_by_intensity\n", "\n", "%matplotlib widget"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Load data\n", "## Dataset"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ds = ImageD11.sinograms.dataset.load(dset_path)\n", "print(ds)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Parameters\n", "Specify the path to your parameter file.\n", "\n", "You can optionally set up some default parameters for either an Eiger or Frelon detector like so:\n", "```python\n", "from ImageD11.parameters import AnalysisSchema\n", "asc = AnalysisSchema.from_default(detector='eiger') # or detector='frelon'\n", "asc.save('./pars.json')\n", "```\n", "Please note in this case that you will still have to update the `geometry.par` values accordingly for your experiment. \n", "If you haven't already, you should run one of the calibration notebooks to determine these."]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["ds.parfile = parfile\n", "ds.save()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Phases\n", "If the parameter file was a json, we can access the unit cells via `ds.phases.unitcells`"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["ds.phases = ds.get_phases_from_disk()\n", "ds.phases.unitcells"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ucell = ds.phases.unitcells[phase_str]\n", "print(ucell.lattice_parameters, ucell.spacegroup)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["## Peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_3d = ds.get_cf_3d_from_disk()\n", "ds.update_colfile_pars(cf_3d, phase_name=phase_str) \n", "cf_3d_path = 'cf_3d.flt'\n", "cf_3d.writefile(cf_3d_path)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Visualise data\n", "### $d^{*}$ vs $\\eta$"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["skip = 1 # we can skip peaks to speed up plotting if needed\n", "ucell.makerings(cf_3d.ds.max())\n", "fig, ax = plt.subplots(figsize=(10,5), layout='constrained')\n", "ax.plot(cf_3d.ds[::skip], cf_3d.eta[::skip], ',')\n", "ax.vlines(ucell.ringds, -50, 50, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel=r'$\\eta~(\\degree)$', title='2D azimuthal transform')\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Filtration\n", "Here we are filtering our peaks (`cf_3d`) to select only the strongest ones for indexing purposes only! \n", "We first filter the peaks in $d^{*}$ to keep only those close to the predicted peaks from the unit cell. \n", "We then sort our peaks by intensity, and take a certain intensity-weighted fraction of them. \n", "`dstol`: The tolerance in $d^{*}$ between a peak and a predicted reflection. \n", "`dsmax`: The maximum allowed peak $d^{*}$ value. Used to limit the number of rings given to the indexer - 6-8 rings max are normally sufficient. \n", "`frac`: The intensity fraction: `frac=0.9` keeps 90% of the peak intensity. We recommend that you choose a value close to the 'elbow' of the plot."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_strong = select_ring_peaks_by_intensity(cf_3d, frac=cf_strong_frac, dsmax=cf_strong_dsmax, dstol=cf_strong_dstol, ucell=ucell, doplot=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["skip = 1 # we can skip peaks to speed up plotting if needed\n", "fig, ax = plt.subplots(figsize=(10, 5), constrained_layout=True)\n", "ax.plot(cf_3d.ds[::skip], cf_3d.sum_intensity[::skip],',', label='cf_3d')\n", "ax.plot(cf_strong.ds[::skip], cf_strong.sum_intensity[::skip],',', label='cf_strong')\n", "ax.vlines(ucell.ringds, 1e3, 1e4, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='Intensity', yscale='log', title='Peak filtration')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["### Look for Friedel pairs"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# compute Lorenz factor\n", "lf = ImageD11.refinegrains.lf(cf_strong.tth, cf_strong.eta)\n", "\n", "f = plt.figure(figsize=(15,5), layout='constrained')\n", "ax = f.add_subplot()\n", "\n", "# select peaks between 3 and 5 degrees in omega\n", "om1 = (cf_strong.omega < 5) & (cf_strong.omega > 3)\n", "\n", "# plot omega against intensity for those peaks, coloured by eta (azimuthal position on the ring)\n", "ax.scatter(cf_strong.omega[om1], cf_strong.sum_intensity[om1], c=cf_strong.eta[om1], marker='o')\n", "\n", "# the friedel pair of these peaks should be 180 degrees away in eta\n", "etapair = 180 - cf_strong.eta\n", "\n", "# modulate\n", "etapair = np.where(etapair > 180, etapair - 360, etapair)\n", "\n", "# select peaks for the friedel pairs between 183 and 185 degrees\n", "om2 = (cf_strong.omega < 185) & (cf_strong.omega > 183)\n", "\n", "# plot omega against intensity for the friedel pairs as crosses\n", "ax.scatter(cf_strong.omega[om2] - 180, cf_strong.sum_intensity[om2], c=etapair[om2], marker='+')\n", "ax.semilogy()\n", "\n", "ax.set(xlabel=r'$\\omega~(\\degree)$', ylabel='peak intensity', title=r'Coloured by $\\eta~(\\degree)$')\n", "\n", "# for valid friedel pairs, we should see 'o' and '+' markers close together in omega and intensity, with similar colours (eta)\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["def calc_tth_eta( c, pi, pj ):\n", " dX = c.xl[pi] + c.xl[pj]\n", " dY = c.yl[pi] + c.yl[pj]\n", " dZ = c.zl[pi] - c.zl[pj]\n", " r = np.sqrt(dY*dY + dZ*dZ)\n", " tth = np.degrees( np.arctan2( r, dX ) )\n", " eta = np.degrees(np.arctan2( -dY, dZ ))\n", " return tth, eta\n", "\n", "def find_friedel_pairs(cf_in, womega=1.5, weta=0.2, wtth=1.5, wI=0.5, doplot=False):\n", " # create a 4-dimensional tree\n", " # dimensions are omega, eta, tth, intensity\n", " t1 = scipy.spatial.cKDTree( np.transpose( [ \n", " womega*(cf_in.omega%360),\n", " weta*(cf_in.eta%360),\n", " wtth*cf_in.tth,\n", " wI*np.log10(cf_in.sum_intensity) ] ))\n", " \n", " # create another tree for the friedel pair side (omega + 180, 180 - eta)\n", " t2 = scipy.spatial.cKDTree( np.transpose([ \n", " womega*((cf_in.omega+180)%360),\n", " weta*((180-cf_in.eta)%360),\n", " wtth* cf_in.tth,\n", " wI*np.log10(cf_in.sum_intensity) ] ))\n", " \n", " # create a distance matrix between trees with a max distance of 1, returning a sparse matrix\n", " coo = t1.sparse_distance_matrix( t2, max_distance=1, output_type='coo_matrix' ) # 1 degree eta might be tight?\n", " \n", " inds = np.arange(cf_in.nrows)\n", " \n", " # mask for peaks on one side of the friedel pair\n", " p1 = inds[coo.row]\n", " # mask for peaks on the other side of the friedel pair\n", " p2 = inds[coo.col]\n", " \n", " # compute tth-eta of friedel pairs\n", " tth, eta = calc_tth_eta( cf_in, p1, p2 )\n", " # mask for intensity for friedel pairs\n", " s1 = cf_3d.sum_intensity[p1]\n", " s2 = cf_3d.sum_intensity[p2]\n", " \n", " # convert tth to dstar\n", " dstar = 2*np.sin(np.radians(tth)/2)/cf_in.parameters.get('wavelength')\n", " \n", " if doplot:\n", " f,a = plt.subplots(2,1,figsize=(20,6), layout='constrained', sharex=True)\n", " a[0].hist2d(dstar,eta,bins=(2000,360), norm='log', weights=s1+s2)\n", " a[0].plot(ucell.ringds, np.zeros_like(ucell.ringds),\"|r\",lw=1,ms=90)\n", " a[0].set(ylabel=r'$\\eta~(\\degree)$')\n", " a[1].hist2d(dstar,coo.data, # sum of squares of distance matrix\n", " # np.log(s1+s2),\n", " bins=(1000,128), norm='log');\n", " a[1].vlines(ucell.ringds, -50, 50, color='red')\n", " a[1].set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='distance for search')\n", " f.suptitle(r'Top: $d^{*}~(\\AA^{-1})$ vs $\\eta~(\\degree)$ of Friedel pairs \\n Bottom: $d^{*}~(\\AA^{-1})$ vs 4D tree distance')\n", " plt.show()\n", " \n", " if doplot:\n", " f,a = plt.subplots(t1.data.shape[1],1,figsize=(20,6), layout='constrained', sharex=True)\n", " for i in range(t1.data.shape[1]):\n", " a[i].hist2d(dstar, t1.data[coo.row,i] - t2.data[coo.col,i], bins=(1000,128), norm='log')\n", " a[i].vlines(ucell.ringds, -0.1, 0.1, color='red')\n", " a[i].set(ylabel=[r'$\\omega~(\\degree)$', r'$\\eta~(\\degree)$', r'$2\\theta~(\\degree)$', 'Log peak intensity'][i])\n", " f.suptitle(r'$d^{*}~(\\AA^{-1})$ vs error in [$\\omega~(\\degree)$, $\\eta~(\\degree)$, $2\\theta~(\\degree)$, intensity] for the friedel pair')\n", " f.supxlabel(r'$d^{*}~(\\AA^{-1})$')\n", " plt.show()\n", " \n", " # Mask to powder rings\n", " m = np.zeros_like(p1, dtype=bool)\n", " for d in ucell.ringds:\n", " m |= abs(dstar - d)<0.002\n", " \n", " # make columnfiles for each side of the friedel pair\n", " c1 = cf_in.copyrows( p1[m] )\n", " c2 = cf_in.copyrows( p2[m] )\n", " \n", " c1.tth[:] = tth[m]\n", " c2.tth[:] = tth[m]\n", " c1.ds[:] = dstar[m]\n", " c2.ds[:] = dstar[m]\n", " \n", " if doplot:\n", " fig, ax = plt.subplots(layout='constrained')\n", " ax.plot(c1.eta%360, eta[m]%360,',')\n", " ax.set(xlabel=r'$\\eta~(\\degree)$', ylabel=r'$\\eta~(\\degree)$', title=r'Observed vs computed $\\eta~(\\degree)$ for Friedel pairs (c1)')\n", " plt.show()\n", " \n", " # computed eta values (variable eta) matches c1, so we take c1.eta as eta, then recompute c2.eta\n", " c1.eta[:] = eta[m]\n", " e2 = 180 - eta[m]\n", " c2.eta[:] = np.where( e2 > 180, e2-360, e2)\n", " \n", " # combine paired peaks into one columnfile\n", " cpair = ImageD11.columnfile.colfile_from_dict({\n", " t: np.concatenate( (c1[t], c2[t]) ) for t in c1.titles } )\n", " cpair.parameters = cf_in.parameters\n", " \n", " if doplot:\n", " fig, ax = plt.subplots(figsize=(20,6), layout='constrained')\n", " ax.plot(c1.ds, c1.eta, ',')\n", " ax.plot(c2.ds, c2.eta, ',')\n", " ax.plot(cpair.ds, cpair.eta, ',')\n", " ax.vlines(ucell.ringds, -50, 50, color='red')\n", " ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel=r'$\\eta~(\\degree)$')\n", " plt.show()\n", " \n", " cpair.gx[:],cpair.gy[:],cpair.gz[:] = ImageD11.transform.compute_g_vectors( cpair.tth, cpair.eta, cpair.omega, cpair.parameters.get('wavelength') )\n", " \n", " if doplot:\n", " fig, ax = plt.subplots(figsize=(20,6), layout='constrained')\n", " ax.plot(cpair.ds, cpair.sum_intensity*np.exp(5*cpair.ds**2),',')\n", " ax.vlines(ucell.ringds, 1e3, 1e4, color='red')\n", " ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='Weighted Sum intensity', yscale='log')\n", " plt.show()\n", " \n", " return cpair"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_friedel_pairs = find_friedel_pairs(cf_strong, womega=womega, weta=weta, wtth=wtth, wI=wI, doplot=True)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["skip = 1 # we can skip peaks to speed up plotting if needed\n", "fig, ax = plt.subplots(figsize=(10, 5), constrained_layout=True)\n", "ax.plot(cf_3d.ds[::skip], cf_3d.eta[::skip],',', label='cf_3d')\n", "ax.plot(cf_friedel_pairs.ds[::skip], cf_friedel_pairs.eta[::skip],',', label='friedel pairs')\n", "ax.vlines(ucell.ringds, -50, 50, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel=r'$\\eta~(\\degree)$', title='2D azimuthal transform')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["skip = 1 # we can skip peaks to speed up plotting if needed\n", "fig, ax = plt.subplots(figsize=(10, 5), constrained_layout=True)\n", "ax.plot(cf_3d.ds[::skip], cf_3d.sum_intensity[::skip],',', label='cf_3d')\n", "ax.plot(cf_friedel_pairs.ds[::skip], cf_friedel_pairs.sum_intensity[::skip],',', label='friedel pairs')\n", "ax.vlines(ucell.ringds, 1e3, 1e4, color='red')\n", "ax.set(xlabel=r'$d^{*}~(\\AA^{-1})$', ylabel='Intensity', yscale='log', title='Peak filtration')\n", "ax.legend()\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Indexing\n", "Now we index the Friedel pair peaks"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["cosine_tol = np.cos(np.radians(90 - ds.ostep))\n", "_, indexer = utils.do_index(cf=cf_friedel_pairs,\n", " dstol=indexer_ds_tol,\n", " forgen=rings_for_gen,\n", " foridx=rings_for_scoring,\n", " hkl_tols=hkl_tols_seq,\n", " fracs=fracs,\n", " cosine_tol=cosine_tol,\n", " max_grains=max_grains,\n", " unitcell=ucell\n", ")"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["indexer.histogram_drlv_fit()\n", "fig, ax = plt.subplots(layout='constrained', figsize=(10, 5))\n", "for row in indexer.histogram:\n", " ax.plot(indexer.bins[1:-1], row[:-1],'-')\n", "ax.set(xlabel='Peak error', ylabel='npeaks')\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {"tags": []}, "source": ["# Grain refinement"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["nproc = max( ImageD11.cImageD11.cores_available() - 1 , 1)\n", "omega_slop = ds.ostep/2\n", "gridpars['TOLSEQ'] = [hkl_tols_seq[0],]\n", "gridpars['COSTOL'] = np.cos(np.radians(90 - ds.ostep))\n", "gridpars['NPROC'] = nproc\n", "gridpars['NTHREAD'] = 1\n", "gridpars['OMEGAFLOAT'] = omega_slop\n", "gridpars['SYMMETRY'] = symmetry\n", "gridpars['RING1'] = rings_for_gen\n", "gridpars['RING2'] = rings_for_gen\n", "cf_indexed = indexer.colfile.copy()\n", "cf_indexed.addcolumn(indexer.ga.copy(), 'labels')\n", "cf_indexed.addcolumn(np.zeros(cf_indexed.nrows), 'drlv2')\n", "for v in 'xyz':\n", " cf_3d.parameters.stepsizes[f't_{v}'] = 0.1\n", "fittedgrains = []\n", "for i in range(len(indexer.ubis)):\n", " grains = [ImageD11.grain.grain(indexer.ubis[i].copy() ),]\n", " # only take indexed spots using Friedel pairs\n", " cfit = ImageD11.columnfile.colfile_from_dict(\n", " { t:cf_indexed[t][indexer.ga==i+1] for t in cf_indexed.titles} )\n", " if cfit.nrows == 0:\n", " continue\n", " fitted = ImageD11.grid_index_parallel.domap( cf_3d.parameters,\n", " cfit,\n", " grains,\n", " gridpars )\n", " if len(fitted) > 0:\n", " fittedgrains.append( fitted[0] )"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_grain_positions(fittedgrains, colour='npks', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["fig, ax = plt.subplots(figsize=(10, 7), layout='constrained')\n", "ax.hist([float(grain.npks) for grain in fittedgrains], bins=30)\n", "ax.set(xlabel='Number of peaks per grain', ylabel='Count', title='Histogram of peaks per grain')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# filter out grains with fewer than absolute_minpks peaks\n", "# most grains should have a high number of peaks\n", "# choose absolute_minpks such that the low-peak grains are removed\n", "grains_filtered = [grain for grain in fittedgrains if float(grain.npks) > absolute_minpks]"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["utils.plot_grain_positions(grains_filtered, colour='npks', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["filtered_map_path = 'nice_grains.map'\n", "ImageD11.grain.write_grain_file(filtered_map_path, grains_filtered)"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# run makemap again against all peaks\n", "new_filtered_map_path = 'nice_grains.map.new'\n", "new_cf_3d_path = cf_3d_path + '.new'\n", "final_makemap_tol = hkl_tols_seq[0]\n", "oldparfile = phase_str + '.par'\n", "ds.phases.to_old_pars_file(oldparfile, phase_str)\n", "makemap_output = !makemap.py -p {oldparfile} -u {filtered_map_path} -U {new_filtered_map_path} -f {cf_3d_path} -s {symmetry} -t {final_makemap_tol} --omega_slop={omega_slop} --no_sort\n", "grains_final = ImageD11.grain.read_grain_file(new_filtered_map_path)\n", "cf_3d = ImageD11.columnfile.columnfile(new_cf_3d_path)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_grain_positions(grains_final, colour='npks', centre_plot=False, size_scaling=0.5)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["utils.plot_grain_histograms(new_cf_3d_path, new_filtered_map_path, oldparfile, omega_slop, tol=hkl_tols_seq[0])"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["unit_cell_lengths = np.array([np.sort(g.unitcell.copy()) for g in grains_final])\n", "median_unit_cell = np.median(unit_cell_lengths, axis=0)\n", "print(\"Median unit cell:\", median_unit_cell)\n", "fig, ax = plt.subplots(constrained_layout=True)\n", "ax.plot(unit_cell_lengths[:,:3])\n", "ax.hlines(median_unit_cell[:3], 0, len(unit_cell_lengths))\n", "ax.set(xlabel=\"Grain ID\", ylabel=\"Unit cell length\")\n", "plt.show()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Export Data"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["# write 3D columnfile to disk\n", "ImageD11.columnfile.colfile_to_hdf(cf_3d, ds.col3dfile, name='peaks')\n", "ds.save_grains_to_disk(grains_final, phase_name=phase_str)\n", "ds.save()"]}, {"cell_type": "markdown", "metadata": {}, "source": ["# Deleting temporary files"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["for path in [\n", " cf_3d_path,\n", " filtered_map_path,\n", " new_filtered_map_path,\n", " new_cf_3d_path,\n", "]:\n", " if os.path.exists(path):\n", " os.remove(path)"]}], "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}