def test03_sample_eval_pdf(variant_scalar_rgb, interaction): from mitsuba.core.math import InvPi from mitsuba.core.warp import square_to_uniform_sphere from mitsuba.render import BSDFContext from mitsuba.core.xml import load_string bsdf = load_string("""<bsdf version="2.0.0" type="twosided"> <bsdf type="diffuse"> <rgb name="reflectance" value="0.1, 0.1, 0.1"/> </bsdf> <bsdf type="diffuse"> <rgb name="reflectance" value="0.9, 0.9, 0.9"/> </bsdf> </bsdf>""") n = 5 ctx = BSDFContext() for u in ek.arange(UInt32, n): for v in ek.arange(UInt32, n): interaction.wi = square_to_uniform_sphere([u / float(n-1), v / float(n-1)]) up = ek.dot(interaction.wi, [0, 0, 1]) > 0 for x in ek.arange(UInt32, n): for y in ek.arange(UInt32, n): sample = [x / float(n-1), y / float(n-1)] (bs, s_value) = bsdf.sample(ctx, interaction, 0.5, sample) if ek.any(s_value > 0): # Multiply by square_to_cosine_hemisphere_theta s_value *= bs.wo[2] * InvPi if not up: s_value *= -1 e_value = bsdf.eval(ctx, interaction, bs.wo) p_pdf = bsdf.pdf(ctx, interaction, bs.wo) assert ek.allclose(s_value, e_value, atol=1e-2) assert ek.allclose(bs.pdf, p_pdf) assert not ek.any(ek.isnan(e_value) | ek.isnan(s_value))
def test06_rgb2spec_fetch_eval_mean(variant_scalar_spectral): from mitsuba.render import srgb_model_fetch, srgb_model_eval, srgb_model_mean from mitsuba.core import MTS_WAVELENGTH_MIN, MTS_WAVELENGTH_MAX, MTS_WAVELENGTH_SAMPLES import numpy as np rgb_values = np.array([ [0, 0, 0], [0.0129831, 0.0129831, 0.0129831], [0.0241576, 0.0241576, 0.0241576], [0.0423114, 0.0423114, 0.0423114], [0.0561285, 0.0561285, 0.0561285], [0.0703601, 0.0703601, 0.0703601], [0.104617, 0.104617, 0.104617], [0.171441, 0.171441, 0.171441], [0.242281, 0.242281, 0.242281], [0.814846, 0.814846, 0.814846], [0.913098, 0.913098, 0.913098], [0.930111, 0.930111, 0.930111], [0.955973, 0.955973, 0.955973], [0.973445, 0.973445, 0.973445], [0.982251, 0.982251, 0.982251], [0.991102, 0.991102, 0.991102], [1, 1, 1], ]) wavelengths = np.linspace(MTS_WAVELENGTH_MIN, MTS_WAVELENGTH_MAX, MTS_WAVELENGTH_SAMPLES) for i in range(rgb_values.shape[0]): rgb = rgb_values[i, :] assert np.all((rgb >= 0.0) & (rgb <= 1.0)), "Invalid RGB attempted" coeff = srgb_model_fetch(rgb) mean = srgb_model_mean(coeff) value = srgb_model_eval(coeff, wavelengths) assert not ek.any(ek.isnan(coeff)), "{} => coeff = {}".format( rgb, coeff) assert not ek.any(ek.isnan(mean)), "{} => mean = {}".format(rgb, mean) assert not ek.any(ek.isnan(value)), "{} => value = {}".format( rgb, value)
def test09_eval_parameterization(variant_scalar_rgb, variant_packet_rgb): from mitsuba.core.xml import load_string shape = load_string(''' <shape type="obj" version="2.0.0"> <string name="filename" value="resources/data/common/meshes/rectangle.obj"/> </shape> ''') print(shape) si = shape.eval_parameterization([-0.01, 0.5]) assert not ek.any(si.is_valid()) si = shape.eval_parameterization([1.0 - 1e-7, 1.0 - 1e-7]) assert ek.all(si.is_valid()) assert ek.allclose(si.p, [1, 1, 0]) si = shape.eval_parameterization([1e-7, 1e-7]) assert ek.all(si.is_valid()) assert ek.allclose(si.p, [-1, -1, 0]) si = shape.eval_parameterization([.2, .3]) assert ek.all(si.is_valid()) assert ek.allclose(si.p, [-.6, -.4, 0])
def render_sample(scene, sampler, rays, bdata, heightmap_pybind, bssrdf=None): """ Sample RTE TODO: Support multi channel sampling Args: scene: Target scene object sampler: Sampler object for random number rays: Given rays for sampling bdata: BSSRDF Data object heightmap_pybind: Object for getting height map around incident position. Refer src/librender/python/heightmap.cpp Returns: result: Sampling RTE result valid_rays: Mask data whether rays are valid or not scatter: Scatter components of Sampling RTE result non_scatter: Non scatter components of Sampling RTE result invalid_sample: Sampling RTE result with invalid sampled data by VAEBSSRDF """ eta = Float(1.0) emission_weight = Float(1.0) throughput = Spectrum(1.0) result = Spectrum(0.0) scatter = Spectrum(0.0) non_scatter = Spectrum(0.0) invalid_sample = Spectrum(0.0) active = True is_bssrdf = False ##### First interaction ##### si = scene.ray_intersect(rays, active) active = si.is_valid() & active valid_rays = si.is_valid() emitter = si.emitter(scene, active) depth = 0 # Set channel # At and after evaluating BSSRDF, a ray consider only this one channel n_channels = 3 channel = UInt32( ek.min(sampler.next_1d(active) * n_channels, n_channels - 1)) d_out_local = Vector3f().zero() d_out_pdf = Float(0) sss = Mask(False) while (True): depth += 1 if config.aovs and depth == 2: sss = is_bssrdf ##### Interaction with emitters ##### emission_val = emission_weight * throughput * Emitter.eval_vec( emitter, si, active) result += ek.select(active, emission_val, Spectrum(0.0)) invalid_sample += ek.select(active, emission_val, Spectrum(0.0)) scatter += ek.select(active & sss, emission_val, Spectrum(0.0)) non_scatter += ek.select(active & ~sss, emission_val, Spectrum(0.0)) active = active & si.is_valid() # Process russian roulette if depth > config.rr_depth: q = ek.min(ek.hmax(throughput) * ek.sqr(eta), 0.95) active = active & (sampler.next_1d(active) < q) throughput *= ek.rcp(q) # Stop if the number of bouces exceeds the given limit bounce, or # all rays are invalid. latter check is done only when the limit # bounce is infinite if depth >= config.max_depth: break ##### Emitter sampling ##### bsdf = si.bsdf(rays) ctx = BSDFContext() active_e = active & has_flag(BSDF.flags_vec(bsdf), BSDFFlags.Smooth) ds, emitter_val = scene.sample_emitter_direction( si, sampler.next_2d(active_e), True, active_e) active_e &= ek.neq(ds.pdf, 0.0) # Query the BSDF for that emitter-sampled direction wo = si.to_local(ds.d) bsdf_val = BSDF.eval_vec(bsdf, ctx, si, wo, active_e) # Determine density of sampling that same direction using BSDF sampling bsdf_pdf = BSDF.pdf_vec(bsdf, ctx, si, wo, active_e) mis = ek.select(ds.delta, Float(1), mis_weight(ds.pdf, bsdf_pdf)) emission_val = mis * throughput * bsdf_val * emitter_val result += ek.select(active, emission_val, Spectrum(0.0)) invalid_sample += ek.select(active, emission_val, Spectrum(0.0)) scatter += ek.select(active & sss, emission_val, Spectrum(0.0)) non_scatter += ek.select(active & ~sss, emission_val, Spectrum(0.0)) ##### BSDF sampling ##### bs, bsdf_val = BSDF.sample_vec(bsdf, ctx, si, sampler.next_1d(active), sampler.next_2d(active), active) ##### BSSRDF replacing ##### if (config.enable_bssrdf): # Replace bsdf samples by ones of BSSRDF bs.wo = ek.select(is_bssrdf, d_out_local, bs.wo) bs.pdf = ek.select(is_bssrdf, d_out_pdf, bs.pdf) bs.sampled_component = ek.select(is_bssrdf, UInt32(1), bs.sampled_component) bs.sampled_type = ek.select(is_bssrdf, UInt32(+BSDFFlags.DeltaTransmission), bs.sampled_type) ############################ throughput *= ek.select(is_bssrdf, Float(1.0), bsdf_val) active &= ek.any(ek.neq(throughput, 0)) eta *= bs.eta # Intersect the BSDF ray against the scene geometry rays = RayDifferential3f(si.spawn_ray(si.to_world(bs.wo))) si_bsdf = scene.ray_intersect(rays, active) ##### Checking BSSRDF ##### if (config.enable_bssrdf): # Whether the BSDF is BSS RDF or not? is_bssrdf = (active & has_flag(BSDF.flags_vec(bsdf), BSDFFlags.BSSRDF) & (Frame3f.cos_theta(bs.wo) < Float(0.0)) & (Frame3f.cos_theta(si.wi) > Float(0.0))) # Decide whether we should use 0-scattering or multiple scattering is_zero_scatter = utils_render.check_zero_scatter( sampler, si_bsdf, bs, channel, is_bssrdf) is_bssrdf = is_bssrdf & ~is_zero_scatter throughput *= ek.select(is_bssrdf, ek.sqr(bs.eta), Float(1.0)) ########################### ###### Process for BSSRDF ###### if (config.enable_bssrdf and not ek.none(is_bssrdf)): # Get projected samples from BSSRDF projected_si, project_suc, abs_prob = bssrdf.sample_bssrdf( scene, bsdf, bs, si, bdata, heightmap_pybind, channel, is_bssrdf) if config.visualize_invalid_sample and (depth <= 1): active = active & (~is_bssrdf | project_suc) invalid_sample += ek.select((is_bssrdf & (~project_suc)), Spectrum([100, 0, 0]), Spectrum(0.0)) # Sample outgoing direction from projected position d_out_local, d_out_pdf = utils_render.resample_wo( sampler, is_bssrdf) # Apply absorption probability throughput *= ek.select(is_bssrdf, Spectrum(1) - abs_prob, Spectrum(1)) # Replace interactions by sampled ones from BSSRDF si_bsdf = SurfaceInteraction3f().masked_si(si_bsdf, projected_si, is_bssrdf) ################################ # Determine probability of having sampled that same # direction using emitter sampling emitter = si_bsdf.emitter(scene, active) ds = DirectionSample3f(si_bsdf, si) ds.object = emitter delta = has_flag(bs.sampled_type, BSDFFlags.Delta) emitter_pdf = ek.select(delta, Float(0.0), scene.pdf_emitter_direction(si, ds)) emission_weight = mis_weight(bs.pdf, emitter_pdf) si = si_bsdf return result, valid_rays, scatter, non_scatter, invalid_sample
def run(self, significance_level=0.01, test_count=1, quiet=False): """ Run the Chi^2 test Parameter ``significance_level`` (float): Denotes the desired significance level (e.g. 0.01 for a test at the 1% significance level) Parameter ``test_count`` (int): Specifies the total number of statistical tests run by the user. This value will be used to adjust the provided significance level so that the combination of the entire set of tests has the provided significance level. Returns → bool: ``True`` upon success, ``False`` if the null hypothesis was rejected. """ from mitsuba.core import UInt32, Float64 from mitsuba.core.math import chi2 from mitsuba.python.math import rlgamma if self.histogram is None: self.tabulate_histogram() if self.pdf is None: self.tabulate_pdf() index = UInt32( [i[0] for i in sorted(enumerate(self.pdf), key=lambda x: x[1])]) # Sort entries by expected frequency (increasing) pdf = Float64(ek.gather(self.pdf, index)) histogram = Float64(ek.gather(self.histogram, index)) # Compute chi^2 statistic and pool low-valued cells chi2val, dof, pooled_in, pooled_out = \ chi2(histogram, pdf, 5) if dof < 1: self._log('Failure: The number of degrees of freedom is too low!') self.fail = True if ek.any(ek.eq(pdf, 0) & ek.neq(histogram, 0)): self._log('Failure: Found samples in a cell with expected ' 'frequency 0. Rejecting the null hypothesis!') self.fail = True if pooled_in > 0: self._log('Pooled %i low-valued cells into %i cells to ' 'ensure sufficiently high expected cell frequencies' % (pooled_in, pooled_out)) pdf_time = (self.pdf_end - self.pdf_start) * 1000 histogram_time = (self.histogram_end - self.histogram_start) * 1000 self._log('Histogram sum = %f (%.2f ms), PDF sum = %f (%.2f ms)' % (self.histogram_sum, histogram_time, self.pdf_sum, pdf_time)) self._log('Chi^2 statistic = %f (d.o.f = %i)' % (chi2val, dof)) # Probability of observing a test statistic at least as # extreme as the one here assuming that the distributions match self.p_value = 1 - rlgamma(dof / 2, chi2val / 2) # Apply the Šidák correction term, since we'll be conducting multiple # independent hypothesis tests. This accounts for the fact that the # probability of a failure increases quickly when several hypothesis # tests are run in sequence. significance_level = 1.0 - \ (1.0 - significance_level) ** (1.0 / test_count) if self.fail: self._log('Not running the test for reasons listed above. Target ' 'density and histogram were written to "chi2_data.py') result = False elif self.p_value < significance_level \ or not ek.isfinite(self.p_value): self._log('***** Rejected ***** the null hypothesis (p-value = %f,' ' significance level = %f). Target density and histogram' ' were written to "chi2_data.py".' % (self.p_value, significance_level)) result = False else: self._log('Accepted the null hypothesis (p-value = %f, ' 'significance level = %f)' % (self.p_value, significance_level)) result = True if not quiet: print(self.messages) if not result: self._dump_tables() return result
def compare_results(res_a, res_b, atol=0.0): assert ek.all(res_a.is_valid() == res_b.is_valid()) if ek.any(res_a.is_valid()): assert ek.allclose(res_a.t, res_b.t, atol=atol), "\n%s\n\n%s" % (res_a.t, res_b.t)
diff_vertex_ref = [] diff_vertex_init = [] for j in range(10): opt = Adam(params_opt, lr = 0.001) # opt = SGD(params_opt, lr = 0.001, momentum = 0.9) for i in range(10): unravel(vertex_positions + Vector3f(0,0,1) * params_opt['displacements'], params[vertex_pos_key]) params.set_dirty(vertex_pos_key) params.update() image = render(scene) if j == 0 and i == 0: image_init = image if ek.any(ek.any(ek.isnan(params[vertex_pos_key]))): print("[WARNING] NaNs in the vertex positions.") if ek.any(ek.isnan(image)): print("[WARNING] NaNs in the image.") # Write a gamma encoded PNG image_np = image.numpy().reshape(height, width, 3) output_file = output_path + 'out_%03i_%03i.png' % (j, i) print("Writing image %s" % (output_file)) Bitmap(image_np).convert(pixel_format=Bitmap.PixelFormat.RGB, component_format=Struct.Type.UInt8, srgb_gamma=True).write(output_file) # Objective function if task == 'plain2bumpy' or task == 'bumpy2bumpy': loss = ek.hsum(ek.hsum(ek.sqr(image - image_ref))) / (height*width*3) if task == 'bumpy2plain':