diff --git a/image_analysis/scale_merge/RotationScaleMerge.cpp b/image_analysis/scale_merge/RotationScaleMerge.cpp index fef918578..0ad713512 100644 --- a/image_analysis/scale_merge/RotationScaleMerge.cpp +++ b/image_analysis/scale_merge/RotationScaleMerge.cpp @@ -4478,6 +4478,104 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool resid * resid / factor, o.d}); } } + fit_error_model(samples); + + // ---- The error model refitted about the mean the merge takes. ---- + // The fit above is made about a mean that weighs each full by its COUNTING variance. Where the + // equivalents of a reflection agree to within counting statistics that is the merge's own centre, + // and the model it gives is the model the merge applies. Where they do not - a systematic error + // the counting variance does not know about - it is the wrong centre, and in the worst way: the + // full with the fewest counts has the smallest variance, so the mean, and every deviation the + // model is fitted on, is pulled toward the observations that read lowest. Measured on a strongly + // absorbing crystal whose equivalents spread over a factor 100: the mean of (0 4 0) sat at 21k + // among observations from 11k to 1.9M, the deviations of the rest read as hundreds of counting + // sigmas, a ran into its bound and the six-sigma test about the median taken with the same + // weights deleted 63% of the observations - the strong ones (SHELXL R1 0.50 on that merge). + // So refit about the mean the MERGE takes - each full weighted by the variance the fitted model + // gives it, evaluated at the reflection's mean - until the model stops moving; the outlier + // test's median below takes the same weights. Where counting statistics were right the first fit + // is the answer and nothing moves; where b dominates, the weights even out, as the model says. + // Following Blessing (1997) J. Appl. Cryst. 30, 421-426: the centre an outlier is judged from + // is weighted as the merge weighs. + if (error_model_active) { + // Fulls in group order, so each pass over a group's members is one contiguous walk and the + // groups split across threads without every thread reading every full. + std::vector gstart(n_groups + 1, 0); + for (int i = 0; i < n_full; ++i) + if (mf.group[i] >= 0 && cnt[mf.group[i]] >= 2) ++gstart[mf.group[i] + 1]; + for (int g = 0; g < n_groups; ++g) gstart[g + 1] += gstart[g]; + std::vector member(gstart[n_groups]); + { + std::vector fill(gstart.begin(), gstart.end() - 1); + for (int i = 0; i < n_full; ++i) + if (mf.group[i] >= 0 && cnt[mf.group[i]] >= 2) member[fill[mf.group[i]]++] = i; + } + std::vector next_mean; + std::vector next; + constexpr int REFIT_ROUNDS = 10; + for (int round = 0; round < REFIT_ROUNDS; ++round) { + const double a = error_model_a, b = error_model_b; + const auto model_var = [&](int i, double mean) { + const double sc = static_cast(mf.sigma[i]) * mf.corr[i]; + return a * counting_variance(fulls[i], mean, sc * sc) + (b * mean) * (b * mean); + }; + std::vector> part(ThreadsForWork(member.size(), nthreads)); + const int nt = static_cast(part.size()); + next_mean.assign(n_groups, NAN); + // Each group's mean and samples come from its own members in index order, so the result + // does not depend on how the groups were split. + ParallelFor(nt, nt, [&](int t) { + const int g0 = static_cast(static_cast(n_groups) * t / nt); + const int g1 = static_cast(static_cast(n_groups) * (t + 1) / nt); + for (int g = g0; g < g1; ++g) { + if (gstart[g + 1] - gstart[g] < 2 || !std::isfinite(em_mean[g])) continue; + double sw = 0.0, swI = 0.0, swh[2] = {0.0, 0.0}, swIh[2] = {0.0, 0.0}; + int nh[2] = {0, 0}; + for (int q = gstart[g]; q < gstart[g + 1]; ++q) { + const int i = member[q]; + const double v = model_var(i, em_mean[g]); + if (!(v > 0.0)) continue; + const double I_corr = static_cast(mf.I[i]) * mf.corr[i]; + sw += 1.0 / v; swI += I_corr / v; + if (merge_friedel && group_has_hands[g]) { + swh[obs_hand[i]] += 1.0 / v; swIh[obs_hand[i]] += I_corr / v; nh[obs_hand[i]]++; + } + } + if (!(sw > 0.0)) continue; + const double mean = swI / sw; + next_mean[g] = mean; + // The samples about the hand's own mean where it has two of its own, as above. + for (int q = gstart[g]; q < gstart[g + 1]; ++q) { + const int i = member[q]; + const double v = model_var(i, em_mean[g]); + if (!(v > 0.0)) continue; + const int hh = obs_hand[i]; + const bool on_hand = merge_friedel && group_has_hands[g] && nh[hh] >= 2 && swh[hh] > 0.0; + const double centre = on_hand ? swIh[hh] / swh[hh] : mean; + const double factor = 1.0 - (1.0 / v) / (on_hand ? swh[hh] : sw); + if (factor < 0.05) continue; + const double sc = static_cast(mf.sigma[i]) * mf.corr[i]; + const double resid = static_cast(mf.I[i]) * mf.corr[i] - centre; + part[t].push_back({counting_variance(fulls[i], mean, sc * sc), centre * centre, + resid * resid / factor, mf.d[i]}); + } + } + }); + for (int g = 0; g < n_groups; ++g) + if (!std::isfinite(next_mean[g])) next_mean[g] = em_mean[g]; + next.clear(); + for (auto &v : part) next.insert(next.end(), v.begin(), v.end()); + em_mean.swap(next_mean); + samples.swap(next); + fit_error_model(samples); + if (std::fabs(error_model_a - a) <= 1e-3 * a + && std::fabs(error_model_b - b) <= 1e-3 * std::max(b, 1e-6)) + break; + } +#ifdef JFJOCH_USE_CUDA + if (use_gpu_merge) gpu_->SetEmMean(em_mean.data()); +#endif + } // Per-group outlier-rejection median of I*corr (host both paths - a per-group median is awkward on // the GPU; cheap here, cnt >= 3 filter from the em pass). Fed to the merge accumulate. @@ -4540,15 +4638,21 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool // Inverse-variance WEIGHTED median: a frame the crystal barely diffracted on is scaled up by // 1/G together with its sigma, so a plain median lets two such observations outvote one // well-measured one - and the test below then rejects the well-measured one against its - // own small sigma. - std::vector> iv(start[n_sets]); // (I*corr, 1/(sigma*corr)^2) + // own small sigma. The variance is the model's, at the reflection's mean - the weight the + // merge gives the observation (see the centre refit above). + std::vector> iv(start[n_sets]); // (I*corr, 1/model variance) { std::vector fill(start.begin(), start.end() - 1); for (int i = 0; i < n_full; ++i) { const int g = mf.group[i]; if (g < 0) continue; const float sc = mf.sigma[i] * mf.corr[i]; - const std::pair v{mf.I[i] * mf.corr[i], sc > 0.0f ? 1.0f / (sc * sc) : 0.0f}; + const double mean = std::isfinite(em_mean[g]) ? em_mean[g] : static_cast(mf.I[i]) * mf.corr[i]; + const double mv = error_model_active + ? error_model_a * counting_variance(fulls[i], mean, static_cast(sc) * sc) + + (error_model_b * mean) * (error_model_b * mean) + : static_cast(sc) * sc; + const std::pair v{mf.I[i] * mf.corr[i], mv > 0.0 ? static_cast(1.0 / mv) : 0.0f}; if (cnt[g] >= 3) iv[fill[g]++] = v; if (!pair_needed.empty() && pair_needed[pair_of_group[g]]) iv[fill[n_groups + pair_of_group[g]]++] = v; @@ -4575,7 +4679,6 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool reject_median[g] = cnt[g] >= 3 ? set_median[g] : !pair_needed.empty() ? set_median[n_groups + pair_of_group[g]] : NAN; } - fit_error_model(samples); } // The full's sigma under the error model, with the variance evaluated at intensity I_for_b. diff --git a/image_analysis/scale_merge/RotationScaleMergeGPU.cu b/image_analysis/scale_merge/RotationScaleMergeGPU.cu index 0ecf08707..257886bc3 100644 --- a/image_analysis/scale_merge/RotationScaleMergeGPU.cu +++ b/image_analysis/scale_merge/RotationScaleMergeGPU.cu @@ -1126,6 +1126,14 @@ void RotationScaleMergeGPU::SetFrameCellOk(const uint8_t *frame_cell_ok) { // The per-group inv-var mean (em_mean) + the per-full leverage-corrected error-model samples over the // resident+scaled fulls. Stashes the filter context for the later MergeAccum/MergeRmeas calls. +void RotationScaleMergeGPU::SetEmMean(const double *em_mean) { + DeviceGuard guard(impl_->device, impl_->available); + auto &d = *impl_; + if (d.n_groups > 0) + CopyAndWait(d.m_em_mean.get(), em_mean, size_t(d.n_groups) * sizeof(double), cudaMemcpyHostToDevice, + impl_->s(), "ul em_mean"); +} + void RotationScaleMergeGPU::MergeEmSamples(bool for_search, double min_partiality, const uint8_t *hand, const uint8_t *has_hands, double *em_mean_out, int32_t *cnt_out, double *s2_out, diff --git a/image_analysis/scale_merge/RotationScaleMergeGPU.h b/image_analysis/scale_merge/RotationScaleMergeGPU.h index 98aa1b18a..349343b1a 100644 --- a/image_analysis/scale_merge/RotationScaleMergeGPU.h +++ b/image_analysis/scale_merge/RotationScaleMergeGPU.h @@ -103,6 +103,9 @@ public: // half-set weights multiplied by it. Requires MergeEmSamples first (em_mean resident). // reject_var_add (n_groups) widens the pooled cut by the shell's own measured Bijvoet // variance; null leaves the plain n-sigma test. + // Replace the per-group means MergeEmSamples left on the device (n_groups values): the merge's + // model sigmas are evaluated at them. + void SetEmMean(const double *em_mean); void MergeAccum(double error_model_a, double error_model_b, bool error_model_active, bool reject_outliers, double reject_nsigma, const float *reject_median, const float *reject_var_add, diff --git a/tools/battery/README.md b/tools/battery/README.md index eae047c93..ce514aab5 100644 --- a/tools/battery/README.md +++ b/tools/battery/README.md @@ -180,6 +180,8 @@ export `JFJOCH_BATTERY_SITE=/data/battery/site.json`. "baseline": "/data/battery/runs/", "baseline_private": null, "pdb_cache": "/data/battery/pdb_cache", + "cod_cache": "/data/battery/cod_cache", + "shelxl": "/opt/xtal/ccp4-9/bin/shelxl", "arms": { "open": {"manifest": "open.json", "reference": "deposition", "data_root": "/home/data/open"}, "inhouse": {"manifest": "inhouse.json", "reference": "xds", "data_root": "/home/data/inhouse"}, @@ -193,6 +195,9 @@ A relative `manifest` path is resolved against `tools/battery/`. `gpulock` is a `rugnux` is prefixed with under `--gpulock`. At PSI it is a wrapper script that queues for one of the shared GPU slots. Set it to `null` if you have no such wrapper. `pdb_cache` (optional) is where the deposited models and their metadata are cached for `--model` and the REFMAC check. +`cod_cache` (optional, default `/data/battery/cod_cache`) caches the small molecules' COD structures, +and `shelxl` (optional; else `shelxl` on `PATH`, e.g. from CCP4) is the SHELXL the small-molecule +check calls - without one the check is skipped and says so. ## Running @@ -323,6 +328,26 @@ and that shell's limit: the model never saw these, so clearly above zero is sign `dep_kind` (`I` or `F`), `dep_d_min` (the deposited data's limit), `dep_n_common`, `dep_status` and `dep_reason`. +### The SHELXL check (small molecules, always on) + +`tools/battery/shelx_check.py` refines a small-molecule set's published structure against our +`p.hkl` with SHELXL, the ground truth a chemical crystallographer would use. The structure is the +row's `cod` entry of the Crystallography Open Database (downloaded once into `cod_cache`). One fixed +recipe, so two runs compare: the data reindexed into the COD setting (every integer matrix with +entries -1..1 and det +1 that maps our cell onto the COD cell within 3% is tried with 6 cycles, the +lowest R1 wins), non-H anisotropic, H fixed at the COD positions with the COD U, EXTI refined, +`MERG 2` (SHELXL merges equivalents itself, so a merged or an unmerged HKLF 4 file both work), +weights from SHELXL's own suggestion over three rounds of 12 cycles. It also scores the data +against |Fc| of the COD model as published (gemmi, one scale, nothing refined), which no refinement +can absorb. `report` and `compare` compute it for an older run that lacks it (temporary directory; +about 5-40 s a set). Reported, never scored. Row keys: `shx_r1` (R1 for Fo > 4 sigma, `shx_n4` of +them), `shx_r1_all`, `shx_wr2`, `shx_goof`, `shx_exti`, `shx_wght_a`/`shx_wght_b` (the suggested +weights; a near SHELXL's 0.2 ceiling means sigmas or strong reflections are off), `shx_peak`/ +`shx_hole` (residual density, e/A^3), `shx_rint`/`shx_rsigma` (as SHELXL prints them; R(int) only +means something for unmerged data), `shx_k_top` (/ of the strongest analysis-of-variance +bin; below 1: strong reflections read low), `shx_fixed_r1`, `shx_cod`, `shx_status`, `shx_reason`. +`python3 shelx_check.py ` runs it on one finished set. + `model_sweep.py`, which ran `rugnux --model` over the open arm as a separate sweep, is retired. The open arm's command does the same inside the battery. @@ -396,6 +421,7 @@ was run `--unforced`), so its forced XDS-arm rows are left out the same way. | `rmodel`, `rmodel_shell_scaled`, `radial_misfit` | open arm with a model: R_MODEL, R_MODEL_SHELL_SCALED and MODEL_RADIAL_MISFIT - R over all the reflections, with and without one free scale per resolution shell, and how big that rescale was. `rmodel_shell_scaled` is the R that compares between runs (below) | | `refmac_rfree`, `refmac_rwork`, `refmac_rfree_depflags`, `refmac_rfree_depdata`, `refmac_rfree_ratio`, `refmac_twin`, `refmac_untwinned`, `refmac_status`, `refmac_reason`, `refmac_refined_*`, `refmac_shared_free_n` | the REFMAC check (`--model-check`, open arm; see its section for which R-free is which) | | `dep_status`, `dep_reason`, `dep_kind`, `dep_d_min`, `dep_n_common`, `dep_cc_delta_all`, `dep_cc_delta_outer`, `dep_beyond_cc`, `dep_beyond_d` | open arm with a model: our merge against the depositor's data per shell (`depdata_check.py`, above) | +| `shx_*` | small molecule with a `cod` structure: the SHELXL check (`shelx_check.py`, above) | | `wall_s`, `rugnux_wall_s`, `elapsed_s`, `exit_code`, `gpu_others`, `rugnux_verdict` | timing (`wall_s` is rugnux's own WALL_TIME, not the time spent waiting for the GPU queue), the exit code, other GPU processes seen before the set, and rugnux's own verdict line | ## The report @@ -417,6 +443,9 @@ SVG, no external files): the deposited limit, one row per set, sorted by the outer-shell difference; - on the XDS arms the **like-for-like table**: the reference-range numbers beside XDS's, with the rows where rugnux's cut is coarser marked as coverage; +- for the small molecules, the **SHELXL table**: R1, wR2, GooF, EXTI, weights, residual density, + R(int)/R(sigma), the strongest bin's K and the fixed-model R1(F) of the COD structure refined + against our data; - the **failures**, and **one row per set** with all the numbers; - if there is a baseline, the **delta against it**: pass rates per arm on the common sets, and every set that moved beyond noise. @@ -443,7 +472,7 @@ $B compare RUN_A RUN_B --rerun-changed # rerun the changed sets wit `compare` pairs rows by arm and set id, following the manifests' `aliases` across renames. A run from before schema 3 is compared through its `bare` rows (see the schema above). It lists every row whose verdict, space group, lattice, d_min, ISa, R_meas, CC1/2, completeness, cell, R-free, -reference-range R_meas, lowest-shell R_meas or ISa (where both runs have them), or time moved by more than the noise +reference-range R_meas, lowest-shell R_meas or ISa, SHELXL R1, wR2, GooF or EXTI (where both runs have them), or time moved by more than the noise thresholds in `report.py` (`NOISE`). Those thresholds are a first guess. `--rerun-changed` measures the noise directly: it reruns the changed sets with A's saved binary and options. A set that moves again under the same binary is noise. A set that @@ -494,6 +523,9 @@ whole range; the manifest keeps the rule used as `dmin_rule`. disagrees with an unpinned manifest input. Add the row to `open.json` with the deposited reference (`sg`, `sgno`, `cell`, `dmin`) and tags. Set `"pinned": true` when the choice between sweeps was deliberate. Record the source and DOI in `docs/EXTERNAL_TEST_DATA.md`. +- **Small molecules** carry `"cod": ""`, the published structure the SHELXL check refines + (pick an entry whose Niggli-reduced cell and space group match the row's reference; prefer a + modern, ordered, low-R one). - **Every row** carries `wavelength` (A), the value rugnux reads from the image headers (`WAVELENGTH` in `p_report.txt`). It is descriptive only; nothing scores it. - **Inhouse / private**: add the row (`id`, `input`, tags, and `"expect": "no_lattice"` for a diff --git a/tools/battery/battery.py b/tools/battery/battery.py index 87742a9a7..05ecefde0 100644 --- a/tools/battery/battery.py +++ b/tools/battery/battery.py @@ -62,6 +62,7 @@ import report # noqa: E402 import score # noqa: E402 import model_check # noqa: E402 the deposited model (--model); REFMAC check (--model-check) +import shelx_check # noqa: E402 SHELXL refinement of a small molecule's COD structure import depdata_check # noqa: E402 our merge vs the depositor's data, shell by shell PDB_ID = re.compile(r"^[0-9][A-Za-z0-9]{3}$") @@ -338,7 +339,7 @@ def run_one(run_dir, binary, e, opts): row = {"set": e["id"], "arm": e["arm"], "tags": e.get("tags", []), "input": e["input_path"], "gpu_others": gpu_others(), "model": None, "model_note": None, "rfree_deposited": None, "rfree_ratio": None, "cmd": None, "exit_code": None, "elapsed_s": None, "wall_s": None} - row.update({k: None for k in REFMAC_KEYS + depdata_check.KEYS}) + row.update({k: None for k in REFMAC_KEYS + depdata_check.KEYS + shelx_check.KEYS}) if not os.path.exists(e["input_path"]): row.update(score.judge(e, {}, "no input")) return row @@ -372,6 +373,10 @@ def run_one(run_dir, binary, e, opts): row.update(depdata_check.check_set(wd, e["id"], opts["pdb_cache"])) if opts["model_check"] and e["arm"] == "open": row.update(check_model(e, wd)) + if e.get("cod"): + # small molecule: its published structure refined against our p.hkl (report only) + row.update(shelx_check.check(wd, e["cod"], opts.get("cod_cache") or shelx_check.DEFAULT_CACHE, + opts.get("shelxl"))) return row @@ -550,6 +555,8 @@ def cmd_run(a, site): subset = a.only or (f"tier {a.tier}" if a.tier else None) opts = {"threads": a.threads, "timeout": a.timeout, "model_check": a.model_check and "open" in arms, "pdb_cache": site.get("pdb_cache") or model_check.DEFAULT_CACHE, + "cod_cache": site.get("cod_cache") or shelx_check.DEFAULT_CACHE, + "shelxl": shelx_check.find_shelxl(site.get("shelxl")), "gpulock": site["gpulock"] if a.gpulock else None, "extra_args": a.extra.split(), "runs_root": a.runs_root or site["runs_root"]} if a.gpulock and not site.get("gpulock"): @@ -586,6 +593,8 @@ def cmd_abort(a, site): def cmd_compare(a, site): man_a, res_a = report.load_run(a.run_a, a.allow_incomplete) man_b, res_b = report.load_run(a.run_b, a.allow_incomplete) + report.fill_shelx(a.run_a, man_a, res_a) + report.fill_shelx(a.run_b, man_b, res_b) rows = report.compare_rows(res_a, res_b) doc = report.Doc(f"{os.path.basename(os.path.normpath(a.run_a))} vs " f"{os.path.basename(os.path.normpath(a.run_b))}") @@ -608,6 +617,8 @@ def cmd_compare(a, site): opts = dict(man_a["options"], runs_root=a.runs_root or site["runs_root"]) opts["gpulock"] = opts["gpulock"] and site.get("gpulock") opts.setdefault("pdb_cache", site.get("pdb_cache") or model_check.DEFAULT_CACHE) + opts.setdefault("cod_cache", site.get("cod_cache") or shelx_check.DEFAULT_CACHE) + opts.setdefault("shelxl", shelx_check.find_shelxl(site.get("shelxl"))) label = "rerunA-" + man_a["label"] rerun = run_sets(site, sets, man_a["arms"], os.path.join(a.run_a, "bin", "rugnux"), None, label, opts, ",".join(e["id"] for e in sets)) @@ -865,6 +876,8 @@ def main(): site = load_site(a.site) report.ALIASES = load_aliases(site) report.PDB_CACHE = site.get("pdb_cache") or model_check.DEFAULT_CACHE + report.COD_CACHE = site.get("cod_cache") or shelx_check.DEFAULT_CACHE + report.SHELXL = shelx_check.find_shelxl(site.get("shelxl")) report.MANIFESTS = {arm: {e["id"]: e for e in load_sets(site, arm)} for arm, cfg in site["arms"].items() if os.path.exists(cfg["manifest"])} {"run": cmd_run, "list": cmd_list, "compare": cmd_compare, "report": cmd_report, diff --git a/tools/battery/inhouse.json b/tools/battery/inhouse.json index a82530e26..356ad822e 100644 --- a/tools/battery/inhouse.json +++ b/tools/battery/inhouse.json @@ -38,11 +38,11 @@ {"id": "myob_x06da_sparse", "input": "myob_x06da_sparse/MyoB2-5_7cef9c_master.h5", "wavelength": 0.95373, "ref": {"sgno": 3, "cell": [35.388, 28.752, 64.083, 90.0, 106.352, 90.0], "anomalous": false, "isa": 5.46, "completeness": 73.7, "r_meas": 0.326, "cc_half": 0.972, "multiplicity": 5.21, "dmin_low": 5.92, "r_meas_low": 0.146, "dmin": 2.0, "dmin_rule": "xds_range", "dmin_xds": 2.0, "dmax": 50.0}, "tags": ["h5", "myoglobin", "twin"]}, {"id": "nothing_2", "input": "nothing_2/test-28_3400ac_master.h5", "wavelength": 0.99988, "expect": "no_lattice", "tags": ["h5", "control"]}, {"id": "nothing_1", "input": "nothing_1/test-28_9bf604_master.h5", "wavelength": 0.99988, "expect": "no_lattice", "tags": ["h5", "control"]}, - {"id": "aspirin_x10sa_20keV", "input": "aspirin_x10sa_20keV/aspirin_1_002_master.h5", "wavelength": 0.61993, "tags": ["h5", "monoclinic", "small-molecule"], "ref": {"sgno": 4, "cell": [11.262, 6.543, 11.257, 90.0, 95.916, 90.0], "anomalous": true, "isa": 27.97, "completeness": 84.0, "r_meas": 0.032, "cc_half": 0.999, "multiplicity": 3.14, "dmin_low": 2.01, "r_meas_low": 0.03, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "P 1 21/c 1", "sgno": 14}, "ref_override_why": "aspirin form I, P 21/c; COD 7050897 - C. C. Wilson, New J. Chem. 26 (2002) 1733-1739, doi:10.1039/b203775k. XDS reports only Sohncke groups (P 21)"}, - {"id": "aspirin_x10sa_25keV", "input": "aspirin_x10sa_25keV/aspirin_1_001_master.h5", "wavelength": 0.49594, "tags": ["h5", "monoclinic", "small-molecule"], "ref": {"sgno": 4, "cell": [11.255, 6.541, 11.259, 90.0, 95.916, 90.0], "anomalous": true, "isa": 29.55, "completeness": 86.6, "r_meas": 0.033, "cc_half": 0.999, "multiplicity": 3.15, "dmin_low": 1.63, "r_meas_low": 0.03, "dmin": 0.55, "dmin_rule": "xds_range", "dmin_xds": 0.55, "dmax": 50.0}, "ref_override": {"sg": "P 1 21/c 1", "sgno": 14}, "ref_override_why": "aspirin form I, P 21/c; COD 7050897 - C. C. Wilson, New J. Chem. 26 (2002) 1733-1739, doi:10.1039/b203775k. XDS reports only Sohncke groups (P 21)"}, - {"id": "citricacid_x10sa_20keV", "input": "citricacid_x10sa_20keV/citricacid_1_005_master.h5", "wavelength": 0.61993, "tags": ["h5", "monoclinic", "small-molecule"], "ref": {"sgno": 4, "cell": [11.454, 5.579, 12.67, 90.0, 111.587, 90.0], "anomalous": true, "isa": 20.55, "completeness": 81.0, "r_meas": 0.04, "cc_half": 0.997, "multiplicity": 3.1, "dmin_low": 2.02, "r_meas_low": 0.043, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "P 1 21/c 1", "sgno": 14}, "ref_override_why": "anhydrous citric acid, P 21/a (P 21/c in the standard setting); COD 5000063 - J. P. Glusker, J. A. Minkin, A. L. Patterson, Acta Cryst. B25 (1969) 1066-1072, doi:10.1107/S0567740869003542. XDS reports only Sohncke groups (P 21)"}, - {"id": "hepes_x10sa_20keV", "input": "hepes_x10sa_20keV/hepes_1_004_master.h5", "wavelength": 0.61993, "tags": ["h5", "orthorhombic", "small-molecule"], "ref": {"sgno": 19, "cell": [8.348, 9.575, 27.068, 90.0, 90.0, 90.0], "anomalous": true, "isa": 28.39, "completeness": 91.6, "r_meas": 0.03, "cc_half": 0.999, "multiplicity": 5.64, "dmin_low": 2.0, "r_meas_low": 0.035, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "P b c a", "sgno": 61}, "ref_override_why": "HEPES, P b c a; COD 2224210 (100 K, 8.341 9.567 27.066) - P. Sledz, T. Minor, M. Chruszcz, Acta Cryst. E65 (2009) o3027-o3028, doi:10.1107/S1600536809042512. XDS reports only Sohncke groups (P 21 21 21)"}, - {"id": "yag_x10sa_20keV", "input": "yag_x10sa_20keV/yag_2_004_master.h5", "wavelength": 0.61993, "tags": ["h5", "cubic", "small-molecule"], "ref": {"sgno": 211, "cell": [11.997, 11.997, 11.997, 90.0, 90.0, 90.0], "anomalous": true, "isa": 3.2, "completeness": 99.0, "r_meas": 0.425, "cc_half": 0.958, "multiplicity": 27.96, "dmin_low": 1.99, "r_meas_low": 0.447, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "I a -3 d", "sgno": 230}, "ref_override_why": "Y3Al5O12 garnet, I a -3 d; COD 2003066 - A. Nakatsuka, A. Yoshiasa, T. Yamanaka, Acta Cryst. B55 (1999) 266-272, doi:10.1107/S0108768198012567. XDS reports only Sohncke groups (I 4 3 2)"}, - {"id": "lcystine_x10sa_20keV", "input": "lcystine_x10sa_20keV/lcystine_2_004_master.h5", "wavelength": 0.61993, "tags": ["h5", "hexagonal", "small-molecule"], "ref_override": {"sg": "P 61 2 2", "sgno": 178, "cell": [5.422, 5.422, 56.275, 90.0, 90.0, 120.0]}, "ref_override_why": "hexagonal L-cystine, P 61 2 2; COD 5000005 - B. M. Oughton and P. M. Harrison, Acta Cryst. 12 (1959) 396-404, doi:10.1107/S0365110X59001177. No XDS reference: XDS indexes under 10% of the spots of either sweep, so the row is scored on lattice and symmetry only"}, - {"id": "lcystine_x10sa_25keV", "input": "lcystine_x10sa_25keV/lcystine_2_003_master.h5", "wavelength": 0.49594, "tags": ["h5", "hexagonal", "small-molecule"], "ref_override": {"sg": "P 61 2 2", "sgno": 178, "cell": [5.422, 5.422, 56.275, 90.0, 90.0, 120.0]}, "ref_override_why": "hexagonal L-cystine, P 61 2 2; COD 5000005 - B. M. Oughton and P. M. Harrison, Acta Cryst. 12 (1959) 396-404, doi:10.1107/S0365110X59001177. No XDS reference: XDS indexes under 10% of the spots of either sweep, so the row is scored on lattice and symmetry only"} + {"id": "aspirin_x10sa_20keV", "input": "aspirin_x10sa_20keV/aspirin_1_002_master.h5", "wavelength": 0.61993, "cod": "7050897", "tags": ["h5", "monoclinic", "small-molecule"], "ref": {"sgno": 4, "cell": [11.262, 6.543, 11.257, 90.0, 95.916, 90.0], "anomalous": true, "isa": 27.97, "completeness": 84.0, "r_meas": 0.032, "cc_half": 0.999, "multiplicity": 3.14, "dmin_low": 2.01, "r_meas_low": 0.03, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "P 1 21/c 1", "sgno": 14}, "ref_override_why": "aspirin form I, P 21/c; COD 7050897 - C. C. Wilson, New J. Chem. 26 (2002) 1733-1739, doi:10.1039/b203775k. XDS reports only Sohncke groups (P 21)"}, + {"id": "aspirin_x10sa_25keV", "input": "aspirin_x10sa_25keV/aspirin_1_001_master.h5", "wavelength": 0.49594, "cod": "7050897", "tags": ["h5", "monoclinic", "small-molecule"], "ref": {"sgno": 4, "cell": [11.255, 6.541, 11.259, 90.0, 95.916, 90.0], "anomalous": true, "isa": 29.55, "completeness": 86.6, "r_meas": 0.033, "cc_half": 0.999, "multiplicity": 3.15, "dmin_low": 1.63, "r_meas_low": 0.03, "dmin": 0.55, "dmin_rule": "xds_range", "dmin_xds": 0.55, "dmax": 50.0}, "ref_override": {"sg": "P 1 21/c 1", "sgno": 14}, "ref_override_why": "aspirin form I, P 21/c; COD 7050897 - C. C. Wilson, New J. Chem. 26 (2002) 1733-1739, doi:10.1039/b203775k. XDS reports only Sohncke groups (P 21)"}, + {"id": "citricacid_x10sa_20keV", "input": "citricacid_x10sa_20keV/citricacid_1_005_master.h5", "wavelength": 0.61993, "cod": "5000063", "tags": ["h5", "monoclinic", "small-molecule"], "ref": {"sgno": 4, "cell": [11.454, 5.579, 12.67, 90.0, 111.587, 90.0], "anomalous": true, "isa": 20.55, "completeness": 81.0, "r_meas": 0.04, "cc_half": 0.997, "multiplicity": 3.1, "dmin_low": 2.02, "r_meas_low": 0.043, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "P 1 21/c 1", "sgno": 14}, "ref_override_why": "anhydrous citric acid, P 21/a (P 21/c in the standard setting); COD 5000063 - J. P. Glusker, J. A. Minkin, A. L. Patterson, Acta Cryst. B25 (1969) 1066-1072, doi:10.1107/S0567740869003542. XDS reports only Sohncke groups (P 21)"}, + {"id": "hepes_x10sa_20keV", "input": "hepes_x10sa_20keV/hepes_1_004_master.h5", "wavelength": 0.61993, "cod": "2224210", "tags": ["h5", "orthorhombic", "small-molecule"], "ref": {"sgno": 19, "cell": [8.348, 9.575, 27.068, 90.0, 90.0, 90.0], "anomalous": true, "isa": 28.39, "completeness": 91.6, "r_meas": 0.03, "cc_half": 0.999, "multiplicity": 5.64, "dmin_low": 2.0, "r_meas_low": 0.035, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "P b c a", "sgno": 61}, "ref_override_why": "HEPES, P b c a; COD 2224210 (100 K, 8.341 9.567 27.066) - P. Sledz, T. Minor, M. Chruszcz, Acta Cryst. E65 (2009) o3027-o3028, doi:10.1107/S1600536809042512. XDS reports only Sohncke groups (P 21 21 21)"}, + {"id": "yag_x10sa_20keV", "input": "yag_x10sa_20keV/yag_2_004_master.h5", "wavelength": 0.61993, "cod": "2003066", "tags": ["h5", "cubic", "small-molecule"], "ref": {"sgno": 211, "cell": [11.997, 11.997, 11.997, 90.0, 90.0, 90.0], "anomalous": true, "isa": 3.2, "completeness": 99.0, "r_meas": 0.425, "cc_half": 0.958, "multiplicity": 27.96, "dmin_low": 1.99, "r_meas_low": 0.447, "dmin": 0.68, "dmin_rule": "xds_range", "dmin_xds": 0.68, "dmax": 50.0}, "ref_override": {"sg": "I a -3 d", "sgno": 230}, "ref_override_why": "Y3Al5O12 garnet, I a -3 d; COD 2003066 - A. Nakatsuka, A. Yoshiasa, T. Yamanaka, Acta Cryst. B55 (1999) 266-272, doi:10.1107/S0108768198012567. XDS reports only Sohncke groups (I 4 3 2)"}, + {"id": "lcystine_x10sa_20keV", "input": "lcystine_x10sa_20keV/lcystine_2_004_master.h5", "wavelength": 0.61993, "cod": "1513328", "tags": ["h5", "hexagonal", "small-molecule"], "ref_override": {"sg": "P 61 2 2", "sgno": 178, "cell": [5.422, 5.422, 56.275, 90.0, 90.0, 120.0]}, "ref_override_why": "hexagonal L-cystine, P 61 2 2; COD 5000005 - B. M. Oughton and P. M. Harrison, Acta Cryst. 12 (1959) 396-404, doi:10.1107/S0365110X59001177. No XDS reference: XDS indexes under 10% of the spots of either sweep, so the row is scored on lattice and symmetry only"}, + {"id": "lcystine_x10sa_25keV", "input": "lcystine_x10sa_25keV/lcystine_2_003_master.h5", "wavelength": 0.49594, "cod": "1513328", "tags": ["h5", "hexagonal", "small-molecule"], "ref_override": {"sg": "P 61 2 2", "sgno": 178, "cell": [5.422, 5.422, 56.275, 90.0, 90.0, 120.0]}, "ref_override_why": "hexagonal L-cystine, P 61 2 2; COD 5000005 - B. M. Oughton and P. M. Harrison, Acta Cryst. 12 (1959) 396-404, doi:10.1107/S0365110X59001177. No XDS reference: XDS indexes under 10% of the spots of either sweep, so the row is scored on lattice and symmetry only"} ]} diff --git a/tools/battery/open.json b/tools/battery/open.json index 1a602d4eb..5327d7a6f 100644 --- a/tools/battery/open.json +++ b/tools/battery/open.json @@ -156,11 +156,11 @@ {"id": "9zm0", "input": "9zm0/Atg23ANNS_9zm0_9ZM0/data/SeAtg23_B_10_2115_master.h5", "wavelength": 0.97988, "ref": {"sg": "P 1 21 1", "sgno": 4, "cell": [50.409, 30.101, 91.244, 90.0, 97.146, 90.0], "dmin": 2.1}, "tags": ["h5", "monoclinic"]}, {"id": "9zmu", "input": "9zmu/BrmeA_18154_a_B2-Apo_9zmu/data/PSL-0613_7518_master.h5", "wavelength": 0.97856, "ref": {"sg": "P 65 2 2", "sgno": 179, "cell": [47.81, 47.81, 492.58, 90.0, 90.0, 120.0], "dmin": 1.98}, "tags": ["h5", "hexagonal"]}, {"id": "cuhf2", "input": "cuhf2/03_CuHF2pyz2PF6b_P_O/CuHF2pyz2PF6b_P_O_01.nxs", "wavelength": 0.4859, "pinned": true, "tags": ["nxs", "small-molecule"]}, - {"id": "cytidine", "input": "cytidine/20151020-Cytidine-2th-30/fixed-omega--180-phi-scan01_00001.cbf", "wavelength": 0.68966, "ref": {"sg": "P 21 21 21", "sgno": 19, "cell": [13.98, 14.788, 5.119, 90.0, 90.0, 90.0], "dmin": null}, "tags": ["cbf", "orthorhombic", "small-molecule"]}, - {"id": "dnba", "input": "dnba/35dnba_30K_2_04_00001.cbf", "wavelength": 0.6889, "ref": {"sg": "C 1 2/c 1", "sgno": 15, "cell": [20.2635, 8.7575, 9.6697, 90.0, 109.941, 90.0], "dmin": 0.48}, "tags": ["cbf", "monoclinic", "small-molecule"]}, - {"id": "lalanine", "input": "lalanine/pgw240050_01_00001.cbf", "wavelength": 0.6889, "ref": {"sg": "P 21 21 21", "sgno": 19, "cell": [5.7952, 5.933, 12.362, 90.0, 90.0, 90.0], "dmin": null}, "tags": ["cbf", "orthorhombic", "small-molecule"], "tiers": {"smoke": "small molecule, miniCBF"}}, - {"id": "metformin", "input": "metformin/013_Mmetformin_01_master.h5", "wavelength": 0.4859, "ref": {"sg": "P 1 21/c 1", "sgno": 14, "cell": [7.9104, 13.8794, 7.931, 90.0, 114.606, 90.0], "dmin": 0.45}, "tags": ["h5", "monoclinic", "small-molecule"], "tiers": {"smoke": "small molecule, Diamond I19 NXmx master"}}, - {"id": "nidppe", "input": "nidppe/001_NiDppeCl2_01_master.h5", "wavelength": 0.4859, "ref": {"sg": "P 1 21/c 1", "sgno": 14, "cell": [11.2779, 13.3386, 15.8739, 90.0, 98.7953, 90.0], "dmin": 0.77}, "tags": ["h5", "monoclinic", "small-molecule"]}, + {"id": "cytidine", "input": "cytidine/20151020-Cytidine-2th-30/fixed-omega--180-phi-scan01_00001.cbf", "wavelength": 0.68966, "ref": {"sg": "P 21 21 21", "sgno": 19, "cell": [13.98, 14.788, 5.119, 90.0, 90.0, 90.0], "dmin": null}, "cod": "2001311", "tags": ["cbf", "orthorhombic", "small-molecule"]}, + {"id": "dnba", "input": "dnba/35dnba_30K_2_04_00001.cbf", "wavelength": 0.6889, "ref": {"sg": "C 1 2/c 1", "sgno": 15, "cell": [20.2635, 8.7575, 9.6697, 90.0, 109.941, 90.0], "dmin": 0.48}, "cod": "4510615", "tags": ["cbf", "monoclinic", "small-molecule"]}, + {"id": "lalanine", "input": "lalanine/pgw240050_01_00001.cbf", "wavelength": 0.6889, "ref": {"sg": "P 21 21 21", "sgno": 19, "cell": [5.7952, 5.933, 12.362, 90.0, 90.0, 90.0], "dmin": null}, "cod": "2104782", "tags": ["cbf", "orthorhombic", "small-molecule"], "tiers": {"smoke": "small molecule, miniCBF"}}, + {"id": "metformin", "input": "metformin/013_Mmetformin_01_master.h5", "wavelength": 0.4859, "ref": {"sg": "P 1 21/c 1", "sgno": 14, "cell": [7.9104, 13.8794, 7.931, 90.0, 114.606, 90.0], "dmin": 0.45}, "cod": "2108029", "tags": ["h5", "monoclinic", "small-molecule"], "tiers": {"smoke": "small molecule, Diamond I19 NXmx master"}}, + {"id": "nidppe", "input": "nidppe/001_NiDppeCl2_01_master.h5", "wavelength": 0.4859, "ref": {"sg": "P 1 21/c 1", "sgno": 14, "cell": [11.2779, 13.3386, 15.8739, 90.0, 98.7953, 90.0], "dmin": 0.77}, "cod": "2012031", "tags": ["h5", "monoclinic", "small-molecule"]}, {"id": "5mln", "input": "5mln/5mln/data/CmADHx6_w1_2_0001.cbf", "wavelength": 0.8729, "ref": {"sg": "P 21 2 21", "sgno": 18, "cell": [74.178, 80.425, 80.52, 90.0, 90.0, 90.0], "dmin": 1.6}, "tags": ["cbf"]}, {"id": "5t39", "input": "5t39/10mMfuc-12h.001", "wavelength": 0.97872, "ref": {"sg": "P 1 21 1", "sgno": 4, "cell": [50.222, 41.27, 58.504, 90.0, 98.58, 90.0], "dmin": 1.1004}, "tags": ["marccd"]}, {"id": "6cdl", "input": "6cdl/nnnn_6cdl/data/wt_32-14A_p6n6.0001", "wavelength": 1.0, "ref": {"sg": "P 21 21 2", "sgno": 18, "cell": [58.26, 85.91, 46.051, 90.0, 90.0, 90.0], "dmin": 1.25}, "tags": ["marccd"]}, diff --git a/tools/battery/report.py b/tools/battery/report.py index 69c0cdff9..b93def55e 100644 --- a/tools/battery/report.py +++ b/tools/battery/report.py @@ -8,6 +8,7 @@ import sys import depdata_check import score +import shelx_check from render import Doc, ratio_dots, verdict_bars # A change smaller than these is treated as run-to-run noise. They are a starting point, to be @@ -26,6 +27,10 @@ NOISE = { "refres_isa": ("rel", 0.05), "refres_lowres_r_meas": ("rel", 0.05), "wall_s": ("rel", 0.25), # and at least 10 s - see beyond_noise() + "shx_r1": ("abs", 0.003), # SHELXL refinement of a small molecule's COD structure + "shx_wr2": ("abs", 0.005), + "shx_goof": ("abs", 0.03), + "shx_exti": ("abs", 0.02), } @@ -100,6 +105,29 @@ def fill_depdata(run_dir, res): r.update(out) +def _shelx(job): + os.nice(10) + return shelx_check.check_tmp(*job) + + +def fill_shelx(run_dir, man, res): + """The SHELXL refinement (shelx_check.py) for small-molecule rows of a run made before it + existed, from the saved p.hkl, four sets at a time. The COD id comes from today's manifest.""" + own = {(e["arm"], e["id"]): e for e in man["sets"]} + todo = [] + for r in res: + e = MANIFESTS.get(r["arm"], {}).get(key(r)[1]) or own.get((r["arm"], r["set"])) or {} + wd = os.path.join(run_dir, "work", r["arm"], r["set"]) + if e.get("cod") and "shx_status" not in r and os.path.exists(os.path.join(wd, "p.hkl")): + todo.append((r, (wd, e["cod"], COD_CACHE or shelx_check.DEFAULT_CACHE, SHELXL))) + if not todo or not SHELXL: + return + print(f"SHELXL refinement for {len(todo)} small-molecule sets of an older run ...", file=sys.stderr) + with multiprocessing.Pool(4) as pool: + for (r, _), out in zip(todo, pool.map(_shelx, [j for _, j in todo], chunksize=1)): + r.update(out) + + def schema1(man, res): """Read a run from before the variants (results schema 1) as one: it ran each set once, plain on the open arm and with XDS's settings on the XDS arms - unless --unforced, which left the @@ -164,6 +192,10 @@ MANIFESTS = {} # the site's cache of deposited models and structure factors (battery.py sets it) PDB_CACHE = None +# the site's cache of COD structures and the SHELXL binary (battery.py sets them; None: no SHELXL) +COD_CACHE = None +SHELXL = None + def key(r): return (r["arm"], ALIASES.get(r["arm"], {}).get(r["set"], r["set"])) @@ -224,6 +256,9 @@ def changes(ra, rb): for name in ("refres_r_meas", "refres_isa", "refres_lowres_r_meas"): if ra.get(name) is not None and rb.get(name) is not None and beyond_noise(name, ra[name], rb[name]): out.append(name) + for name in ("shx_r1", "shx_wr2", "shx_goof", "shx_exti"): + if ra.get(name) is not None and rb.get(name) is not None and beyond_noise(name, ra[name], rb[name]): + out.append("SHELXL " + name[4:]) if beyond_noise("wall_s", ra.get("wall_s"), rb.get("wall_s")): out.append("time") return out @@ -248,7 +283,8 @@ def arrow(x, y, fmt=lambda v: str(v)): def compare_table(doc, rows, only_changed=True): head = ["set", "arm", "verdict", "space group", "d_min", "ISa", "R_meas", "CC1/2", "cell dev %", "R_model (shell-scaled)", "R_free", "radial misfit", - "ref-range R_meas", "ref-range low-res R_meas", "time s", "beyond noise"] + "ref-range R_meas", "ref-range low-res R_meas", "SHELXL R1", "SHELXL wR2", "SHELXL GooF", + "SHELXL EXTI", "time s", "beyond noise"] out = [] for (arm, s), ra, rb, ch in rows: if only_changed and not ch: @@ -267,6 +303,10 @@ def compare_table(doc, rows, only_changed=True): arrow(ra.get("refres_r_meas"), rb.get("refres_r_meas"), lambda v: f"{100 * v:.1f}%"), arrow(ra.get("refres_lowres_r_meas"), rb.get("refres_lowres_r_meas"), lambda v: f"{100 * v:.1f}%"), + arrow(ra.get("shx_r1"), rb.get("shx_r1"), lambda v: f"{v:.4f}"), + arrow(ra.get("shx_wr2"), rb.get("shx_wr2"), lambda v: f"{v:.4f}"), + arrow(ra.get("shx_goof"), rb.get("shx_goof"), lambda v: f"{v:.3f}"), + arrow(ra.get("shx_exti"), rb.get("shx_exti"), lambda v: f"{v:.3f}"), arrow(ra.get("wall_s"), rb.get("wall_s"), lambda v: f"{v:.0f}"), ", ".join(ch)]) doc.table(head, out, row_class=lambda r: "fail" if "verdict" in r[-1] else "") @@ -316,6 +356,7 @@ def build(run_dir, baseline=None, allow_incomplete=False): if baseline: check_baseline(baseline, man.get("private")) fill_depdata(run_dir, res) + fill_shelx(run_dir, man, res) b = man["binary"] doc = Doc(f"Rugnux battery - {os.path.basename(os.path.normpath(run_dir))}") if man.get("private"): @@ -508,6 +549,33 @@ def build(run_dir, baseline=None, allow_incomplete=False): "its observations. The low-resolution R_meas is the lowest shell of each table (the shells " "are XDS's, so both cover the same reflections); reported like everything here.") + shx = [r for r in res if r.get("shx_status")] + if shx: + doc.h(3, "Small molecules: SHELXL refinement of the published structure") + doc.p("The set's structure from the Crystallography Open Database (COD id) refined against our " + "p.hkl by SHELXL with one fixed recipe (shelx_check.py: data reindexed into the COD " + "setting, non-H anisotropic, H fixed at the COD positions, EXTI refined, three rounds with " + "the weights SHELXL suggests, MERG 2), the way a chemical crystallographer judges data. " + "WGHT a near its 0.2 ceiling and a large EXTI mean the strong reflections or the sigmas are " + "off; K top is / of SHELXL's strongest analysis-of-variance bin (below 1: strong " + "reflections read low). Fixed-model R1(F) scores the data against |Fc| of the COD model as " + "published, one scale, nothing refined. R(int) means something only for unmerged data. " + "Reported, never scored.") + rows = [] + for r in sorted(shx, key=lambda r: (order.get(r["arm"], 9), r["set"])): + rows.append([r["set"], r["arm"], r.get("shx_cod") or "-", f(r.get("d_min")), + f(r.get("shx_r1"), "{:.4f}") + (f" ({r['shx_n4']})" if r.get("shx_n4") else ""), + f(r.get("shx_wr2"), "{:.4f}"), f(r.get("shx_goof"), "{:.3f}"), + f(r.get("shx_exti"), "{:.3f}"), + f(r.get("shx_wght_a"), "{:.3f}") + " / " + f(r.get("shx_wght_b"), "{:.2f}"), + f(r.get("shx_peak")) + " / " + f(r.get("shx_hole")), + f(r.get("shx_rint"), "{:.4f}") + " / " + f(r.get("shx_rsigma"), "{:.4f}"), + f(r.get("shx_k_top"), "{:.3f}"), f(r.get("shx_fixed_r1"), "{:.4f}"), + r["shx_status"] if r["shx_status"] == "ok" else f"{r['shx_status']}: {r.get('shx_reason')}"]) + doc.table(["set", "arm", "COD", "own d_min", "R1 >4sig (n)", "wR2", "GooF", "EXTI", "WGHT a / b", + "peak / hole e/A3", "R(int) / R(sigma)", "K top", "fixed-model R1(F)", "status"], + rows, num=range(3, 13)) + derived = {r["set"]: r for r in res if (r.get("d_min_ref_rule") or "xds_range") != "xds_range"} if derived: doc.p("XDS merged past its own signal (CC1/2 of its finest shell not significant), so the " @@ -580,6 +648,7 @@ def build(run_dir, baseline=None, allow_incomplete=False): if baseline: bman, bres = load_run(baseline) + fill_shelx(baseline, bman, bres) doc.h(2, f"Delta vs baseline {os.path.basename(os.path.normpath(baseline))}") doc.p(f"Baseline rugnux {bman['binary'].get('version', '?')}. Pass rates on the sets both runs have:") both = {key(r) for r in res} & {key(r) for r in bres} diff --git a/tools/battery/shelx_check.py b/tools/battery/shelx_check.py new file mode 100644 index 000000000..119919429 --- /dev/null +++ b/tools/battery/shelx_check.py @@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +"""SHELXL refinement of a small-molecule set's reference structure (COD) against rugnux's p.hkl. + +Ground truth for small molecules, the way a chemical crystallographer would judge the data: the +published structure is refined against our intensities with a fixed recipe, and R1, wR2, GooF, +extinction, the weighting scheme and the residual density are read back. Reported, never scored. + +Recipe (the same for every run, so two runs compare): + - the data are reindexed into the COD setting: every integer matrix (entries -1..1, det +1) that + maps the data cell onto the COD cell within 3% is tried with a 6-cycle refinement, and the one + with the lowest R1 is kept (lowest by a wide margin on every set so far); + - non-H atoms anisotropic, H atoms fixed at the COD positions with their COD U, occupancies + fixed at the COD values, EXTI refined; + - weights: WGHT 0.1, then three rounds of 12 cycles each with the weights SHELXL suggests; + - MERG 2 (SHELXL merges equivalents itself, Friedel mates too for a centrosymmetric group), so + the same recipe takes a merged or an unmerged HKLF 4 file; R(int)/R(sigma) are read where + SHELXL prints them (meaningful for unmerged data only). + - "fixed-model R1(F)": the data scored against |Fc| of the COD model as published (gemmi, no + refinement, one scale): a check that does not depend on what SHELXL can absorb into ADPs or EXTI. + +Derived from the small-molecule harness of the 2026-10 data-quality work (codref.py/fixedmodel.py). +SHELXL is called, not shipped: give its path as site key "shelxl" or have it on PATH (it comes with +CCP4). The COD entries are downloaded once into the site's "cod_cache". +""" +import itertools +import os +import re +import shutil +import subprocess +import sys +import tempfile +import urllib.request + +import gemmi +import numpy as np + +DEFAULT_CACHE = "/data/battery/cod_cache" +COD_URL = "https://www.crystallography.net/cod/{}.cif" + +KEYS = ("shx_status", "shx_reason", "shx_cod", "shx_r1", "shx_n4", "shx_r1_all", "shx_wr2", + "shx_goof", "shx_exti", "shx_wght_a", "shx_wght_b", "shx_peak", "shx_hole", "shx_rint", + "shx_rsigma", "shx_k_top", "shx_fixed_r1") + + +def find_shelxl(site_path=None): + if site_path and os.path.exists(site_path): + return site_path + return shutil.which("shelxl") + + +def cod_cif(cod_id, cache): + """The COD entry's CIF, downloaded into the cache on first use.""" + os.makedirs(cache, exist_ok=True) + path = os.path.join(cache, f"{cod_id}.cif") + if not os.path.exists(path): + data = urllib.request.urlopen(COD_URL.format(cod_id), timeout=60).read() + tmp = path + ".part" + with open(tmp, "wb") as fh: + fh.write(data) + os.replace(tmp, path) + return path + + +def read_report(path): + out = {} + for line in open(path, errors="replace"): + if "=" in line: + k, v = line.split("=", 1) + out[k.strip()] = v.strip() + return out + + +def read_hkl(path): + """[(h, k, l, rest of line)] of an HKLF 4 file, up to its 0 0 0 terminator.""" + out = [] + for line in open(path): + if len(line) < 12 or not line.strip(): + continue + h, k, l = int(line[0:4]), int(line[4:8]), int(line[8:12]) + if h == k == l == 0: + break + out.append((h, k, l, line[12:].rstrip("\n"))) + return out + + +def write_hkl(refl, M, path): + with open(path, "w") as fh: + for h, k, l, rest in refl: + n = M @ np.array([h, k, l]) + fh.write("%4d%4d%4d%s\n" % (n[0], n[1], n[2], rest)) + fh.write(" 0 0 0 0.00 0.00\n") + + +def cell_after(dcell, M): + """Cell of the axes a' = M a (rows of M in the data's axes).""" + A = np.array(dcell.orth.mat.tolist()) + N = A @ np.array(M).T + length = [np.linalg.norm(N[:, i]) for i in range(3)] + ang = lambda u, v: np.degrees(np.arccos(np.dot(u, v) / np.linalg.norm(u) / np.linalg.norm(v))) + return length + [ang(N[:, 1], N[:, 2]), ang(N[:, 0], N[:, 2]), ang(N[:, 0], N[:, 1])] + + +def spacegroup(st): + return gemmi.find_spacegroup_by_name(st.spacegroup_hm) + + +def reindex_candidates(st, dcell): + ref = st.cell.parameters + rots = [np.array(o.rot) // 24 for o in spacegroup(st).operations().sym_ops] + out = [] + for e in itertools.product((-1, 0, 1), repeat=9): + M = np.array(e).reshape(3, 3) + if round(np.linalg.det(M)) != 1: + continue + c = cell_after(dcell, M) + if all(abs(c[i] - ref[i]) / ref[i] < 0.03 for i in range(3)) and \ + all(abs(c[i] - ref[i]) < 2.0 for i in range(3, 6)): + # one per class of matrices equivalent under the model's point group + if not any(any(np.array_equal(R @ M, U) for R in rots) for U, _ in out): + out.append((M, c)) + return out + + +def write_ins(st, lam, cellp, wght, cycles, path): + sg = spacegroup(st) + ops = sg.operations() + centro = ops.is_centrosymmetric() + latt = {"P": 1, "I": 2, "R": 3, "F": 4, "A": 5, "B": 6, "C": 7}[sg.hm[0]] + symm = [] + for o in ops.sym_ops: + R = np.array(o.rot) // 24 + if np.array_equal(R, np.eye(3, dtype=int)) and not any(o.tran): + continue + if centro and round(np.linalg.det(R)) < 0: + continue + symm.append(o.triplet().upper()) + counts = {} + for s in st.get_all_unit_cell_sites(): + counts[s.element.name] = counts.get(s.element.name, 0) + s.occ + elems = sorted(counts, key=lambda e: (e != "C", e != "H", e)) + lines = ["TITL cod", "CELL %.5f %.4f %.4f %.4f %.3f %.3f %.3f" % (lam, *cellp), + "ZERR 1 0.001 0.001 0.001 0.01 0.01 0.01", "LATT %d" % (latt if centro else -latt)] + lines += ["SYMM " + s for s in symm] + lines += ["SFAC " + " ".join(elems), "UNIT " + " ".join(str(max(1, round(counts[e]))) for e in elems), + f"L.S. {cycles}", "LIST 4", "FMAP 2", "PLAN 5", "MERG 2", "EXTI 0", "WGHT " + wght, + "FVAR 1.0"] + names, atoms, nonh = set(), [], [] + for i, s in enumerate(st.sites): + name = re.sub(r"[^A-Za-z0-9]", "", s.label)[:4] + if not name or name in names: # SHELXL names: 4 characters, unique + name = f"{s.element.name[:1]}{i:03d}"[:4] + names.add(name) + sf = elems.index(s.element.name) + 1 + x, y, z = s.fract.x, s.fract.y, s.fract.z + occ = 10.0 + (s.occ if s.occ > 0 else 1.0) + if s.element.name == "H": + u = s.u_iso if s.u_iso > 0 else 0.05 + atoms.append("%-4s %d %9.5f %9.5f %9.5f %8.5f %8.5f" % (name, sf, 10 + x, 10 + y, 10 + z, occ, 10 + u)) + else: + u = s.u_iso if s.u_iso > 0 else 0.02 + atoms.append("%-4s %d %9.5f %9.5f %9.5f %8.5f %8.5f" % (name, sf, x, y, z, occ, u)) + nonh.append(name) + lines += ["ANIS " + " ".join(nonh[i:i + 12]) for i in range(0, len(nonh), 12)] + lines += atoms + ["HKLF 4", "END"] + with open(path, "w") as fh: + fh.write("\n".join(lines) + "\n") + + +def run_shelxl(shelxl, name, cwd): + env = dict(os.environ, OMP_NUM_THREADS="4") + subprocess.run([shelxl, name], cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + env=env, timeout=900) + lst_p, res_p = os.path.join(cwd, name + ".lst"), os.path.join(cwd, name + ".res") + lst = open(lst_p, errors="replace").read() if os.path.exists(lst_p) else "" + res = open(res_p, errors="replace").read() if os.path.exists(res_p) else "" + last = lambda pat, text=lst: (re.findall(pat, text, re.M) or [None])[-1] + num = lambda s: float(s) if s is not None else None + wght = (last(r"^WGHT\s+(.*)$", res) or "").split() + k_top = None + i = lst.rfind("Analysis of variance for reflections employed in refinement") + if i >= 0: + m = re.search(r"\n\s+K\s+([\d. ]+)", lst[i:i + 3000]) + k_top = num(m.group(1).split()[-1]) if m else None + n4 = last(r"R1 =\s*[\d.]+ for\s+(\d+) Fo > 4sig") + return {"shx_r1": num(last(r"R1 =\s*([\d.]+) for\s+\d+ Fo > 4sig")), + "shx_n4": int(n4) if n4 else None, + "shx_r1_all": num(last(r"and\s+([\d.]+) for all")), + "shx_wr2": num(last(r"wR2 =\s*([\d.]+)")), + "shx_goof": num(last(r"GooF = S =\s*([\d.]+)")), + "shx_peak": num(last(r"Highest peak\s+([\d.-]+)")), + "shx_hole": num(last(r"Deepest hole\s+([\d.-]+)")), + "shx_rint": num(last(r"R\(int\) =\s*([\d.]+)")), + "shx_rsigma": num(last(r"R\(sigma\) =\s*([\d.]+)")), + "shx_exti": num(last(r"^EXTI\s+([\d.]+)", res)), + "shx_wght_a": num(wght[0]) if wght else None, + "shx_wght_b": num(wght[1]) if len(wght) > 1 else None, + "shx_k_top": k_top}, " ".join(wght) + + +def fixed_model_r1(st, refl, M): + """R1(F) of the (reindexed) data against |Fc| of the COD model as published, one scale.""" + sg = spacegroup(st) + ops = sg.operations() + asu = gemmi.ReciprocalAsu(sg) + calc = gemmi.StructureFactorCalculatorX(st.cell) + st.setup_cell_images() + groups = {} + for h, k, l, rest in refl: + n = M @ np.array([h, k, l]) + if ops.is_systematically_absent(list(map(int, n))): + continue + p = rest.split() + i, s = float(p[0]), float(p[1]) + if s <= 0: + continue + groups.setdefault(tuple(asu.to_asu(list(map(int, n)), ops)[0]), []).append((i, s)) + if not groups: + return None + fo, fc = [], [] + for hkl, obs in groups.items(): + w = [1 / s ** 2 for _, s in obs] + fo.append(sum(i * wi for (i, _), wi in zip(obs, w)) / sum(w)) + fc.append(abs(calc.calculate_sf_from_small_structure(st, list(hkl))) ** 2) + fo, fc = np.array(fo), np.array(fc) + fo = fo / (np.sum(fo * fc) / np.sum(fc * fc)) + Fo, Fc = np.sqrt(np.clip(fo, 0, None)), np.sqrt(fc) + return round(float(np.sum(np.abs(Fo - Fc)) / np.sum(Fo)), 4) + + +def check(wd, cod_id, cache=DEFAULT_CACHE, shelxl=None, work=None): + """shx_* fields for one finished set in work dir `wd` (p.hkl + p_report.txt). `work`: where + SHELXL runs (default /shelx).""" + out = {k: None for k in KEYS} + out["shx_cod"] = cod_id + if not shelxl: + return dict(out, shx_status="skipped", shx_reason="SHELXL not available (site key 'shelxl' or PATH)") + hkl, rep_p = os.path.join(wd, "p.hkl"), os.path.join(wd, "p_report.txt") + if not os.path.exists(hkl) or not os.path.exists(rep_p): + return dict(out, shx_status="skipped", shx_reason="no p.hkl") + try: + rep = read_report(rep_p) + dcell = gemmi.UnitCell(*map(float, rep["UNIT_CELL_CONSTANTS"].split())) + lam = float(rep["WAVELENGTH"]) + st = gemmi.read_small_structure(cod_cif(cod_id, cache)) + refl = read_hkl(hkl) + cands = reindex_candidates(st, dcell) + if not cands: + return dict(out, shx_status="skipped", shx_reason="data cell does not match the COD cell") + work = work or os.path.join(wd, "shelx") + os.makedirs(work, exist_ok=True) + best = None + for j, (M, c) in enumerate(cands): + d = os.path.join(work, f"trial{j}") + os.makedirs(d, exist_ok=True) + write_hkl(refl, M, os.path.join(d, "t.hkl")) + write_ins(st, lam, c, "0.1", 6, os.path.join(d, "t.ins")) + r1 = run_shelxl(shelxl, "t", d)[0]["shx_r1"] + if r1 is not None and (best is None or r1 < best[0]): + best = (r1, M, c) + if best is None: + return dict(out, shx_status="error", shx_reason="SHELXL gave no R1 in any setting") + _, M, c = best + d = os.path.join(work, "final") + os.makedirs(d, exist_ok=True) + write_hkl(refl, M, os.path.join(d, "f.hkl")) + wght = "0.1" + for _ in range(3): + write_ins(st, lam, c, wght, 12, os.path.join(d, "f.ins")) + vals, suggested = run_shelxl(shelxl, "f", d) + wght = suggested or wght + out.update(vals) + out["shx_fixed_r1"] = fixed_model_r1(st, refl, M) + out["shx_status"] = "ok" if vals["shx_r1"] is not None else "error" + if vals["shx_r1"] is None: + out["shx_reason"] = "SHELXL did not finish the refinement (see shelx/final/f.lst)" + except Exception as ex: # a failing check must not lose the set's result + out.update(shx_status="error", shx_reason=f"{type(ex).__name__}: {ex}"[:300]) + return out + + +def check_tmp(wd, cod_id, cache, shelxl): + """check() for a finished (read-only) run directory: SHELXL works in a temporary directory.""" + with tempfile.TemporaryDirectory(prefix="shelx_") as tmp: + return check(wd, cod_id, cache, shelxl, tmp) + + +if __name__ == "__main__": + # shelx_check.py [cod cache] + print(check_tmp(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else DEFAULT_CACHE, + find_shelxl())) diff --git a/tools/battery/site.example.json b/tools/battery/site.example.json index 13e24c8ff..df32abe73 100644 --- a/tools/battery/site.example.json +++ b/tools/battery/site.example.json @@ -6,6 +6,8 @@ "baseline": null, "baseline_private": null, "pdb_cache": "/path/to/battery/pdb_cache", + "cod_cache": "/path/to/battery/cod_cache", + "shelxl": null, "arms": { "open": {"manifest": "open.json", "reference": "deposition", "data_root": "/path/to/battery/open"}, "inhouse": {"manifest": "inhouse.json", "reference": "xds", "data_root": "/path/to/battery/inhouse"}