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