File: observable.cpp

package info (click to toggle)
quantlib 1.39-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 41,264 kB
  • sloc: cpp: 396,561; makefile: 6,539; python: 272; sh: 154; lisp: 86
file content (400 lines) | stat: -rw-r--r-- 12,450 bytes parent folder | download | duplicates (2)
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
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2015 Klaus Spanderen

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include "toplevelfixture.hpp"
#include "utilities.hpp"
#include <ql/indexes/ibor/euribor.hpp>
#include <ql/math/randomnumbers/mt19937uniformrng.hpp>
#include <ql/patterns/observable.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/termstructures/volatility/capfloor/capfloortermvolsurface.hpp>
#include <ql/termstructures/volatility/optionlet/strippedoptionlet.hpp>
#include <ql/termstructures/volatility/optionlet/strippedoptionletadapter.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/time/calendars/nullcalendar.hpp>
#include <chrono>
#include <thread>

#ifdef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN
#include <atomic>
#include <mutex>
#include <thread>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <list>
#endif

using namespace QuantLib;
using namespace boost::unit_test_framework;

BOOST_FIXTURE_TEST_SUITE(QuantLibTests, TopLevelFixture)

BOOST_AUTO_TEST_SUITE(ObservableTests)

class UpdateCounter : public Observer {
  public:
    UpdateCounter() = default;
    void update() override { ++counter_; }
    Size counter() const { return counter_; }

  private:
    Size counter_ = 0;
};

class RestoreUpdates { // NOLINT(cppcoreguidelines-special-member-functions)
  public:
    ~RestoreUpdates() {
        ObservableSettings::instance().enableUpdates();
    }
};

#ifdef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN
class MTUpdateCounter : public Observer {
  public:
    MTUpdateCounter() : counter_(0) {
        ++instanceCounter_;
    }
    ~MTUpdateCounter() {
        --instanceCounter_;
    }
    void update() {
        ++counter_;
    }
    int counter() { return counter_; }
    static int instanceCounter() { return instanceCounter_; }

  private:
    std::atomic<int> counter_;
    static std::atomic<int> instanceCounter_;
};

std::atomic<int> MTUpdateCounter::instanceCounter_(0);

class GarbageCollector {
  public:
    GarbageCollector() : terminate_(false) { }

    void addObj(const ext::shared_ptr<MTUpdateCounter>& updateCounter) {
        std::lock_guard<std::mutex> lock(mutex_);
        objList.push_back(updateCounter);
    }

    void run() {
        while(!terminate_) {
            Size objListSize;
            {
                std::lock_guard<std::mutex> lock(mutex_);
                objListSize = objList.size();
            }

            if (objListSize > 20) {
                // trigger gc
                while (objListSize > 0) {
                    std::lock_guard<std::mutex> lock(mutex_);
                    objList.pop_front();
                    objListSize = objList.size();
                }
            }

            std::this_thread::sleep_for(std::chrono::milliseconds(2));
        }
        objList.clear();
    }

    void terminate() {
        terminate_ = true;
    }
  private:
    std::mutex mutex_;
    std::atomic<bool> terminate_;

    std::list<ext::shared_ptr<MTUpdateCounter> > objList;
};
#endif


BOOST_AUTO_TEST_CASE(testObservableSettings) {

    BOOST_TEST_MESSAGE("Testing observable settings...");

    const ext::shared_ptr<SimpleQuote> quote(new SimpleQuote(100.0));
    UpdateCounter updateCounter;

    updateCounter.registerWith(quote);
    if (updateCounter.counter() != 0) {
        BOOST_FAIL("update counter value is not zero");
    }

   quote->setValue(1.0);
   if (updateCounter.counter() != 1) {
       BOOST_FAIL("update counter value is not one");
   }

   ObservableSettings::instance().disableUpdates(false);
   quote->setValue(2.0);
   if (updateCounter.counter() != 1) {
       BOOST_FAIL("update counter value is not one");
   }
   ObservableSettings::instance().enableUpdates();
   if (updateCounter.counter() != 1) {
       BOOST_FAIL("update counter value is not one");
   }

   ObservableSettings::instance().disableUpdates(true);
   quote->setValue(3.0);
   if (updateCounter.counter() != 1) {
       BOOST_FAIL("update counter value is not one");
   }
   ObservableSettings::instance().enableUpdates();
   if (updateCounter.counter() != 2) {
       BOOST_FAIL("update counter value is not two");
   }

   UpdateCounter updateCounter2;
   updateCounter2.registerWith(quote);
   ObservableSettings::instance().disableUpdates(true);
   for (Size i=0; i < 10; ++i) {
       quote->setValue(Real(i));
   }
   if (updateCounter.counter() != 2) {
       BOOST_FAIL("update counter value is not two");
   }
   ObservableSettings::instance().enableUpdates();
   if (updateCounter.counter() != 3 || updateCounter2.counter() != 1) {
       BOOST_FAIL("update counter values are not correct");
   }
}


