Source code for picogl.tests.test_molecular_mesh

"""Tests for molecular mesh data builders."""

from __future__ import annotations

from dataclasses import dataclass
from types import SimpleNamespace

import numpy as np
import pytest
from molib.gl.mesh.atom.point import AtomPointsMesh
from molib.gl.mesh.atom.point_geometry import AtomPointGeometry
from molib.gl.mesh.atom.sphere import AtomSpheresMesh
from molib.gl.mesh.bond.cylinder import BondCylindersMesh
from molib.gl.mesh.bond.line import BondLinesMesh
from picogl.backend.gl.enums import GLDrawMode
from picogl.core.geometry.sphere import SphereGeometrySpec, SphereMesh, sphere_mesh
from picogl.renderer.molecular import BondGeometry


@dataclass
[docs] class _Atom:
[docs] x: float
[docs] y: float
[docs] z: float
[docs] chain_id: str
[docs] def test_atom_xyz_prefers_coords_over_xyz() -> None: """atom_xyz lives on entities.coords, not the sphere mesh module.""" from molib.entities.coords import atom_xyz class _Coords: coords = (1.0, 2.0, 3.0) x = 9.0 y = 9.0 z = 9.0 class _XYZ: x = 4.0 y = 5.0 z = 6.0 assert atom_xyz(_Coords()) == (1.0, 2.0, 3.0) assert atom_xyz(_XYZ()) == (4.0, 5.0, 6.0) assert atom_xyz(np.array([7.0, 8.0, 9.0])) == (7.0, 8.0, 9.0) sphere = sphere_mesh(radius=0.2, slices=16, stacks=16) assert sphere.positions.shape == (17 * 17, 3) assert sphere.normals.shape == sphere.positions.shape assert sphere.indices.size == 16 * 16 * 6
[docs] def test_atom_radius_uses_atom3d_field_or_fallback() -> None: from molib.entities.coords import atom_radius class _WithRadius: radius = 1.7 class _Missing: pass assert atom_radius(_WithRadius(), 0.2) == pytest.approx(1.7) assert atom_radius(_Missing(), 0.2) == pytest.approx(0.2) assert atom_radius(SimpleNamespace(radius=None), 0.3) == pytest.approx(0.3) assert atom_radius(SimpleNamespace(radius=0.0), 0.3) == pytest.approx(0.3)
[docs] def test_atoms_mesh_single_atom_counts() -> None: atom = _Atom(1.0, 2.0, 3.0, "A") mesh = AtomSpheresMesh([atom], radius=0.2, slices=16, stacks=16) data = mesh.to_mesh_data() template = sphere_mesh(0.2, 16, 16) assert data.vertices.shape[0] == template.positions.shape[0] assert data.normals.shape[0] == template.positions.shape[0] assert data.colors.shape[0] == template.positions.shape[0] assert data.indices.size == template.indices.size assert data.vertices[0, 0] == pytest.approx(1.0 + template.positions[0, 0]) assert mesh.draw_mode == GLDrawMode.TRIANGLES
@dataclass
[docs] class _AtomCoords:
[docs] coords: tuple[float, float, float]
[docs] chain_id: str
[docs] def test_atoms_mesh_accepts_coords_attribute() -> None: """MoLib Atom3D-style objects expose coords, not x/y/z.""" atom = _AtomCoords((1.0, 2.0, 3.0), "A") data = AtomSpheresMesh([atom], radius=0.2, slices=4, stacks=4).to_mesh_data() template = sphere_mesh(0.2, 4, 4) assert data.vertices[0, 0] == pytest.approx(1.0 + template.positions[0, 0])
[docs] def test_atoms_mesh_color_fn_receives_atom() -> None: atom = _Atom(0.0, 0.0, 0.0, "X") seen: list[object] = [] def color_fn(a: object) -> tuple[float, float, float]: seen.append(a) return (0.1, 0.2, 0.3) data = AtomSpheresMesh( [atom], color_fn=color_fn, radius=0.2, slices=4, stacks=4 ).to_mesh_data() assert seen == [atom] assert data.colors.shape[0] == data.vertices.shape[0] np.testing.assert_allclose(data.colors[0], (0.1, 0.2, 0.3))
[docs] def test_atoms_mesh_two_atoms_vectorized_expand() -> None: """Two atoms expand one template: tiled normals, repeated colors, offset EBO.""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(5.0, 0.0, 0.0, "B") def color_fn(atom: _Atom) -> tuple[float, float, float]: return (1.0, 0.0, 0.0) if atom.chain_id == "A" else (0.0, 1.0, 0.0) data = AtomSpheresMesh( [atom_a, atom_b], color_fn=color_fn, radius=0.2, slices=4, stacks=4, ).to_mesh_data() template = sphere_mesh(0.2, 4, 4) n_verts = template.positions.shape[0] n_idx = int(template.indices.size) assert data.vertices.shape == (2 * n_verts, 3) assert data.normals.shape == (2 * n_verts, 3) assert data.colors.shape == (2 * n_verts, 3) assert data.indices.size == 2 * n_idx np.testing.assert_allclose(data.vertices[:n_verts], template.positions) np.testing.assert_allclose( data.vertices[n_verts:], template.positions + np.array([5.0, 0.0, 0.0]) ) np.testing.assert_allclose(data.normals, np.tile(template.normals, (2, 1))) np.testing.assert_allclose( data.colors[:n_verts], np.broadcast_to((1.0, 0.0, 0.0), (n_verts, 3)) ) np.testing.assert_allclose( data.colors[n_verts:], np.broadcast_to((0.0, 1.0, 0.0), (n_verts, 3)) ) np.testing.assert_array_equal( data.indices[n_idx:], np.asarray(template.indices) + n_verts ) assert data.draw_info.vertices_per_item == n_verts assert data.draw_info.elements_per_item == n_idx
[docs] def test_atoms_mesh_per_atom_radii_override_uniform_radius() -> None: """Per-atom radii scale the template independently of geometry.radius.""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(5.0, 0.0, 0.0, "B") data = AtomSpheresMesh( [atom_a, atom_b], radius=1.0, slices=4, stacks=4, radii=(0.5, 2.0), ).to_mesh_data() template = sphere_mesh(1.0, 4, 4) n_verts = template.positions.shape[0] np.testing.assert_allclose(data.vertices[:n_verts], template.positions * 0.5) np.testing.assert_allclose( data.vertices[n_verts:], template.positions * 2.0 + np.array([5.0, 0.0, 0.0], dtype=np.float32), )
[docs] def test_atoms_mesh_default_color_fn_uses_chain_palette() -> None: """Omitting color_fn must not crash; colors follow make_chain_color_fn.""" from molib.pdb.color import make_chain_color_fn atoms = [_Atom(0.0, 0.0, 0.0, "A"), _Atom(1.0, 0.0, 0.0, "B")] data = AtomSpheresMesh(atoms, radius=0.2, slices=4, stacks=4).to_mesh_data() expected_fn = make_chain_color_fn(["A", "B"]) n_verts = data.vertices.shape[0] // 2 np.testing.assert_allclose(data.colors[0], expected_fn(atoms[0])) np.testing.assert_allclose(data.colors[n_verts], expected_fn(atoms[1]))
[docs] def test_bonds_mesh_single_bond() -> None: atom1 = _Atom(0.0, 0.0, 0.0, "A") atom2 = _Atom(1.0, 0.0, 0.0, "A") mesh = BondCylindersMesh( [atom1, atom2], indices=[[0, 1]], color_fn=lambda _atom: (1.0, 0.0, 0.0), color_bonds=True, ) data = mesh.to_mesh_data() segments = 8 assert data.vertices.shape == (2 * segments, 3) assert data.normals.shape == (2 * segments, 3) assert data.colors.shape == (2 * segments, 3) assert data.indices.size == 6 * segments assert mesh.draw_mode == GLDrawMode.TRIANGLES
[docs] def test_bonds_mesh_cylinder_normals_perpendicular_to_axis() -> None: atom1 = _Atom(0.0, 0.0, 0.0, "A") atom2 = _Atom(1.0, 0.0, 0.0, "A") data = BondCylindersMesh( [atom1, atom2], indices=[[0, 1]], segments=12, color_fn=lambda _atom: (1.0, 0.0, 0.0), color_bonds=True, ).to_mesh_data() full_rings = np.reshape(data.vertices, (-1, 2, 3)) assert np.allclose(full_rings[:, 0, 0], 0.0) assert np.allclose(full_rings[:, 1, 0], 1.0) assert np.allclose(data.normals[:, 0], 0.0) radial = np.linalg.norm(data.vertices[:, 1:], axis=1) assert np.allclose(radial, 0.06)
[docs] def test_bonds_mesh_custom_radius_and_color_fn() -> None: atom1 = _Atom(0.0, 0.0, 0.0, "A") atom2 = _Atom(1.0, 1.0, 1.0, "A") data = BondCylindersMesh( [atom1, atom2], indices=[[0, 1]], radius=0.3, segments=4, color_fn=lambda _chain: (1.0, 0.0, 0.0), color_bonds=True, ).to_mesh_data() assert data.vertices.shape == (8, 3) assert data.indices.size == 24 np.testing.assert_allclose(data.colors[0], (1.0, 0.0, 0.0)) start = np.array([0.0, 0.0, 0.0]) end = np.array([1.0, 1.0, 1.0]) bottom_ring = data.vertices[0::2] top_ring = data.vertices[1::2] np.testing.assert_allclose( np.linalg.norm(bottom_ring - start, axis=1), 0.3, rtol=1e-6 ) np.testing.assert_allclose(np.linalg.norm(top_ring - end, axis=1), 0.3, rtol=1e-6)
[docs] def test_atoms_mesh_custom_geometry() -> None: atom = _Atom(0.0, 0.0, 0.0, "A") spec = SphereGeometrySpec(radius=0.4, slices=4, stacks=4) sphere = SphereMesh(spec) data = AtomSpheresMesh([atom], geometry=spec).to_mesh_data() assert data.vertices.shape[0] == sphere.vertices_per_item assert data.draw_info.elements_per_item == sphere.elements_per_item assert data.draw_info.vertices_per_item == sphere.vertices_per_item
[docs] def test_bonds_mesh_custom_geometry() -> None: atom1 = _Atom(0.0, 0.0, 0.0, "A") atom2 = _Atom(1.0, 0.0, 0.0, "A") geometry = BondGeometry(radius=0.2, segments=6) data = BondCylindersMesh( [atom1, atom2], indices=[[0, 1]], geometry=geometry, color_fn=lambda _atom: (1.0, 0.0, 0.0), color_bonds=True, ).to_mesh_data() assert data.vertices.shape == (geometry.vertices_per_item, 3) assert data.indices.size == geometry.elements_per_item assert data.draw_info.elements_per_item == geometry.elements_per_item
[docs] def test_bonds_mesh_two_bonds_vectorized_expand() -> None: """Two shafts: doubled vertex count, per-shaft colors, offset EBO.""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "A") atom_c = _Atom(0.0, 2.0, 0.0, "B") atom_d = _Atom(0.0, 3.0, 0.0, "B") def color_fn(atom: _Atom) -> tuple[float, float, float]: return (1.0, 0.0, 0.0) if atom.chain_id == "A" else (0.0, 1.0, 0.0) data = BondCylindersMesh( [atom_a, atom_b, atom_c, atom_d], indices=[[0, 1], [2, 3]], color_fn=color_fn, color_bonds=True, segments=4, ).to_mesh_data() n_verts = 2 * 4 n_idx = 6 * 4 assert data.vertices.shape == (2 * n_verts, 3) assert data.colors.shape == (2 * n_verts, 3) assert data.indices.size == 2 * n_idx first = BondCylindersMesh( [atom_a, atom_b], indices=[[0, 1]], color_fn=color_fn, color_bonds=True, segments=4, ).to_mesh_data() np.testing.assert_allclose(data.vertices[:n_verts], first.vertices) np.testing.assert_allclose( data.colors[:n_verts], np.broadcast_to((1.0, 0.0, 0.0), (n_verts, 3)) ) np.testing.assert_allclose( data.colors[n_verts:], np.broadcast_to((0.0, 1.0, 0.0), (n_verts, 3)) ) np.testing.assert_array_equal( np.asarray(data.indices).ravel()[n_idx:], np.asarray(first.indices).ravel() + n_verts, )
[docs] def test_bonds_mesh_skips_zero_length_without_repeating_color() -> None: """A collapsed pair adds neither vertices nor a color block.""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "A") collapsed = _Atom(0.0, 0.0, 0.0, "B") data = BondCylindersMesh( [atom_a, atom_b, collapsed], indices=[[0, 0], [0, 1], [2, 2]], color_fn=lambda atom: ( (0.0, 0.0, 1.0) if atom.chain_id == "A" else (1.0, 0.0, 0.0) ), color_bonds=True, segments=4, ).to_mesh_data() n_verts = 2 * 4 assert data.vertices.shape == (n_verts, 3) assert data.colors.shape == (n_verts, 3) np.testing.assert_allclose( data.colors, np.broadcast_to((0.0, 0.0, 1.0), (n_verts, 3)) ) np.testing.assert_array_equal(data.item_keys, np.array([[0, 1]], dtype=np.uint32)) np.testing.assert_array_equal( data.color_source_indices, np.repeat(np.array([0], dtype=np.uint32), n_verts), )
[docs] def test_bonds_mesh_item_keys_match_surviving_pairs() -> None: """Pair metadata omits collapsed shafts and gathers from atom A.""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(0.0, 0.0, 0.0, "A") atom_c = _Atom(1.5, 0.0, 0.0, "A") data = BondCylindersMesh( [atom_a, atom_b, atom_c], indices=[[0, 1], [0, 2]], color_bonds=False, segments=4, ).to_mesh_data() np.testing.assert_array_equal(data.item_keys, np.array([[0, 2]], dtype=np.uint32)) np.testing.assert_array_equal( data.color_source_indices, np.repeat(np.array([0], dtype=np.uint32), data.draw_info.vertices_per_item), )
[docs] def test_bonds_mesh_empty_has_empty_pair_metadata() -> None: data = BondCylindersMesh([]).to_mesh_data() assert data.vertices.shape[0] == 0 np.testing.assert_array_equal(data.item_keys, np.zeros((0, 2), dtype=np.uint32)) np.testing.assert_array_equal( data.color_source_indices, np.zeros((0,), dtype=np.uint32) )
[docs] def test_bonds_mesh_color_bonds_false_broadcasts_bond_color() -> None: atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "B") bond_color = (0.2, 0.4, 0.6) data = BondCylindersMesh( [atom_a, atom_b], indices=[[0, 1]], bond_color=bond_color, color_bonds=False, segments=4, ).to_mesh_data() n_verts = 2 * 4 assert data.colors.shape == (n_verts, 3) np.testing.assert_allclose(data.colors, np.broadcast_to(bond_color, (n_verts, 3)))
[docs] def test_atoms_mesh_empty_uses_geometry_draw_info() -> None: spec = SphereGeometrySpec(slices=8, stacks=8) sphere = SphereMesh(spec) data = AtomSpheresMesh([], geometry=spec).to_mesh_data() assert data.vertices.shape[0] == 0 assert data.draw_info.vertices_per_item == sphere.vertices_per_item assert data.draw_info.elements_per_item == sphere.elements_per_item
[docs] def test_to_legacy_glmesh_without_upload() -> None: atom = _Atom(0.0, 0.0, 0.0, "B") mesh = AtomSpheresMesh([atom]) legacy = mesh.to_legacy_glmesh(upload=False) assert legacy.vao is None
[docs] def test_to_glmesh_without_upload() -> None: atom = _Atom(0.0, 0.0, 0.0, "A") mesh = AtomSpheresMesh([atom]) modern = mesh.to_glmesh(upload=False) assert modern.vao is None
[docs] def test_atom_point_geometry_is_one_origin_vertex() -> None: geometry = AtomPointGeometry(radius=0.4) template = geometry.build() assert geometry.vertices_per_item == 1 assert geometry.elements_per_item == 1 assert template.positions.shape == (1, 3) np.testing.assert_allclose(template.positions, [[0.0, 0.0, 0.0]]) np.testing.assert_allclose(template.normals, [[0.0, 0.0, 0.0]]) assert template.indices is None
[docs] def test_atom_points_mesh_two_atoms_unindexed() -> None: """Two atoms: one vertex each, colors not repeated, no EBO.""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(5.0, 1.0, 2.0, "B") def color_fn(atom: _Atom) -> tuple[float, float, float]: return (1.0, 0.0, 0.0) if atom.chain_id == "A" else (0.0, 1.0, 0.0) data = AtomPointsMesh( [atom_a, atom_b], color_fn=color_fn, radius=0.2, ).to_mesh_data() assert data.vertices.shape == (2, 3) np.testing.assert_allclose(data.vertices[0], [0.0, 0.0, 0.0]) np.testing.assert_allclose(data.vertices[1], [5.0, 1.0, 2.0]) assert data.colors.shape == (2, 3) np.testing.assert_allclose(data.colors[0], (1.0, 0.0, 0.0)) np.testing.assert_allclose(data.colors[1], (0.0, 1.0, 0.0)) assert data.indices is None or np.asarray(data.indices).size == 0 assert data.draw_info.mode == GLDrawMode.POINTS assert data.draw_info.indexed is False assert data.draw_info.vertices_per_item == 1 assert data.draw_info.elements_per_item == 1
[docs] def test_atom_points_mesh_color_fn_called_once_per_atom() -> None: atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "B") seen: list[object] = [] def color_fn(atom: object) -> tuple[float, float, float]: seen.append(atom) return (0.1, 0.2, 0.3) AtomPointsMesh([atom_a, atom_b], color_fn=color_fn).to_mesh_data() assert seen == [atom_a, atom_b]
[docs] def test_atom_points_mesh_empty_is_unindexed_points() -> None: data = AtomPointsMesh([]).to_mesh_data() assert data.vertices.shape[0] == 0 assert data.draw_info.mode == GLDrawMode.POINTS assert data.draw_info.indexed is False assert data.draw_info.vertices_per_item == 1 assert data.draw_info.elements_per_item == 1
[docs] def test_bond_lines_mesh_two_atoms_one_pair() -> None: """Two atoms and one pair: one vertex each, LINES indices [0, 1].""" atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "A") data = BondLinesMesh( [atom_a, atom_b], indices=[[0, 1]], color_bonds=False, ).to_mesh_data() assert data.vertices.shape == (2, 3) np.testing.assert_allclose(data.vertices[0], [0.0, 0.0, 0.0]) np.testing.assert_allclose(data.vertices[1], [1.0, 0.0, 0.0]) np.testing.assert_array_equal(np.asarray(data.indices).ravel(), [0, 1]) assert data.draw_info.mode == GLDrawMode.LINES assert data.draw_info.indexed is True assert data.draw_info.elements_per_item == 2 assert data.draw_info.vertices_per_item != 2
[docs] def test_bond_lines_mesh_color_bonds_false_broadcasts_bond_color() -> None: atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "B") bond_color = (0.2, 0.4, 0.6) data = BondLinesMesh( [atom_a, atom_b], indices=[[0, 1]], bond_color=bond_color, color_bonds=False, ).to_mesh_data() assert data.colors.shape == (2, 3) np.testing.assert_allclose(data.colors, np.broadcast_to(bond_color, (2, 3)))
[docs] def test_bond_lines_mesh_color_fn_called_once_per_atom() -> None: atom_a = _Atom(0.0, 0.0, 0.0, "A") atom_b = _Atom(1.0, 0.0, 0.0, "B") seen: list[object] = [] def color_fn(atom: object) -> tuple[float, float, float]: seen.append(atom) return (0.1, 0.2, 0.3) BondLinesMesh( [atom_a, atom_b], indices=[[0, 1]], color_fn=color_fn, color_bonds=True, ).to_mesh_data() assert seen == [atom_a, atom_b]
[docs] def test_bond_lines_mesh_empty_is_indexed_lines() -> None: data = BondLinesMesh([]).to_mesh_data() assert data.vertices.shape[0] == 0 assert data.draw_info.mode == GLDrawMode.LINES assert data.draw_info.indexed is True assert data.draw_info.elements_per_item == 2 assert data.draw_info.vertices_per_item == 1