<commit_before>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#include <cstdio>
#include <nix.hpp>
#include <nix/NDArray.hpp>
#include <queue>
#include <random>
#include <type_traits>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdexcept>

/* ************************************ */

class Stopwatch {

public:
    typedef std::chrono::high_resolution_clock::time_point time_point_t;
    typedef std::chrono::high_resolution_clock clock_t;

    Stopwatch() : t_start(clock_t::now()) { };

    ssize_t ms() {
        time_point_t t_end = clock_t::now();
        ssize_t count = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
        return count;
    }

private:
    time_point_t t_start;
};

/* ************************************ */

class RndGenBase {
public:
    RndGenBase() : rd(), rd_gen(rd()) { };

protected:
    std::random_device rd;
    std::mt19937 rd_gen;
};

template<typename T, typename Enable = void>
class RndGen { };

template<typename T>
class RndGen<T, typename std::enable_if<std::is_floating_point<T>::value >::type> : RndGenBase {
public:
    RndGen() : dis(-1024.0, +1024.0) { };

    T operator()(void) {
        return dis(rd_gen);
    };

private:
    std::uniform_real_distribution<T> dis;
};

template<typename T>
class RndGen<T, typename std::enable_if<std::is_integral<T>::value >::type> : RndGenBase {
public:
    RndGen() : dis(-1024, +1024) { };

    T operator()(void) {
        return dis(rd_gen);
    };

private:
    std::uniform_real_distribution<T> dis;
};

/* ************************************ */

template<typename T>
class BlockGenerator {
public:

    BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { };

    std::vector<T> make_block() {
        std::vector<T> block(blocksize);
        std::generate(block.begin(), block.end(), std::ref(rnd_gen));
        return block;
    }

    std::vector<T> next_block() {
        std::unique_lock<std::mutex> lock(mtx);

        if (queue.empty()) {
            cnd.wait(lock, [this]{ return !queue.empty(); });
        }

        std::vector<T> x(std::move(queue.front()));
        queue.pop();
        cnd.notify_all();
        return x;
    }

    void worker_thread() {
        while (do_run) {
            std::unique_lock<std::mutex> lock(mtx);
            std::vector<T> block = make_block();

            if (queue.size() > bufsize) {
                //wait until there is room
                cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;});
                if (!do_run) {
                    return;
                }
            }

            queue.push(std::move(block));
            cnd.notify_all();
        }
    }

    void start_worker() {
        workers.emplace_back(&BlockGenerator::worker_thread, this);
    }

    ~BlockGenerator() {
        do_run = false;
        cnd.notify_all();
        for (auto &w : workers) {
            w.join();
        }
    }

    double speed_test() {

        Stopwatch sw;

        size_t N = 100;
        size_t iterations = 0;

        do {
            Stopwatch inner;

            for (size_t i = 0; i < N; i++) {
                std::vector<double> block = next_block();
                iterations++;
            }

            if (inner.ms() < 100) {
                N *= 2;
            }

        } while (sw.ms() < 1000);

        ssize_t count = sw.ms();
        return iterations * blocksize * sizeof(T) * (1000.0/count) / (1024.0*1024.0);
    }

private:
    bool do_run = true;
    size_t blocksize;
    size_t bufsize;
    RndGen<T> rnd_gen;
    std::mutex mtx;
    std::condition_variable cnd;
    std::queue<std::vector<T>> queue;
    std::vector<std::thread> workers;
};

class Config {

public:
    Config(nix::DataType data_type, const nix::NDSize &blocksize)
            : data_type(data_type), block_size(blocksize) {

        sdim = find_single_dim();
        shape = blocksize;
        shape[sdim] = 0;

        make_name();
    };

    size_t find_single_dim() {
        size_t sdim;
        bool have_rdim = false;
        for (size_t i = 0; i < block_size.size(); i ++) {
            if (block_size[i] == 1) {
                sdim = i;
                have_rdim = true;
            }
        }

        if (!have_rdim) {
            throw std::runtime_error("Could not find singelton dimension");
        }
        return sdim;
    }

    nix::DataType dtype() const { return data_type; }
    const nix::NDSize& size() const { return block_size; }
    const nix::NDSize& extend() const { return shape; }
    size_t singleton_dimension() const { return sdim; }
    const std::string & name() const { return my_name; };

private:
    void make_name() {
        std::stringstream s;

        s << data_type << "@{ ";
        for (auto x : block_size) {
            s << x << " ";
        }
        s << "}";

        my_name = s.str();
    }

private:
    const nix::DataType data_type;
    const nix::NDSize block_size;

    size_t        sdim;
    nix::NDSize   shape;

    std::string   my_name;
};

class Benchmark {
public:
    Benchmark(const Config &cfg) : config(cfg) { }
    const Config & cfg() const { return config; }

    nix::DataArray openDataArray(nix::Block block) const {
        const std::string &cfg_name = config.name();
        std::vector<nix::DataArray> v = block.dataArrays(nix::util::NameFilter<nix::DataArray>(cfg_name));
        if (v.empty()) {
            return block.createDataArray(cfg_name, "nix.test.da", config.dtype(), config.extend());
        } else {
            return v[0];
        }
    }

    virtual ~Benchmark() { }

    virtual double speed_in_mbs() {
        return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) *
                (1000.0/millis) / (1024 * 1024);
    }

    template<typename F>
    ssize_t time_it(F func) {
        Stopwatch watch;
        func();
        return watch.ms();
    }

    virtual void run(nix::Block block) = 0;
    virtual std::string id() = 0;

protected:
    double calc_speed_mbs(ssize_t ms, size_t iterations) {
        return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/ms) /
                (1024.0*1024.0);
    }

protected:
    const Config config;
    size_t       count;
    double       millis;
};

class GeneratorBenchmark : public Benchmark {
public:
    GeneratorBenchmark(const Config &cfg)
            : Benchmark(cfg) {

    };

    void run(nix::Block block) override {
        switch (config.dtype()) {

            case nix::DataType::Double:
                test_speed<double>();
                break;

            default:
                throw std::runtime_error("Unsupported DataType!");
        }
    }

    template<typename T>
    void test_speed() {
        size_t nelms = config.size().nelms();
        BlockGenerator<T> generator(nelms, 10);
        generator.start_worker();
        speed = generator.speed_test();
    }

    double speed_in_mbs() override {
        return speed;
    }

    std::string id() override {
        return "P";
    }

private:
    double speed;
};

class WriteBenchmark : public Benchmark {

public:
    WriteBenchmark(const Config &cfg)
            : Benchmark(cfg) {
    };

    void test_write_io(nix::Block block) {
        nix::DataArray da = openDataArray(block);

        switch (config.dtype()) {

            case nix::DataType::Double:
                do_write_test<double>(da);
                break;

            default:
                throw std::runtime_error("Unsupported DataType!");
        }
    }

    void run(nix::Block block) override {
        test_write_io(block);
    }

    double speed_in_mbs() override {
        return speed_write;
    }

    std::string id() override {
        return "W";
    }

private:
    template<typename T>
    void do_write_test(nix::DataArray da) {
        size_t nelms = config.size().nelms();
        BlockGenerator<T> generator(nelms, 10);
        generator.start_worker();

        size_t N = 100;
        size_t iterations = 0;

        nix::NDSize pos = {0, 0};
        Stopwatch sw;
        ssize_t ms = 0;
        do {
            Stopwatch inner;

            for (size_t i = 0; i < N; i++) {
                std::vector<T> block = generator.next_block();
                da.dataExtent(config.size() + pos);
                da.setData(config.dtype(), block.data(), config.size(), pos);
                pos[config.singleton_dimension()] += 1;
                iterations++;
            }

            if (inner.ms() < 100) {
                N *= 2;
            }

        } while ((ms = sw.ms()) < 3*1000);
        speed_write = calc_speed_mbs(ms, iterations);
    }

private:
    double        speed_write;
};

class ReadBenchmark : public Benchmark {

public:
    ReadBenchmark(const Config &cfg)
            : Benchmark(cfg) {
    };

    void test_read_io(nix::Block block) {
        nix::DataArray da = openDataArray(block);
        speed_read = test_read_io(da);
    }

    double test_read_io(nix::DataArray da) {

        nix::NDArray array(config.dtype(), config.size());
        nix::NDSize extend = da.dataExtent();
        size_t N = extend[config.singleton_dimension()];

        nix::NDSize pos = {0, 0};

        ssize_t ms = time_it([this, &da, &N, &pos, &array] {
            for(size_t i = 0; i < N; i++) {
                da.getData(config.dtype(), array.data(), config.size(), pos);
                pos[config.singleton_dimension()] += 1;
            }
        });

        return calc_speed_mbs(ms, N);
    }

    void run(nix::Block block) override {
        test_read_io(block);
    }

    double speed_in_mbs() override {
        return speed_read;
    }

    std::string id() override {
        return "R";
    }

private:
    double        speed_read;
};

class ReadPolyBenchmark : public ReadBenchmark {

public:
    ReadPolyBenchmark(const Config &cfg)
            : ReadBenchmark(cfg) {
    };

    void test_read_io_polynom(nix::Block block) {
        nix::DataArray da = openDataArray(block);

        da.polynomCoefficients({3, 4, 5, 6});

        speed_read_poly = test_read_io(da);
    }

    void run(nix::Block block) override {
        test_read_io_polynom(block);
    }

    double speed_in_mbs() override {
        return speed_read_poly;
    }

    std::string id() override {
        return "P";
    }

private:
    double        speed_read_poly;
};

/* ************************************ */

static std::vector<Config> make_configs() {

    std::vector<Config> configs;

    configs.emplace_back(nix::DataType::Double, nix::NDSize{2048, 1});
    configs.emplace_back(nix::DataType::Double, nix::NDSize{1, 2048});

    return configs;
}

