Skip to content

Commit

Permalink
python: change SpaceGroup.__eq__
Browse files Browse the repository at this point in the history
instead of comparing addresses, compare Hall symbols

With multiple modules/C++ libraries, we might have multiple
copies of inline variables from C++ headers and comparing
addresses won't work.
  • Loading branch information
wojdyr committed Aug 28, 2024
1 parent 32a4ff6 commit a861714
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
10 changes: 7 additions & 3 deletions python/sym.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -185,9 +185,13 @@ void add_symmetry(py::module& m) {
h(i, j) = hkl[j];
}
}, py::arg("miller_array").noconvert())
// In Python, SpaceGroup always points to an entry in spacegroup_tables::main.
.def("__eq__", [](const SpaceGroup& a, const SpaceGroup& b) { return &a == &b; },
py::is_operator())
// Check equality by comparing Hall symbol strings.
// In Python, SpaceGroup always points to an entry in spacegroup_tables::main,
// so Hall symbols are consistent. The same settings with different H-M names
// (see space group 65 in the ITB list) are considered equal.
.def("__eq__", [](const SpaceGroup& a, const SpaceGroup& b) {
return strcmp(a.hall, b.hall) == 0;
}, py::is_operator())
.def("__repr__", [](const SpaceGroup &self) {
return "<gemmi.SpaceGroup(\"" + self.xhm() + "\")>";
})
Expand Down
22 changes: 13 additions & 9 deletions tests/test_symmetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,17 +326,21 @@ def check_xhm(name, xhm):
self.assertEqual(gemmi.SpaceGroup(4005).hm, 'I 1 2 1')
self.assertIsNone(gemmi.find_spacegroup_by_name('abc'))

def test_equality(self):
# Tests if all functions return a reference, because __eq__ compares
# pointers to C++ objects.
def test_identity(self):
# Checks that all functions return a reference, not a copy
p1 = gemmi.find_spacegroup_by_number(1)
self.assertEqual(gemmi.find_spacegroup_by_name('P1'), p1)
self.assertEqual(gemmi.SpaceGroup(1), p1)
self.assertEqual(gemmi.SpaceGroup('P 1'), p1)
self.assertTrue(gemmi.find_spacegroup_by_name('P1') is p1)
#self.assertTrue(gemmi.SpaceGroup(1) is p1)
#self.assertTrue(gemmi.SpaceGroup('P 1') is p1)
gops = gemmi.GroupOps([gemmi.Op()])
self.assertEqual(gemmi.find_spacegroup_by_ops(gops), p1)
self.assertEqual(next(gemmi.spacegroup_table()), p1)
self.assertEqual(next(gemmi.spacegroup_table_itb()), p1)
self.assertTrue(gemmi.find_spacegroup_by_ops(gops) is p1)
self.assertTrue(next(gemmi.spacegroup_table()) is p1)
self.assertTrue(next(gemmi.spacegroup_table_itb()) is p1)

a = gemmi.SpaceGroup("C c c a:1")
b = gemmi.SpaceGroup("C c c b:1")
self.assertTrue(a == b)
self.assertTrue(a is not b)

def test_groupops(self):
gops = gemmi.GroupOps([gemmi.Op(t) for t in ['x, y, z',
Expand Down

0 comments on commit a861714

Please sign in to comment.