// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #include #ifdef __APPLE__ #include #include #include #include #include "../image_analysis/structure_refinement/ModelGrid.h" #include "../image_analysis/structure_refinement/RefinementXray.h" #include "../image_analysis/structure_refinement/ShrinkMaskMetal.h" // The bulk-solvent mask shrunk on the Apple GPU (ShrinkMaskMetal.h) is the CPU's, bit for bit. A Mac without a // Metal device fails rather than skips, as in ModelDensityMetalTest.cpp. namespace { // Atoms in clusters over the cell - so that the mask has an edge to shrink everywhere and boxes wrap at every face. gemmi::Model clustered_atoms(const gemmi::UnitCell &cell) { std::mt19937 rng(29); std::uniform_real_distribution frac(0.0, 1.0); std::normal_distribution spread(0.0, 2.5); const gemmi::El elements[] = {gemmi::El::C, gemmi::El::N, gemmi::El::O, gemmi::El::S}; gemmi::Model model(1); gemmi::Chain chain("A"); gemmi::Residue res; res.name = "UNK"; res.seqid = gemmi::SeqId(1, ' '); for (int c = 0; c < 40; c++) { const gemmi::Position centre = cell.orthogonalize(gemmi::Fractional(frac(rng), frac(rng), frac(rng))); for (int i = 0; i < 50; i++) { gemmi::Atom a; a.name = "X"; a.element = elements[i % 4]; a.pos = centre + gemmi::Position(spread(rng), spread(rng), spread(rng)); a.b_iso = 20.0f; a.occ = 1.0f; res.atoms.push_back(a); } } chain.residues.push_back(res); model.chains.push_back(chain); return model; } void check_same_mask(const gemmi::UnitCell &cell, const char *group, double d_min) { const gemmi::SpaceGroup &sg = *gemmi::find_spacegroup_by_name(group); gemmi::Grid cpu = BulkSolventMask::MaskGrid(cell, sg, d_min); cpu.data.resize(cpu.point_count()); gemmi::Grid gpu = cpu; const std::vector leaders = OrbitLeaders(cpu, 4); const gemmi::Model model = clustered_atoms(cell); PutMaskOnGrid(cpu, model, leaders, 4, false); const size_t before = ShrinkMaskMetalCalls(); PutMaskOnGrid(gpu, model, leaders, 4, true); REQUIRE(ShrinkMaskMetalCalls() == before + 1); // the GPU shrank it REQUIRE(gpu.data.size() == cpu.data.size()); size_t different = 0, solvent = 0; for (size_t i = 0; i < cpu.data.size(); i++) { different += std::memcmp(&cpu.data[i], &gpu.data[i], sizeof(float)) != 0; solvent += cpu.data[i] >= 1.0f; } CAPTURE(group, solvent, cpu.data.size()); CHECK(solvent > cpu.data.size() / 10); CHECK(solvent < cpu.data.size() * 9 / 10); CHECK(different == 0); } } TEST_CASE("ShrinkMaskMetal_BitIdenticalToCPU", "[portable][Metal]") { // Triclinic, so that the offsets are not symmetric in the axes; then a group with symmetry. check_same_mask(gemmi::UnitCell(41, 46, 52, 81, 96, 107), "P 1", 2.0); check_same_mask(gemmi::UnitCell(50, 56, 63, 90, 90, 90), "P 21 21 21", 1.6); } #endif