int main(int argc, char **argv)
{
    nix::File fd = nix::File::open("iospeed.h5", nix::FileMode::Overwrite);
    nix::Block block = fd.createBlock("speed", "nix.test");

    std::vector<Config> configs = make_configs();
    std::vector<Benchmark *> marks;

    std::cout << "Performing generators tests..." << std::endl;
    for (const Config &cfg : configs) {
        GeneratorBenchmark *benchmark = new GeneratorBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << "Performing write tests..." << std::endl;
    for (const Config &cfg : configs) {
        WriteBenchmark *benchmark = new WriteBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << "Performing read tests..." << std::endl;
    for (const Config &cfg : configs) {
        ReadBenchmark *benchmark = new ReadBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << "Performing read (poly) tests..." << std::endl;
    for (const Config &cfg : configs) {
        ReadPolyBenchmark *benchmark = new ReadPolyBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << " === Reports ===" << std::endl;
    for (Benchmark *mark : marks) {
        std::cout << mark->cfg().name() << ", " << mark->id() << ", "
                << mark->speed_in_mbs() << " MB/s" << std::endl;
        delete mark;
    }

    return 0;
}
<commit_msg>[test] Benchmark: use base class recording<commit_after>// Copyright © 2014 German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>

#include <cstdio>
#include <nix.hpp>
#include <nix/NDArray.hpp>
#include <queue>
#include <random>
#include <type_traits>
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <stdexcept>

/* ************************************ */

class Stopwatch {

public:
    typedef std::chrono::high_resolution_clock::time_point time_point_t;
    typedef std::chrono::high_resolution_clock clock_t;

    Stopwatch() : t_start(clock_t::now()) { };

    ssize_t ms() {
        time_point_t t_end = clock_t::now();
        ssize_t count = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
        return count;
    }

private:
    time_point_t t_start;
};

/* ************************************ */

class RndGenBase {
public:
    RndGenBase() : rd(), rd_gen(rd()) { };

protected:
    std::random_device rd;
    std::mt19937 rd_gen;
};

template<typename T, typename Enable = void>
class RndGen { };

template<typename T>
class RndGen<T, typename std::enable_if<std::is_floating_point<T>::value >::type> : RndGenBase {
public:
    RndGen() : dis(-1024.0, +1024.0) { };

    T operator()(void) {
        return dis(rd_gen);
    };

private:
    std::uniform_real_distribution<T> dis;
};

template<typename T>
class RndGen<T, typename std::enable_if<std::is_integral<T>::value >::type> : RndGenBase {
public:
    RndGen() : dis(-1024, +1024) { };

    T operator()(void) {
        return dis(rd_gen);
    };

private:
    std::uniform_real_distribution<T> dis;
};

/* ************************************ */

template<typename T>
class BlockGenerator {
public:

    BlockGenerator(size_t blocksize, size_t bufsize) : blocksize(blocksize), bufsize(bufsize) { };

    std::vector<T> make_block() {
        std::vector<T> block(blocksize);
        std::generate(block.begin(), block.end(), std::ref(rnd_gen));
        return block;
    }

    std::vector<T> next_block() {
        std::unique_lock<std::mutex> lock(mtx);

        if (queue.empty()) {
            cnd.wait(lock, [this]{ return !queue.empty(); });
        }

        std::vector<T> x(std::move(queue.front()));
        queue.pop();
        cnd.notify_all();
        return x;
    }

    void worker_thread() {
        while (do_run) {
            std::unique_lock<std::mutex> lock(mtx);
            std::vector<T> block = make_block();

            if (queue.size() > bufsize) {
                //wait until there is room
                cnd.wait(lock, [this]{ return !do_run || queue.size() < bufsize;});
                if (!do_run) {
                    return;
                }
            }

            queue.push(std::move(block));
            cnd.notify_all();
        }
    }

    void start_worker() {
        workers.emplace_back(&BlockGenerator::worker_thread, this);
    }

    ~BlockGenerator() {
        do_run = false;
        cnd.notify_all();
        for (auto &w : workers) {
            w.join();
        }
    }

    double speed_test() {

        Stopwatch sw;

        size_t N = 100;
        size_t iterations = 0;

        do {
            Stopwatch inner;

            for (size_t i = 0; i < N; i++) {
                std::vector<double> block = next_block();
                iterations++;
            }

            if (inner.ms() < 100) {
                N *= 2;
            }

        } while (sw.ms() < 1000);

        ssize_t count = sw.ms();
        return iterations * blocksize * sizeof(T) * (1000.0/count) / (1024.0*1024.0);
    }

private:
    bool do_run = true;
    size_t blocksize;
    size_t bufsize;
    RndGen<T> rnd_gen;
    std::mutex mtx;
    std::condition_variable cnd;
    std::queue<std::vector<T>> queue;
    std::vector<std::thread> workers;
};

class Config {

public:
    Config(nix::DataType data_type, const nix::NDSize &blocksize)
            : data_type(data_type), block_size(blocksize) {

        sdim = find_single_dim();
        shape = blocksize;
        shape[sdim] = 0;

        make_name();
    };

    size_t find_single_dim() {
        size_t sdim;
        bool have_rdim = false;
        for (size_t i = 0; i < block_size.size(); i ++) {
            if (block_size[i] == 1) {
                sdim = i;
                have_rdim = true;
            }
        }

        if (!have_rdim) {
            throw std::runtime_error("Could not find singelton dimension");
        }
        return sdim;
    }

    nix::DataType dtype() const { return data_type; }
    const nix::NDSize& size() const { return block_size; }
    const nix::NDSize& extend() const { return shape; }
    size_t singleton_dimension() const { return sdim; }
    const std::string & name() const { return my_name; };

private:
    void make_name() {
        std::stringstream s;

        s << data_type << "@{ ";
        for (auto x : block_size) {
            s << x << " ";
        }
        s << "}";

        my_name = s.str();
    }

private:
    const nix::DataType data_type;
    const nix::NDSize block_size;

    size_t        sdim;
    nix::NDSize   shape;

    std::string   my_name;
};

class Benchmark {
public:
    Benchmark(const Config &cfg) : config(cfg) { }
    const Config & cfg() const { return config; }

    nix::DataArray openDataArray(nix::Block block) const {
        const std::string &cfg_name = config.name();
        std::vector<nix::DataArray> v = block.dataArrays(nix::util::NameFilter<nix::DataArray>(cfg_name));
        if (v.empty()) {
            return block.createDataArray(cfg_name, "nix.test.da", config.dtype(), config.extend());
        } else {
            return v[0];
        }
    }

    virtual ~Benchmark() { }

    virtual double speed_in_mbs() {
        return count * config.size().nelms() * nix::data_type_to_size(config.dtype()) *
                (1000.0/millis) / (1024 * 1024);
    }

    template<typename F>
    ssize_t time_it(F func) {
        Stopwatch watch;
        func();
        return watch.ms();
    }

    virtual void run(nix::Block block) = 0;
    virtual std::string id() = 0;

protected:
    double calc_speed_mbs(ssize_t ms, size_t iterations) {
        return iterations * config.size().nelms() * nix::data_type_to_size(config.dtype()) * (1000.0/ms) /
                (1024.0*1024.0);
    }

protected:
    const Config config;
    size_t       count;
    double       millis;
};

class GeneratorBenchmark : public Benchmark {
public:
    GeneratorBenchmark(const Config &cfg)
            : Benchmark(cfg) {

    };

    void run(nix::Block block) override {
        switch (config.dtype()) {

            case nix::DataType::Double:
                test_speed<double>();
                break;

            default:
                throw std::runtime_error("Unsupported DataType!");
        }
    }

    template<typename T>
    void test_speed() {
        size_t nelms = config.size().nelms();
        BlockGenerator<T> generator(nelms, 10);
        generator.start_worker();
        speed = generator.speed_test();
    }

    double speed_in_mbs() override {
        return speed;
    }

    std::string id() override {
        return "P";
    }

private:
    double speed;
};

class WriteBenchmark : public Benchmark {

public:
    WriteBenchmark(const Config &cfg)
            : Benchmark(cfg) {
    };

    void test_write_io(nix::Block block) {
        nix::DataArray da = openDataArray(block);

        switch (config.dtype()) {

            case nix::DataType::Double:
                do_write_test<double>(da);
                break;

            default:
                throw std::runtime_error("Unsupported DataType!");
        }
    }

    void run(nix::Block block) override {
        test_write_io(block);
    }

    std::string id() override {
        return "W";
    }

private:
    template<typename T>
    void do_write_test(nix::DataArray da) {
        size_t nelms = config.size().nelms();
        BlockGenerator<T> generator(nelms, 10);
        generator.start_worker();

        size_t N = 100;
        size_t iterations = 0;

        nix::NDSize pos = {0, 0};
        Stopwatch sw;
        ssize_t ms = 0;
        do {
            Stopwatch inner;

            for (size_t i = 0; i < N; i++) {
                std::vector<T> block = generator.next_block();
                da.dataExtent(config.size() + pos);
                da.setData(config.dtype(), block.data(), config.size(), pos);
                pos[config.singleton_dimension()] += 1;
                iterations++;
            }

            if (inner.ms() < 100) {
                N *= 2;
            }

        } while ((ms = sw.ms()) < 3*1000);

        this->count = iterations;
        this->millis = ms;
    }
};

class ReadBenchmark : public Benchmark {

public:
    ReadBenchmark(const Config &cfg)
            : Benchmark(cfg) {
    };

    void test_read_io(nix::Block block) {
        nix::DataArray da = openDataArray(block);
        millis = test_read_io(da);
    }

    double test_read_io(nix::DataArray da) {

        nix::NDArray array(config.dtype(), config.size());
        nix::NDSize extend = da.dataExtent();
        size_t N = extend[config.singleton_dimension()];

        nix::NDSize pos = {0, 0};

        ssize_t ms = time_it([this, &da, &N, &pos, &array] {
            for(size_t i = 0; i < N; i++) {
                da.getData(config.dtype(), array.data(), config.size(), pos);
                pos[config.singleton_dimension()] += 1;
            }
        });

        this->count = N;
        return ms;
    }

    void run(nix::Block block) override {
        test_read_io(block);
    }

    std::string id() override {
        return "R";
    }
};

class ReadPolyBenchmark : public ReadBenchmark {

public:
    ReadPolyBenchmark(const Config &cfg)
            : ReadBenchmark(cfg) {
    };

    void test_read_io_polynom(nix::Block block) {
        nix::DataArray da = openDataArray(block);
        da.polynomCoefficients({3, 4, 5, 6});
        millis = test_read_io(da);
    }

    void run(nix::Block block) override {
        test_read_io_polynom(block);
    }

    std::string id() override {
        return "P";
    }
};

/* ************************************ */

static std::vector<Config> make_configs() {

    std::vector<Config> configs;

    configs.emplace_back(nix::DataType::Double, nix::NDSize{2048, 1});
    configs.emplace_back(nix::DataType::Double, nix::NDSize{1, 2048});

    return configs;
}

int main(int argc, char **argv)
{
    nix::File fd = nix::File::open("iospeed.h5", nix::FileMode::Overwrite);
    nix::Block block = fd.createBlock("speed", "nix.test");

    std::vector<Config> configs = make_configs();
    std::vector<Benchmark *> marks;

    std::cout << "Performing generators tests..." << std::endl;
    for (const Config &cfg : configs) {
        GeneratorBenchmark *benchmark = new GeneratorBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << "Performing write tests..." << std::endl;
    for (const Config &cfg : configs) {
        WriteBenchmark *benchmark = new WriteBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << "Performing read tests..." << std::endl;
    for (const Config &cfg : configs) {
        ReadBenchmark *benchmark = new ReadBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << "Performing read (poly) tests..." << std::endl;
    for (const Config &cfg : configs) {
        ReadPolyBenchmark *benchmark = new ReadPolyBenchmark(cfg);
        benchmark->run(block);
        marks.push_back(benchmark);
    }

    std::cout << " === Reports ===" << std::endl;
    for (Benchmark *mark : marks) {
        std::cout << mark->cfg().name() << ", " << mark->id() << ", "
                << mark->speed_in_mbs() << " MB/s" << std::endl;
        delete mark;
    }

    return 0;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>
#include <stan/math/prim/mat/fun/cholesky_decompose.hpp>
#include <stan/math/rev/scal/fun/value_of_rec.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>

namespace stan {
  namespace math {

    class cholesky_decompose_v_vari : public vari {
    public:
      int M_;  // A.rows() = A.cols()
      int block_size_;
      typedef Eigen::Block<Eigen::MatrixXd> Block_;
      vari** variRefA_;
      vari** variRefL_;

      /* Constructor for cholesky function
       *
       * Stores varis for A
       * Instantiates and stores varis for L
       * Instantiates and stores dummy vari for
       * upper triangular part of var result returned
       * in cholesky_decompose function call
       *
       * variRefL aren't on the chainable
       * autodiff stack, only used for storage
       * and computation. Note that varis for
       * L are constructed externally in
       * cholesky_decompose.
       *
       * block_size_ determined using the same
       * calculation Eigen/LLT.h
       *
       * @param matrix A
       * @param matrix L, cholesky factor of A
       * */
      cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A,
                                const Eigen::Matrix<double, -1, -1>& L_A)
        : vari(0.0),
          M_(A.rows()),
          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)),
          variRefL_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)) {
            size_t pos = 0;
         block_size_ = M_/8;
         block_size_ = (block_size_/16)*16;
         block_size_ = (std::min)((std::max)(block_size_,8), 128);
        for (size_type j = 0; j < M_; ++j) {
          for (size_type i = j; i < M_; ++i) {
            variRefA_[pos] = A.coeffRef(i, j).vi_;
            variRefL_[pos] = new vari(L_A.coeffRef(i, j), false);
            ++pos;
          }
        }
      }

      inline void symbolic_rev(Block_& L,
                               Block_& Lbar,
                               int size) {

        using Eigen::Lower;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        L.transposeInPlace();
        Lbar = (L * Lbar.triangularView<Lower>()).eval();
        Lbar.triangularView<StrictlyUpper>()
          = Lbar.adjoint().triangularView<StrictlyUpper>();
        L.triangularView<Upper>().solveInPlace(Lbar);
        L.triangularView<Upper>().solveInPlace(Lbar.transpose());
      }

      /* Reverse mode differentiation
       * algorithm refernce:
       *
       * Iain Murray: Differentiation of
       * the Cholesky decomposition, 2016.
       *
       * */
      virtual void chain() {
        using Eigen::MatrixXd;
        using Eigen::Lower;
        using Eigen::Block;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        MatrixXd Lbar(M_, M_);
        MatrixXd L(M_, M_);

        Lbar.setZero();
        L.setZero();
        size_t pos = 0;
        for (size_type j = 0; j < M_; ++j) {
          for (size_type i = j; i < M_; ++i) {
            Lbar.coeffRef(i, j) = variRefL_[pos]->adj_;
            L.coeffRef(i, j) = variRefL_[pos]->val_;
            ++pos;
          }
        }

        for (int k = M_; k > 0; k -= block_size_) {
          int j = std::max(0, k - block_size_);
          Block_ R = L.block(j, 0, k - j, j);
          Block_ D = L.block(j, j, k - j, k - j);
          Block_ B = L.block(k, 0, M_ - k, j);
          Block_ C = L.block(k, j, M_ - k, k - j);
          Block_ Rbar = Lbar.block(j, 0, k - j, j);
          Block_ Dbar = Lbar.block(j, j, k - j, k - j);
          Block_ Bbar = Lbar.block(k, 0, M_ - k, j);
          Block_ Cbar = Lbar.block(k, j, M_ - k, k - j);
          if (Cbar.size() > 0) {
            Cbar
              = D.transpose().triangularView<Upper>()
              .solve(Cbar.transpose()).transpose();
            Bbar.noalias() -= Cbar * R;
            Dbar.noalias() -= Cbar.transpose() * C;
          }
          symbolic_rev(D, Dbar, D.rows());
          Rbar.noalias() -= Cbar.transpose() * B;
          Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R;
          Dbar.diagonal().array() *= 0.5;
          Dbar.triangularView<StrictlyUpper>().setZero();
        }
        pos = 0;
        for (size_type j = 0; j < M_; ++j)
          for (size_type i = j; i < M_; ++i)
            variRefA_[pos++]->adj_ += Lbar.coeffRef(i,j);
      }
    };

    /* Reverse mode specialization of
     * cholesky decomposition
     *
     * Internally calls llt rather than using
     * cholesky_decompose in order
     * to use selfadjointView<Lower> optimization.
     *
     * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky
     * when possible
     *
     * Note chainable stack varis are created
     * below in Matrix<var, -1, -1>
     *
     * @param Matrix A
     * @return L cholesky factor of A
     */
    inline Eigen::Matrix<var, -1, -1>
      cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) {
      check_square("cholesky_decompose", "A", A);
      check_symmetric("cholesky_decompose", "A", A);

      Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A));
      Eigen::LLT<Eigen::MatrixXd> L_factor
        = L_A.selfadjointView<Eigen::Lower>().llt();
      check_pos_definite("cholesky_decompose", "m", L_factor);
      L_A = L_factor.matrixL();

      // Memory allocated in arena.
      cholesky_decompose_v_vari *baseVari
        = new cholesky_decompose_v_vari(A, L_A);
      vari dummy(0.0, false);
      Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols());
      size_t pos = 0;
      for (size_type j = 0; j < L.cols(); ++j) {
        for (size_type i = j; i < L.cols(); ++i) {
          L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++];
        }
        for (size_type k = 0; k < j; ++k)
          L.coeffRef(k, j).vi_ = &dummy;
      }
      return L;
    }

  }
}
#endif
<commit_msg>cpplint<commit_after>#ifndef STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP
#define STAN_MATH_REV_MAT_FUN_CHOLESKY_DECOMPOSE_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/mat/fun/typedefs.hpp>
#include <stan/math/prim/mat/fun/cholesky_decompose.hpp>
#include <stan/math/rev/scal/fun/value_of_rec.hpp>
#include <stan/math/rev/scal/fun/value_of.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/mat/fun/value_of_rec.hpp>
#include <stan/math/prim/mat/err/check_pos_definite.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/prim/mat/err/check_symmetric.hpp>
#include <algorithm>

