def test_add_and_remove_independent_variable(): mg = ModelGetter() m = mg.model # Create an independent variable independent_variable = IndependentVariable("time", 1.0, u.s) # Try to add it m.add_independent_variable(independent_variable) # Try to remove it m.remove_independent_variable("time") with pytest.raises(AssertionError): m.add_independent_variable(Parameter("time", 1.0)) # Try to add it twice, which shouldn't fail m.add_independent_variable(independent_variable) m.add_independent_variable(independent_variable) # Try to display it just to make sure it works m.display() # Now try to use it link_law = Powerlaw() link_law.K.value = 1.0 link_law.index.value = -1.0 n_free_before_link = len(m.free_parameters) m.link(m.one.spectrum.main.Powerlaw.K, independent_variable, link_law) # The power law adds two parameters, but the link removes one, so assert len(m.free_parameters) - 1 == n_free_before_link # Now see if it works for t in np.linspace(0, 10, 100): independent_variable.value = t assert m.one.spectrum.main.Powerlaw.K.value == link_law(t)
def test_time_domain_integration(): po = Powerlaw() default_powerlaw = Powerlaw() src = PointSource("test", ra=0.0, dec=0.0, spectral_shape=po) m = Model(src) # type: model.Model # Add time independent variable time = IndependentVariable("time", 0.0, u.s) m.add_independent_variable(time) # Now link one of the parameters with a simple line law line = Line() line.a = 0.0 m.link(po.index, time, line) # Test the display just to make sure it doesn't crash m.display() # Now test the average with the integral energies = np.linspace(1, 10, 10) results = m.get_point_source_fluxes(0, energies, tag=(time, 0, 10)) # type: np.ndarray assert np.all(results == 1.0) # Now test the linking of the normalization, first with a constant then with a line with a certain # angular coefficient m.unlink(po.index) po.index.value = default_powerlaw.index.value line2 = Line() line2.a = 0.0 line2.b = 1.0 m.link(po.K, time, line2) time.value = 1.0 results = m.get_point_source_fluxes(0, energies, tag=(time, 0, 10)) assert np.allclose(results, default_powerlaw(energies)) # Now make something actually happen line2.a = 1.0 line2.b = 1.0 results = m.get_point_source_fluxes(0, energies, tag=(time, 0, 10)) # type: np.ndarray # Compare with analytical result def F(x): return line2.a.value / 2.0 * x**2 + line2.b.value * x effective_norm = (F(10) - F(0)) / 10.0 expected_results = default_powerlaw( energies) * effective_norm # type: np.ndarray assert np.allclose(expected_results, results)