Adapter to test BSDF sampling using the Chi^2 test.
bsdf_type
(string):Name of the BSDF plugin to instantiate.
extra
(string):Additional XML used to specify the BSDF’s parameters.
wi
(array(3,)):Incoming direction, in local coordinates.
Implements Pearson’s chi-square test for goodness of fit of a distribution to a known reference distribution.
The implementation here specifically compares a Monte Carlo sampling strategy on a 2D (or lower dimensional) space against a reference distribution obtained by numerically integrating a probability density function over grid in the distribution’s parameter domain.
domain
(object):An implementation of the domain interface (SphericalDomain
, etc.),
which transforms between the parameter and target domain of the
distribution
sample_func
(function):An importance sampling function which maps an array of uniform variates
of size [sample_dim, sample_count]
to an array of sample_count
samples on the target domain.
pdf_func
(function):Function that is expected to specify the probability density of the
samples produced by sample_func
. The test will try to collect
sufficient statistical evidence to reject this hypothesis.
sample_dim
(int):Number of random dimensions consumed by sample_func
per sample. The
default value is 2
.
sample_count
(int):Total number of samples to be generated. The test will have more
evidence as this number tends to infinity. The default value is
1000000
.
res
(int):Vertical resolution of the generated histograms. The horizontal
resolution will be calculated as res * domain.aspect()
. The
default value of 101
is intentionally an odd number to prevent
issues with floating point precision at sharp boundaries that may
separate the domain into two parts (e.g. top hemisphere of a sphere
parameterization).
ires
(int):Number of horizontal/vertical subintervals used to numerically integrate
the probability density over each histogram cell (using the trapezoid
rule). The default value is 4
.
Notes:
The following attributes are part of the public API:
The implementation may generate a number of messages while running the test, which can be retrieved via this attribute.
The histogram array is populated by the tabulate_histogram()
method
and stored in this attribute.
The probability density function array is populated by the
tabulate_pdf()
method and stored in this attribute.
The p-value of the test is computed in the run()
method and stored
in this attribute.
Invoke the provided sampling strategy many times and generate a
histogram in the parameter domain. If sample_func
returns a tuple
(positions, weights)
instead of just positions, the samples are
considered to be weighted.
Numerically integrate the provided probability density function over
each cell to generate an array resembling the histogram computed by
tabulate_histogram()
. The function uses the trapezoid rule over
intervals discretized into self.ires
separate function evaluations.
Run the Chi^2 test
significance_level
(float):Denotes the desired significance level (e.g. 0.01 for a test at the 1% significance level)
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.
True
upon success, False
if the null hypothesis was
rejected.
The identity map on the line.
Adapter for testing microfacet distribution sampling techniques (separately from BSDF models, which are also tested)
Adapter to test phase function sampling using the Chi^2 test.
phase_type
(string):Name of the phase function plugin to instantiate.
extra
(string):Additional XML used to specify the phase function’s parameters.
wi
(array(3,)):Incoming direction, in local coordinates.
The identity map on the plane
Adapter which permits testing 1D spectral power distributions using the Chi^2 test.
Maps between the unit sphere and a [cos(theta), phi] parameterization.
Base class: mitsuba.python.autodiff.Optimizer
Implements the Adam optimizer presented in the paper Adam: A Method for Stochastic Optimization by Kingman and Ba, ICLR 2015.
lr
:learning rate
beta_1
:controls the exponential averaging of first order gradient moments
beta_2
:controls the exponential averaging of second order gradient moments
Take a gradient step
Base class of all gradient-based optimizers (currently SGD and Adam)
params
:dictionary (name: variable)
of differentiable parameters to be
optimized.
lr
:learning rate
Set the learning rate.
Temporarily disable the generation of gradients.
Base class: mitsuba.python.autodiff.Optimizer
Implements basic stochastic gradient descent with a fixed learning rate
and, optionally, momentum [SMDH13] (0.9 is a typical
parameter value for the momentum
parameter).
The momentum-based SGD uses the update equation
where \(v\) is the velocity, \(p\) are the positions, \(\varepsilon\) is the learning rate, and \(\mu\) is the momentum parameter.
lr
:learning rate
momentum
:momentum factor
Take a gradient step
Internally used function: render the specified Mitsuba scene and return a floating point array containing RGB values and AOVs, if applicable
Perform a differentiable of the scene scene
, returning a floating point
array containing RGB values and AOVs, if applicable.
spp
(None
, int
, or a 2-tuple (int, int)
):Specifies the number of samples per pixel to be used for rendering,
overriding the value that is specified in the scene. If spp=None
,
the original value takes precedence. If spp
is a 2-tuple
(spp_primal: int, spp_deriv: int)
, the first element specifies the
number of samples for the primal pass, and the second specifies the
number of samples for the derivative pass. See the explanation of the
unbiased
parameter for further detail on what these mean.
Memory usage is roughly proportional to the spp
, value, hence this
parameter should be reduced if you encounter out-of-memory errors.
unbiased
(bool
):One potential issue when naively differentiating a rendering algorithm is that the same set of Monte Carlo sample is used to generate both the primal output (i.e. the image) along with derivative output. When the rendering algorithm and objective are jointly differentiated, we end up with expectations of products that do not satisfy the equality \(\mathbb{E}[X Y]=\mathbb{E}[X]\, \mathbb{E}[Y]\) due to correlations between \(X\) and \(Y\) that result from this sample re-use.
When unbiased=True
, the render()
function will generate an
unbiased estimate that de-correlates primal and derivative
components, which boils down to rendering the image twice and naturally
comes at some cost in performance \((\sim 1.6 imes\!)\). Often,
biased gradients are good enough, in which case unbiased=False
should be specified instead.
The number of samples per pixel per pass can be specified separately
for both passes by passing a tuple to the spp
parameter.
Note that unbiased mode is only relevant for reverse-mode differentiation. It is not needed when visualizing parameter gradients in image space using forward-mode differentiation.
optimizer
(mitsuba.python.autodiff.Optimizer
):The optimizer referencing relevant scene parameters must be specified
when unbiased=True
. Otherwise, there is no need to provide this
parameter.
sensor_index
(int
):When the scene contains more than one sensor/camera, this parameter can be specified to select the desired sensor.
Write the linearized RGB image in data
to a PNG/EXR/.. file with
resolution resolution
.
Dictionary-like object that references various parameters used in a Mitsuba
scene graph. Parameters can be read and written using standard syntax
(parameter_map[key]
). The class exposes several non-standard functions,
specifically torch`()
,
update`()
, and
keep`()
.
Private constructor (use
mitsuba.python.util.traverse()
instead)
Converts all Enoki arrays into PyTorch arrays and return them as a dictionary. This is mainly useful when using PyTorch to optimize a Mitsuba scene.
Marks a specific parameter and its parent objects as dirty. A subsequent call
to update`()
will refresh their internal
state. This function is automatically called when overwriting a parameter using
__setitem__`()
.
This function should be called at the end of a sequence of writes to the dictionary. It automatically notifies all modified Mitsuba objects and their parent objects that they should refresh their internal state. For instance, the scene may rebuild the kd-tree when a shape was modified, etc.
Reduce the size of the dictionary by only keeping elements, whose keys are part of the provided list ‘keys’.
Traverse a node of Mitsuba’s scene graph and return a dictionary-like object that can be used to read and write associated scene parameters.
See also mitsuba.python.util.ParameterMap
.
Regularized lower incomplete gamma function based on CEPHES
Enum for different files or dicts containing specific info
File Writing API Populates a dictionary with scene data, then writes it to XML.
Add an entry to a given subdict.
key: dict key value: entry file: the subdict to which to add the data
Add a comment to the scene dict
comment: text of the comment file: the subdict to which to add the comment
Add an include tag to the main file. This is used when splitting the XML scene file in multiple fragments.
file: the file to include
Write a string to file index ind. Optionally indent the string by a number of tabs
ind: index of the file to write to st: text to write tabs: optional number of tabs to add
Open the files for output, using filenames based on the given base name. Create the necessary folders to create the file at the specified path.
name: path to the scene.xml file to write.
Switch next output to the given file index
file: index of the file to start writing to
Write an XML comment to file.
comment: The text of the comment to write file: Index of the file to write to
Write an XML header to a specified file. Optionally add a comment to describe the file.
file: The file to write to comment: Optional comment to add (e.g. “# Geometry file”)
Open an XML tag (e.g. emitter, bsdf…)
name: Name of the tag (emitter, bsdf, shape…) attributes: Additional fileds to add to the opening tag (e.g. name, type…) file: File to write to
Close the last tag we opened in a given file.
file: The file to write to
Write a single-line XML element.
name: Name of the element (e.g. integer, string, rotate…) attributes: Additional fields to add to the element (e.g. name, value…) file: The file to write to
Get the corresponding tag of a given plugin (e.g. ‘bsdf’ for ‘diffuse’) If the given type (e.g. ‘transform’) is not a plugin, returns None.
plugin_type: Name of the type (e.g. ‘diffuse’, ‘ply’…)
Get the tag in which we are currently writing
Traverse the scene graph and look for properties in the defaults dict. For such properties, store their value in a default tag and replace the value by $name in the prop.
scene_dict: The dictionary containing the scene info
Add default properties.
Reorder the scene dict before writing it to file.
Separate the dict into different category-specific subdicts.
If not splitting files, merge them in the end.
scene_dict: The dictionary containing the scene data
Format rgb or spectrum tags to the proper XML output. The entry should contain the name and value of the spectrum entry. The type is passed separately, since it is popped from the dict in write_dict
entry: the dict containing the spectrum entry_type: either ‘spectrum’ or ‘rgb’
Given a filepath, either copy it in the scene folder (in the corresponding directory) or convert it to a relative path.
filepath: the path to the given file tag: the tag this path property belongs to in (shape, texture, spectrum)
Main XML writing routine. Given a dictionary, iterate over its entries and write them to file. Calls itself for nested dictionaries.
data: The dictionary to write to file.
Preprocess then write the input dict to XML file format
scene_dict: The dictionary containing all the scene info.
Converts a mitsuba Transform4f into a dict entry. This dict entry won’t have a ‘type’ because it’s handled in a specific case.
transform: the given transform matrix
Export a transform as a combination of rotation, scale and translation. This helps manually modifying the transform after export (for cameras for instance)
transform: The Transform4f transform matrix to decompose export_scale: Whether to add a scale property or not. (e.g. don’t do it for cameras to avoid clutter)
Copy data and metadata. Return the file’s destination.
Metadata is copied with copystat(). Please see the copystat function for more information.
The destination may be a directory.
If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”.
Function decorator that adds the mitsuba project root to the FileResolver’s search path. This is useful in particular for tests that e.g. load scenes, and need to specify paths to resources.
The file resolver is restored to its previous state once the test’s execution has finished.
Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of the current line, the function name, a list of lines of context from the source code, and the index of the current line within that list. The optional second argument specifies the number of lines of context to return, which are centered around the current line.
Return a list of records for the stack above the caller’s frame.
Fixture to create a temporary file
Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper(). This is a convenience function to simplify applying partial() to update_wrapper().