"""Tests for the RemizovNet PyTorch module.""" import torch from remizov_net.net import RemizovLayer, RemizovNet class TestRemizovLayer: """Test individual RemizovLayer.""" def test_output_shape(self): layer = RemizovLayer(grid_size=64, tau=0.1) x = torch.randn(4, 64) y = layer(x) assert y.shape == (4, 64) def test_a_positive(self): """Coefficient a(x) must always be positive.""" layer = RemizovLayer(grid_size=32, tau=0.1) # Even with negative log_a, softplus keeps a > 0 layer.log_a.data = torch.full((32,), -10.0) assert (layer.a > 0).all() def test_gradient_flows(self): """Gradients should propagate through the layer.""" layer = RemizovLayer(grid_size=32, tau=0.1) x = torch.randn(2, 32, requires_grad=True) y = layer(x) loss = y.sum() loss.backward() assert layer.log_a.grad is not None assert layer.b.grad is not None assert layer.c.grad is not None def test_potential_formula(self): """V(x) = c - b^2/(4a).""" layer = RemizovLayer(grid_size=16, tau=0.1) layer.log_a.data = torch.ones(16) # a ≈ softplus(1) ≈ 1.31 layer.b.data = torch.full((16,), 2.0) layer.c.data = torch.full((16,), 3.0) a = layer.a expected = 3.0 - 4.0 / (4.0 * a) torch.testing.assert_close(layer.potential, expected) class TestRemizovNet: """Test the full RemizovNet.""" def test_output_shape(self): net = RemizovNet(grid_size=64, n_steps=10, total_time=1.0) x = torch.randn(8, 64) y = net(x) assert y.shape == (8, 64) def test_shared_coefficients(self): """Shared mode: all steps use the same parameters.""" net = RemizovNet(grid_size=32, n_steps=5, shared_coeffs=True) params = list(net.parameters()) # Should have exactly 3 parameters: log_a, b, c assert len(params) == 3 def test_independent_coefficients(self): """Independent mode: each step has its own parameters.""" net = RemizovNet(grid_size=32, n_steps=5, shared_coeffs=False) params = list(net.parameters()) # Should have 3 * n_steps = 15 parameters assert len(params) == 15 def test_get_coefficients(self): net = RemizovNet(grid_size=32, n_steps=5, shared_coeffs=True) coeffs = net.get_coefficients() assert "a" in coeffs assert "b" in coeffs assert "c" in coeffs assert coeffs["a"].shape == (32,) def test_equation_string(self): net = RemizovNet(grid_size=16, n_steps=5, shared_coeffs=True) eq = net.equation_string() assert "y''" in eq assert "y'" in eq assert "g(x)" in eq def test_training_step(self): """Single training step should reduce loss.""" net = RemizovNet(grid_size=32, n_steps=5, total_time=1.0) optimizer = torch.optim.Adam(net.parameters(), lr=0.01) g = torch.randn(4, 32) y_target = torch.randn(4, 32) # Training step optimizer.zero_grad() y_pred = net(g) loss = torch.nn.functional.mse_loss(y_pred, y_target) loss.backward() optimizer.step() # After step with torch.no_grad(): y_pred = net(g) loss_after = torch.nn.functional.mse_loss(y_pred, y_target).item() # Loss should decrease (not guaranteed but very likely with random init) # Use a weak check: loss_after should be finite assert torch.isfinite(torch.tensor(loss_after))