#ifdef QL_ENABLE_THREAD_SAFE_OBSERVER_PATTERN

BOOST_AUTO_TEST_CASE(testAsyncGarbagCollector) {

    BOOST_TEST_MESSAGE("Testing observer pattern with an asynchronous "
                       "garbage collector (JVM/.NET use case)...");

    // This test core dumps if used with the ordinary implementation
    // of the observer pattern (comparable situation
    // in JVM or .NET eco systems).

    const ext::shared_ptr<SimpleQuote> quote(new SimpleQuote(-1.0));

    GarbageCollector gc;
    std::thread workerThread(&GarbageCollector::run, &gc);

    for (Size i=0; i < 10000; ++i) {
        const ext::shared_ptr<MTUpdateCounter> observer(new MTUpdateCounter);
        observer->registerWith(quote);
        gc.addObj(observer);

        for (Size j=0; j < 10; ++j)
            quote->setValue(Real(j));
    }

    gc.terminate();
    workerThread.join();

    if (MTUpdateCounter::instanceCounter() != 0) {
        BOOST_FAIL("garbage collection does not work.");
    }
}

BOOST_AUTO_TEST_CASE(testMultiThreadingGlobalSettings) {
	BOOST_TEST_MESSAGE("Testing observer global settings in a "
		               "multithreading environment...");
	
	const ext::shared_ptr<SimpleQuote> quote(new SimpleQuote(-1.0));

    ObservableSettings::instance().disableUpdates(true);

    GarbageCollector gc;
    std::thread workerThread(&GarbageCollector::run, &gc);

    typedef std::list<ext::shared_ptr<MTUpdateCounter> > local_list_type;
    local_list_type localList;

    for (Size i=0; i < 4000; ++i) {
        const ext::shared_ptr<MTUpdateCounter> observer(new MTUpdateCounter);
        observer->registerWith(quote);

        if ((i%4) == 0) {
            localList.push_back(observer);
            for (Size j=0; j < 5; ++j)
                quote->setValue(Real(j));
        }
        gc.addObj(observer);
    }

    gc.terminate();
    workerThread.join();

    if (localList.size() != Size(MTUpdateCounter::instanceCounter())) {
        BOOST_FAIL("garbage collection does not work.");
    }

    for (local_list_type::iterator iter = localList.begin();
        iter != localList.end(); ++iter) {
        if ((*iter)->counter() != 0) {
            BOOST_FAIL("notification should have been blocked");
        }
    }

    ObservableSettings::instance().enableUpdates();

    for (local_list_type::iterator iter = localList.begin();
        iter != localList.end(); ++iter) {
        if ((*iter)->counter() != 1) {
            BOOST_FAIL("only one notification should have been sent");
        }
    }
}
#endif

