{"cells": [{"cell_type": "markdown", "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "source": ["# Notebook to fit y0\n", "\n", "The idea behind this is similar to the idea in DCT and here https://doi.org/10.1107/S1600576724009634, where Friedel pairs are used to locate where diffraction spots come from in space. In those cases we use peaks that are 180 degrees apart. This notebook is looking for peaks that are separated by twotheta. These are the peaks we use in the friedel_rois macro at ID11 that aligns grains on the centre of rotation.\n", "\n", "The pairs we use will have:\n", "- eta -> -eta\n", "- tth -> tth\n", "- gve -> -gve\n", "\n", "Jon Wright. March 2025."]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [ImageD11/nbGui/S3DXRD/fit_y0.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/ImageD11/nbGui/S3DXRD/fit_y0.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": ["parameters"]}, "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", "dset_path = 'si_cube_test/processed/Si_cube/Si_cube_S3DXRD_nt_moves_dty/Si_cube_S3DXRD_nt_moves_dty_dataset.h5'\n", "\n", "par_file = None\n", "# manual override of y0 (ignores any value saved in dataset)\n", "y0_manual = None\n", "# or y0_manual = 0.0 (typical NSCOPE) or 13.5 (typical TDXRD)\n", "is_half_scan = False\n", "# need to know for automatic y0 guessing from scan ranges.\n", "\n", "gvtol = 0.002 # value is often OK"]}, {"cell_type": "code", "execution_count": null, "metadata": {"editable": true, "slideshow": {"slide_type": ""}, "tags": []}, "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 numpy as np\n", "import matplotlib.pyplot as plt\n", "import scipy.spatial\n", "import ImageD11.sinograms.dataset\n", "from ImageD11.sinograms.geometry import recon_bins\n", "from tqdm.autonotebook import tqdm\n", "from scipy.optimize import curve_fit\n", "\n", "%matplotlib ipympl"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ds = ImageD11.sinograms.dataset.load(dset_path)\n", "print(ds)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["if par_file is not None:\n", " # only change if ds has no parfile\n", " if not hasattr(ds, 'parfile') or ds.parfile is None:\n", " ds.parfile = par_file\n", " ds.save()"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["cf_4d = ds.get_cf_4d()\n", "ds.update_colfile_pars(cf_4d)\n", "print(cf_4d.nrows/1e6, \"million peaks read in\")"]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["def find_pairs_minus_eta(cf, gvtol=0.002, doplot=False):\n", " \"\"\"\n", " Locate Friedel pairs with eta -> -eta and g -> -g.\n", " Returns ip, im == indices for eta+ and eta- pairs.\n", " \"\"\"\n", " fp = np.flatnonzero(cf.eta > 0) # was np.mgrid[0:cf.nrows][cf_4d.eta > 0]\n", " fm = np.flatnonzero(cf.eta < 0)\n", " kdp = scipy.spatial.cKDTree( np.transpose((cf.gx[fp], cf.gy[fp], cf.gz[fp])) )\n", " kdm = scipy.spatial.cKDTree( -np.transpose((cf.gx[fm], cf.gy[fm], cf.gz[fm])) )\n", " coo = kdp.sparse_distance_matrix(kdm, gvtol, output_type='coo_matrix')\n", " if doplot:\n", " fig, ax = plt.subplots()\n", " ax.hist(coo.data.flat, bins=500)\n", " ax.set(xlabel='gvtol', ylabel='count')\n", " plt.show()\n", " return fp[coo.row], fm[coo.col]\n", "\n", "\n", "def locate_pairs_affine(cf, pairs):\n", " \"\"\"\n", " ImageD11.sinograms.geometry.dty_values_grain_in_beam_sincos gives:\n", " dty - y0 = -sx sin(w) -sy cos(w)\n", " \n", " Define:\n", " s = [ sx ], R = [ -sin(w1) -cos(w1) ], d = [ dty1 ], 1 = [ 1 ]\n", " [ sy ] [ -sin(w2) -cos(w2) ] [ dty2 ] [ 1 ]\n", "\n", " Now we can write:\n", " R . s = d - y0 * 1\n", " which is equivalent to the original geometry equation.\n", " Rearranging gives:\n", " s = R^-1 . (d - y0 * 1)\n", " expanding:\n", " s = (R^-1 . d) - y0 * (R^-1 . 1)\n", " which is possible because y0 is independent of R.\n", " We define:\n", " s0 = R^-1 . d\n", " v = R^-1 . 1\n", " Therefore:\n", " s = s0 - y0 * v\n", " This is a function of y0: s(y0) = s0 - y0 * v\n", " Which can be evaluated for any value of y0.\n", " Now we need to solve for s0 and v.\n", " We can form matrices:\n", " [ s0 | v ] and [ d | 1 ]\n", " such that:\n", " R . [ s0 | v ] = [ d | 1 ]\n", " We can solve this once and determine s0 and v given R and d.\n", " This whole thing happens over N pairs.\n", "\n", " Returns s0, v, each shape (2, N) == (sx-row, sy-row) over all pairs.\n", " \"\"\"\n", " i1, i2 = pairs\n", " r = np.radians(cf.omega)\n", " so, co = np.sin(r), np.cos(r)\n", " # Per-pair 2x2 matrix R, stacked over N pairs -> (N,2,2)\n", " R = np.transpose(((-so[i1], -co[i1]),\n", " (-so[i2], -co[i2])), axes=(2, 0, 1)) # (N,2,2)\n", " # Data vector d = [dty_i1; dty_i2] per pair (the RHS when y0 = 0)\n", " d = np.transpose((cf.dty[i1], # (N,2)\n", " cf.dty[i2])) \n", " # Right-hand-side matrix\n", " rhs = np.stack([d, np.ones_like(d)], axis=-1) # (N,2,2): [d | 1]\n", " # Solve R . [s0 | v] = [d | 1];\n", " sol = np.linalg.solve(R, rhs) # (N,2,2): [s0 | v]\n", " s0 = sol[..., 0].T # (2,N) == R^-1 . d\n", " v = sol[..., 1].T # (2,N) == R^-1 . 1 \n", " return s0, v\n", "\n", "\n", "def locate_pairs(cf, pairs, y0=0.):\n", " \"\"\"\n", " Fit the centre of mass position of the pairs\n", " cf = colfile\n", " pairs = (ip, im) = indices of low, high pair in cf\n", "\n", " Uses the affine form s(y0) = s0 - y0*v (see locate_pairs_affine), so the\n", " linear solve is done once and evaluating at a given y0 is just a\n", " multiply-and-subtract.\n", "\n", " Returns sx, sy == sample x and y co-ordinates of the peak-pair\n", " \"\"\"\n", " s0, v = locate_pairs_affine(cf, pairs)\n", " sx, sy = s0 - y0 * v\n", " return (sx, sy)\n", "\n", "def fit_y0(cf, pairs, y0s, npks=100_000, nbx=256, nby=256,\n", " fit_window=15, seed=0, doplot=False):\n", " \"\"\"\n", " Find the beam-centre offset y0 that best focuses the pair reconstruction,\n", " i.e. maximises the standard deviation of the 2D histogram of (sx, sy).\n", "\n", " Sweeps y0s on a subsample using the affine relation s(y0) = s0 - y0*v\n", " (no per-y0 solve), scores every y0 on one fixed grid via a single\n", " bincount, then fits a parabola to the peak for sub-grid-step resolution.\n", "\n", " Parameters\n", " ----------\n", " cf : ImageD11 columnfile\n", " pairs : (ip, im) arrays of cf indices for each pair\n", " y0s : array of y0 values to scan\n", " npks : max pairs to subsample (peak location scales like 1/sqrt(n))\n", " nbx, nby : fixed grid size used for scoring\n", " fit_window : points either side of the argmax for the parabola fit\n", " seed : rng seed for the subsample\n", " doplot : draw the stdev curve, fit, and vertex\n", "\n", " Returns\n", " -------\n", " best_y0 : float, the fitted optimum\n", " y0s : the scan grid (unchanged)\n", " stdevs : stdev of the fixed-grid histogram at each y0\n", " \"\"\"\n", " s0, v = locate_pairs_affine(cf, pairs)\n", " y0s = np.asarray(y0s)\n", " n_y0 = len(y0s)\n", "\n", " # subsample the pairs\n", " rng = np.random.default_rng(seed)\n", " N = s0.shape[1]\n", " n_sub = min(N, npks)\n", " sub = rng.choice(N, n_sub, replace=False) if N > n_sub else slice(None)\n", " s0x, s0y = s0[0, sub], s0[1, sub]\n", " vx, vy = v[0, sub], v[1, sub]\n", "\n", " # point positions over the whole sweep: (n_sub, n_y0)\n", " sx = s0x[:, None] - y0s[None, :] * vx[:, None]\n", " sy = s0y[:, None] - y0s[None, :] * vy[:, None]\n", "\n", " # one fixed grid for every y0 (robust extent so outliers don't blow it up)\n", " xlo, xhi = np.percentile(sx, [0.05, 99.95])\n", " ylo, yhi = np.percentile(sy, [0.05, 99.95])\n", " xedges = np.linspace(xlo, xhi, nbx + 1)\n", " yedges = np.linspace(ylo, yhi, nby + 1)\n", "\n", " ix = np.searchsorted(xedges, sx, 'right') - 1\n", " iy = np.searchsorted(yedges, sy, 'right') - 1\n", " ok = (ix >= 0) & (ix < nbx) & (iy >= 0) & (iy < nby) # drops out-of-grid, like histogram2d\n", "\n", " col = np.broadcast_to(np.arange(n_y0), sx.shape)\n", " flat = col[ok] * (nbx * nby) + ix[ok] * nby + iy[ok] # (y0, bin) -> one index\n", " counts = np.bincount(flat, minlength=n_y0 * nbx * nby).reshape(n_y0, nbx * nby)\n", "\n", " B = nbx * nby\n", " sumsq = np.einsum('ij,ij->i', counts, counts).astype(float) # \u03a3c\u00b2 per y0\n", " Ncol = counts.sum(1) # in-grid points per y0\n", " stdevs = np.sqrt(sumsq / B - (Ncol / B) ** 2) # == std of the 2D hist\n", "\n", " # parabola fit to the peak -> sub-grid-step vertex\n", " k = np.argmax(stdevs)\n", " lo, hi = max(0, k - fit_window), min(n_y0, k + fit_window + 1)\n", " a, b, c = np.polyfit(y0s[lo:hi], stdevs[lo:hi], 2)\n", " best_y0 = -b / (2 * a)\n", "\n", " if doplot:\n", " best_std = np.polyval((a, b, c), best_y0)\n", " y0_fit = np.linspace(y0s[lo], y0s[hi - 1], 200)\n", " fig, ax = plt.subplots()\n", " ax.plot(y0s, stdevs, label='stdev')\n", " ax.plot(y0_fit, np.polyval((a, b, c), y0_fit),\n", " color='red', ls='--', label='parabola fit')\n", " ax.axvspan(y0s[lo], y0s[hi - 1], color='red', alpha=0.08)\n", " ax.axvline(best_y0, color='red', label=f'best_y0 = {best_y0:.3f}')\n", " ax.plot(best_y0, best_std, 'ro')\n", " ax.set(xlabel='y0', ylabel='stdev')\n", " ax.legend()\n", " plt.show()\n", "\n", " return best_y0, y0s, stdevs"]}, {"cell_type": "markdown", "metadata": {}, "source": ["The next cell is locating the Friedel pairs. It seems to need about 1 second per million peaks."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["ip, im = find_pairs_minus_eta( cf_4d, gvtol=gvtol, doplot=True )\n", "print('Got',len(ip),'pairs from',cf_4d.nrows,'peaks, fraction paired =',len(ip)*2/cf_4d.nrows )"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# Priority order (decreasing)\n", "# manual override in first cell\n", "# ds attribute\n", "\n", "# fails if no y0 provided at all\n", "\n", "if y0_manual is not None:\n", " print('Using manually supplied y0')\n", " y0_guess = y0_manual\n", "else:\n", " if hasattr(ds, 'y0') and ds.y0 is not None:\n", " print('Using ds.y0')\n", " y0_guess = ds.y0\n", " else:\n", " # not using manual y0, and couldn't find one. guess it from ymax/ymin\n", " if not is_half_scan:\n", " y0_guess = (ds.ymax + ds.ymin)/2\n", " else:\n", " # half scan, not sure\n", " raise ValueError('You must manually supply a y0 value in the first cell to continue.')\n", "print('Using y0:', y0_guess)"]}, {"cell_type": "markdown", "metadata": {}, "source": ["Now fit the positions with the y0 guess. Should be faster than finding the pairs."]}, {"cell_type": "code", "execution_count": null, "metadata": {"tags": []}, "outputs": [], "source": ["sx, sy = locate_pairs( cf_4d, (ip,im), y0 = y0_guess )\n", "bin_edges_guess, bin_centres_guess = recon_bins(ds.ybincens, ds.ymin, ds.ystep, y0_guess)\n", "hist_guess = np.histogram2d(sx, sy, bins=bin_edges_guess)[0]"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained', figsize=(8,8))\n", "ax.pcolormesh(bin_edges_guess, bin_edges_guess, hist_guess)\n", "ax.set_aspect(1)\n", "ax.set(title=f'y0 guess: {y0_guess}', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# now we try this with a range of y0 guesses, and look for peaks in the standard deviation"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# guess += 5 from y0_guess, you can change this as needed\n", "y0_min = y0_guess - 5\n", "y0_max = y0_guess + 5\n", "n_y0 = 200\n", "y0s = np.linspace(y0_min, y0_max, n_y0)\n", "\n", "# choose how many peaks to use to fit - this is faster than using the full array\n", "npks = 500_000 "]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["%%time\n", "\n", "best_y0, y0s, stdevs = fit_y0(cf_4d, (ip, im), y0s, npks=npks, doplot=True, fit_window=30)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# take the results of the Laplace fit:\n", "y0_final = best_y0\n", "# or manually override from your interpretation of the plot:\n", "# y0_final = 0\n", "print(y0_final)"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["sx, sy = locate_pairs( cf_4d, (ip,im), y0 = y0_final )\n", "bin_edges_final, bin_centres_final = recon_bins(ds.ybincens, ds.ymin, ds.ystep, y0_final)\n", "hist_final = np.histogram2d(sx, sy, bins=bin_edges_final)[0]"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["fig, ax = plt.subplots(layout='constrained', figsize=(8,8))\n", "ax.pcolormesh(bin_edges_final, bin_edges_final, hist_final)\n", "ax.set_aspect(1)\n", "ax.set(title=f'y0 final: {y0_final}', xlabel='Sample Y axis -->', ylabel='Sample X axis -->')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["fig, axs = plt.subplots(1, 2, layout='constrained', figsize=(12,6), sharex=True, sharey=True)\n", "axs[0].pcolormesh(bin_edges_guess, bin_edges_guess, hist_guess)\n", "axs[0].set_aspect(1)\n", "axs[0].set(title=f'y0 guess: {y0_guess}')\n", "axs[1].pcolormesh(bin_edges_final, bin_edges_final, hist_final)\n", "axs[1].set_aspect(1)\n", "axs[1].set(title=f'y0 final: {y0_final}')\n", "fig.supxlabel('Sample Y axis -->')\n", "fig.supylabel('Sample X axis -->')\n", "plt.show()"]}, {"cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": ["# save final result to disk\n", "ds.y0 = y0_final\n", "ds.save()"]}], "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}