namespace stan {
  namespace math {

    class cholesky_decompose_v_vari : public vari {
    public:
      int M_;  // A.rows() = A.cols()
      int block_size_;
      typedef Eigen::Block<Eigen::MatrixXd> Block_;
      vari** variRefA_;
      vari** variRefL_;

      /**
       * Constructor for cholesky function.
       *
       * Stores varis for A.
       * Instantiates and stores varis for L.
       * Instantiates and stores dummy vari for
       * upper triangular part of var result returned
       * in cholesky_decompose function call
       *
       * variRefL aren't on the chainable
       * autodiff stack, only used for storage
       * and computation. Note that varis for
       * L are constructed externally in
       * cholesky_decompose.
       *
       * block_size_ determined using the same
       * calculation Eigen/LLT.h
       *
       * @param matrix A
       * @param matrix L, cholesky factor of A
       */
      cholesky_decompose_v_vari(const Eigen::Matrix<var, -1, -1>& A,
                                const Eigen::Matrix<double, -1, -1>& L_A)
        : vari(0.0),
          M_(A.rows()),
          variRefA_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)),
          variRefL_(ChainableStack::memalloc_.alloc_array<vari*>
                    (A.rows() * (A.rows() + 1) / 2)) {
            size_t pos = 0;
         block_size_ = M_/8;
         block_size_ = (block_size_/16)*16;
         block_size_ = (std::min)((std::max)(block_size_, 8), 128);
        for (size_type j = 0; j < M_; ++j) {
          for (size_type i = j; i < M_; ++i) {
            variRefA_[pos] = A.coeffRef(i, j).vi_;
            variRefL_[pos] = new vari(L_A.coeffRef(i, j), false);
            ++pos;
          }
        }
      }

      inline void symbolic_rev(Block_& L,
                               Block_& Lbar,
                               int size) {
        using Eigen::Lower;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        L.transposeInPlace();
        Lbar = (L * Lbar.triangularView<Lower>()).eval();
        Lbar.triangularView<StrictlyUpper>()
          = Lbar.adjoint().triangularView<StrictlyUpper>();
        L.triangularView<Upper>().solveInPlace(Lbar);
        L.triangularView<Upper>().solveInPlace(Lbar.transpose());
      }

      /**
       * Reverse mode differentiation
       * algorithm refernce:
       *
       * Iain Murray: Differentiation of
       * the Cholesky decomposition, 2016.
       *
       */
      virtual void chain() {
        using Eigen::MatrixXd;
        using Eigen::Lower;
        using Eigen::Block;
        using Eigen::Upper;
        using Eigen::StrictlyUpper;
        MatrixXd Lbar(M_, M_);
        MatrixXd L(M_, M_);

        Lbar.setZero();
        L.setZero();
        size_t pos = 0;
        for (size_type j = 0; j < M_; ++j) {
          for (size_type i = j; i < M_; ++i) {
            Lbar.coeffRef(i, j) = variRefL_[pos]->adj_;
            L.coeffRef(i, j) = variRefL_[pos]->val_;
            ++pos;
          }
        }

        for (int k = M_; k > 0; k -= block_size_) {
          int j = std::max(0, k - block_size_);
          Block_ R = L.block(j, 0, k - j, j);
          Block_ D = L.block(j, j, k - j, k - j);
          Block_ B = L.block(k, 0, M_ - k, j);
          Block_ C = L.block(k, j, M_ - k, k - j);
          Block_ Rbar = Lbar.block(j, 0, k - j, j);
          Block_ Dbar = Lbar.block(j, j, k - j, k - j);
          Block_ Bbar = Lbar.block(k, 0, M_ - k, j);
          Block_ Cbar = Lbar.block(k, j, M_ - k, k - j);
          if (Cbar.size() > 0) {
            Cbar
              = D.transpose().triangularView<Upper>()
              .solve(Cbar.transpose()).transpose();
            Bbar.noalias() -= Cbar * R;
            Dbar.noalias() -= Cbar.transpose() * C;
          }
          symbolic_rev(D, Dbar, D.rows());
          Rbar.noalias() -= Cbar.transpose() * B;
          Rbar.noalias() -= Dbar.selfadjointView<Lower>() * R;
          Dbar.diagonal().array() *= 0.5;
          Dbar.triangularView<StrictlyUpper>().setZero();
        }
        pos = 0;
        for (size_type j = 0; j < M_; ++j)
          for (size_type i = j; i < M_; ++i)
            variRefA_[pos++]->adj_ += Lbar.coeffRef(i, j);
      }
    };

    /**
     * Reverse mode specialization of
     * cholesky decomposition
     *
     * Internally calls llt rather than using
     * cholesky_decompose in order
     * to use selfadjointView<Lower> optimization.
     *
     * TODO(rtrangucci): Use Eigen 3.3 inplace Cholesky
     * when possible
     *
     * Note chainable stack varis are created
     * below in Matrix<var, -1, -1>
     *
     * @param Matrix A
     * @return L cholesky factor of A
     */
    inline Eigen::Matrix<var, -1, -1>
      cholesky_decompose(const Eigen::Matrix<var, -1, -1> &A) {
      check_square("cholesky_decompose", "A", A);
      check_symmetric("cholesky_decompose", "A", A);

      Eigen::Matrix<double, -1, -1> L_A(value_of_rec(A));
      Eigen::LLT<Eigen::MatrixXd> L_factor
        = L_A.selfadjointView<Eigen::Lower>().llt();
      check_pos_definite("cholesky_decompose", "m", L_factor);
      L_A = L_factor.matrixL();

      // Memory allocated in arena.
      cholesky_decompose_v_vari *baseVari
        = new cholesky_decompose_v_vari(A, L_A);
      vari dummy(0.0, false);
      Eigen::Matrix<var, -1, -1> L(A.rows(), A.cols());
      size_t pos = 0;
      for (size_type j = 0; j < L.cols(); ++j) {
        for (size_type i = j; i < L.cols(); ++i) {
          L.coeffRef(i, j).vi_ = baseVari->variRefL_[pos++];
        }
        for (size_type k = 0; k < j; ++k)
          L.coeffRef(k, j).vi_ = &dummy;
      }
      return L;
    }

  }
}
#endif
<|endoftext|>


<commit_before>/*
 Hume Library Version 0.4.3
 */

#include "Logger.h"

hm::Logger* hm::Logger::instance = NULL;

namespace hm
{
	Logger::Logger() : level(DEBUGMSG)
	{
		initSession();
	}

	Logger::~Logger()
	{
		if(instance != NULL)
		{
			endSession();
			delete instance;
			instance = NULL;
		}
	}

	Logger* Logger::getLogger()
	{
		if(instance == NULL)
			instance = new Logger();
		return instance;
	}

	LogLevel Logger::getLogLevel()
	{
		return level;
	}

	void Logger::setLogLevel(LogLevel level)
	{
		this->level = level;
		return;
	}

	void Logger::log(std::string msg, LogLevel level)
	{
		if(getLogger()->level < level)
			return;

		Logger* logger = getLogger();

		// Output time.
		time_t raw_time;
		struct tm local_time;
		time(&raw_time);
		local_time = *localtime(&raw_time);
		logger->ofs << std::to_string(local_time.tm_hour) << ":"
		<< std::to_string(local_time.tm_min) << ":"
		<< std::to_string(local_time.tm_sec) << "\t";

		switch(level)
		{
			case ERROR:
				logger->ofs << "ERROR:\t";
				break;
			case WARNING:
				logger->ofs << "WARNING:\t";
				break;
			case INFO:
				logger->ofs << "INFO:\t";
				break;
			case DEBUGMSG:
				logger->ofs << "DEBUGMSG:\t";
				break;
			default:
				logger->ofs << "UNID'd:\t";
				break;
		}

		getLogger()->ofs << msg << std::endl;
		getLogger()->ofs.flush();

		return;
	}

	void Logger::initSession()
	{
		ofs.open("log.txt", std::ios::app | std::ios::out);
		ofs << "NEW LOGGING SESSION = " << " HUME v" << MAJOR_VERSION << "." << MINOR_VERSION << "." << REVISION_VERSION << " ================" << std::endl;
		return;
	}

	void Logger::endSession()
	{
		ofs << "END LOGGING SESSION =============================" << std::endl;
		ofs.close();
		return;
	}
}
<commit_msg>Adjust Hume versioning output.<commit_after>/*
 Hume Library Version 0.4.3
 */

#include "Logger.h"

hm::Logger* hm::Logger::instance = NULL;

namespace hm
{
	Logger::Logger() : level(DEBUGMSG)
	{
		initSession();
	}

	Logger::~Logger()
	{
		if(instance != NULL)
		{
			endSession();
			delete instance;
			instance = NULL;
		}
	}

	Logger* Logger::getLogger()
	{
		if(instance == NULL)
			instance = new Logger();
		return instance;
	}

	LogLevel Logger::getLogLevel()
	{
		return level;
	}

	void Logger::setLogLevel(LogLevel level)
	{
		this->level = level;
		return;
	}

