{"cells": [{"cell_type": "markdown", "id": "8cf5cf9d", "metadata": {}, "source": ["# Choosing twin variants from intensities\n", "\n", "Peak positions only depend on the lattice. When the lattice has more symmetry than the Laue class\n", "of the crystal, indexing returns each grain in one of several orientations that put every peak in\n", "the same place: the **twin variants**. Only the intensities tell them apart.\n", "\n", "| function | role |\n", "|---|---|\n", "| `sym_u.lattice_group(sg)` | lattice symmetry from the space group number |\n", "| `sym_u.twin_operators(sg)` | one operator per twin variant (\"flipmats\") |\n", "| `refinegrains.best_twin_variant` | choice with a known structure (CIF) |\n", "| `refinegrains.consistent_twin_variants` | choice without a structure: R-merge across grains |\n", "| `StructureFactorCorrection.from_cif` | \\|F\\|\u00b2 of every reflection from a CIF (needs Dans_Diffraction) |\n", "\n", "Example: synthetic quartz (P3$_2$21, space group 154). Laue class $\\bar{3}m1$, hexagonal lattice\n", "$6/mmm$: the 180\u00b0 rotation about **c** (Dauphin\u00e9 twin law) gives two variants per grain.\n", "The random numbers come from a fixed seed, so every run gives the same result."]}, {"cell_type": "markdown", "metadata": {}, "source": "Source: [docs/twin_variants.ipynb](https://github.com/FABLE-3DXRD/ImageD11/blob/master/docs/twin_variants.ipynb). Shown as saved in git; the documentation build does not run it."}, {"cell_type": "code", "execution_count": null, "id": "e24827c2", "metadata": {}, "outputs": [], "source": ["import contextlib\n", "import io\n", "import os\n", "import tempfile\n", "\n", "import matplotlib.pyplot as plt\n", "import numpy as np\n", "from scipy.spatial.transform import Rotation\n", "\n", "import ImageD11.columnfile\n", "import ImageD11.grain\n", "import ImageD11.indexing\n", "import ImageD11.refinegrains\n", "import ImageD11.sym_u\n", "import ImageD11.unitcell\n", "from ImageD11 import transform\n", "from ImageD11.refinegrains import lf, polarization\n", "from ImageD11.sinograms.sinogram import StructureFactorCorrection\n", "\n", "rng = np.random.RandomState(2026)\n", "work = tempfile.mkdtemp(prefix=\"twin_variants_\")"]}, {"cell_type": "markdown", "id": "5ae00c2d", "metadata": {}, "source": ["## Structure, geometry and symmetry"]}, {"cell_type": "code", "execution_count": null, "id": "82eda2fd", "metadata": {}, "outputs": [], "source": ["QUARTZ_CIF = \"\"\"data_alpha_quartz\n", "_cell_length_a 4.9134\n", "_cell_length_b 4.9134\n", "_cell_length_c 5.4052\n", "_cell_angle_alpha 90\n", "_cell_angle_beta 90\n", "_cell_angle_gamma 120\n", "_symmetry_space_group_name_H-M 'P 32 2 1'\n", "_symmetry_Int_Tables_number 154\n", "loop_\n", "_symmetry_equiv_pos_as_xyz\n", "x,y,z\n", "-y,x-y,z+2/3\n", "-x+y,-x,z+1/3\n", "y,x,-z\n", "x-y,-y,-z+1/3\n", "-x,-x+y,-z+2/3\n", "loop_\n", "_atom_site_label\n", "_atom_site_type_symbol\n", "_atom_site_fract_x\n", "_atom_site_fract_y\n", "_atom_site_fract_z\n", "Si1 Si 0.4697 0.0000 0.16667\n", "O1 O 0.4135 0.2669 0.28577\n", "\"\"\"\n", "cif_path = os.path.join(work, \"quartz.cif\")\n", "with open(cif_path, \"w\") as f:\n", " f.write(QUARTZ_CIF)\n", "SPACEGROUP = 154\n", "CELL = [4.9134, 4.9134, 5.4052, 90, 90, 120]\n", "\n", "# 2048 x 2048 detector, 47.3 um pixels at 282 mm, 0.2249 Angstrom\n", "GEOMETRY = {\n", " \"chi\": 0.2, \"wedge\": -0.3, \"tilt_x\": 0.004, \"tilt_y\": -0.0012, \"tilt_z\": 0.008,\n", " \"distance\": 282411.0, \"y_center\": 1005.27, \"z_center\": 1009.2, \"y_size\": 47.3, \"z_size\": 47.3,\n", " \"o11\": 1, \"o12\": 0, \"o21\": 0, \"o22\": -1, \"omegasign\": 1.0, \"wavelength\": 0.2249,\n", " \"t_x\": 0.0, \"t_y\": 0.0, \"t_z\": 0.0,\n", "}\n", "NPIX = 2048\n", "TTH_MAX = np.degrees(np.arctan(1.2 * np.hypot(NPIX * 47.3, NPIX * 47.3) / 2 / GEOMETRY[\"distance\"]))\n", "sfc = StructureFactorCorrection.from_cif(cif_path, wavelength=GEOMETRY[\"wavelength\"], tth_max=TTH_MAX)\n", "\n", "lattice = ImageD11.sym_u.lattice_group(SPACEGROUP) # 6/mmm: what indexing sees\n", "laue = ImageD11.sym_u.laue_rotations(SPACEGROUP) # -3m1: what the intensities obey\n", "ops = ImageD11.sym_u.twin_operators(SPACEGROUP) # identity and the Dauphine 2-fold\n", "print(len(ops), \"twin variants, operators:\\n\", np.array(ops).astype(int))"]}, {"cell_type": "markdown", "id": "b82d7e99", "metadata": {}, "source": ["## Synthetic peaks\n", "12 grains with random orientations, positions (\u00b1200 \u00b5m) and volumes. Intensity = volume \u00d7 |F|\u00b2 \u00d7\n", "polarization / `lf` with 5 % noise; reflections below 0.5 % of the strongest are not kept."]}, {"cell_type": "code", "execution_count": null, "id": "5be51276", "metadata": {}, "outputs": [], "source": ["NGRAINS = 12\n", "B = ImageD11.unitcell.unitcell(CELL, SPACEGROUP).B\n", "U = Rotation.random(NGRAINS, random_state=rng).as_matrix()\n", "truth = [{\"ubi\": np.linalg.inv(np.dot(U[i], B)), \"pos\": rng.uniform(-200, 200, 3),\n", " \"volume\": rng.uniform(0.3, 3.0)} for i in range(NGRAINS)]\n", "\n", "uc = ImageD11.unitcell.unitcell(CELL, SPACEGROUP)\n", "uc.makerings(2 * np.sin(np.radians(TTH_MAX / 2)) / GEOMETRY[\"wavelength\"])\n", "hkls = np.array([h for ds in uc.ringds for h in uc.ringhkls[ds]]).T\n", "f2 = sfc.sf_values(hkls) * sfc.valid_mask(hkls)\n", "keep = f2 > 0.005 * f2.max()\n", "\n", "columns = {k: [] for k in (\"sc\", \"fc\", \"omega\", \"sum_intensity\")}\n", "for g in truth:\n", " tth, eta, omega = transform.uncompute_g_vectors(np.dot(np.linalg.inv(g[\"ubi\"]), hkls[:, keep]),\n", " GEOMETRY[\"wavelength\"], GEOMETRY[\"wedge\"], GEOMETRY[\"chi\"])\n", " ok = tth > 0\n", " for k in range(2): # the two diffraction solutions\n", " t, e, o = tth[ok], eta[k][ok], omega[k][ok] % 360\n", " fc, sc = transform.compute_xyz_from_tth_eta(\n", " t, e, o, **dict(GEOMETRY, t_x=g[\"pos\"][0], t_y=g[\"pos\"][1], t_z=g[\"pos\"][2]))\n", " on = (sc > 0) & (sc < NPIX) & (fc > 0) & (fc < NPIX)\n", " inten = g[\"volume\"] * f2[keep][ok] * polarization(t, e) / lf(t, e) * rng.normal(1, 0.05, ok.sum())\n", " for name, v in zip((\"sc\", \"fc\", \"omega\", \"sum_intensity\"), (sc, fc, o, inten)):\n", " columns[name].append(v[on])\n", "\n", "peaks = {k: np.concatenate(v) for k, v in columns.items()}\n", "peaks[\"Number_of_pixels\"] = np.full(len(peaks[\"sc\"]), 10.0)\n", "cf = ImageD11.columnfile.colfile_from_dict(peaks)\n", "cf.parameters.parameters.update(GEOMETRY)\n", "cf.parameters.parameters.update({\"cell__a\": CELL[0], \"cell__b\": CELL[1], \"cell__c\": CELL[2],\n", " \"cell_alpha\": CELL[3], \"cell_beta\": CELL[4], \"cell_gamma\": CELL[5],\n", " \"cell_lattice_[P,A,B,C,I,F,R]\": SPACEGROUP})\n", "cf.updateGeometry()\n", "print(cf.nrows, \"peaks\")"]}, {"cell_type": "markdown", "id": "1d13fac4", "metadata": {}, "source": ["## Indexing in the lattice group\n", "Each UBI is reduced in the lattice group, so every grain comes back once, in an arbitrary twin\n", "variant. `refinegrains` then refines orientations and positions and labels the peaks."]}, {"cell_type": "code", "execution_count": null, "id": "432c2689", "metadata": {}, "outputs": [], "source": ["par_file, flt_file, ubi_file = [os.path.join(work, n) for n in (\"quartz.par\", \"peaks.flt\", \"indexed.ubi\")]\n", "omega_slop, hkl_tol = 0.25, 0.05\n", "log = io.StringIO() # ImageD11 prints a lot\n", "with contextlib.redirect_stdout(log):\n", " uc.makerings(cf.ds.max())\n", " grains, _ = ImageD11.indexing.do_index(cf=cf, unitcell=uc, forgen=[0, 1], foridx=[0, 1, 2, 3, 4],\n", " dstol=0.005, hkl_tols=(0.01, 0.025, 0.05), fracs=(0.9, 0.7))\n", " for g in grains:\n", " g.set_ubi(ImageD11.sym_u.find_uniq_u(g.ubi, lattice))\n", " cf.parameters.saveparameters(par_file)\n", " cf.writefile(flt_file)\n", " ImageD11.grain.write_grain_file(ubi_file, grains)\n", " refined = ImageD11.refinegrains.refinegrains(tolerance=hkl_tol, intensity_tth_range=(0, 180), OmSlop=omega_slop)\n", " refined.loadparameters(par_file)\n", " refined.loadfiltered(flt_file)\n", " refined.readubis(ubi_file)\n", " refined.generate_grains()\n", " refined.refinepositions()\n", " refined.assignlabels(quiet=True)\n", "# print(log.getvalue()) # uncomment to see the ImageD11 output\n", "\n", "# peaks of each grain, g-vectors seen from the grain position\n", "scan = refined.scannames[0]\n", "sd = refined.scandata[scan]\n", "found = []\n", "for gname in refined.grainnames:\n", " gr = refined.grains[(gname, scan)]\n", " pk = sd.copy()\n", " pk.filter(sd.labels == int(gname))\n", " pk.updateGeometry(translation=gr.translation)\n", " found.append({\"ubi\": gr.ubi.copy(), \"pos\": np.array(gr.translation), \"gv\": np.array((pk.gx, pk.gy, pk.gz)).T,\n", " \"intensity\": pk.sum_intensity, \"tth\": pk.tth, \"eta\": pk.eta, \"npeaks\": pk.nrows})\n", "\n", "\n", "def related(ubi_a, ubi_b, group):\n", " \"\"\"ubi_a = M ubi_b with M an integer matrix in group.\"\"\"\n", " M = np.dot(ubi_a, np.linalg.inv(ubi_b))\n", " return np.abs(M - M.round()).max() < 0.05 and group.isMember(M.round())\n", "\n", "\n", "def true_variant(ubi, pos):\n", " \"\"\"True if ubi is the true orientation (up to the Laue class) of the grain at pos.\"\"\"\n", " return any(related(ubi, t[\"ubi\"], laue) and np.linalg.norm(pos - t[\"pos\"]) < 50 for t in truth)\n", "\n", "\n", "print(len(found), \"grains; true variant after indexing:\", sum(true_variant(f[\"ubi\"], f[\"pos\"]) for f in found))"]}, {"cell_type": "markdown", "id": "44edf131", "metadata": {}, "source": ["## With a CIF: `best_twin_variant`\n", "Intensities corrected by `lf` / `polarization` and correlated with the |F|\u00b2 each variant predicts."]}, {"cell_type": "code", "execution_count": null, "id": "15c8fff1", "metadata": {}, "outputs": [], "source": ["for f in found:\n", " f[\"best_ubi\"], f[\"best_scores\"] = ImageD11.refinegrains.best_twin_variant(\n", " f[\"ubi\"], f[\"gv\"], f[\"intensity\"], f[\"tth\"], f[\"eta\"], SPACEGROUP, sfc)\n", "print(\"true variant:\", sum(true_variant(f[\"best_ubi\"], f[\"pos\"]) for f in found), \"of\", len(found))"]}, {"cell_type": "markdown", "id": "fc50410a", "metadata": {}, "source": ["## Without a CIF: `consistent_twin_variants`\n", "The grain with most peaks is the reference; every other grain takes the variant with the lowest\n", "R-merge against the merged reflections. All grains then agree, but only with the reference: if it\n", "was in the twin variant, all are. One `best_twin_variant` call on the reference fixes that when a\n", "CIF is available."]}, {"cell_type": "code", "execution_count": null, "id": "a48124d9", "metadata": {}, "outputs": [], "source": ["corrected = [f[\"intensity\"] * lf(f[\"tth\"], f[\"eta\"]) / polarization(f[\"tth\"], f[\"eta\"]) for f in found]\n", "chosen, choice, rmerge = ImageD11.refinegrains.consistent_twin_variants(\n", " [f[\"ubi\"] for f in found], [f[\"gv\"] for f in found], corrected, SPACEGROUP)\n", "n_true = sum(true_variant(c, f[\"pos\"]) for c, f in zip(chosen, found))\n", "print(\"R-merge alone: true variant for %d of %d (all grains agree: %s)\" % (n_true, len(found), n_true in (0, len(found))))\n", "\n", "ref = int(np.argmax([f[\"npeaks\"] for f in found]))\n", "ref_best, _ = ImageD11.refinegrains.best_twin_variant(chosen[ref], found[ref][\"gv\"], found[ref][\"intensity\"],\n", " found[ref][\"tth\"], found[ref][\"eta\"], SPACEGROUP, sfc)\n", "if not related(ref_best, chosen[ref], laue): # the reference is in the twin variant: flip all\n", " chosen = [np.dot(ops[1], c) for c in chosen]\n", "print(\"R-merge + CIF on the reference: true variant for %d of %d\" % (\n", " sum(true_variant(c, f[\"pos\"]) for c, f in zip(chosen, found)), len(found)))"]}, {"cell_type": "markdown", "id": "1fa17db7", "metadata": {}, "source": ["### Scores\n", "One column per grain: the filled dot is the chosen variant (green if it is the true one), the open dot\n", "the other variant. The longer the grey line, the clearer the choice. Higher is better for the\n", "correlation, lower for the R-merge."]}, {"cell_type": "code", "execution_count": null, "id": "daca39b1", "metadata": {}, "outputs": [], "source": ["x = np.arange(len(found))\n", "fig, ax = plt.subplots(1, 2, figsize=(12, 4.5), layout='constrained')\n", "panels = [(np.array([f[\"best_scores\"] for f in found]), \"best_twin_variant\", \"corr(I, |F|\u00b2)\", np.nanargmax),\n", " (rmerge, \"consistent_twin_variants\", \"R-merge\", np.nanargmin)]\n", "for a, (s, title, ylabel, pick) in zip(ax, panels):\n", " col = pick(s, axis=1)\n", " right = np.array([true_variant(np.dot(ops[c], f[\"ubi\"]), f[\"pos\"]) for c, f in zip(col, found)])\n", " a.vlines(x, s.min(axis=1), s.max(axis=1), color='lightgrey')\n", " a.scatter(x, s[x, 1 - col], facecolors='none', edgecolors='grey', label='other variant')\n", " a.scatter(x[right], s[x, col][right], color='tab:green', label='chosen = true variant')\n", " a.scatter(x[~right], s[x, col][~right], color='tab:red', label='chosen = twin variant')\n", " a.set(xlabel='grain', ylabel=ylabel, title=title, xticks=x)\n", "handles, labels = ax[0].get_legend_handles_labels()\n", "handles2, labels2 = ax[1].get_legend_handles_labels()\n", "for h, l in zip(handles2, labels2):\n", " if l not in labels:\n", " handles.append(h)\n", " labels.append(l)\n", "fig.legend(handles, labels, loc='outside lower center', ncol=3)\n", "plt.show()"]}, {"cell_type": "markdown", "id": "3bf4c6b7", "metadata": {}, "source": ["## Store the grains with their labelled peaks\n", "Write the chosen variants and run makemap as in the TDXRD notebooks. **Give makemap the Laue class\n", "(`-s`), not the lattice group**: makemap calls `makeuniq(symmetry)`, and with the lattice group it puts\n", "every grain back into an arbitrary variant."]}, {"cell_type": "code", "execution_count": null, "id": "95a22b41", "metadata": {}, "outputs": [], "source": ["map_path = os.path.join(work, \"grains_twin.map\")\n", "ImageD11.grain.write_grain_file(map_path, [ImageD11.grain.grain(f[\"best_ubi\"], translation=f[\"pos\"]) for f in found])\n", "makemap_choices = (\"cubic\", \"hexagonal\", \"trigonalH\", \"trigonalP\", \"tetragonal\", \"orthorhombic\",\n", " \"monoclinic_a\", \"monoclinic_b\", \"monoclinic_c\", \"triclinic\")\n", "symmetry_laue = next(n for n in makemap_choices if ImageD11.sym_u.getgroup(n)() is laue)\n", "print(\"makemap symmetry:\", symmetry_laue)"]}, {"cell_type": "code", "execution_count": null, "id": "63abaa09", "metadata": {}, "outputs": [], "source": ["makemap_output = !makemap.py -p {par_file} -u {map_path} -U {map_path} -f {flt_file} -F {flt_file}.unindexed -s {symmetry_laue} -t {hkl_tol} --omega_slop={omega_slop} --no_sort\n", "cf_labelled = ImageD11.columnfile.columnfile(flt_file + \".new\") # labels column: grain of each peak\n", "grains_twin = ImageD11.grain.read_grain_file(map_path)\n", "print(\"stored in the true variant: %d of %d grains\" % (\n", " sum(true_variant(g.ubi, np.array(g.translation)) for g in grains_twin), len(grains_twin)))\n", "print(\"peaks with a grain label: %d of %d\" % ((cf_labelled.labels >= 0).sum(), cf_labelled.nrows))"]}], "metadata": {"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, "language_info": {"name": "python"}}, "nbformat": 4, "nbformat_minor": 5}