BOOST_AUTO_TEST_CASE(testDeepUpdate) {
    BOOST_TEST_MESSAGE("Testing deep update of observers...");

    RestoreUpdates guard;

    Date refDate = Settings::instance().evaluationDate();

    ObservableSettings::instance().disableUpdates(true);

    Handle<YieldTermStructure> yts(
        ext::make_shared<FlatForward>(0, NullCalendar(), 0.02, Actual365Fixed()));
    ext::shared_ptr<IborIndex> ibor = ext::make_shared<Euribor>(3 * Months, yts);
    ext::shared_ptr<SimpleQuote> q = ext::make_shared<SimpleQuote>(0.20);
    std::vector<Real> strikes = {0.01, 0.02};
    std::vector<Date> dates = {refDate + 90, refDate + 180};
    std::vector<std::vector<Handle<Quote> > > quotes = {
        {Handle<Quote>(q), Handle<Quote>(q)},
        {Handle<Quote>(q), Handle<Quote>(q)}
    };

    ext::shared_ptr<StrippedOptionletAdapter> vol =
        ext::make_shared<StrippedOptionletAdapter>(ext::make_shared<StrippedOptionlet>(
            0, NullCalendar(), Unadjusted, ibor, dates, strikes, quotes, Actual365Fixed()));

    Real v1 = vol->volatility(refDate + 100, 0.01);
    q->setValue(0.21);
    Real v2 = vol->volatility(refDate + 100, 0.01);
    vol->update();
    Real v3 = vol->volatility(refDate + 100, 0.01);
    vol->deepUpdate();
    Real v4 = vol->volatility(refDate + 100, 0.01);

    QL_CHECK_CLOSE(v1, 0.2, 1E-10);
    QL_CHECK_CLOSE(v2, 0.2, 1E-10);
    QL_CHECK_CLOSE(v3, 0.2, 1E-10);
    QL_CHECK_CLOSE(v4, 0.21, 1E-10);
}


class DummyObserver : public Observer {
  public:
    DummyObserver() = default;
    void update() override {}
};


BOOST_AUTO_TEST_CASE(testEmptyObserverList) {
	BOOST_TEST_MESSAGE("Testing unregisterWith call on empty observer...");

    const ext::shared_ptr<DummyObserver> dummyObserver=ext::make_shared<DummyObserver>();
    dummyObserver->unregisterWith(ext::make_shared<SimpleQuote>(10.0));
}

BOOST_AUTO_TEST_CASE(testAddAndDeleteObserverDuringNotifyObservers) {
    BOOST_TEST_MESSAGE("Testing addition and deletion of observers during notifyObserver...");

    const ext::shared_ptr<MersenneTwisterUniformRng> rng
        = ext::make_shared<MersenneTwisterUniformRng>();

    const Size nrInitialObserver = 20;
    const Size nrDeleteDuringUpdate = 5;
    const Size nrAdditionalObserver = 100;
    const Size testRuns = 100;

    class TestSetup {
      public:
        explicit TestSetup(ext::shared_ptr<MersenneTwisterUniformRng> m)
        : rng(std::move(m)), observable(ext::make_shared<Observable>()) {}

        ext::shared_ptr<MersenneTwisterUniformRng> rng;
        ext::shared_ptr<Observable> observable;
        std::vector<ext::shared_ptr<Observer> > expected;
        std::vector<ext::shared_ptr<Observer> > additinalObservers;
    };

    class TestObserver: public Observer {
      public:
        explicit TestObserver(TestSetup* setup = nullptr) : setup_(setup) {}

        void update() override {
            ++updates_;

            if (setup_ != nullptr) {
                for (Size i=0; i < nrAdditionalObserver; ++i) {
                    const ext::shared_ptr<Observer> obs
                        = ext::make_shared<TestObserver>();

                    obs->registerWith(setup_->observable);
                    setup_->additinalObservers.push_back(obs);
                }

                for (Size i=0; i < nrDeleteDuringUpdate; ++i) {
                    const unsigned int j
                        = setup_->rng->nextInt32() % setup_->expected.size();

                    if (setup_->expected[j].get() != this)
                        setup_->expected.erase(setup_->expected.begin()+j);
                }
            }
        }

        Size getUpdates() const { return updates_; }

      private:
        TestSetup* const setup_;
        Size updates_ = 0;
    };

    for (Size t=0; t < testRuns; ++t) {
        const ext::shared_ptr<TestSetup> setup = ext::make_shared<TestSetup>(rng);

        for (Size i=0; i < nrInitialObserver; ++i) {
            const ext::shared_ptr<Observer> obs = 
                (i == nrInitialObserver/3 || i == nrInitialObserver/2)
                ? ext::make_shared<TestObserver>(setup.get())
                : ext::make_shared<TestObserver>();

            obs->registerWith(setup->observable);
            setup->expected.push_back(obs);
        }

        setup->observable->notifyObservers();

        for (const auto& obs : setup->expected)
            if (ext::dynamic_pointer_cast<TestObserver>(obs)->getUpdates() == 0) {
                BOOST_FAIL("missed observer update detected");
            }
    }
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()