	void Logger::log(std::string msg, LogLevel level)
	{
		if(getLogger()->level < level)
			return;

		Logger* logger = getLogger();

		// Output time.
		time_t raw_time;
		struct tm local_time;
		time(&raw_time);
		local_time = *localtime(&raw_time);
		logger->ofs << std::to_string(local_time.tm_hour) << ":"
		<< std::to_string(local_time.tm_min) << ":"
		<< std::to_string(local_time.tm_sec) << "\t";

		switch(level)
		{
			case ERROR:
				logger->ofs << "ERROR:\t";
				break;
			case WARNING:
				logger->ofs << "WARNING:\t";
				break;
			case INFO:
				logger->ofs << "INFO:\t";
				break;
			case DEBUGMSG:
				logger->ofs << "DEBUGMSG:\t";
				break;
			default:
				logger->ofs << "UNID'd:\t";
				break;
		}

		getLogger()->ofs << msg << std::endl;
		getLogger()->ofs.flush();

		return;
	}

	void Logger::initSession()
	{
		ofs.open("log.txt", std::ios::app | std::ios::out);
		ofs << "NEW LOGGING SESSION ===== " << "HUME v" << MAJOR_VERSION << "." << MINOR_VERSION << "." << REVISION_VERSION << " ===========" << std::endl;
		return;
	}

	void Logger::endSession()
	{
		ofs << "END LOGGING SESSION =============================" << std::endl;
		ofs.close();
		return;
	}
}
<|endoftext|>


<commit_before>/*	Copyright � 2007-2009 Apple Inc. All Rights Reserved.

	Disclaimer: IMPORTANT:  This Apple software is supplied to you by
			Apple Inc. ("Apple") in consideration of your agreement to the
			following terms, and your use, installation, modification or
			redistribution of this Apple software constitutes acceptance of these
			terms.  If you do not agree with these terms, please do not use,
			install, modify or redistribute this Apple software.

			In consideration of your agreement to abide by the following terms, and
			subject to these terms, Apple grants you a personal, non-exclusive
			license, under Apple's copyrights in this original Apple software (the
			"Apple Software"), to use, reproduce, modify and redistribute the Apple
			Software, with or without modifications, in source and/or binary forms;
			provided that if you redistribute the Apple Software in its entirety and
			without modifications, you must retain this notice and the following
			text and disclaimers in all such redistributions of the Apple Software.
			Neither the name, trademarks, service marks or logos of Apple Inc.
			may be used to endorse or promote products derived from the Apple
			Software without specific prior written permission from Apple.  Except
			as expressly stated in this notice, no other rights or licenses, express
			or implied, are granted by Apple herein, including but not limited to
			any patent rights that may be infringed by your derivative works or by
			other works in which the Apple Software may be incorporated.

			The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
			MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
			THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
			FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
			OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

			IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
			OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
			SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
			INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
			MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
			AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
			STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
			POSSIBILITY OF SUCH DAMAGE.
*/
#include "CARingBuffer.h"
#include "CABitOperations.h"
#include "CAAutoDisposer.h"
#include "CAAtomic.h"

#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <libkern/OSAtomic.h>

CARingBuffer::CARingBuffer() :
	mBuffers(NULL), mNumberChannels(0), mCapacityFrames(0), mCapacityBytes(0)
{

}

CARingBuffer::~CARingBuffer()
{
	Deallocate();
}

void	CARingBuffer::Allocate(int nChannels, UInt32 bytesPerFrame, UInt32 capacityFrames)
{
	Deallocate();

	capacityFrames = NextPowerOfTwo(capacityFrames);

	mNumberChannels = nChannels;
	mBytesPerFrame = bytesPerFrame;
	mCapacityFrames = capacityFrames;
	mCapacityFramesMask = capacityFrames - 1;
	mCapacityBytes = bytesPerFrame * capacityFrames;

	// put everything in one memory allocation, first the pointers, then the deinterleaved channels
	UInt32 allocSize = (mCapacityBytes + sizeof(Byte *)) * nChannels;
	Byte *p = (Byte *)CA_malloc(allocSize);
	memset(p, 0, allocSize);
	mBuffers = (Byte **)p;
	p += nChannels * sizeof(Byte *);
	for (int i = 0; i < nChannels; ++i) {
		mBuffers[i] = p;
		p += mCapacityBytes;
	}

	for (UInt32 i = 0; i<kGeneralRingTimeBoundsQueueSize; ++i)
	{
		mTimeBoundsQueue[i].mStartTime = 0;
		mTimeBoundsQueue[i].mEndTime = 0;
		mTimeBoundsQueue[i].mUpdateCounter = 0;
	}
	mTimeBoundsQueuePtr = 0;
}

void	CARingBuffer::Deallocate()
{
	if (mBuffers) {
		free(mBuffers);
		mBuffers = NULL;
	}
	mNumberChannels = 0;
	mCapacityBytes = 0;
	mCapacityFrames = 0;
}

inline void ZeroRange(Byte **buffers, int nchannels, int offset, int nbytes)
{
	while (--nchannels >= 0) {
		memset(*buffers + offset, 0, nbytes);
		++buffers;
	}
}

inline void StoreABL(Byte **buffers, int destOffset, const AudioBufferList *abl, int srcOffset, int nbytes)
{
	int nchannels = abl->mNumberBuffers;
	const AudioBuffer *src = abl->mBuffers;
	while (--nchannels >= 0) {
		memcpy(*buffers + destOffset, (Byte *)src->mData + srcOffset, nbytes);
		++buffers;
		++src;
	}
}

inline void FetchABL(AudioBufferList *abl, int destOffset, Byte **buffers, int srcOffset, int nbytes)
{
	int nchannels = abl->mNumberBuffers;
	AudioBuffer *dest = abl->mBuffers;
	while (--nchannels >= 0) {
		memcpy((Byte *)dest->mData + destOffset, *buffers + srcOffset, nbytes);
		++buffers;
		++dest;
	}
}

inline void ZeroABL(AudioBufferList *abl, int destOffset, int nbytes)
{
	int nBuffers = abl->mNumberBuffers;
	AudioBuffer *dest = abl->mBuffers;
	while (--nBuffers >= 0) {
		memset((Byte *)dest->mData + destOffset, 0, nbytes);
		++dest;
	}
}

CARingBufferError	CARingBuffer::Store(const AudioBufferList *abl, UInt32 framesToWrite, SampleTime startWrite)
{
	if(0 == framesToWrite)
		return noErr;

	if (framesToWrite > mCapacityFrames)
		return kCARingBufferError_TooMuch;		// too big!

	SampleTime endWrite = startWrite + framesToWrite;

	if (startWrite < EndTime()) {
		// going backwards, throw everything out
		SetTimeBounds(startWrite, startWrite);
	} else if (endWrite - StartTime() <= mCapacityFrames) {
		// the buffer has not yet wrapped and will not need to
	} else {
		// advance the start time past the region we are about to overwrite
		SampleTime newStart = endWrite - mCapacityFrames;	// one buffer of time behind where we're writing
		SampleTime newEnd = std::max(newStart, EndTime());
		SetTimeBounds(newStart, newEnd);
	}

	// write the new frames
	Byte **buffers = mBuffers;
	int nchannels = mNumberChannels;
	int offset0, offset1, nbytes;
	SampleTime curEnd = EndTime();

	if (startWrite > curEnd) {
		// we are skipping some samples, so zero the range we are skipping
		offset0 = FrameOffset(curEnd);
		offset1 = FrameOffset(startWrite);
		if (offset0 < offset1)
			ZeroRange(buffers, nchannels, offset0, offset1 - offset0);
		else {
			ZeroRange(buffers, nchannels, offset0, mCapacityBytes - offset0);
			ZeroRange(buffers, nchannels, 0, offset1);
		}
		offset0 = offset1;
	} else {
		offset0 = FrameOffset(startWrite);
	}

	offset1 = FrameOffset(endWrite);
	if (offset0 < offset1)
		StoreABL(buffers, offset0, abl, 0, offset1 - offset0);
	else {
		nbytes = mCapacityBytes - offset0;
		StoreABL(buffers, offset0, abl, 0, nbytes);
		StoreABL(buffers, 0, abl, nbytes, offset1);
	}

	// now update the end time
	SetTimeBounds(StartTime(), endWrite);

	return kCARingBufferError_OK;	// success
}

void	CARingBuffer::SetTimeBounds(SampleTime startTime, SampleTime endTime)
{
	UInt32 nextPtr = mTimeBoundsQueuePtr + 1;
	UInt32 index = nextPtr & kGeneralRingTimeBoundsQueueMask;

	mTimeBoundsQueue[index].mStartTime = startTime;
	mTimeBoundsQueue[index].mEndTime = endTime;
	mTimeBoundsQueue[index].mUpdateCounter = nextPtr;
	CAAtomicCompareAndSwap32Barrier(mTimeBoundsQueuePtr, mTimeBoundsQueuePtr + 1, (SInt32*)&mTimeBoundsQueuePtr);
}

CARingBufferError	CARingBuffer::GetTimeBounds(SampleTime &startTime, SampleTime &endTime)
{
	for (int i=0; i<8; ++i) // fail after a few tries.
	{
		UInt32 curPtr = mTimeBoundsQueuePtr;
		UInt32 index = curPtr & kGeneralRingTimeBoundsQueueMask;
		CARingBuffer::TimeBounds* bounds = mTimeBoundsQueue + index;

		startTime = bounds->mStartTime;
		endTime = bounds->mEndTime;
		UInt32 newPtr = bounds->mUpdateCounter;

		if (newPtr == curPtr)
			return kCARingBufferError_OK;
	}
	return kCARingBufferError_CPUOverload;
}

CARingBufferError	CARingBuffer::ClipTimeBounds(SampleTime& startRead, SampleTime& endRead)
{
	SampleTime startTime, endTime;

	CARingBufferError err = GetTimeBounds(startTime, endTime);
	if (err) return err;

	startRead = std::max(startRead, startTime);
	endRead = std::min(endRead, endTime);
	endRead = std::max(endRead, startRead);

	return kCARingBufferError_OK;	// success
}

CARingBufferError	CARingBuffer::Fetch(AudioBufferList *abl, UInt32 nFrames, SampleTime startRead)
{
	if(0 == nFrames)
		return noErr;

	SampleTime endRead = startRead + nFrames;

	SampleTime startRead0 = startRead;
	SampleTime endRead0 = endRead;
	SampleTime size;

	CARingBufferError err = ClipTimeBounds(startRead, endRead);
	if (err) return err;
	size = endRead - startRead;

	SInt32 destStartOffset = startRead - startRead0;
	if (destStartOffset > 0) {
		ZeroABL(abl, 0, destStartOffset * mBytesPerFrame);
	}

	SInt32 destEndSize = endRead0 - endRead;
	if (destEndSize > 0) {
		ZeroABL(abl, destStartOffset + size, destEndSize * mBytesPerFrame);
	}

	Byte **buffers = mBuffers;
	int offset0 = FrameOffset(startRead);
	int offset1 = FrameOffset(endRead);
	int nbytes;

	if (offset0 < offset1) {
		FetchABL(abl, destStartOffset, buffers, offset0, nbytes = offset1 - offset0);
	} else {
		nbytes = mCapacityBytes - offset0;
		FetchABL(abl, destStartOffset, buffers, offset0, nbytes);
		FetchABL(abl, destStartOffset + nbytes, buffers, 0, offset1);
		nbytes += offset1;
	}

	int nchannels = abl->mNumberBuffers;
	AudioBuffer *dest = abl->mBuffers;
	while (--nchannels >= 0)
	{
		dest->mDataByteSize = nbytes;
		dest++;
	}

	return noErr;
}
<commit_msg>Don't crash if the ring buffer doesn't contain the requested audio Apple bug number 9523959<commit_after>/*	Copyright � 2007-2009 Apple Inc. All Rights Reserved.

	Disclaimer: IMPORTANT:  This Apple software is supplied to you by
			Apple Inc. ("Apple") in consideration of your agreement to the
			following terms, and your use, installation, modification or
			redistribution of this Apple software constitutes acceptance of these
			terms.  If you do not agree with these terms, please do not use,
			install, modify or redistribute this Apple software.

			In consideration of your agreement to abide by the following terms, and
			subject to these terms, Apple grants you a personal, non-exclusive
			license, under Apple's copyrights in this original Apple software (the
			"Apple Software"), to use, reproduce, modify and redistribute the Apple
			Software, with or without modifications, in source and/or binary forms;
			provided that if you redistribute the Apple Software in its entirety and
			without modifications, you must retain this notice and the following
			text and disclaimers in all such redistributions of the Apple Software.
			Neither the name, trademarks, service marks or logos of Apple Inc.
			may be used to endorse or promote products derived from the Apple
			Software without specific prior written permission from Apple.  Except
			as expressly stated in this notice, no other rights or licenses, express
			or implied, are granted by Apple herein, including but not limited to
			any patent rights that may be infringed by your derivative works or by
			other works in which the Apple Software may be incorporated.

			The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
			MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
			THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
			FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
			OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

			IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
			OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
			SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
			INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
			MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
			AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
			STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
			POSSIBILITY OF SUCH DAMAGE.
*/
#include "CARingBuffer.h"
#include "CABitOperations.h"
#include "CAAutoDisposer.h"
#include "CAAtomic.h"

