Nori  24
ttest.cpp
1 /*
2  This file is part of Nori, a simple educational ray tracer
3 
4  Copyright (c) 2015 by Wenzel Jakob
5 
6  Nori is free software; you can redistribute it and/or modify
7  it under the terms of the GNU General Public License Version 3
8  as published by the Free Software Foundation.
9 
10  Nori is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU General Public License for more details.
14 
15  You should have received a copy of the GNU General Public License
16  along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18 
19 #include <nori/scene.h>
20 #include <nori/bsdf.h>
21 #include <nori/camera.h>
22 #include <nori/integrator.h>
23 #include <nori/sampler.h>
24 #include <hypothesis.h>
25 #include <pcg32.h>
26 
27 /*
28  * =======================================================================
29  * WARNING WARNING WARNING WARNING WARNING WARNING
30  * =======================================================================
31  * Remember to put on SAFETY GOGGLES before looking at this file. You
32  * are most certainly not expected to read or understand any of it.
33  * =======================================================================
34  */
35 
36 NORI_NAMESPACE_BEGIN
37 
61 class StudentsTTest : public NoriObject {
62 public:
63  StudentsTTest(const PropertyList &propList) {
64  /* The null hypothesis will be rejected when the associated
65  p-value is below the significance level specified here. */
66  m_significanceLevel = propList.getFloat("significanceLevel", 0.01f);
67 
68  /* This parameter specifies a list of incidence angles that will be tested */
69  std::vector<std::string> angles = tokenize(propList.getString("angles", ""));
70  for (auto angle : angles)
71  m_angles.push_back(toFloat(angle));
72 
73  /* This parameter specifies a list of distances from the origin, for light source testing */
74  std::vector<std::string> distances = tokenize(propList.getString("distances", ""));
75  for (auto distance : distances)
76  m_distances.push_back(toFloat(distance));
77 
78  /* This parameter specifies a list of reference values, one for each angle */
79  std::vector<std::string> references = tokenize(propList.getString("references", ""));
80  for (auto angle : references)
81  m_references.push_back(toFloat(angle));
82 
83  /* Number of BSDF samples that should be generated (default: 100K) */
84  m_sampleCount = propList.getInteger("sampleCount", 100000);
85  }
86 
87  virtual ~StudentsTTest() {
88  for (auto bsdf : m_bsdfs)
89  delete bsdf;
90  for (auto emitter : m_emitters)
91  delete emitter;
92  for (auto scene : m_scenes)
93  delete scene;
94  }
95 
96  virtual void addChild(NoriObject *obj) override {
97  switch (obj->getClassType()) {
98  case EBSDF:
99  m_bsdfs.push_back(static_cast<BSDF *>(obj));
100  break;
101 
102  case EEmitter:
103  m_emitters.push_back(static_cast<Emitter *>(obj));
104  break;
105  // TODO: allow area lights?
106 
107  case EScene:
108  m_scenes.push_back(static_cast<Scene *>(obj));
109  break;
110 
111  default:
112  throw NoriException("StudentsTTest::addChild(<%s>) is not supported!",
113  classTypeName(obj->getClassType()));
114  }
115  }
116 
118  virtual void activate() override {
119  int total = 0, passed = 0;
120  pcg32 random;
121 
122  if (!m_bsdfs.empty()) {
123  if (m_references.size() != m_bsdfs.size() * m_angles.size())
124  throw NoriException("Specified a different number of angles and reference values! %d != %d x %d",
125  m_references.size(), m_bsdfs.size(), m_angles.size());
126  if (!m_emitters.empty() || !m_scenes.empty())
127  throw NoriException("Cannot test BSDFs, emitters, and scenes at the same time!");
128 
129  /* Test each registered BSDF */
130  int ctr = 0;
131  for (auto bsdf : m_bsdfs) {
132  for (float angle : m_angles) {
133  float reference = m_references[ctr++];
134 
135  cout << "------------------------------------------------------" << endl;
136  cout << "Testing (angle=" << angle << "): " << bsdf->toString() << endl;
137  ++total;
138 
139  BSDFQueryRecord bRec(sphericalDirection(degToRad(angle), 0), Point2f());
140 
141  cout << "Drawing " << m_sampleCount << " samples .. " << endl;
142  double mean=0, variance = 0;
143  for (int k=0; k<m_sampleCount; ++k) {
144  Point2f sample(random.nextFloat(), random.nextFloat());
145  double result = (double) bsdf->sample(bRec, sample).getLuminance();
146 
147  /* Numerically robust online variance estimation using an
148  algorithm proposed by Donald Knuth (TAOCP vol.2, 3rd ed., p.232) */
149  double delta = result - mean;
150  mean += delta / (double) (k+1);
151  variance += delta * (result - mean);
152  }
153  variance /= m_sampleCount - 1;
154  std::pair<bool, std::string>
155  result = hypothesis::students_t_test(mean, variance, reference,
156  m_sampleCount, m_significanceLevel, (int) m_references.size());
157 
158  if (result.first)
159  ++passed;
160  cout << result.second << endl;
161  }
162  }
163  } else if (!m_emitters.empty()) {
164  if (m_references.size() != m_emitters.size() * m_distances.size())
165  throw NoriException("Specified a different number of distances and reference values! %d != %d x %d",
166  m_references.size(), m_emitters.size(), m_distances.size());
167  if (!m_bsdfs.empty() || !m_scenes.empty())
168  throw NoriException("Cannot test BSDFs, emitters, and scenes at the same time!");
169 
170  /* Test each registered emitter */
171  int ctr = 0;
172  for (auto emitter : m_emitters) {
173  for (float distance : m_distances) {
174  float reference = m_references[ctr++];
175 
176  cout << "------------------------------------------------------" << endl;
177  cout << "Testing (distance=" << distance << "): " << emitter->toString() << endl;
178  ++total;
179 
180  Point3f ref(0, 0, distance);
181  EmitterQueryRecord lRec(ref);
182 
183  cout << "Drawing " << m_sampleCount << " samples .. " << endl;
184  double mean=0, variance = 0;
185  bool fields_correct = true;
186  bool eval_correct = true;
187  bool pdf_correct = true;
188  std::string reason;
189  for (int k=0; k<m_sampleCount; ++k) {
190  Point2f sample(random.nextFloat(), random.nextFloat());
191  double result = (double) emitter->sample(lRec, sample).getLuminance();
192 
193  // Check if the fields of the EmitterQueryRecord are correctly set
194  Vector3f ref2p = lRec.p - lRec.ref;
195  Vector3f wi = ref2p.normalized();
196  auto vectorEqual = [](const Vector3f &a, const Vector3f &b) {
197  return (a - b).squaredNorm() < 1e-5f;
198  };
199  if (!vectorEqual(ref, lRec.ref)) {
200  fields_correct = false;
201  reason = "`ref` is incorrect";
202  }
203  else if (!vectorEqual(wi, lRec.wi)) {
204  fields_correct = false;
205  reason = "`wi` is incorrect";
206  }
207  else if (!vectorEqual(ref, lRec.shadowRay.o) || !vectorEqual(wi, lRec.shadowRay.d)) {
208  fields_correct = false;
209  reason = "`shadowRay.o` or `shadowRay.d` is incorrect";
210  }
211  else if (std::abs(lRec.shadowRay.maxt - lRec.shadowRay.mint - ref2p.norm()) > 1e-3) {
212  fields_correct = false;
213  reason = "`shadowRay.maxt` - `shadowRay.mint` should equal to the distance between `ref` and `p`";
214  }
215 
216  /* Numerically robust online variance estimation using an
217  algorithm proposed by Donald Knuth (TAOCP vol.2, 3rd ed., p.232) */
218  double delta = result - mean;
219  mean += delta / (double) (k+1);
220  variance += delta * (result - mean);
221  }
222 
223  variance /= m_sampleCount - 1;
224  std::pair<bool, std::string>
225  result = hypothesis::students_t_test(mean, variance, reference,
226  m_sampleCount, m_significanceLevel, (int) m_references.size());
227 
228  cout << result.second << endl;
229 
230  if (!result.first) {
231  cout << "The return of `sample` method is incorrect" << endl;
232  continue;
233  }
234  if (!fields_correct) {
235  cout << "EmitterQueryRecord fields are not set correctly during sampling: " << reason << endl;
236  continue;
237  }
238  if (!eval_correct) {
239  cout << "Either `eval` method is wrongly implemented or `pdf` field is incorrectly set" << endl;
240  continue;
241  }
242  if (!pdf_correct) {
243  cout << "Either `pdf` method is wrongly implemented or `pdf` field is incorrectly set" << endl;
244  continue;
245  }
246 
247  ++passed;
248  }
249  }
250  } else {
251  if (m_references.size() != m_scenes.size())
252  throw NoriException("Specified a different number of scenes and reference values!");
253  if (!m_bsdfs.empty() || !m_emitters.empty())
254  throw NoriException("Cannot test BSDFs, emitters, and scenes at the same time!");
255 
256  Sampler *sampler = static_cast<Sampler *>(
258 
259  int ctr = 0;
260  for (auto scene : m_scenes) {
261  const Integrator *integrator = scene->getIntegrator();
262  const Camera *camera = scene->getCamera();
263  float reference = m_references[ctr++];
264 
265  cout << "------------------------------------------------------" << endl;
266  cout << "Testing scene: " << scene->toString() << endl;
267  ++total;
268 
269  cout << "Generating " << m_sampleCount << " paths.. " << endl;
270 
271  double mean = 0, variance = 0;
272  for (int k=0; k<m_sampleCount; ++k) {
273  /* Sample a ray from the camera */
274  Ray3f ray;
275  Point2f pixelSample = (sampler->next2D().array()
276  * camera->getOutputSize().cast<float>().array()).matrix();
277  Color3f value = camera->sampleRay(ray, pixelSample, sampler->next2D());
278 
279  /* Compute the incident radiance */
280  value *= integrator->Li(scene, sampler, ray);
281 
282  /* Numerically robust online variance estimation using an
283  algorithm proposed by Donald Knuth (TAOCP vol.2, 3rd ed., p.232) */
284  double result = (double) value.getLuminance();
285  double delta = result - mean;
286  mean += delta / (double) (k+1);
287  variance += delta * (result - mean);
288  }
289  variance /= m_sampleCount - 1;
290 
291  std::pair<bool, std::string>
292  result = hypothesis::students_t_test(mean, variance, reference,
293  m_sampleCount, m_significanceLevel, (int) m_references.size());
294 
295  if (result.first)
296  ++passed;
297  cout << result.second << endl;
298  }
299  }
300  cout << "Passed " << passed << "/" << total << " tests." << endl;
301 
302  if (passed < total) {
303  throw std::runtime_error("Failed some of the tests");
304  }
305  }
306 
307  virtual std::string toString() const override {
308  return tfm::format(
309  "StudentsTTest[\n"
310  " significanceLevel = %f,\n"
311  " sampleCount= %i\n"
312  "]",
313  m_significanceLevel,
314  m_sampleCount
315  );
316  }
317 
318  virtual EClassType getClassType() const override { return ETest; }
319 private:
320  std::vector<BSDF *> m_bsdfs;
321  std::vector<Emitter *> m_emitters;
322  std::vector<Scene *> m_scenes;
323  std::vector<float> m_angles;
324  std::vector<float> m_distances;
325  std::vector<float> m_references;
326  float m_significanceLevel;
327  int m_sampleCount;
328 };
329 
330 NORI_REGISTER_CLASS(StudentsTTest, "ttest");
331 NORI_NAMESPACE_END
Superclass of all bidirectional scattering distribution functions.
Definition: bsdf.h:60
Generic camera interface.
Definition: camera.h:35
const Vector2i & getOutputSize() const
Return the size of the output image in pixels.
Definition: camera.h:62
virtual Color3f sampleRay(Ray3f &ray, const Point2f &samplePosition, const Point2f &apertureSample) const =0
Importance sample a ray according to the camera's response function.
Superclass of all emitters.
Definition: emitter.h:64
Abstract integrator (i.e. a rendering technique)
Definition: integrator.h:35
virtual Color3f Li(const Scene *scene, Sampler *sampler, const Ray3f &ray) const =0
Sample the incident radiance along a ray.
Simple exception class, which stores a human-readable error description.
Definition: common.h:148
static NoriObject * createInstance(const std::string &name, const PropertyList &propList)
Construct an instance from the class of the given name.
Definition: object.h:158
Base class of all objects.
Definition: object.h:32
static std::string classTypeName(EClassType type)
Turn a class type into a human-readable string.
Definition: object.h:51
virtual EClassType getClassType() const =0
Return the type of object (i.e. Mesh/BSDF/etc.) provided by this instance.
This is an associative container used to supply the constructors of NoriObject subclasses with parame...
Definition: proplist.h:32
float getFloat(const std::string &name) const
Get a float property, and throw an exception if it does not exist.
std::string getString(const std::string &name) const
Get a string property, and throw an exception if it does not exist.
int getInteger(const std::string &name) const
Get an integer property, and throw an exception if it does not exist.
Abstract sample generator.
Definition: sampler.h:63
virtual Point2f next2D()=0
Retrieve the next two component values from the current sample.
Main scene data structure.
Definition: scene.h:34
virtual void activate() override
Invoke a series of t-tests on the provided input.
Definition: ttest.cpp:118
virtual void addChild(NoriObject *obj) override
Add a child object to the current instance.
Definition: ttest.cpp:96
virtual EClassType getClassType() const override
Return the type of object (i.e. Mesh/BSDF/etc.) provided by this instance.
Definition: ttest.cpp:318
virtual std::string toString() const override
Return a brief string summary of the instance (for debugging purposes)
Definition: ttest.cpp:307
Convenience data structure used to pass multiple parameters to the evaluation and sampling routines i...
Definition: bsdf.h:30
Represents a linear RGB color value.
Definition: color.h:29
float getLuminance() const
Return the associated luminance.
Definition: common.cpp:233
Data record for conveniently querying and sampling the direct illumination technique implemented by a...
Definition: emitter.h:31
Vector3f wi
Direction between the hit point and the emitter point.
Definition: emitter.h:39
Point3f ref
Origin point from which we sample the emitter.
Definition: emitter.h:33
Ray3f shadowRay
Shadow ray.
Definition: emitter.h:43
Point3f p
Sampled point on the emitter.
Definition: emitter.h:35
VectorType d
Ray direction.
Definition: ray.h:44
Scalar mint
Minimum position on the ray segment.
Definition: ray.h:46
Scalar maxt
Maximum position on the ray segment.
Definition: ray.h:47
PointType o
Ray origin.
Definition: ray.h:43