Repository navigation
Expand file tree
/
Copy pathOneDimensionalDeviate.cpp
More file actions
404 lines (380 loc) · 17.2 KB
/
Copy pathOneDimensionalDeviate.cpp
File metadata and controls
404 lines (380 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/* -*- c++ -*-
* Copyright (c) 2012-2014 by the GalSim developers team on GitHub
* https://github.com/GalSim-developers
*
* This file is part of GalSim: The modular galaxy image simulation toolkit.
* https://github.com/GalSim-developers/GalSim
*
* GalSim is free software: redistribution and use in source and binary forms,
* with or without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions, and the disclaimer given in the accompanying LICENSE
* file.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions, and the disclaimer given in the documentation
* and/or other materials provided with the distribution.
*/
//#define DEBUGLOGGING
#include "OneDimensionalDeviate.h"
#include "integ/Int.h"
#include "SBProfile.h"
// Define this variable to find azimuth (and sometimes radius within a unit disc) of 2d photons by
// drawing a uniform deviate for theta, instead of drawing 2 deviates for a point on the unit
// circle and rejecting corner photons.
// The relative speed of the two methods was tested as part of issue #163, and the results
// are collated in devutils/external/time_photon_shooting.
// The conclusion was that using sin/cos was faster for icpc, but not g++ or clang++.
#ifdef _INTEL_COMPILER
#define USE_COS_SIN
#endif
#ifdef DEBUGLOGGING
#include <fstream>
std::ostream* dbgout = new std::ofstream("debug.out");
int verbose_level = 2;
#endif
namespace galsim {
// Wrapper class for doing integrals over annuli
template <class F>
class RTimesF: public std::unary_function<double,double> {
public:
RTimesF(const F& function): _function(function) {}
double operator()(double r) const { return 2.*M_PI*r*_function(r); }
private:
const F& _function;
};
// Function to isolate an extremum of function in an interval.
bool findExtremum( const FluxDensity& function,
double xmin,
double xmax,
double& extremum,
int divisionSteps,
double xFractionalTolerance = 1e-4)
{
if (xmax < xmin) std::swap(xmax,xmin);
const double xTolerance = xFractionalTolerance*(xmax-xmin);
// First bracket extremum by division into fixed number of steps
double xStep = (xmax - xmin) / divisionSteps;
double x1 = xmin;
double x2 = xmin + xStep;
double f1 = function(x1);
double f2 = function(x2);
double df1 = f2 - f1;
double x3 = xmin + 2*xStep;
double f3 = function(x3);
double df2 = f3 - f2;
while (df1 * df2 >= 0.) {
if (x3 >= xmax)
return false; // no extremum bracketed.
x1 = x2;
f1 = f2;
x2 = x3;
f2 = f3;
df1 = df2;
x3 += xStep;
f3 = function(x3);
df2 = f3 - f2;
}
// First guess is that minimum is in half of bracket with lowest gradient
bool fatLeft = std::abs(df1) < std::abs(df2);
// Then use golden sections to localize - could use Brent's method for speed.
const double GOLDEN = 2./(1+sqrt(5.));
while (std::abs(x3-x1) > xTolerance) {
if (fatLeft) {
// Split left-hand interval
double xTrial = x1 + GOLDEN*(x2-x1);
double fTrial = function(xTrial);
double dfTrial = f2 - fTrial;
if (df1 * dfTrial <= 0.) {
// Now bracketed in 1 / trial / 2
x3 = x2;
f3 = f2;
x2 = xTrial;
f2 = fTrial;
df1 = f2 - f1;
df2 = dfTrial;
fatLeft = true;
} else {
// Extremum is in trial / 2 / 3
x1 = xTrial;
f1 = fTrial;
df1 = dfTrial;
fatLeft = false;
}
} else {
// Split right-hand interval (2 / trial / 3)
double xTrial = x2 - GOLDEN*(x3-x2);
double fTrial = function(xTrial);
double dfTrial = fTrial - f2;
if (dfTrial * df2 <= 0.) {
// Now bracketed in 2 / trial / 3
x1 = x2;
f1 = f2;
x2 = xTrial;
f2 = fTrial;
df1 = dfTrial;
df2 = f3 - f2;
fatLeft = false;
} else {
// Extremum is in 1 / 2 / trial
x3 = xTrial;
f3 = fTrial;
df2 = dfTrial;
fatLeft = true;
}
}
}
extremum = x2;
return true;
}
double Interval::interpolateFlux(double fraction) const
{
// Find the x (or radius) value that encloses fraction
// of the flux in this Interval if the function were constant
// over the interval.
if (_isRadial) {
double rsq = _xLower*_xLower*(1.-fraction) + _xUpper*_xUpper*fraction;
return sqrt(rsq);
} else {
return _xLower + (_xUpper - _xLower)*fraction;
}
return 0.; // Will never get here.
}
// Select a photon from within the interval. unitRandom
// as an initial random value, more from ud if needed for rejections.
void Interval::drawWithin(double unitRandom, double& x, double& flux,
UniformDeviate ud) const
{
xdbg<<"drawWithin interval\n";
xdbg<<"_flux = "<<_flux<<std::endl;
double fractionOfInterval = std::min(unitRandom, 1.);
xdbg<<"fractionOfInterval = "<<fractionOfInterval<<std::endl;
fractionOfInterval = std::max(0., fractionOfInterval);
xdbg<<"fractionOfInterval => "<<fractionOfInterval<<std::endl;
x = interpolateFlux(fractionOfInterval);
xdbg<<"x = "<<x<<std::endl;
flux = 1.;
if (_useRejectionMethod) {
xdbg<<"use rejection\n";
while ( ud() > std::abs((*_fluxDensityPtr)(x)) * _invMaxAbsDensity) {
x = interpolateFlux(ud());
}
xdbg<<"x => "<<x<<std::endl;
if (_flux < 0) flux = -1.;
} else {
flux = (*_fluxDensityPtr)(x) * _invMeanAbsDensity;
}
xdbg<<"flux = "<<flux<<std::endl;
}
void Interval::checkFlux() const
{
if (_fluxIsReady) return;
if (_isRadial) {
// Integrate r*F
RTimesF<FluxDensity> integrand(*_fluxDensityPtr);
_flux = integ::int1d(integrand,
_xLower, _xUpper,
_gsparams->integration_relerr,
_gsparams->integration_abserr);
} else {
// Integrate the input function
_flux = integ::int1d(*_fluxDensityPtr,
_xLower, _xUpper,
_gsparams->integration_relerr,
_gsparams->integration_abserr);
}
_fluxIsReady = true;
}
// Divide an interval into ones that are sufficiently small. It's small enough if either
// (a) The max/min FluxDensity ratio in the interval is small enough, i.e. close to constant, or
// (b) The total flux in the interval is below smallFlux.
// In the former case, photons will be selected by drawing from a uniform distribution and then
// adjusting weights by flux. In latter case, rejection sampling will be used to select
// within interval.
std::list<Interval> Interval::split(double smallFlux)
{
// Get the flux in this interval
checkFlux();
if (_isRadial) {
_invMeanAbsDensity = std::abs( (M_PI*(_xUpper*_xUpper - _xLower*_xLower)) / _flux );
} else {
_invMeanAbsDensity = std::abs( (_xUpper - _xLower) / _flux );
}
double densityLower = (*_fluxDensityPtr)(_xLower);
double densityUpper = (*_fluxDensityPtr)(_xUpper);
_invMaxAbsDensity = 1. / std::max(std::abs(densityLower), std::abs(densityUpper));
std::list<Interval> result;
double densityVariation = 0.;
if (std::abs(densityLower) > 0. && std::abs(densityUpper) > 0.)
densityVariation = densityLower / densityUpper;
if (densityVariation > 1.) densityVariation = 1. / densityVariation;
if (densityVariation > _gsparams->allowed_flux_variation) {
// Don't split if flux range is small
_useRejectionMethod = false;
result.push_back(*this);
} else if (std::abs(_flux) < smallFlux) {
// Don't split further, as it will be rare to be in this interval
// and rejection is ok.
_useRejectionMethod = true;
result.push_back(*this);
} else {
// Split the interval. Call (recursively) split() for left & right
double midpoint = 0.5*(_xLower + _xUpper);
Interval left(*_fluxDensityPtr, _xLower, midpoint, _isRadial, _gsparams);
Interval right(*_fluxDensityPtr, midpoint, _xUpper, _isRadial, _gsparams);
std::list<Interval> add = left.split(smallFlux);
result.splice(result.end(), add);
add = right.split(smallFlux);
result.splice(result.end(), add);
}
return result;
}
OneDimensionalDeviate::OneDimensionalDeviate(const FluxDensity& fluxDensity,
std::vector<double>& range,
bool isRadial,
const GSParamsPtr& gsparams) :
_fluxDensity(fluxDensity),
_positiveFlux(0.),
_negativeFlux(0.),
_isRadial(isRadial),
_gsparams(gsparams)
{
dbg<<"Start ODD constructor\n";
dbg<<"Input range has "<<range.size()<<" entries\n";
dbg<<"radial? = "<<isRadial<<std::endl;
// Typedef for indices of standard containers, which don't like int values
typedef std::vector<double>::size_type Index;
// First calculate total flux so we know when an interval is a small amt of flux
for (Index iRange = 0; iRange < range.size()-1; iRange++) {
xdbg<<"range "<<iRange<<" = "<<range[iRange]<<" ... "<<range[iRange+1]<<std::endl;
// Integrate total flux (and sign) in each range
Interval segment(fluxDensity, range[iRange], range[iRange+1], _isRadial, _gsparams);
double rangeFlux = segment.getFlux();
if (rangeFlux >= 0.) _positiveFlux += rangeFlux;
else _negativeFlux += std::abs(rangeFlux);
}
dbg<<"posFlux = "<<_positiveFlux<<std::endl;
dbg<<"negFlux = "<<_negativeFlux<<std::endl;
double totalAbsoluteFlux = _positiveFlux + _negativeFlux;
dbg<<"totFlux = "<<totalAbsoluteFlux<<std::endl;
// Now break each range into Intervals
for (Index iRange = 0; iRange < range.size()-1; iRange++) {
// See if there is an extremum to split this range:
double extremum;
if (findExtremum(_fluxDensity,
range[iRange],
range[iRange+1],
extremum,
_gsparams->range_division_for_extrema)) {
xdbg<<"range "<<iRange<<" = "<<range[iRange]<<" ... "<<range[iRange+1]<<
" has an extremum at "<<extremum<<std::endl;
// Do 2 ranges
{
Interval splitit(_fluxDensity, range[iRange], extremum, _isRadial, _gsparams);
std::list<Interval> leftList = splitit.split(
_gsparams->small_fraction_of_flux * totalAbsoluteFlux);
xdbg<<"Add "<<leftList.size()<<" intervals on left of extremem\n";
_pt.insert(_pt.end(), leftList.begin(), leftList.end());
}
{
Interval splitit(_fluxDensity, extremum, range[iRange+1], _isRadial, _gsparams);
std::list<Interval> rightList = splitit.split(
_gsparams->small_fraction_of_flux * totalAbsoluteFlux);
xdbg<<"Add "<<rightList.size()<<" intervals on right of extremem\n";
_pt.insert(_pt.end(), rightList.begin(), rightList.end());
}
} else {
// Just single Interval in this range, no extremum:
Interval splitit(
_fluxDensity, range[iRange], range[iRange+1], _isRadial, _gsparams);
std::list<Interval> leftList = splitit.split(
_gsparams->small_fraction_of_flux * totalAbsoluteFlux);
xdbg<<"Add "<<leftList.size()<<" intervals\n";
_pt.insert(_pt.end(), leftList.begin(), leftList.end());
}
}
dbg<<"Total of "<<_pt.size()<<" intervals\n";
// Build the ProbabilityTree
_pt.buildTree();
}
boost::shared_ptr<PhotonArray> OneDimensionalDeviate::shoot(int N, UniformDeviate ud) const
{
dbg<<"OneDimentionalDeviate shoot: N = "<<N<<std::endl;
dbg<<"Target flux = 1.\n";
dbg<<"isradial? "<<_isRadial<<std::endl;
dbg<<"N = "<<N<<std::endl;
assert(N>=0);
boost::shared_ptr<PhotonArray> result(new PhotonArray(N));
if (N==0) return result;
double totalAbsoluteFlux = getPositiveFlux() + getNegativeFlux();
dbg<<"totalAbsFlux = "<<totalAbsoluteFlux<<std::endl;
double fluxPerPhoton = totalAbsoluteFlux / N;
dbg<<"fluxPerPhoton = "<<fluxPerPhoton<<std::endl;
// For each photon, first decide which Interval it's in, then drawWithin the interval.
for (int i=0; i<N; i++) {
if (_isRadial) {
#ifdef USE_COS_SIN
double unitRandom = ud();
Interval* chosen = _pt.find(unitRandom);
// Now draw a radius from within selected interval
double radius, flux;
chosen->drawWithin(unitRandom, radius, flux, ud);
// Draw second ud to get azimuth
double theta = 2.*M_PI*ud();
result->setPhoton(i,
radius*std::cos(theta), radius*std::sin(theta),
flux*fluxPerPhoton);
#else
// Alternate method: doesn't need sin & cos but needs sqrt
// First get a point uniformly distributed in unit circle
double xu, yu, rsq;
do {
xu = 2.*ud()-1.;
yu = 2.*ud()-1.;
rsq = xu*xu+yu*yu;
} while (rsq>=1. || rsq==0.);
// Now rsq is unit deviate from 0 to 1
double unitRandom = rsq;
const Interval* chosen = _pt.find(unitRandom);
// Now draw a radius from within selected interval
double radius, flux;
chosen->drawWithin(unitRandom, radius, flux, ud);
// Rescale x & y:
double rScale = radius / std::sqrt(rsq);
result->setPhoton(i,xu*rScale, yu*rScale, flux*fluxPerPhoton);
#endif
} else {
// Simple 1d interpolation
double unitRandom = ud();
const Interval* chosen = _pt.find(unitRandom);
// Now draw an x from within selected interval
double x, flux;
chosen->drawWithin(unitRandom, x, flux, ud);
result->setPhoton(i, x, 0., flux*fluxPerPhoton);
}
}
dbg<<"OneDimentionalDeviate Realized flux = "<<result->getTotalFlux()<<std::endl;
// This next bit is probably a bad idea, especially for profiles that have some
// negative flux. It is possible for the random photons to end up totalling a
// negative value. This should be allowed. And certainly rescaling to get the
// correct flux would be wrong (it would involve a sign flip). Similarly, Gary
// pointed out that it is conceivable for someone to want to draw a profile with
// zero total flux. We don't want to rescale all the photons to 0.
#if 0
// The flux realized from photon shooting a OneDimensionalDeviate won't necessarily
// match exactly the target flux because of the possibility of variable flux for the
// photons, and also positive and negative photons partially canceling out in a
// stochastic way.
// So rescale the image to get the correct flux.
double targetFlux = getPositiveFlux() - getNegativeFlux();
double realizedFlux = result->getTotalFlux();
dbg<<"targetFlux = "<<targetFlux<<std::endl;
dbg<<"realizedFlux = "<<realizedFlux<<std::endl;
double scale = targetFlux / realizedFlux;
dbg<<"Rescale result by "<<scale<<std::endl;
result->scaleFlux(scale);
#endif
return result;
}
} // namespace galsim