#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <libkern/OSAtomic.h>

CARingBuffer::CARingBuffer() :
	mBuffers(NULL), mNumberChannels(0), mCapacityFrames(0), mCapacityBytes(0)
{

}

CARingBuffer::~CARingBuffer()
{
	Deallocate();
}

void	CARingBuffer::Allocate(int nChannels, UInt32 bytesPerFrame, UInt32 capacityFrames)
{
	Deallocate();

	capacityFrames = NextPowerOfTwo(capacityFrames);

	mNumberChannels = nChannels;
	mBytesPerFrame = bytesPerFrame;
	mCapacityFrames = capacityFrames;
	mCapacityFramesMask = capacityFrames - 1;
	mCapacityBytes = bytesPerFrame * capacityFrames;

	// put everything in one memory allocation, first the pointers, then the deinterleaved channels
	UInt32 allocSize = (mCapacityBytes + sizeof(Byte *)) * nChannels;
	Byte *p = (Byte *)CA_malloc(allocSize);
	memset(p, 0, allocSize);
	mBuffers = (Byte **)p;
	p += nChannels * sizeof(Byte *);
	for (int i = 0; i < nChannels; ++i) {
		mBuffers[i] = p;
		p += mCapacityBytes;
	}

	for (UInt32 i = 0; i<kGeneralRingTimeBoundsQueueSize; ++i)
	{
		mTimeBoundsQueue[i].mStartTime = 0;
		mTimeBoundsQueue[i].mEndTime = 0;
		mTimeBoundsQueue[i].mUpdateCounter = 0;
	}
	mTimeBoundsQueuePtr = 0;
}

void	CARingBuffer::Deallocate()
{
	if (mBuffers) {
		free(mBuffers);
		mBuffers = NULL;
	}
	mNumberChannels = 0;
	mCapacityBytes = 0;
	mCapacityFrames = 0;
}

inline void ZeroRange(Byte **buffers, int nchannels, int offset, int nbytes)
{
	while (--nchannels >= 0) {
		memset(*buffers + offset, 0, nbytes);
		++buffers;
	}
}

inline void StoreABL(Byte **buffers, int destOffset, const AudioBufferList *abl, int srcOffset, int nbytes)
{
	int nchannels = abl->mNumberBuffers;
	const AudioBuffer *src = abl->mBuffers;
	while (--nchannels >= 0) {
		memcpy(*buffers + destOffset, (Byte *)src->mData + srcOffset, nbytes);
		++buffers;
		++src;
	}
}

inline void FetchABL(AudioBufferList *abl, int destOffset, Byte **buffers, int srcOffset, int nbytes)
{
	int nchannels = abl->mNumberBuffers;
	AudioBuffer *dest = abl->mBuffers;
	while (--nchannels >= 0) {
		memcpy((Byte *)dest->mData + destOffset, *buffers + srcOffset, nbytes);
		++buffers;
		++dest;
	}
}

inline void ZeroABL(AudioBufferList *abl, int destOffset, int nbytes)
{
	int nBuffers = abl->mNumberBuffers;
	AudioBuffer *dest = abl->mBuffers;
	while (--nBuffers >= 0) {
		memset((Byte *)dest->mData + destOffset, 0, nbytes);
		++dest;
	}
}

CARingBufferError	CARingBuffer::Store(const AudioBufferList *abl, UInt32 framesToWrite, SampleTime startWrite)
{
	if(0 == framesToWrite)
		return noErr;

	if (framesToWrite > mCapacityFrames)
		return kCARingBufferError_TooMuch;		// too big!

	SampleTime endWrite = startWrite + framesToWrite;

	if (startWrite < EndTime()) {
		// going backwards, throw everything out
		SetTimeBounds(startWrite, startWrite);
	} else if (endWrite - StartTime() <= mCapacityFrames) {
		// the buffer has not yet wrapped and will not need to
	} else {
		// advance the start time past the region we are about to overwrite
		SampleTime newStart = endWrite - mCapacityFrames;	// one buffer of time behind where we're writing
		SampleTime newEnd = std::max(newStart, EndTime());
		SetTimeBounds(newStart, newEnd);
	}

	// write the new frames
	Byte **buffers = mBuffers;
	int nchannels = mNumberChannels;
	int offset0, offset1, nbytes;
	SampleTime curEnd = EndTime();

	if (startWrite > curEnd) {
		// we are skipping some samples, so zero the range we are skipping
		offset0 = FrameOffset(curEnd);
		offset1 = FrameOffset(startWrite);
		if (offset0 < offset1)
			ZeroRange(buffers, nchannels, offset0, offset1 - offset0);
		else {
			ZeroRange(buffers, nchannels, offset0, mCapacityBytes - offset0);
			ZeroRange(buffers, nchannels, 0, offset1);
		}
		offset0 = offset1;
	} else {
		offset0 = FrameOffset(startWrite);
	}

	offset1 = FrameOffset(endWrite);
	if (offset0 < offset1)
		StoreABL(buffers, offset0, abl, 0, offset1 - offset0);
	else {
		nbytes = mCapacityBytes - offset0;
		StoreABL(buffers, offset0, abl, 0, nbytes);
		StoreABL(buffers, 0, abl, nbytes, offset1);
	}

	// now update the end time
	SetTimeBounds(StartTime(), endWrite);

	return kCARingBufferError_OK;	// success
}

void	CARingBuffer::SetTimeBounds(SampleTime startTime, SampleTime endTime)
{
	UInt32 nextPtr = mTimeBoundsQueuePtr + 1;
	UInt32 index = nextPtr & kGeneralRingTimeBoundsQueueMask;

	mTimeBoundsQueue[index].mStartTime = startTime;
	mTimeBoundsQueue[index].mEndTime = endTime;
	mTimeBoundsQueue[index].mUpdateCounter = nextPtr;
	CAAtomicCompareAndSwap32Barrier(mTimeBoundsQueuePtr, mTimeBoundsQueuePtr + 1, (SInt32*)&mTimeBoundsQueuePtr);
}

CARingBufferError	CARingBuffer::GetTimeBounds(SampleTime &startTime, SampleTime &endTime)
{
	for (int i=0; i<8; ++i) // fail after a few tries.
	{
		UInt32 curPtr = mTimeBoundsQueuePtr;
		UInt32 index = curPtr & kGeneralRingTimeBoundsQueueMask;
		CARingBuffer::TimeBounds* bounds = mTimeBoundsQueue + index;

		startTime = bounds->mStartTime;
		endTime = bounds->mEndTime;
		UInt32 newPtr = bounds->mUpdateCounter;

		if (newPtr == curPtr)
			return kCARingBufferError_OK;
	}
	return kCARingBufferError_CPUOverload;
}

CARingBufferError	CARingBuffer::ClipTimeBounds(SampleTime& startRead, SampleTime& endRead)
{
	SampleTime startTime, endTime;

	CARingBufferError err = GetTimeBounds(startTime, endTime);
	if (err) return err;

	startRead = std::max(startRead, startTime);
	endRead = std::min(endRead, endTime);
	endRead = std::max(endRead, startRead);

	return kCARingBufferError_OK;	// success
}

