def test_kernel_dict_post_load(mode_mono): from mitsuba.python.util import traverse kernel_dict = KernelDict( data={ "type": "directional", "irradiance": { "type": "irregular", "wavelengths": "400, 500", "values": "1, 1", }, }, post_load={ "irradiance.wavelengths": np.array([400.0, 500.0, 600.0]), "irradiance.values": np.array([0.0, 1.0, 2.0]), }, ) # Without post-load update, buffers are initialised as in data obj = kernel_dict.load(post_load_update=False) params = traverse(obj) assert params["irradiance.wavelengths"] == np.array([400.0, 500.0]) assert params["irradiance.values"] == np.array([1.0, 1.0]) # Without post-load update, buffers are initialised as in post_load obj = kernel_dict.load(post_load_update=True) params = traverse(obj) assert params["irradiance.wavelengths"] == np.array([400.0, 500.0, 600.0]) assert params["irradiance.values"] == np.array([0.0, 1.0, 2.0])
def test_rpv(mode_mono): ctx = KernelDictContext() # Default constructor surface = RPVSurface() # Check if produced scene can be instantiated kernel_dict = KernelDict.from_elements(surface, ctx=ctx) assert kernel_dict.load() is not None # Construct from floats surface = RPVSurface(width=ureg.Quantity(1000.0, "km"), rho_0=0.3, k=1.4, g=-0.23) assert np.allclose(surface.width, ureg.Quantity(1e6, ureg.m)) # Construct from mixed spectrum types surface = RPVSurface( width=ureg.Quantity(1000.0, "km"), rho_0=0.3, k={ "type": "uniform", "value": 0.3 }, g={ "type": "interpolated", "wavelengths": [300.0, 800.0], "values": [-0.23, 0.23], }, ) # Check if produced scene can be instantiated assert KernelDict.from_elements(surface, ctx=ctx).load() is not None
def test_solar_irradiance(mode_mono): # Default context ctx = KernelDictContext() # We can instantiate the element s = SolarIrradianceSpectrum() # Unsupported solar spectrum keywords raise with pytest.raises(ValueError): SolarIrradianceSpectrum(dataset="doesnt_exist") # Produced kernel dict is valid assert KernelDict.from_elements(s, ctx=ctx).load() # A more detailed specification still produces a valid object s = SolarIrradianceSpectrum(scale=2.0) assert KernelDict.from_elements(s, ctx=ctx).load() # Element doesn't work out of the supported spectral range s = SolarIrradianceSpectrum(dataset="thuillier_2003") with pytest.raises(ValueError): ctx = KernelDictContext(spectral_ctx={"wavelength": 2400.0}) s.kernel_dict(ctx) # solid_2017_mean dataset can be used ctx = KernelDictContext() s = SolarIrradianceSpectrum(dataset="solid_2017_mean") assert KernelDict.from_elements(s, ctx=ctx).load()
def test_kernel_dict_duplicate_id(): from eradiate.contexts import KernelDictContext from eradiate.scenes.illumination import illumination_factory # Upon trying to add a scene element, whose ID is already present # in the KernelDict, a Warning must be issued. with pytest.warns(Warning): kd = KernelDict({ "testmeasure": { "type": "directional", "id": "testmeasure", "irradiance": { "type": "interpolated", "wavelengths": [400, 500], "values": [1, 1], }, } }) kd.add( illumination_factory.convert({ "type": "directional", "id": "testmeasure", "irradiance": { "type": "interpolated", "wavelengths": [400, 500], "values": [2, 2], }, }), ctx=KernelDictContext(), )
def test_kernel_dict_construct(): # Object creation is possible only if a variant is set importlib.reload( mitsuba ) # Required to ensure that any variant set by another test is unset with pytest.raises(KernelVariantError): KernelDict() mitsuba.set_variant("scalar_mono") # variant attribute is set properly kernel_dict = KernelDict({}) assert kernel_dict.variant == "scalar_mono"
def test_multi_radiancemeter_noargs(mode_mono): # Instantiation succeeds s = MultiRadiancemeterMeasure() # The kernel dict can be instantiated ctx = KernelDictContext() assert KernelDict.from_elements(s, ctx=ctx).load()
def test_leaf_cloud_kernel_dict(mode_mono): """Partial unit testing for :meth:`LeafCloud.kernel_dict`.""" ctx = KernelDictContext() cloud_id = "my_cloud" cloud = LeafCloud( id=cloud_id, leaf_positions=[[0, 0, 0], [1, 1, 1]], leaf_orientations=[[1, 0, 0], [0, 1, 0]], leaf_radii=[0.1, 0.1], leaf_reflectance=0.5, leaf_transmittance=0.5, ) kernel_dict = cloud.kernel_dict(ctx=ctx) # The BSDF is bilambertian with the parameters we initially set assert kernel_dict[f"bsdf_{cloud_id}"] == { "type": "bilambertian", "reflectance": {"type": "uniform", "value": 0.5}, "transmittance": {"type": "uniform", "value": 0.5}, } # Leaves are disks for shape_key in [f"{cloud_id}_leaf_0", f"{cloud_id}_leaf_1"]: assert kernel_dict[shape_key]["type"] == "disk" # Kernel dict is valid assert KernelDict(kernel_dict).load()
def test_discrete_canopy_padded(mode_mono, tempfile_leaves, tempfile_spheres): """Unit tests for :meth:`.DiscreteCanopy.padded`""" ctx = KernelDictContext() canopy = DiscreteCanopy.leaf_cloud_from_files( id="canopy", size=[100, 100, 30], leaf_cloud_dicts=[ { "instance_filename": tempfile_spheres, "leaf_cloud_filename": tempfile_leaves, "sub_id": "leaf_cloud", } ], ) # The padded canopy object is valid and instantiable padded_canopy = canopy.padded_copy(2) assert padded_canopy assert KernelDict.from_elements(padded_canopy, ctx=ctx).load() # Padded canopy has (2*padding + 1) ** 2 times more instances than original assert len(padded_canopy.instances(ctx)) == len(canopy.instances(ctx)) * 25 # Padded canopy has 2*padding + 1 times larger horizontal size than original assert np.allclose(padded_canopy.size[:2], 5 * canopy.size[:2]) # Padded canopy has same vertical size as original assert padded_canopy.size[2] == canopy.size[2]
def test_path(mode_mono): # Basic specification integrator = PathIntegrator() ctx = KernelDictContext() assert integrator.kernel_dict(ctx)["integrator"] == {"type": "path"} assert KernelDict.from_elements(integrator, ctx=ctx).load() is not None # More detailed specification integrator = PathIntegrator(max_depth=5, rr_depth=3, hide_emitters=False) assert integrator.kernel_dict(ctx)["integrator"] == { "type": "path", "max_depth": 5, "rr_depth": 3, "hide_emitters": False, } assert KernelDict.from_elements(integrator, ctx=ctx).load() is not None
def test_black(mode_mono): ctx = KernelDictContext() # Default constructor bs = BlackSurface() # Check if produced scene can be instantiated kernel_dict = KernelDict.from_elements(bs, ctx=ctx) assert kernel_dict.load() is not None # Check if the correct kernel dict is created ls = LambertianSurface(reflectance={"type": "uniform", "value": 0}) assert KernelDict.from_elements(ls, ctx=ctx) == KernelDict.from_elements( bs, ctx=ctx )
def test_checkerboard(mode_mono): ctx = KernelDictContext() # Default constructor s = CheckerboardSurface() # Check if produced scene can be instantiated kernel_dict = KernelDict.from_elements(s, ctx=ctx) assert kernel_dict.load() is not None # Constructor with arguments s = CheckerboardSurface( width=1000.0, reflectance_a=0.5, reflectance_b=0.1, scale_pattern=1.5 ) # Check if produced scene can be instantiated assert KernelDict.from_elements(s, ctx=ctx).load() is not None
def test_homogeneous_phase_function(mode_mono, phase_id, ref): """Supports all available phase function types.""" r = HomogeneousAtmosphere(phase={"type": phase_id}) # The resulting object produces a valid kernel dictionary ctx = KernelDictContext(ref=ref) kernel_dict = KernelDict.from_elements(r, ctx=ctx) assert kernel_dict.load() is not None
def test_discrete_canopy_homogeneous(mode_mono): ctx = KernelDictContext() # The generate_homogeneous() constructor returns a valid canopy object canopy = DiscreteCanopy.homogeneous( n_leaves=1, leaf_radius=0.1, l_horizontal=10, l_vertical=3 ) assert KernelDict.from_elements(canopy, ctx=ctx).load()
def test_molecular_atmosphere_default(mode_mono, tmpdir, ussa76_approx_test_absorption_data_set): """Default MolecularAtmosphere constructor produces a valid kernel dictionary.""" spectral_ctx = SpectralContext.new(wavelength=550.0) ctx = KernelDictContext(spectral_ctx=spectral_ctx) atmosphere = MolecularAtmosphere(absorption_data_sets=dict( us76_u86_4=ussa76_approx_test_absorption_data_set)) assert KernelDict.from_elements(atmosphere, ctx=ctx).load() is not None
def test_isotropic(modes_all): ctx = KernelDictContext() # Default constructor phase = IsotropicPhaseFunction() # Check if produced kernel dict can be instantiated kernel_dict = KernelDict.from_elements(phase, ctx=ctx) assert kernel_dict.load() is not None
def test_multi_radiancemeter_args(mode_mono): # Instantiation succeeds s = MultiRadiancemeterMeasure( origins=[[0, 0, 0]] * 3, directions=[[1, 0, 0], [0, 1, 0], [0, 0, 1]] ) # The kernel dict can be instantiated ctx = KernelDictContext() assert KernelDict.from_elements(s, ctx=ctx).load()
def test_leaf_cloud_from_file(mode_mono, tempfile_leaves): """Unit testing for :meth:`LeafCloud.from_file`.""" ctx = KernelDictContext() # A LeafCloud instance can be loaded from a file on the hard drive cloud = LeafCloud.from_file(tempfile_leaves) assert len(cloud.leaf_positions) == 5 assert np.allclose(cloud.leaf_radii, 0.1 * ureg.m) # Produced kernel dict is valid assert KernelDict.from_elements(cloud, ctx=ctx).load()
def test_lambertian(mode_mono): ctx = KernelDictContext() # Default constructor ls = LambertianSurface() # Check if produced scene can be instantiated kernel_dict = KernelDict.from_elements(ls, ctx=ctx) assert kernel_dict.load() is not None # Constructor with arguments ls = LambertianSurface(width=1000.0, reflectance={ "type": "uniform", "value": 0.3 }) # Check if produced scene can be instantiated assert KernelDict.from_elements(ls, ctx=ctx).load() is not None
def test_volpathmis(mode_mono): # Basic specification integrator = VolPathMISIntegrator() ctx = KernelDictContext() assert integrator.kernel_dict(ctx)["integrator"] == {"type": "volpathmis"} assert KernelDict.from_elements(integrator, ctx=ctx).load() is not None # More detailed specification integrator = VolPathMISIntegrator(max_depth=5, rr_depth=3, hide_emitters=False, use_spectral_mis=True) assert integrator.kernel_dict(ctx)["integrator"] == { "type": "volpathmis", "max_depth": 5, "rr_depth": 3, "hide_emitters": False, "use_spectral_mis": True, } assert KernelDict.from_elements(integrator, ctx=ctx).load() is not None
def test_distant_flux_construct(modes_all): # Test default constructor d = DistantFluxMeasure() ctx = KernelDictContext() assert KernelDict.from_elements(d, ctx=ctx).load() is not None # Test target support # -- Target a point d = DistantFluxMeasure(target=[0, 0, 0]) assert KernelDict.from_elements(d, ctx=ctx).load() is not None # -- Target an axis-aligned rectangular patch d = DistantFluxMeasure(target={ "type": "rectangle", "xmin": 0, "xmax": 1, "ymin": 0, "ymax": 1 }) assert KernelDict.from_elements(d, ctx=ctx).load() is not None
def test_molecular_atmosphere_afgl_1986( mode_mono, tmpdir, afgl_1986_test_absorption_data_sets, ): """MolecularAtmosphere 'afgl_1986' constructor produces a valid kernel dictionary.""" spectral_ctx = SpectralContext.new(wavelength=550.0) ctx = KernelDictContext(spectral_ctx=spectral_ctx) atmosphere = MolecularAtmosphere.afgl_1986( absorption_data_sets=afgl_1986_test_absorption_data_sets) assert KernelDict.from_elements(atmosphere, ctx=ctx).load() is not None
def test_hg(mode_mono): ctx = KernelDictContext() # Default constructor phase = HenyeyGreensteinPhaseFunction() # Construct with custom asymmetry parameter phase = HenyeyGreensteinPhaseFunction(g=0.25) # Check if produced kernel dict can be instantiated kernel_dict = KernelDict.from_elements(phase, ctx=ctx) assert kernel_dict.load() is not None
def test_centralpatch_instantiate(mode_mono): ctx = KernelDictContext() # Default constructor cs = CentralPatchSurface() # Check if produced scene can be instantiated kernel_dict = KernelDict.from_elements(cs, ctx=ctx) assert kernel_dict.load() is not None # background width must be AUTO with pytest.raises(ValueError): cs = CentralPatchSurface( width=1000.0, central_patch=LambertianSurface(reflectance={ "type": "uniform", "value": 0.3 }), background_surface=LambertianSurface(reflectance={ "type": "uniform", "value": 0.3 }, width=10 * ureg.m), ) # Constructor with arguments cs = CentralPatchSurface( width=1000.0, central_patch=LambertianSurface(reflectance={ "type": "uniform", "value": 0.3 }), background_surface=LambertianSurface(reflectance={ "type": "uniform", "value": 0.8 }), ) # Check if produced scene can be instantiated assert KernelDict.from_elements(cs, ctx=ctx).load() is not None
def test_abstract_tree_dispatch_leaf_cloud(mode_mono, tempfile_leaves): """Test if contained LeafCloud is instantiated in all variants""" ctx = KernelDictContext() # A LeafCloud instance can be loaded from a file on the hard drive tree = AbstractTree(leaf_cloud=LeafCloud.from_file(tempfile_leaves)) assert len(tree.leaf_cloud.leaf_positions) == 5 assert np.allclose(tree.leaf_cloud.leaf_radii, 0.1 * ureg.m) # Produced kernel dict is valid assert KernelDict.from_elements(tree.leaf_cloud, ctx=ctx).load() # When passing a dict for the leaf_cloud field, the 'type' param can be omitted assert AbstractTree( leaf_cloud={ "leaf_positions": [[0, 0, 0], [1, 1, 1]], "leaf_orientations": [[0, 0, 1], [1, 0, 0]], "leaf_radii": [0.1, 0.1], }) # Dispatch to from_file if requested tree1 = AbstractTree(leaf_cloud=LeafCloud.from_file(tempfile_leaves)) tree2 = AbstractTree(leaf_cloud={ "construct": "from_file", "filename": tempfile_leaves }) # assert leaf clouds are equal assert np.all( tree1.leaf_cloud.leaf_positions == tree2.leaf_cloud.leaf_positions) assert np.all(tree1.leaf_cloud.leaf_orientations == tree2.leaf_cloud.leaf_orientations) assert np.all(tree1.leaf_cloud.leaf_radii == tree2.leaf_cloud.leaf_radii) assert np.all(tree1.leaf_cloud.leaf_transmittance == tree2.leaf_cloud.leaf_transmittance) assert np.all( tree1.leaf_cloud.leaf_reflectance == tree2.leaf_cloud.leaf_reflectance) # Dispatch to generator if requested tree = AbstractTree( leaf_cloud={ "construct": "cuboid", "n_leaves": 100, "l_horizontal": 10.0, "l_vertical": 1.0, "leaf_radius": 10.0, "leaf_radius_units": "cm", }) assert len(tree.leaf_cloud.leaf_radii) == 100 assert len(tree.leaf_cloud.leaf_positions) == 100 assert np.allclose(tree.leaf_cloud.leaf_radii, 10.0 * ureg.cm)
def test_constant(mode_mono): # Constructor c = ConstantIllumination() ctx = KernelDictContext() assert c.kernel_dict(ctx)[c.id] == { "type": "constant", "radiance": { "type": "uniform", "value": 1.0 }, } assert KernelDict.from_elements(c, ctx=ctx).load() is not None # Check if a more detailed spec is valid c = ConstantIllumination(radiance={"type": "uniform", "value": 1.0}) assert KernelDict.from_elements(c, ctx=ctx).load() is not None # Check if 'uniform' shortcut works c = ConstantIllumination(radiance={"type": "uniform", "value": 1.0}) assert KernelDict.from_elements(c, ctx=ctx).load() is not None # Check if super lazy way works too c = ConstantIllumination(radiance=1.0) assert KernelDict.from_elements(c, ctx=ctx).load() is not None
def test_kernel_dict_check(mode_mono): # Check method raises upon missing scene type kernel_dict = KernelDict({}) with pytest.raises(ValueError): kernel_dict.check() # Check method raises if dict and set variants are incompatible mitsuba.set_variant("scalar_mono_double") with pytest.raises(KernelVariantError): kernel_dict.check()
def test_perspective(mode_mono): # Constructor d = PerspectiveCameraMeasure() ctx = KernelDictContext() assert KernelDict.from_elements(d, ctx=ctx).load() # Origin and target cannot be the same for point in [[0, 0, 0], [1, 1, 1], [-1, 0.5, 1.3333]]: with pytest.raises(ValueError): PerspectiveCameraMeasure(origin=point, target=point) # Up must differ from the camera's viewing direction with pytest.raises(ValueError): PerspectiveCameraMeasure(origin=[0, 1, 0], target=[1, 0, 0], up=[1, -1, 0])
def test_mesh_tree_element_load(mode_mono, tmp_file, request): """ Instantiate MeshTreeElement objects from obj and ply files and load the corresponding Mitsuba objects. """ tmp_file = request.getfixturevalue(tmp_file) ctx = KernelDictContext(ref=True) tree_element = MeshTreeElement( id="mesh_tree_obj", mesh_filename=tmp_file, mesh_units=ureg.m, reflectance=0.5, transmittance=0.5, ) d = {**tree_element.bsdfs(ctx), **tree_element.shapes(ctx)} assert KernelDict(d).load()
def test_discrete_canopy_from_files(mode_mono, tempfile_spheres, tempfile_leaves): ctx = KernelDictContext() # The from_files() constructor returns a valid canopy object canopy = DiscreteCanopy.leaf_cloud_from_files( size=[1, 1, 1], leaf_cloud_dicts=[ { "sub_id": "spheres_1", "instance_filename": tempfile_spheres, "leaf_cloud_filename": tempfile_leaves, }, { "sub_id": "spheres_2", "instance_filename": tempfile_spheres, "leaf_cloud_filename": tempfile_leaves, }, ], ) assert KernelDict.from_elements(canopy, ctx=ctx).load()
def test_homogeneous_kernel_dict(mode_mono, ref): """ Produces kernel dictionaries that can be loaded by the kernel. """ from mitsuba.core.xml import load_dict r = HomogeneousAtmosphere() ctx = KernelDictContext(ref=False) dict_phase = onedict_value(r.kernel_phase(ctx)) assert load_dict(dict_phase) is not None dict_medium = onedict_value(r.kernel_media(ctx)) assert load_dict(dict_medium) is not None dict_shape = onedict_value(r.kernel_shapes(ctx)) assert load_dict(dict_shape) is not None ctx = KernelDictContext(ref=ref) kernel_dict = KernelDict.from_elements(r, ctx=ctx) assert kernel_dict.load() is not None