CARingBufferError	CARingBuffer::Fetch(AudioBufferList *abl, UInt32 nFrames, SampleTime startRead)
{
	if(0 == nFrames)
		return noErr;

	SampleTime endRead = startRead + nFrames;

	SampleTime startRead0 = startRead;
	SampleTime endRead0 = endRead;
	SampleTime size;

	CARingBufferError err = ClipTimeBounds(startRead, endRead);
	if (err) return err;
	size = endRead - startRead;

	// Don't perform out-of-bounds writes
	if((startRead - startRead0) > nFrames || (endRead0 - endRead) > nFrames) {
		ZeroABL(abl, 0, nFrames * mBytesPerFrame);
		return noErr;
	}

	SInt32 destStartOffset = startRead - startRead0;
	if (destStartOffset > 0) {
		ZeroABL(abl, 0, destStartOffset * mBytesPerFrame);
	}

	SInt32 destEndSize = endRead0 - endRead;
	if (destEndSize > 0) {
		ZeroABL(abl, destStartOffset + size, destEndSize * mBytesPerFrame);
	}

	Byte **buffers = mBuffers;
	int offset0 = FrameOffset(startRead);
	int offset1 = FrameOffset(endRead);
	int nbytes;

	if (offset0 < offset1) {
		FetchABL(abl, destStartOffset, buffers, offset0, nbytes = offset1 - offset0);
	} else {
		nbytes = mCapacityBytes - offset0;
		FetchABL(abl, destStartOffset, buffers, offset0, nbytes);
		FetchABL(abl, destStartOffset + nbytes, buffers, 0, offset1);
		nbytes += offset1;
	}

	int nchannels = abl->mNumberBuffers;
	AudioBuffer *dest = abl->mBuffers;
	while (--nchannels >= 0)
	{
		dest->mDataByteSize = nbytes;
		dest++;
	}

	return noErr;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2018 Robot Garden, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "wheelencoder.h"
#include <FastGPIO.h>
#include <EnableInterrupt.h>

static const long MIN_CHANGE_TIME = 1000; // 1000us = 1ms is minimum time between ticks.

static volatile long left_ticks = 0;
static volatile long right_ticks = 0;

static volatile int last_left_state;
static volatile long last_left_time;

static volatile int last_right_state;
static volatile long last_right_time;

static const signed char ENC_STATES [] = {
  0,  // 00 -> 00
  1,  // 00 -> 01
  -1, // 00 -> 10
  0,  // 00 -> 11 (shouldn't happen)
  -1, // 01 -> 00
  0,  // 01 -> 01
  0,  // 01 -> 10 (shouldn't happen)
  1,  // 01 -> 11
  1,  // 10 -> 00
  0,  // 10 -> 01 (shouldn't happen)
  0,  // 10 -> 10
  -1, // 10 -> 11
  0,  // 11 -> 00 (shouldn't happen)
  -1, // 11 -> 01
  1,  // 11 -> 10
  0   // 11 -> 11
};

static void updateTicks(volatile long &ticks, volatile int &last_state, volatile long &last_time,
  int new_state) {

  long new_time = micros();
  if (new_time-last_time > MIN_CHANGE_TIME) {
    ticks += ENC_STATES[last_state<<2 | new_state];
    last_state = new_state;
    last_time = new_time;
  }
}

// Update the left encoder when either encoder pin changes.
static void leftISR() {
  int new_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()<<1
     | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh();
  updateTicks(left_ticks, last_left_state, last_left_time, new_state);
}

// Update the encoder when the right A pin changes.
static void rightISR() {
  int new_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()<<1
     | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh();
  updateTicks(right_ticks, last_right_state, last_right_time, new_state);
}

/**
 *
 */
void initWheelEncoder() {
  FastGPIO::Pin<LEFT_ENCODER_PIN_A>::setInputPulledUp();
  FastGPIO::Pin<LEFT_ENCODER_PIN_B>::setInputPulledUp();

  FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::setInputPulledUp();
  FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::setInputPulledUp();

  enableInterrupt(LEFT_ENCODER_PIN_A, leftISR, CHANGE);
  enableInterrupt(LEFT_ENCODER_PIN_B, leftISR, CHANGE);
  enableInterrupt(RIGHT_ENCODER_PIN_A, rightISR, CHANGE);
  enableInterrupt(RIGHT_ENCODER_PIN_B, rightISR, CHANGE);

  resetEncoders();
}

/* Wrap the encoder reading function */
double readTicks(int i) {
  if (i == LEFT_ENCODER) {
    return left_ticks;
  } else {
    return right_ticks;
  }
}

/* Wrap the encoder reset function */
void resetEncoder(int i) {
  if (i == LEFT_ENCODER) {
    left_ticks = 0;
    last_left_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()<<1
      | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh();
    last_left_time = micros();
  } else {
    right_ticks = 0;
    last_right_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()<<1
      | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh();
    last_right_time = micros();
  }
}

void resetEncoders() {
  resetEncoder(LEFT_ENCODER);
  resetEncoder(RIGHT_ENCODER);
}

<commit_msg>Fix detection of wheel direction<commit_after>/**
 * Copyright 2018 Robot Garden, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include "wheelencoder.h"
#include <FastGPIO.h>
#include <EnableInterrupt.h>

static const long MIN_CHANGE_TIME = 1000; // 1000us = 1ms is minimum time between ticks.

static volatile long left_ticks = 0;
static volatile long right_ticks = 0;

static volatile int last_left_state;
static volatile long last_left_time;

static volatile int last_right_state;
static volatile long last_right_time;

// Encodes how much to increment the ticks based on the last state and the new state.
// The states are encoded as "B<<1 | A" for the A & B interrupt pins.
// Indices into the array are:
//   last_state<<2 | new_state
// The commend next to each value shows "last_state -> new_state".
static const signed char ENC_STATES [] = {
  0,  // 00 -> 00
  1,  // 00 -> 01
  -1, // 00 -> 10
  0,  // 00 -> 11 (shouldn't happen)
  -1, // 01 -> 00
  0,  // 01 -> 01
  0,  // 01 -> 10 (shouldn't happen)
  1,  // 01 -> 11
  1,  // 10 -> 00
  0,  // 10 -> 01 (shouldn't happen)
  0,  // 10 -> 10
  -1, // 10 -> 11
  0,  // 11 -> 00 (shouldn't happen)
  -1, // 11 -> 01
  1,  // 11 -> 10
  0   // 11 -> 11
};

static void updateTicks(volatile long &ticks, volatile int &last_state, volatile long &last_time,
  int new_state) {

  long new_time = micros();
  if (new_time-last_time > MIN_CHANGE_TIME) {
    ticks += ENC_STATES[last_state<<2 | new_state];
    last_state = new_state;
    last_time = new_time;
  }
}

// Update the left encoder when either encoder pin changes.
static void leftISR() {
  int new_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()
     | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh()<<1;
  updateTicks(left_ticks, last_left_state, last_left_time, new_state);
}

// Update the encoder when the right A pin changes.
static void rightISR() {
  int new_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()
     | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh()<<1;
  updateTicks(right_ticks, last_right_state, last_right_time, new_state);
}

/**
 *
 */
void initWheelEncoder() {
  FastGPIO::Pin<LEFT_ENCODER_PIN_A>::setInputPulledUp();
  FastGPIO::Pin<LEFT_ENCODER_PIN_B>::setInputPulledUp();

  FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::setInputPulledUp();
  FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::setInputPulledUp();

  enableInterrupt(LEFT_ENCODER_PIN_A, leftISR, CHANGE);
  enableInterrupt(LEFT_ENCODER_PIN_B, leftISR, CHANGE);
  enableInterrupt(RIGHT_ENCODER_PIN_A, rightISR, CHANGE);
  enableInterrupt(RIGHT_ENCODER_PIN_B, rightISR, CHANGE);

  resetEncoders();
}

/* Wrap the encoder reading function */
double readTicks(int i) {
  if (i == LEFT_ENCODER) {
    return left_ticks;
  } else {
    return right_ticks;
  }
}

/* Wrap the encoder reset function */
void resetEncoder(int i) {
  if (i == LEFT_ENCODER) {
    left_ticks = 0;
    last_left_state = FastGPIO::Pin<LEFT_ENCODER_PIN_A>::isInputHigh()<<1
      | FastGPIO::Pin<LEFT_ENCODER_PIN_B>::isInputHigh();
    last_left_time = micros();
  } else {
    right_ticks = 0;
    last_right_state = FastGPIO::Pin<RIGHT_ENCODER_PIN_A>::isInputHigh()<<1
      | FastGPIO::Pin<RIGHT_ENCODER_PIN_B>::isInputHigh();
    last_right_time = micros();
  }
}

void resetEncoders() {
  resetEncoder(LEFT_ENCODER);
  resetEncoder(RIGHT_ENCODER);
}

<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include "TestBlock.hpp"

#include <nix/util/util.hpp>

#include <nix/valid/validate.hpp>
#include <nix/Exception.hpp>

#include <ctime>

using namespace std;
using namespace nix;
using namespace valid;

void TestBlock::setUp() {
    startup_time = time(NULL);
    file = File::open("test_block.h5", FileMode::Overwrite);

    section = file.createSection("foo_section", "metadata");

    block = file.createBlock("block_one", "dataset");
    block_other = file.createBlock("block_two", "dataset");
    block_null  = nix::none;
}

void TestBlock::tearDown() {
    file.close();
}

void TestBlock::testValidate() {
    valid::Result result = validate(block);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
    CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}

void TestBlock::testId() {
    CPPUNIT_ASSERT(block.id().size() == 36);
}

void TestBlock::testName() {
    CPPUNIT_ASSERT(block.name() == "block_one");
}

void TestBlock::testType() {
    CPPUNIT_ASSERT(block.type() == "dataset");
    string typ = util::createId();
    block.type(typ);
    CPPUNIT_ASSERT(block.type() == typ);
}

void TestBlock::testDefinition() {
    string def = util::createId();
    block.definition(def);
    CPPUNIT_ASSERT(*block.definition() == def);
}

void TestBlock::testMetadataAccess() {
    CPPUNIT_ASSERT(!block.metadata());

    block.metadata(section);
    CPPUNIT_ASSERT(block.metadata());

    // test none-unsetter
    block.metadata(none);
    CPPUNIT_ASSERT(!block.metadata());
    // test deleter removing link too
    block.metadata(section);
    file.deleteSection(section.id());
    CPPUNIT_ASSERT(!block.metadata());
    // re-create section
    section = file.createSection("foo_section", "metadata");
}

void TestBlock::testSourceAccess() {
    vector<string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
    Source s;
    CPPUNIT_ASSERT_THROW(block.hasSource(s), std::runtime_error);
    CPPUNIT_ASSERT(block.sourceCount() == 0);
    CPPUNIT_ASSERT(block.sources().size() == 0);
    CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
    CPPUNIT_ASSERT(!block.hasSource("invalid_id"));

    vector<string> ids;
    for (const auto &name : names) {
        Source src = block.createSource(name, "channel");
        CPPUNIT_ASSERT(src.name() == name);
        CPPUNIT_ASSERT(block.hasSource(name));
        CPPUNIT_ASSERT(block.hasSource(src));

        ids.push_back(src.id());
    }
    CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"),
                         DuplicateName);

    CPPUNIT_ASSERT(block.sourceCount() == names.size());
    CPPUNIT_ASSERT(block.sources().size() == names.size());

    for (const auto &id : ids) {
        Source src = block.getSource(id);
        CPPUNIT_ASSERT(block.hasSource(id) == true);
        CPPUNIT_ASSERT(src.id() == id);
        block.deleteSource(id);
    }

    s = block.createSource("test", "test");
    CPPUNIT_ASSERT(block.sourceCount() == 1);
    CPPUNIT_ASSERT_NO_THROW(block.deleteSource(s));

    CPPUNIT_ASSERT(block.sourceCount() == 0);
    CPPUNIT_ASSERT(block.sources().size() == 0);
    CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
}

void TestBlock::testDataArrayAccess() {
    vector<string> names = { "data_array_a", "data_array_b", "data_array_c",
                             "data_array_d", "data_array_e" };
    DataArray data_array, a;

    CPPUNIT_ASSERT(block.dataArrayCount() == 0);
    CPPUNIT_ASSERT(block.dataArrays().size() == 0);
    CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);

    vector<string> ids;
    for (const auto &name : names) {
        data_array = block.createDataArray(name, "channel",
                                           DataType::Double, nix::NDSize({ 0 }));
        CPPUNIT_ASSERT(data_array.name() == name);
        CPPUNIT_ASSERT(data_array.type() == "channel");

        ids.push_back(data_array.id());
    }
    CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })),
                         DuplicateName);
    CPPUNIT_ASSERT(block.hasDataArray(data_array));
    CPPUNIT_ASSERT_THROW(block.hasDataArray(a), std::runtime_error);
    CPPUNIT_ASSERT(block.dataArrayCount() == names.size());
    CPPUNIT_ASSERT(block.dataArrays().size() == names.size());

    for (const auto &name : names) {
        DataArray da_name = block.getDataArray(name);
        CPPUNIT_ASSERT(da_name);

        DataArray da_id = block.getDataArray(da_name.id());
        CPPUNIT_ASSERT(da_id);
        CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name());
    }

    vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel"));
    CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size());

    filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c"));
    CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size());
    if (filteredArrays.size() > 0) {
        boost::optional<std::string> name = filteredArrays[0].name();
        CPPUNIT_ASSERT(name && *name == "data_array_c");
    }

    for (auto it = ids.begin(); it != ids.end(); it++) {
        DataArray data_array = block.getDataArray(*it);
        CPPUNIT_ASSERT(block.hasDataArray(*it) == true);
        CPPUNIT_ASSERT(data_array.id() == *it);

        block.deleteDataArray(*it);
    }
    CPPUNIT_ASSERT_THROW(block.deleteDataArray(a), std::runtime_error);
    CPPUNIT_ASSERT(block.dataArrayCount() == 0);
    CPPUNIT_ASSERT(block.dataArrays().size() == 0);
    CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);

}

void TestBlock::testTagAccess() {
    vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
    vector<string> array_names = { "data_array_a", "data_array_b", "data_array_c",
                                   "data_array_d", "data_array_e" };
    vector<DataArray> refs;
    Tag tag, t;
    for (const auto &name : array_names) {
        refs.push_back(block.createDataArray(name,
                                             "reference",
                                             DataType::Double,
                                             nix::NDSize({ 0 })));
    }

    CPPUNIT_ASSERT(block.tagCount() == 0);
    CPPUNIT_ASSERT(block.tags().size() == 0);
    CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
    CPPUNIT_ASSERT_THROW(block.hasTag(t), std::runtime_error);

    vector<string> ids;
    for (auto it = names.begin(); it != names.end(); ++it) {
        tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4});
        tag.references(refs);
        CPPUNIT_ASSERT(tag.name() == *it);
        CPPUNIT_ASSERT(block.hasTag(tag));
        ids.push_back(tag.id());
    }
    CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}),
                         DuplicateName);

    CPPUNIT_ASSERT(block.tagCount() == names.size());
    CPPUNIT_ASSERT(block.tags().size() == names.size());

    for (auto it = ids.begin(); it != ids.end(); ++it) {
        tag = block.getTag(*it);
        CPPUNIT_ASSERT(block.hasTag(*it) == true);
        CPPUNIT_ASSERT(tag.id() == *it);

        block.deleteTag(*it);
    }

    tag = block.createTag("test", "test", {0.0});
    CPPUNIT_ASSERT(block.hasTag(tag));
    CPPUNIT_ASSERT_NO_THROW(block.deleteTag(tag));
    CPPUNIT_ASSERT_THROW(block.deleteTag(t), std::runtime_error);

    CPPUNIT_ASSERT(block.tagCount() == 0);
    CPPUNIT_ASSERT(block.tags().size() == 0);
    CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
}

void TestBlock::testMultiTagAccess() {
    vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
    MultiTag mtag, m;
    // create a valid positions data array below
    typedef boost::multi_array<double, 3>::index index;
    DataArray positions = block.createDataArray("array_one",
                                                "testdata",
                                                DataType::Double,
                                                nix::NDSize({ 3, 4, 2 }));
    boost::multi_array<double, 3> A(boost::extents[3][4][2]);
    int values = 0;
    for(index i = 0; i != 3; ++i)
        for(index j = 0; j != 4; ++j)
            for(index k = 0; k != 2; ++k)
                A[i][j][k] = values++;

    positions.setData(A);

    CPPUNIT_ASSERT(block.multiTagCount() == 0);
    CPPUNIT_ASSERT(block.multiTags().size() == 0);
    CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
    CPPUNIT_ASSERT_THROW(block.hasMultiTag(m), std::runtime_error);
    vector<string> ids;
    for (auto it = names.begin(); it != names.end(); it++) {
        mtag = block.createMultiTag(*it, "segment", positions);
        CPPUNIT_ASSERT(mtag.name() == *it);
        CPPUNIT_ASSERT(block.hasMultiTag(mtag));
        ids.push_back(mtag.id());
    }
    CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions),
                         DuplicateName);

    CPPUNIT_ASSERT(block.multiTagCount() == names.size());
    CPPUNIT_ASSERT(block.multiTags().size() == names.size());

    for (auto it = ids.begin(); it != ids.end(); it++) {
        mtag = block.getMultiTag(*it);
        CPPUNIT_ASSERT(block.hasMultiTag(*it) == true);
        CPPUNIT_ASSERT(mtag.id() == *it);

        block.deleteMultiTag(*it);
    }
    mtag = block.createMultiTag("test", "test", positions);
    CPPUNIT_ASSERT(block.hasMultiTag(mtag));
    CPPUNIT_ASSERT_THROW(block.deleteMultiTag(m), std::runtime_error);
    CPPUNIT_ASSERT_NO_THROW(block.deleteMultiTag(mtag));
    CPPUNIT_ASSERT(block.multiTagCount() == 0);
    CPPUNIT_ASSERT(block.multiTags().size() == 0);
    CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
}

void TestBlock::testOperators() {
    CPPUNIT_ASSERT(block_null == false);
    CPPUNIT_ASSERT(block_null == none);

    CPPUNIT_ASSERT(block != false);
    CPPUNIT_ASSERT(block != none);

    CPPUNIT_ASSERT(block == block);
    CPPUNIT_ASSERT(block != block_other);

    block_other = block;
    CPPUNIT_ASSERT(block == block_other);

    block_other = none;
    CPPUNIT_ASSERT(block_null == false);
    CPPUNIT_ASSERT(block_null == none);
}

void TestBlock::testCreatedAt() {
    CPPUNIT_ASSERT(block.createdAt() >= startup_time);
    time_t past_time = time(NULL) - 10000000;
    block.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(block.createdAt() == past_time);
}

void TestBlock::testUpdatedAt() {
    CPPUNIT_ASSERT(block.updatedAt() >= startup_time);
}

void TestBlock::testCompare() {
    string other_name = block_other.name();
    string block_name = block.name();

    CPPUNIT_ASSERT(block.compare(block) == 0);
    CPPUNIT_ASSERT(block.compare(block_other) ==  block_name.compare(other_name));
}
<commit_msg>[TestBlock] change Throw asserts checks to expect UninitializedEntity<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include "TestBlock.hpp"

#include <nix/util/util.hpp>

#include <nix/valid/validate.hpp>
#include <nix/Exception.hpp>

#include <ctime>

using namespace std;
using namespace nix;
using namespace valid;

void TestBlock::setUp() {
    startup_time = time(NULL);
    file = File::open("test_block.h5", FileMode::Overwrite);

    section = file.createSection("foo_section", "metadata");

    block = file.createBlock("block_one", "dataset");
    block_other = file.createBlock("block_two", "dataset");
    block_null  = nix::none;
}

void TestBlock::tearDown() {
    file.close();
}

void TestBlock::testValidate() {
    valid::Result result = validate(block);
    CPPUNIT_ASSERT(result.getErrors().size() == 0);
    CPPUNIT_ASSERT(result.getWarnings().size() == 0);
}

void TestBlock::testId() {
    CPPUNIT_ASSERT(block.id().size() == 36);
}

void TestBlock::testName() {
    CPPUNIT_ASSERT(block.name() == "block_one");
}

void TestBlock::testType() {
    CPPUNIT_ASSERT(block.type() == "dataset");
    string typ = util::createId();
    block.type(typ);
    CPPUNIT_ASSERT(block.type() == typ);
}

void TestBlock::testDefinition() {
    string def = util::createId();
    block.definition(def);
    CPPUNIT_ASSERT(*block.definition() == def);
}

void TestBlock::testMetadataAccess() {
    CPPUNIT_ASSERT(!block.metadata());

    block.metadata(section);
    CPPUNIT_ASSERT(block.metadata());

    // test none-unsetter
    block.metadata(none);
    CPPUNIT_ASSERT(!block.metadata());
    // test deleter removing link too
    block.metadata(section);
    file.deleteSection(section.id());
    CPPUNIT_ASSERT(!block.metadata());
    // re-create section
    section = file.createSection("foo_section", "metadata");
}

void TestBlock::testSourceAccess() {
    vector<string> names = { "source_a", "source_b", "source_c", "source_d", "source_e" };
    Source s;
    CPPUNIT_ASSERT_THROW(block.hasSource(s), UninitializedEntity);
    CPPUNIT_ASSERT(block.sourceCount() == 0);
    CPPUNIT_ASSERT(block.sources().size() == 0);
    CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
    CPPUNIT_ASSERT(!block.hasSource("invalid_id"));

    vector<string> ids;
    for (const auto &name : names) {
        Source src = block.createSource(name, "channel");
        CPPUNIT_ASSERT(src.name() == name);
        CPPUNIT_ASSERT(block.hasSource(name));
        CPPUNIT_ASSERT(block.hasSource(src));

        ids.push_back(src.id());
    }
    CPPUNIT_ASSERT_THROW(block.createSource(names[0], "channel"),
                         DuplicateName);

    CPPUNIT_ASSERT(block.sourceCount() == names.size());
    CPPUNIT_ASSERT(block.sources().size() == names.size());

    for (const auto &id : ids) {
        Source src = block.getSource(id);
        CPPUNIT_ASSERT(block.hasSource(id) == true);
        CPPUNIT_ASSERT(src.id() == id);
        block.deleteSource(id);
    }

    s = block.createSource("test", "test");
    CPPUNIT_ASSERT(block.sourceCount() == 1);
    CPPUNIT_ASSERT_NO_THROW(block.deleteSource(s));

    CPPUNIT_ASSERT(block.sourceCount() == 0);
    CPPUNIT_ASSERT(block.sources().size() == 0);
    CPPUNIT_ASSERT(block.getSource("invalid_id") == false);
}

void TestBlock::testDataArrayAccess() {
    vector<string> names = { "data_array_a", "data_array_b", "data_array_c",
                             "data_array_d", "data_array_e" };
    DataArray data_array, a;

    CPPUNIT_ASSERT(block.dataArrayCount() == 0);
    CPPUNIT_ASSERT(block.dataArrays().size() == 0);
    CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);

    vector<string> ids;
    for (const auto &name : names) {
        data_array = block.createDataArray(name, "channel",
                                           DataType::Double, nix::NDSize({ 0 }));
        CPPUNIT_ASSERT(data_array.name() == name);
        CPPUNIT_ASSERT(data_array.type() == "channel");

        ids.push_back(data_array.id());
    }
    CPPUNIT_ASSERT_THROW(block.createDataArray(names[0], "channel", DataType::Double, nix::NDSize({ 0 })),
                         DuplicateName);
    CPPUNIT_ASSERT(block.hasDataArray(data_array));
    CPPUNIT_ASSERT_THROW(block.hasDataArray(a), UninitializedEntity);
    CPPUNIT_ASSERT(block.dataArrayCount() == names.size());
    CPPUNIT_ASSERT(block.dataArrays().size() == names.size());

    for (const auto &name : names) {
        DataArray da_name = block.getDataArray(name);
        CPPUNIT_ASSERT(da_name);

        DataArray da_id = block.getDataArray(da_name.id());
        CPPUNIT_ASSERT(da_id);
        CPPUNIT_ASSERT_EQUAL(da_name.name(), da_id.name());
    }

    vector<DataArray> filteredArrays = block.dataArrays(util::TypeFilter<DataArray>("channel"));
    CPPUNIT_ASSERT_EQUAL(names.size(), filteredArrays.size());

    filteredArrays = block.dataArrays(util::NameFilter<DataArray>("data_array_c"));
    CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), filteredArrays.size());
    if (filteredArrays.size() > 0) {
        boost::optional<std::string> name = filteredArrays[0].name();
        CPPUNIT_ASSERT(name && *name == "data_array_c");
    }

    for (auto it = ids.begin(); it != ids.end(); it++) {
        DataArray data_array = block.getDataArray(*it);
        CPPUNIT_ASSERT(block.hasDataArray(*it) == true);
        CPPUNIT_ASSERT(data_array.id() == *it);

        block.deleteDataArray(*it);
    }
    CPPUNIT_ASSERT_THROW(block.deleteDataArray(a), UninitializedEntity);
    CPPUNIT_ASSERT(block.dataArrayCount() == 0);
    CPPUNIT_ASSERT(block.dataArrays().size() == 0);
    CPPUNIT_ASSERT(block.getDataArray("invalid_id") == false);

}

void TestBlock::testTagAccess() {
    vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
    vector<string> array_names = { "data_array_a", "data_array_b", "data_array_c",
                                   "data_array_d", "data_array_e" };
    vector<DataArray> refs;
    Tag tag, t;
    for (const auto &name : array_names) {
        refs.push_back(block.createDataArray(name,
                                             "reference",
                                             DataType::Double,
                                             nix::NDSize({ 0 })));
    }

    CPPUNIT_ASSERT(block.tagCount() == 0);
    CPPUNIT_ASSERT(block.tags().size() == 0);
    CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
    CPPUNIT_ASSERT_THROW(block.hasTag(t), UninitializedEntity);

    vector<string> ids;
    for (auto it = names.begin(); it != names.end(); ++it) {
        tag = block.createTag(*it, "segment", {0.0, 2.0, 3.4});
        tag.references(refs);
        CPPUNIT_ASSERT(tag.name() == *it);
        CPPUNIT_ASSERT(block.hasTag(tag));
        ids.push_back(tag.id());
    }
    CPPUNIT_ASSERT_THROW(block.createTag(names[0], "segment", {0.0, 2.0, 3.4}),
                         DuplicateName);

    CPPUNIT_ASSERT(block.tagCount() == names.size());
    CPPUNIT_ASSERT(block.tags().size() == names.size());

    for (auto it = ids.begin(); it != ids.end(); ++it) {
        tag = block.getTag(*it);
        CPPUNIT_ASSERT(block.hasTag(*it) == true);
        CPPUNIT_ASSERT(tag.id() == *it);

        block.deleteTag(*it);
    }

    tag = block.createTag("test", "test", {0.0});
    CPPUNIT_ASSERT(block.hasTag(tag));
    CPPUNIT_ASSERT_NO_THROW(block.deleteTag(tag));
    CPPUNIT_ASSERT_THROW(block.deleteTag(t), UninitializedEntity);

    CPPUNIT_ASSERT(block.tagCount() == 0);
    CPPUNIT_ASSERT(block.tags().size() == 0);
    CPPUNIT_ASSERT(block.getTag("invalid_id") == false);
}

void TestBlock::testMultiTagAccess() {
    vector<string> names = { "tag_a", "tag_b", "tag_c", "tag_d", "tag_e" };
    MultiTag mtag, m;
    // create a valid positions data array below
    typedef boost::multi_array<double, 3>::index index;
    DataArray positions = block.createDataArray("array_one",
                                                "testdata",
                                                DataType::Double,
                                                nix::NDSize({ 3, 4, 2 }));
    boost::multi_array<double, 3> A(boost::extents[3][4][2]);
    int values = 0;
    for(index i = 0; i != 3; ++i)
        for(index j = 0; j != 4; ++j)
            for(index k = 0; k != 2; ++k)
                A[i][j][k] = values++;

    positions.setData(A);

    CPPUNIT_ASSERT(block.multiTagCount() == 0);
    CPPUNIT_ASSERT(block.multiTags().size() == 0);
    CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
    CPPUNIT_ASSERT_THROW(block.hasMultiTag(m), UninitializedEntity);
    vector<string> ids;
    for (auto it = names.begin(); it != names.end(); it++) {
        mtag = block.createMultiTag(*it, "segment", positions);
        CPPUNIT_ASSERT(mtag.name() == *it);
        CPPUNIT_ASSERT(block.hasMultiTag(mtag));
        ids.push_back(mtag.id());
    }
    CPPUNIT_ASSERT_THROW(block.createMultiTag(names[0], "segment", positions),
                         DuplicateName);

    CPPUNIT_ASSERT(block.multiTagCount() == names.size());
    CPPUNIT_ASSERT(block.multiTags().size() == names.size());

    for (auto it = ids.begin(); it != ids.end(); it++) {
        mtag = block.getMultiTag(*it);
        CPPUNIT_ASSERT(block.hasMultiTag(*it) == true);
        CPPUNIT_ASSERT(mtag.id() == *it);

        block.deleteMultiTag(*it);
    }
    mtag = block.createMultiTag("test", "test", positions);
    CPPUNIT_ASSERT(block.hasMultiTag(mtag));
    CPPUNIT_ASSERT_THROW(block.deleteMultiTag(m), UninitializedEntity);
    CPPUNIT_ASSERT_NO_THROW(block.deleteMultiTag(mtag));
    CPPUNIT_ASSERT(block.multiTagCount() == 0);
    CPPUNIT_ASSERT(block.multiTags().size() == 0);
    CPPUNIT_ASSERT(block.getMultiTag("invalid_id") == false);
}

void TestBlock::testOperators() {
    CPPUNIT_ASSERT(block_null == false);
    CPPUNIT_ASSERT(block_null == none);

    CPPUNIT_ASSERT(block != false);
    CPPUNIT_ASSERT(block != none);

    CPPUNIT_ASSERT(block == block);
    CPPUNIT_ASSERT(block != block_other);

    block_other = block;
    CPPUNIT_ASSERT(block == block_other);

    block_other = none;
    CPPUNIT_ASSERT(block_null == false);
    CPPUNIT_ASSERT(block_null == none);
}

void TestBlock::testCreatedAt() {
    CPPUNIT_ASSERT(block.createdAt() >= startup_time);
    time_t past_time = time(NULL) - 10000000;
    block.forceCreatedAt(past_time);
    CPPUNIT_ASSERT(block.createdAt() == past_time);
}

void TestBlock::testUpdatedAt() {
    CPPUNIT_ASSERT(block.updatedAt() >= startup_time);
}

void TestBlock::testCompare() {
    string other_name = block_other.name();
    string block_name = block.name();

    CPPUNIT_ASSERT(block.compare(block) == 0);
    CPPUNIT_ASSERT(block.compare(block_other) ==  block_name.compare(other_name));
}
<|endoftext|>


<commit_before>// Qubit teleporation circuit simulator
// Source: ./examples/circuits/noisy_teleport_qubit_circuit.cpp
#include <iostream>

#include "qpp.h"

int main() {
    using namespace qpp;
    std::cout << ">> Qubit noisy teleportation quantum circuit simulation\n\n";

    // quantum circuit with 3 qubits and 2 classical bits
    QCircuit qc{3, 2};
    // set the qubit 0 to a random state
    cmat U = randU(2);
    // apply the gate U with name randU to qubit 0
    qc.gate(U, 0, "randU");

    // set the MES between qubits 1 and 2
    qc.gate(gt.H, 1);
    qc.CTRL(gt.X, 1, 2);

    // perform the Bell measurement between qubits 0 and 1
    qc.CTRL(gt.X, 0, 1);
    qc.gate(gt.H, 0);
    qc.measureZ(0, 0);
    qc.measureZ(1, 1);

    // apply the classical controls
    qc.cCTRL(gt.X, 1, 2);
    qc.cCTRL(gt.Z, 0, 2);

    // initialize the noisy quantum engine with an amplitude damping noise model
    // and a quantum circuit; in C++17 you can make use of the class template
    // argument deduction rules to simply write
    // QNoisyEngine qNoisyEngine{qc, QubitAmplitudeDampingNoise{0.99}};
    QNoisyEngine<QubitAmplitudeDampingNoise> qNoisyEngine{
        qc, QubitAmplitudeDampingNoise{0.99}};

    // display the quantum circuit
    std::cout << ">> BEGIN CIRCUIT\n";
    std::cout << qNoisyEngine.get_circuit() << '\n';
    std::cout << ">> END CIRCUIT\n\n";

    // execute the circuit
    for (auto&& step : qc)
        qNoisyEngine.execute(step);

    // display the measurement statistics
    std::cout << ">> BEGIN AFTER RUNNING\n";
    std::cout << qNoisyEngine << '\n';
    std::cout << ">> END AFTER RUNNING\n\n";

    // verify how successful the teleportation was
    ket psi_initial = U * 0_ket;
    ket psi_final = qNoisyEngine.get_psi();
    std::cout << ">> Initial state:\n";
    std::cout << disp(psi_initial) << '\n';
    std::cout << ">> Teleported state:\n";
    std::cout << disp(psi_final) << '\n';
    std::cout << ">> Norm difference: " << norm(psi_final - psi_initial)
              << '\n';
}
<commit_msg>commit<commit_after>// Qubit teleporation circuit simulator
// Source: ./examples/circuits/noisy_teleport_qubit_circuit.cpp
#include <iostream>

#include "qpp.h"

int main() {
    using namespace qpp;
    std::cout << ">> Qubit noisy teleportation quantum circuit simulation\n\n";

    // quantum circuit with 3 qubits and 2 classical bits
    QCircuit qc{3, 2};
    // set the qubit 0 to a random state
    cmat U = randU(2);
    // apply the gate U with name randU to qubit 0
    qc.gate(U, 0, "randU");

    // set the MES between qubits 1 and 2
    qc.gate(gt.H, 1);
    qc.CTRL(gt.X, 1, 2);

    // perform the Bell measurement between qubits 0 and 1
    qc.CTRL(gt.X, 0, 1);
    qc.gate(gt.H, 0);
    qc.measureZ(0, 0);
    qc.measureZ(1, 1);

    // apply the classical controls
    qc.cCTRL(gt.X, 1, 2);
    qc.cCTRL(gt.Z, 0, 2);

    // initialize the noisy quantum engine with an amplitude damping noise model
    // and a quantum circuit; in C++17 you can make use of the class template
    // argument deduction rules to simply write
    // QNoisyEngine noisy_engine{qc, QubitAmplitudeDampingNoise{0.99}};
    QNoisyEngine<QubitAmplitudeDampingNoise> noisy_engine{
        qc, QubitAmplitudeDampingNoise{0.99}};

    // display the quantum circuit
    std::cout << ">> BEGIN CIRCUIT\n";
    std::cout << noisy_engine.get_circuit() << '\n';
    std::cout << ">> END CIRCUIT\n\n";

    // execute the circuit
    for (auto&& step : qc)
        noisy_engine.execute(step);

    // display the measurement statistics
    std::cout << ">> BEGIN AFTER RUNNING\n";
    std::cout << noisy_engine << '\n';
    std::cout << ">> END AFTER RUNNING\n\n";

    // verify how successful the teleportation was
    ket psi_initial = U * 0_ket;
    ket psi_final = noisy_engine.get_psi();
    std::cout << ">> Initial state:\n";
    std::cout << disp(psi_initial) << '\n';
    std::cout << ">> Teleported state:\n";
    std::cout << disp(psi_final) << '\n';
    std::cout << ">> Norm difference: " << norm(psi_final - psi_initial)
              << '\n';
}
<|endoftext|>


<commit_before>#include "commands.h"

#include "Workspace.h"
#include <busyUtils/busyUtils.h>
#include <iostream>

using namespace busy;

namespace commands {

void cleanAll() {
	utils::rm("./build", true);
	utils::mkdir("./build");

	//!TODO reset lastCompileTime

	auto dirs = utils::listDirs(".busy", true);
	for (auto d : dirs) {
		utils::rm(".busy/" + d, true);
	}

	auto files = utils::listFiles(".busy", false);
	for (auto f : files) {
		if (f != "workspace.bin") {
			utils::rm(".busy/" + f, false);
		}
	}
	std::cout << "clean all done" << std::endl;

}

}
<commit_msg>cleanall now cleans all<commit_after>#include "commands.h"

#include "Workspace.h"
#include <busyUtils/busyUtils.h>
#include <iostream>

using namespace busy;

namespace commands {

void cleanAll() {
	utils::rm("./build", true);
	utils::mkdir("./build");
	utils::rm(".busy", true, true);
	std::cout << "clean all done" << std::endl;

}

}
<|endoftext|>


<commit_before>#include "Application.h"
#include "MainMenuScene.h"
#include "SceneManager.h"

LRESULT WINAPI fakeWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    Application* app = reinterpret_cast<Application*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
    if (app != nullptr)
    {
        return app->WindowProc(hWnd, Msg, wParam, lParam);
    }
    else
    {
        return DefWindowProc(hWnd, Msg, wParam, lParam);
    }
}

Application::Application()
    :_renderer(), _handle()
{
}

Application::~Application()
{
}

int Application::run(HINSTANCE hInstance, const int& nCmdShow)
{
    WNDCLASSEX wc = {0};
    wc.cbSize = sizeof(wc);
    wc.lpszClassName = "WND";
    wc.hInstance = hInstance;
    wc.lpfnWndProc = fakeWindowProc;
    wc.hCursor = LoadCursor(hInstance, IDC_ARROW);

    int ret = RegisterClassEx(&wc);

    RECT wndRect;
    wndRect.right = 500;
    wndRect.bottom = 500;
    BOOL b = AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, FALSE);
    assert(b);

    _handle = CreateWindowEx(0, "WND", "15 PUZZLE", WS_OVERLAPPEDWINDOW, 0, 0, wndRect.right, wndRect.bottom, nullptr, nullptr, hInstance, nullptr);

    _renderer.init(_handle, 500, 500);

    SceneManager::getSingleton().setActiveScene(new MainMenuScene(&_renderer));

    ShowWindow(_handle, nCmdShow);

    MSG msg = {0};
    size_t frameCounter = 0;

    SetWindowLongPtr(_handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));

    while(true)
    {
        if (PeekMessage(&msg, _handle, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            if (msg.message == WM_QUIT)
            {
                break;
            }
        }
        else
        {
            SceneManager& sceneMgr = SceneManager::getSingleton();
            sceneMgr.update();

            if (frameCounter == 10)
            {
                sceneMgr.getActiveScene()->update();
                frameCounter = 0;
            }
            sceneMgr.getActiveScene()->render();
            ++frameCounter;
        }
    }

    ret = UnregisterClass("WND", hInstance);

    return 0;
}

LRESULT WINAPI Application::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    switch(Msg)
    {
    case WM_SIZE:
        {
            uint32_t width = LOWORD(lParam);
            uint32_t height = HIWORD(lParam);
            _renderer.resize(width, height);
        }
        return 0;

    default:
        return DefWindowProc(hWnd, Msg, wParam, lParam);
    }
}

void Application::Shutdown()
{
    PostQuitMessage(0);
}<commit_msg>In case using close window button(X) application continue working in background mode<commit_after>#include "Application.h"
#include "MainMenuScene.h"
#include "SceneManager.h"

LRESULT WINAPI fakeWindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    Application* app = reinterpret_cast<Application*>(GetWindowLongPtr(hWnd, GWLP_USERDATA));
    if (app != nullptr)
    {
        return app->WindowProc(hWnd, Msg, wParam, lParam);
    }
    else
    {
        return DefWindowProc(hWnd, Msg, wParam, lParam);
    }
}

Application::Application()
    :_renderer(), _handle()
{
}

Application::~Application()
{
}

int Application::run(HINSTANCE hInstance, const int& nCmdShow)
{
    WNDCLASSEX wc = {0};
    wc.cbSize = sizeof(wc);
    wc.lpszClassName = "WND";
    wc.hInstance = hInstance;
    wc.lpfnWndProc = fakeWindowProc;
    wc.hCursor = LoadCursor(hInstance, IDC_ARROW);

    int ret = RegisterClassEx(&wc);

    RECT wndRect;
    wndRect.right = 500;
    wndRect.bottom = 500;
    BOOL b = AdjustWindowRect(&wndRect, WS_OVERLAPPEDWINDOW, FALSE);
    assert(b);

    _handle = CreateWindowEx(0, "WND", "15 PUZZLE", WS_OVERLAPPEDWINDOW, 0, 0, wndRect.right, wndRect.bottom, nullptr, nullptr, hInstance, nullptr);

    _renderer.init(_handle, 500, 500);

    SceneManager::getSingleton().setActiveScene(new MainMenuScene(&_renderer));

    ShowWindow(_handle, nCmdShow);

    MSG msg = {0};
    size_t frameCounter = 0;

    SetWindowLongPtr(_handle, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));

    while(true)
    {
        if (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            if (msg.message == WM_QUIT)
            {
                break;
            }
        }
        else
        {
            SceneManager& sceneMgr = SceneManager::getSingleton();
            sceneMgr.update();

            if (frameCounter == 10)
            {
                sceneMgr.getActiveScene()->update();
                frameCounter = 0;
            }
            sceneMgr.getActiveScene()->render();
            ++frameCounter;
        }
    }

    ret = UnregisterClass("WND", hInstance);

    return 0;
}

LRESULT WINAPI Application::WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
    switch(Msg)
    {
    case WM_SIZE:
        {
            uint32_t width = LOWORD(lParam);
            uint32_t height = HIWORD(lParam);
            _renderer.resize(width, height);
        }
        return 0L;

    case WM_DESTROY:
        {
            PostQuitMessage(0);
        }
        return 0L;

    default:
        return DefWindowProc(hWnd, Msg, wParam, lParam);
    }
}

void Application::Shutdown()
{
    PostQuitMessage(0);
}
<|endoftext|>