<commit_before>/*
    This file is part of Akregator.

    Copyright (C) 2005 Frank Osterfeld <frank.osterfeld@kdemail.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "dragobjects.h"
#include "feed.h"

#include <q3cstring.h>
//Added by qt3to4:
#include <QList>

namespace Akregator {

class Article;

ArticleDrag::ArticleDrag(const QList<Article>& articles, QWidget* dragSource, const char* name)
: K3URLDrag(articleURLs(articles), dragSource), m_items(articlesToDragItems(articles))
{
    setObjectName(name);
}

bool ArticleDrag::canDecode(const QMimeSource* e)
{
    return e->provides("akregator/articles");
}

bool ArticleDrag::decode(const QMimeSource* e, QList<ArticleDragItem>& articles)
{
    articles.clear();
    QByteArray array = e->encodedData("akregator/articles");

    QDataStream stream( &array,QIODevice::ReadOnly);
    stream.setVersion(QDataStream::Qt_3_1);

    while (!stream.atEnd())
    {
        ArticleDragItem i;
        stream >> i.feedURL;
        stream >> i.guid;
        articles.append(i);
    }

    return true;
}

const char* ArticleDrag::format(int i) const
{
    if (i == 0)
        return "text/uri-list";
    else if (i == 1)
        return "akregator/articles";

    return 0;
}

QByteArray ArticleDrag::encodedData(const char* mime) const
{
    Q3CString mimetype(mime);
    if (mimetype == "akregator/articles")
    {
        QByteArray ba;
        QDataStream stream( &ba,QIODevice::WriteOnly);
        stream.setVersion(QDataStream::Qt_3_1);

        QList<ArticleDragItem>::ConstIterator end = m_items.end();
        for (QList<ArticleDragItem>::ConstIterator it = m_items.begin(); it != end; ++it)
        {
            stream << (*it).feedURL;
            stream << (*it).guid;
        }
        return ba;
    }
    else
    {
        return K3URLDrag::encodedData(mime);
    }
}

QList<ArticleDragItem> ArticleDrag::articlesToDragItems(const QList<Article>& articles)
{
    QList<ArticleDragItem> items;

    QList<Article>::ConstIterator end(articles.end());

    for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
    {
        ArticleDragItem i;
        i.feedURL = (*it).feed() ? (*it).feed()->xmlUrl() : "";
        i.guid = (*it).guid();
        items.append(i);
    }

    return items;
}

KURL::List ArticleDrag::articleURLs(const QList<Article>& articles)
{
    KURL::List urls;
    QList<Article>::ConstIterator end(articles.end());
    for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
        urls.append((*it).link());
    return urls;
}

} // namespace Akregator
<commit_msg>Q3CString--<commit_after>/*
    This file is part of Akregator.

    Copyright (C) 2005 Frank Osterfeld <frank.osterfeld@kdemail.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include "dragobjects.h"
#include "feed.h"

#include <q3cstring.h>
//Added by qt3to4:
#include <QList>

namespace Akregator {

class Article;

ArticleDrag::ArticleDrag(const QList<Article>& articles, QWidget* dragSource, const char* name)
: K3URLDrag(articleURLs(articles), dragSource), m_items(articlesToDragItems(articles))
{
    setObjectName(name);
}

bool ArticleDrag::canDecode(const QMimeSource* e)
{
    return e->provides("akregator/articles");
}

bool ArticleDrag::decode(const QMimeSource* e, QList<ArticleDragItem>& articles)
{
    articles.clear();
    QByteArray array = e->encodedData("akregator/articles");

    QDataStream stream( &array,QIODevice::ReadOnly);
    stream.setVersion(QDataStream::Qt_3_1);

    while (!stream.atEnd())
    {
        ArticleDragItem i;
        stream >> i.feedURL;
        stream >> i.guid;
        articles.append(i);
    }

    return true;
}

const char* ArticleDrag::format(int i) const
{
    if (i == 0)
        return "text/uri-list";
    else if (i == 1)
        return "akregator/articles";

    return 0;
}

QByteArray ArticleDrag::encodedData(const char* mime) const
{
    QByteArray mimetype(mime);
    if (mimetype == "akregator/articles")
    {
        QByteArray ba;
        QDataStream stream( &ba,QIODevice::WriteOnly);
        stream.setVersion(QDataStream::Qt_3_1);

        QList<ArticleDragItem>::ConstIterator end = m_items.end();
        for (QList<ArticleDragItem>::ConstIterator it = m_items.begin(); it != end; ++it)
        {
            stream << (*it).feedURL;
            stream << (*it).guid;
        }
        return ba;
    }
    else
    {
        return K3URLDrag::encodedData(mime);
    }
}

QList<ArticleDragItem> ArticleDrag::articlesToDragItems(const QList<Article>& articles)
{
    QList<ArticleDragItem> items;

    QList<Article>::ConstIterator end(articles.end());

    for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
    {
        ArticleDragItem i;
        i.feedURL = (*it).feed() ? (*it).feed()->xmlUrl() : "";
        i.guid = (*it).guid();
        items.append(i);
    }

    return items;
}

KURL::List ArticleDrag::articleURLs(const QList<Article>& articles)
{
    KURL::List urls;
    QList<Article>::ConstIterator end(articles.end());
    for (QList<Article>::ConstIterator it = articles.begin(); it != end; ++it)
        urls.append((*it).link());
    return urls;
}

} // namespace Akregator
<|endoftext|>


<commit_before><commit_msg>Base: Active RenderContext in Surface extraction to be able to download GL representations (closes #348)<commit_after><|endoftext|>


<commit_before>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

//
// bench.cpp : spdlog benchmarks
//
#include "spdlog/spdlog.h"
#include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/null_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"

#include "utils.h"
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <memory>
#include <string>
#include <thread>

using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;

void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);

int main(int argc, char *argv[])
{

    spdlog::default_logger()->set_pattern("[%^%l%$] %v");
    int howmany = 1000000;
    int queue_size = howmany + 2;
    int threads = 10;
    size_t file_size = 30 * 1024 * 1024;
    size_t rotating_files = 5;

    try
    {

        if (argc > 1)
            howmany = atoi(argv[1]);
        if (argc > 2)
            threads = atoi(argv[2]);
        if (argc > 3)
            queue_size = atoi(argv[3]);

        spdlog::info("**************************************************************");
        spdlog::info("Single thread, {:n} iterations", howmany);
        spdlog::info("**************************************************************");

        auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
        bench(howmany, std::move(basic_st));

        basic_st.reset();
        auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
        bench(howmany, std::move(rotating_st));

        auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
        bench(howmany, std::move(daily_st));

        bench(howmany, spdlog::create<null_sink_st>("null_st"));

        spdlog::info("**************************************************************");
        spdlog::info("Default API. Single thread, {:n} iterations", howmany);
        spdlog::info("**************************************************************");

        basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
        bench_default_api(howmany, std::move(basic_st));

        rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
        bench_default_api(howmany, std::move(rotating_st));

        daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
        bench_default_api(howmany, std::move(daily_st));

        bench_default_api(howmany, spdlog::create<null_sink_st>("null_st"));

        spdlog::info("**************************************************************");
        spdlog::info("C-string. Single thread, {:n} iterations", howmany);
        spdlog::info("**************************************************************");

        basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_cs.log", true);
        bench_c_string(howmany, std::move(basic_st));

        rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_cs.log", file_size, rotating_files);
        bench_c_string(howmany, std::move(rotating_st));

        daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_cs.log");
        bench_c_string(howmany, std::move(daily_st));

        bench_c_string(howmany, spdlog::create<null_sink_st>("null_st"));

        spdlog::info("**************************************************************");
        spdlog::info("{:n} threads sharing same logger, {:n} iterations", threads, howmany);
        spdlog::info("**************************************************************");

        auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
        bench_mt(howmany, std::move(basic_mt), threads);

        auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files);
        bench_mt(howmany, std::move(rotating_mt), threads);

        auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
        bench_mt(howmany, std::move(daily_mt), threads);
        bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads);

        spdlog::info("**************************************************************");
        spdlog::info("Asyncronous.. {:n} threads sharing same logger, {:n} iterations", threads, howmany);
        spdlog::info("**************************************************************");

        for (int i = 0; i < 3; ++i)
        {
            spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
            auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
            bench_mt(howmany, std::move(as), threads);
        }
    }
    catch (std::exception &ex)
    {
        spdlog::error(ex.what());
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
    using std::chrono::high_resolution_clock;
    auto start = high_resolution_clock::now();
    for (auto i = 0; i < howmany; ++i)
    {
        log->info("Hello logger: msg number {}", i);
    }

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();

    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
    spdlog::drop(log->name());
}

void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
    using std::chrono::high_resolution_clock;
    vector<thread> threads;
    auto start = high_resolution_clock::now();
    for (int t = 0; t < thread_count; ++t)
    {
        threads.push_back(std::thread([&]() {
            for (int j = 0; j < howmany / thread_count; j++)
            {
                log->info("Hello logger: msg number {}", j);
            }
        }));
    }

    for (auto &t : threads)
    {
        t.join();
    };

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();
    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
    spdlog::drop(log->name());
}

void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
{
    using std::chrono::high_resolution_clock;
    auto orig_default = spdlog::default_logger();
    spdlog::set_default_logger(log);
    auto start = high_resolution_clock::now();
    for (auto i = 0; i < howmany; ++i)
    {
        spdlog::info("Hello logger: msg number {}", i);
    }

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();
    spdlog::drop(log->name());
    spdlog::set_default_logger(std::move(orig_default));
    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}

void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
{
    const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
                      "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem "
                      "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed "
                      "augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare "
                      "nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";
    using std::chrono::high_resolution_clock;
    auto orig_default = spdlog::default_logger();
    spdlog::set_default_logger(log);
    auto start = high_resolution_clock::now();
    for (auto i = 0; i < howmany; ++i)
    {
        spdlog::log(level::info, msg);
    }

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();
    spdlog::drop(log->name());
    spdlog::set_default_logger(std::move(orig_default));
    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}
<commit_msg>bench C-string title<commit_after>//
// Copyright(c) 2015 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//

//
// bench.cpp : spdlog benchmarks
//
#include "spdlog/spdlog.h"
#include "spdlog/async.h"
#include "spdlog/sinks/basic_file_sink.h"
#include "spdlog/sinks/daily_file_sink.h"
#include "spdlog/sinks/null_sink.h"
#include "spdlog/sinks/rotating_file_sink.h"

#include "utils.h"
#include <atomic>
#include <cstdlib> // EXIT_FAILURE
#include <memory>
#include <string>
#include <thread>

using namespace std;
using namespace std::chrono;
using namespace spdlog;
using namespace spdlog::sinks;
using namespace utils;

void bench(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count);
void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log);
void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log);

int main(int argc, char *argv[])
{

    spdlog::default_logger()->set_pattern("[%^%l%$] %v");
    int howmany = 1000000;
    int queue_size = howmany + 2;
    int threads = 10;
    size_t file_size = 30 * 1024 * 1024;
    size_t rotating_files = 5;

    try
    {

        if (argc > 1)
            howmany = atoi(argv[1]);
        if (argc > 2)
            threads = atoi(argv[2]);
        if (argc > 3)
            queue_size = atoi(argv[3]);

        spdlog::info("**************************************************************");
        spdlog::info("Single thread, {:n} iterations", howmany);
        spdlog::info("**************************************************************");

        auto basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
        bench(howmany, std::move(basic_st));

        basic_st.reset();
        auto rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
        bench(howmany, std::move(rotating_st));

        auto daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
        bench(howmany, std::move(daily_st));

        bench(howmany, spdlog::create<null_sink_st>("null_st"));

        spdlog::info("**************************************************************");
        spdlog::info("Default API. Single thread, {:n} iterations", howmany);
        spdlog::info("**************************************************************");

        basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_st.log", true);
        bench_default_api(howmany, std::move(basic_st));

        rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_st.log", file_size, rotating_files);
        bench_default_api(howmany, std::move(rotating_st));

        daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_st.log");
        bench_default_api(howmany, std::move(daily_st));

        bench_default_api(howmany, spdlog::create<null_sink_st>("null_st"));

        spdlog::info("**************************************************************");
        spdlog::info("C-string (500 bytes). Single thread, {:n} iterations", howmany);
        spdlog::info("**************************************************************");

        basic_st = spdlog::basic_logger_st("basic_st", "logs/basic_cs.log", true);
        bench_c_string(howmany, std::move(basic_st));

        rotating_st = spdlog::rotating_logger_st("rotating_st", "logs/rotating_cs.log", file_size, rotating_files);
        bench_c_string(howmany, std::move(rotating_st));

        daily_st = spdlog::daily_logger_st("daily_st", "logs/daily_cs.log");
        bench_c_string(howmany, std::move(daily_st));

        bench_c_string(howmany, spdlog::create<null_sink_st>("null_st"));

        spdlog::info("**************************************************************");
        spdlog::info("{:n} threads sharing same logger, {:n} iterations", threads, howmany);
        spdlog::info("**************************************************************");

        auto basic_mt = spdlog::basic_logger_mt("basic_mt", "logs/basic_mt.log", true);
        bench_mt(howmany, std::move(basic_mt), threads);

        auto rotating_mt = spdlog::rotating_logger_mt("rotating_mt", "logs/rotating_mt.log", file_size, rotating_files);
        bench_mt(howmany, std::move(rotating_mt), threads);

        auto daily_mt = spdlog::daily_logger_mt("daily_mt", "logs/daily_mt.log");
        bench_mt(howmany, std::move(daily_mt), threads);
        bench_mt(howmany, spdlog::create<null_sink_mt>("null_mt"), threads);

        spdlog::info("**************************************************************");
        spdlog::info("Asyncronous.. {:n} threads sharing same logger, {:n} iterations", threads, howmany);
        spdlog::info("**************************************************************");

        for (int i = 0; i < 3; ++i)
        {
            spdlog::init_thread_pool(static_cast<size_t>(queue_size), 1);
            auto as = spdlog::basic_logger_mt<spdlog::async_factory>("async", "logs/basic_async.log", true);
            bench_mt(howmany, std::move(as), threads);
        }
    }
    catch (std::exception &ex)
    {
        spdlog::error(ex.what());
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}

void bench(int howmany, std::shared_ptr<spdlog::logger> log)
{
    using std::chrono::high_resolution_clock;
    auto start = high_resolution_clock::now();
    for (auto i = 0; i < howmany; ++i)
    {
        log->info("Hello logger: msg number {}", i);
    }

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();

    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
    spdlog::drop(log->name());
}

void bench_mt(int howmany, std::shared_ptr<spdlog::logger> log, int thread_count)
{
    using std::chrono::high_resolution_clock;
    vector<thread> threads;
    auto start = high_resolution_clock::now();
    for (int t = 0; t < thread_count; ++t)
    {
        threads.push_back(std::thread([&]() {
            for (int j = 0; j < howmany / thread_count; j++)
            {
                log->info("Hello logger: msg number {}", j);
            }
        }));
    }

    for (auto &t : threads)
    {
        t.join();
    };

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();
    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
    spdlog::drop(log->name());
}

void bench_default_api(int howmany, std::shared_ptr<spdlog::logger> log)
{
    using std::chrono::high_resolution_clock;
    auto orig_default = spdlog::default_logger();
    spdlog::set_default_logger(log);
    auto start = high_resolution_clock::now();
    for (auto i = 0; i < howmany; ++i)
    {
        spdlog::info("Hello logger: msg number {}", i);
    }

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();
    spdlog::drop(log->name());
    spdlog::set_default_logger(std::move(orig_default));
    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}

void bench_c_string(int howmany, std::shared_ptr<spdlog::logger> log)
{
    const char *msg = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum pharetra metus cursus "
                      "lacus placerat congue. Nulla egestas, mauris a tincidunt tempus, enim lectus volutpat mi, eu consequat sem "
                      "libero nec massa. In dapibus ipsum a diam rhoncus gravida. Etiam non dapibus eros. Donec fringilla dui sed "
                      "augue pretium, nec scelerisque est maximus. Nullam convallis, sem nec blandit maximus, nisi turpis ornare "
                      "nisl, sit amet volutpat neque massa eu odio. Maecenas malesuada quam ex, posuere congue nibh turpis duis.";
    using std::chrono::high_resolution_clock;
    auto orig_default = spdlog::default_logger();
    spdlog::set_default_logger(log);
    auto start = high_resolution_clock::now();
    for (auto i = 0; i < howmany; ++i)
    {
        spdlog::log(level::info, msg);
    }

    auto delta = high_resolution_clock::now() - start;
    auto delta_d = duration_cast<duration<double>>(delta).count();
    spdlog::drop(log->name());
    spdlog::set_default_logger(std::move(orig_default));
    spdlog::info("{:<16} Elapsed: {:0.2f} secs {:>16n}/sec", log->name(), delta_d, int(howmany / delta_d));
}
<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ----------------------------------------------------------------------
 */

/** @file
 * Definitions for the Spatial Pooler
 */

#ifndef NTA_spatial_pooler_HPP
#define NTA_spatial_pooler_HPP

#include <cstring>
#include <iostream>
#include <nta/math/SparseBinaryMatrix.hpp>
#include <nta/math/SparseMatrix.hpp>
#include <nta/types/types.hpp>
#include <string>
#include <vector>

using namespace std;

namespace nta {
  namespace algorithms {
    namespace spatial_pooler {

      /////////////////////////////////////////////////////////////////////////
      /// CLA spatial pooler implementation in C++.
      ///
      /// @b Responsibility
      /// The Spatial Pooler is responsible for creating a sparse distributed
      /// representation of the input. It computes the set of active columns.
      /// It maintains the state of the proximal dendrites between the columns
      /// and the inputs bits and keeps track of the activity and overlap
      /// duty cycles
      ///
      /// @b Description
      /// Todo.
      ///
      /////////////////////////////////////////////////////////////////////////
      class SpatialPooler {
        public:
          SpatialPooler();

          ~SpatialPooler() {}

          virtual UInt version() const {
            return version_;
          };

          virtual void compute(UInt inputVector[], bool learn,
                               UInt activeVector[]);

          virtual void save(ostream& outStream);
          virtual void load(istream& inStream);

          virtual UInt persistentSize();

          UInt getNumColumns();
          UInt getNumInputs();

          UInt getPotentialRadius();
          void setPotentialRadius(UInt potentialRadius);

          Real getPotentialPct();
          void setPotentialPct(Real potentialPct);

          bool getGlobalInhibition();
          void setGlobalInhibition(bool globalInhibition);

          Int getNumActiveColumnsPerInhArea();
          void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea);

          Real getLocalAreaDensity();
          void setLocalAreaDensity(Real localAreaDensity);

          UInt getStimulusThreshold();
          void setStimulusThreshold(UInt stimulusThreshold);

          UInt getInhibitionRadius();
          void setInhibitionRadius(UInt inhibitionRadius);

          UInt getDutyCyclePeriod();
          void setDutyCyclePeriod(UInt dutyCyclePeriod);

          Real getMaxBoost();
          void setMaxBoost(Real maxBoost);

          UInt getIterationNum();
          void setIterationNum(UInt iterationNum);

          UInt getIterationLearnNum();
          void setIterationLearnNum(UInt iterationLearnNum);

          UInt getSpVerbosity();
          void setSpVerbosity(UInt spVerbosity);

          UInt getUpdatePeriod();
          void setUpdatePeriod(UInt updatePeriod);

          Real getSynPermTrimThreshold();
          void setSynPermTrimThreshold(Real synPermTrimThreshold);

          Real getSynPermActiveInc();
          void setSynPermActiveInc(Real synPermActiveInc);

          Real getSynPermInactiveDec();
          void setSynPermInactiveDec(Real synPermInactiveDec);

          Real getSynPermBelowStimulusInc();
          void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc);

          Real getSynPermConnected();
          void setSynPermConnected(Real setSynPermConnected);

          Real getMinPctOverlapDutyCycles();
          void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles);

          Real getMinPctActiveDutyCycles();
          void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles);

          void getBoostFactors(Real boostFactors[]);
          void setBoostFactors(Real boostFactors[]);

          void getOverlapDutyCycles(Real overlapDutyCycles[]);
          void setOverlapDutyCycles(Real overlapDutyCycles[]);

          void getActiveDutyCycles(Real activeDutyCycles[]);
          void setActiveDutyCycles(Real activeDutyCycles[]);

          void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]);
          void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]);

          void getMinActiveDutyCycles(Real minActiveDutyCycles[]);
          void setMinActiveDutyCycles(Real minActiveDutyCycles[]);

          void getPotential(UInt column, UInt potential[]);
          void setPotential(UInt column, UInt potential[]);

          void getPermanence(UInt column, Real permanence[]);
          void setPermanence(UInt column, Real permanence[]);

          void getConnectedSynapses(UInt column, UInt connectedSynapses[]);

          void getConnectedCounts(UInt connectedCounts[]);

          // Implementation methods. all methods below this line are
          // NOT part of the public API

          void stripNeverLearned_(UInt activeArray[]);

          void toDense_(vector<UInt>& sparse,
                        UInt dense[],
                        UInt n);

          void boostOverlaps_(vector<UInt>& overlaps,
                              vector<Real>& boostedOverlaps);
          void range_(Int start, Int end, UInt ubound, bool wrapAround,
                      vector<UInt>& rangeVector);

          vector<UInt> mapPotential1D_(UInt column, bool wrapAround);
          Real initPermConnected_();
          Real initPermNonConnected_();
          vector<Real> initPermanence_(vector<UInt>& potential,
                                       Real connectedPct);
          void clip_(vector<Real>& perm, bool trim);
          void updatePermanencesForColumn_(vector<Real>& perm, UInt column,
                                           bool raisePerm=true);
          UInt countConnected_(vector<Real>& perm);
          UInt raisePermanencesToThreshold_(vector<Real>& perm,
                                            vector<UInt>& potential);

          void calculateOverlap_(UInt inputVector[],
                                 vector<UInt>& overlap);
          void calculateOverlapPct_(vector<UInt>& overlaps,
                                    vector<Real>& overlapPct);

          bool isWinner_(Real score, vector<pair<UInt, Real> >& winners,
                         UInt numWinners);

          void addToWinners_(UInt index, Real score,
                             vector<pair<UInt, Real> >& winners);

          void inhibitColumns_(vector<Real>& overlaps,
                               vector<UInt>& activeColumns);
          void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density,
                                     vector<UInt>& activeColumns);
          void inhibitColumnsLocal_(vector<Real>& overlaps, Real density,
                                    vector<UInt>& activeColumns);

          void getNeighbors1D_(UInt column, vector<UInt>& dimensions,
                               UInt radius, bool wrapAround,
                               vector<UInt>& neighbors);
          void getNeighbors2D_(UInt column, vector<UInt>& dimensions,
                               UInt radius, bool wrapAround,
                               vector<UInt>& neighbors);
          void cartesianProduct_(vector<vector<UInt> >& vecs,
                                 vector<vector<UInt> >& product);

          void getNeighborsND_(UInt column, vector<UInt>& dimensions,
                               UInt radius, bool wrapAround,
                               vector<UInt>& neighbors);

          void adaptSynapses_(UInt inputVector[],
                              vector<UInt>& activeColumns);
          void bumpUpWeakColumns_();

          void updateInhibitionRadius_();
          Real avgColumnsPerInput_();
          Real avgConnectedSpanForColumn1D_(UInt column);
          Real avgConnectedSpanForColumn2D_(UInt column);
          Real avgConnectedSpanForColumnND_(UInt column);
          void updateMinDutyCycles_();
          void updateMinDutyCyclesGlobal_();
          void updateMinDutyCyclesLocal_();
          static  void updateDutyCyclesHelper_(vector<Real>& dutyCycles,
                                               vector<UInt>& newValues,
                                               UInt period);
          void updateDutyCycles_(vector<UInt>& overlaps,
                                 UInt activeArray[]);
          void updateBoostFactors_();
          void updateBookeepingVars_(bool learn);

          bool isUpdateRound_();

          virtual void initialize(vector<UInt> inputDimensions,
                                  vector<UInt> columnDimensions,
                                  UInt potentialRadius=16,
                                  Real potentialPct=0.5,
                                  bool globalInhibition=true,
                                  Real localAreaDensity=-1.0,
                                  UInt numActiveColumnsPerInhArea=10,
                                  UInt stimulusThreshold=0,
                                  Real synPermInactiveDec=0.01,
                                  Real synPermActiveInc=0.1,
                                  Real synPermConnected=0.1,
                                  Real minPctOverlapDutyCycles=0.001,
                                  Real minPctActiveDutyCycles=0.001,
                                  UInt dutyCyclePeriod=1000,
                                  Real maxBoost=10.0,
                                  Int seed=1,
                                  UInt spVerbosity=0);

          void seed_(UInt64 seed);

          //-------------------------------------------------------------------
          // Debugging helpers
          //-------------------------------------------------------------------

          // Print the main SP creation parameters
          void printParameters();

          // Print the given UInt array in a nice format
          void printState(vector<UInt> &state);

          // Print the given Real array in a nice format
          void printState(vector<Real> &state);

        protected:
          UInt numInputs_;
          UInt numColumns_;
          vector<UInt> columnDimensions_;
          vector<UInt> inputDimensions_;
          UInt potentialRadius_;
          Real potentialPct_;
          Real initConnectedPct_;
          bool globalInhibition_;
          Int numActiveColumnsPerInhArea_;
          Real localAreaDensity_;
          UInt stimulusThreshold_;
          UInt inhibitionRadius_;
          UInt dutyCyclePeriod_;
          Real maxBoost_;
          UInt iterationNum_;
          UInt iterationLearnNum_;
          UInt spVerbosity_;
          UInt updatePeriod_;

          Real synPermMin_;
          Real synPermMax_;
          Real synPermTrimThreshold_;
          Real synPermInactiveDec_;
          Real synPermActiveInc_;
          Real synPermBelowStimulusInc_;
          Real synPermConnected_;

          vector<Real> boostFactors_;
          vector<Real> overlapDutyCycles_;
          vector<Real> activeDutyCycles_;
          vector<Real> minOverlapDutyCycles_;
          vector<Real> minActiveDutyCycles_;

          Real minPctOverlapDutyCycles_;
          Real minPctActiveDutyCycles_;

          SparseMatrix<UInt,Real,Int,Real64> permanences_;
          SparseBinaryMatrix<UInt,UInt> potentialPools_;
          SparseBinaryMatrix<UInt, UInt> connectedSynapses_;
          vector<UInt> connectedCounts_;

          vector<UInt> overlaps_;
          vector<Real> overlapsPct_;
          vector<Real> boostedOverlaps_;
          vector<UInt> activeColumns_;
          vector<Real> tieBreaker_;

          UInt version_;
          Random rng_;

      };
    } // end namespace spatial_pooler
  } // end namespace algorithms
} // end namespace nta
#endif // NTA_spatial_pooler_HPP
<commit_msg>Added initial documentation<commit_after>/* ---------------------------------------------------------------------
 * Numenta Platform for Intelligent Computing (NuPIC)
 * Copyright (C) 2013, Numenta, Inc.  Unless you have an agreement
 * with Numenta, Inc., for a separate license for this software code, the
 * following terms and conditions apply:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see http://www.gnu.org/licenses.
 *
 * http://numenta.org/licenses/
 * ----------------------------------------------------------------------
 */

/** @file
 * Definitions for the Spatial Pooler
 */

#ifndef NTA_spatial_pooler_HPP
#define NTA_spatial_pooler_HPP

#include <cstring>
#include <iostream>
#include <nta/math/SparseBinaryMatrix.hpp>
#include <nta/math/SparseMatrix.hpp>
#include <nta/types/types.hpp>
#include <string>
#include <vector>

using namespace std;

namespace nta {
  namespace algorithms {
    namespace spatial_pooler {

      /**
       * CLA spatial pooler implementation in C++.
       *
       * ### Description
       * The Spatial Pooler is responsible for creating a sparse distributed
       * representation of the input. Given an input it computes a set of sparse
       * active columns and simultaneously updates its permanences, duty cycles,
       * etc.
       *
       * The primary public interfaces to this function are the "initialize"
       * and "compute" methods.
       *
       * Example usage:
       *
       *     SpatialPooler sp;
       *     sp.initialize(inputDimensions, columnDimensions, <parameters>);
       *     while (true) {
       *        <get input vector>
       *        sp.compute(inputVector, learn, activeColumns)
       *        <do something with output>
       *     }
       *
       */
      class SpatialPooler {
        public:
          SpatialPooler();

          ~SpatialPooler() {}

          /**
          Initialize the spatial pooler using the given parameters.

          @param inputDimensions A list of integers representing the
                dimensions of the input vector. Format is [height, width,
                depth, ...], where each value represents the size of the
                dimension. For a topology of one dimesion with 100 inputs
                use [100]. For a two dimensional topology of 10x5
                use [10,5].

          @param columnDimensions A list of integers representing the
                dimensions of the columns in the region. Format is [height,
                width, depth, ...], where each value represents the size of
                the dimension. For a topology of one dimesion with 2000
                columns use 2000, or [2000]. For a three dimensional
                topology of 32x64x16 use [32, 64, 16].

          @param potentialRadius This parameter deteremines the extent of the
                input that each column can potentially be connected to. This
                can be thought of as the input bits that are visible to each
                column, or a 'receptive field' of the field of vision. A large
                enough value will result in global coverage, meaning
                that each column can potentially be connected to every input
                bit. This parameter defines a square (or hyper square) area: a
                column will have a max square potential pool with sides of
                length (2 * potentialRadius + 1).

          @param potentialPct The percent of the inputs, within a column's
                potential radius, that a column can be connected to. If set to
                1, the column will be connected to every input within its
                potential radius. This parameter is used to give each column a
                unique potential pool when a large potentialRadius causes
                overlap between the columns. At initialization time we choose
                ((2*potentialRadius + 1)^(# inputDimensions) * potentialPct)
                input bits to comprise the column's potential pool.

          @param globalInhibition If true, then during inhibition phase the
                winning columns are selected as the most active columns from the
                region as a whole. Otherwise, the winning columns are selected
                with resepct to their local neighborhoods. Global inhibition
                boosts performance significantly but there is no topology at the
                output.

          @param localAreaDensity The desired density of active columns within
                a local inhibition area (the size of which is set by the
                internally calculated inhibitionRadius, which is in turn
                determined from the average size of the connected potential
                pools of all columns). The inhibition logic will insure that at
                most N columns remain ON within a local inhibition area, where
                N = localAreaDensity * (total number of columns in inhibition
                area). If localAreaDensity is set to a negative value output
                sparsity will be determined by the numActivePerInhArea.

          @param numActivePerInhArea An alternate way to control the sparsity of
                active columns. If numActivePerInhArea is specified then
                localAreaDensity must less than 0, and vice versa. When
                numActivePerInhArea > 0, the inhibition logic will insure that
                at most 'numActivePerInhArea' columns remain ON within a local
                inhibition area (the size of which is set by the internally
                calculated inhibitionRadius). When using this method, as columns
                learn and grow their effective receptive fields, the
                inhibitionRadius will grow, and hence the net density of the
                active columns will *decrease*. This is in contrast to the
                localAreaDensity method, which keeps the density of active
                columns the same regardless of the size of their receptive
                fields.

          @param stimulusThreshold This is a number specifying the minimum
                number of synapses that must be active in order for a column to
                turn ON. The purpose of this is to prevent noisy input from
                activating columns.

          @param synPermInactiveDec The amount by which the permanence of an
                inactive synapse is decremented in each learning step.

          @param synPermActiveInc The amount by which the permanence of an
                active synapse is incremented in each round.

          @param synPermConnected The default connected threshold. Any synapse
                whose permanence value is above the connected threshold is
                a "connected synapse", meaning it can contribute to
                the cell's firing.

          @param minPctOvlerapDutyCycle A number between 0 and 1.0, used to set
                a floor on how often a column should have at least
                stimulusThreshold active inputs. Periodically, each column looks
                at the overlap duty cycle of all other column within its
                inhibition radius and sets its own internal minimal acceptable
                duty cycle to: minPctDutyCycleBeforeInh * max(other columns'
                duty cycles). On each iteration, any column whose overlap duty
                cycle falls below this computed value will get all of its
                permanence values boosted up by synPermActiveInc. Raising all
                permanences in response to a sub-par duty cycle before
                inhibition allows a cell to search for new inputs when either
                its previously learned inputs are no longer ever active, or when
                the vast majority of them have been "hijacked" by other columns.

          @param minPctActiveDutyCycle A number between 0 and 1.0, used to set
                a floor on how often a column should be activate. Periodically,
                each column looks at the activity duty cycle of all other
                columns within its inhibition radius and sets its own internal
                minimal acceptable duty cycle to:

                    minPctDutyCycleAfterInh * max(other columns' duty cycles).

                On each iteration, any column whose duty cycle after inhibition
                falls below this computed value will get its internal boost
                factor increased.

          @param dutyCyclePeriod The period used to calculate duty cycles.
                Higher values make it take longer to respond to changes in
                boost. Shorter values make it potentially more unstable and
                likely to oscillate.

          @param maxBoost The maximum overlap boost factor. Each column's
                overlap gets multiplied by a boost factor before it gets
                considered for inhibition. The actual boost factor for a column
                is a number between 1.0 and maxBoost. A boost factor of 1.0 is
                used if the duty cycle is >= minOverlapDutyCycle, maxBoost is
                used if the duty cycle is 0, and any duty cycle in between is
                linearly extrapolated from these 2 endpoints.

          @param seed Seed for our random number generator. If seed is < 0
                a randomly generated seed is used. The behavior of the spatial
                pooler is deterministic once the seed is set.

          @param spVerbosity spVerbosity level: 0, 1, 2, or 3

           */
          virtual void initialize(vector<UInt> inputDimensions,
                                  vector<UInt> columnDimensions,
                                  UInt potentialRadius=16,
                                  Real potentialPct=0.5,
                                  bool globalInhibition=true,
                                  Real localAreaDensity=-1.0,
                                  UInt numActiveColumnsPerInhArea=10,
                                  UInt stimulusThreshold=0,
                                  Real synPermInactiveDec=0.01,
                                  Real synPermActiveInc=0.1,
                                  Real synPermConnected=0.1,
                                  Real minPctOverlapDutyCycles=0.001,
                                  Real minPctActiveDutyCycles=0.001,
                                  UInt dutyCyclePeriod=1000,
                                  Real maxBoost=10.0,
                                  Int seed=1,
                                  UInt spVerbosity=0);

          /**
          This is the main workshorse method of the SpatialPooler class. This
          method takes an input vector and computes the set of output active
          columns. If 'learn' is set to True, this method also performs
          learning.

          @param inputVector An array of integer 0's and 1's that comprises
                the input to the spatial pooler. The length of the
                array must match the total number of input bits implied by
                the constructor (also returned by the method getNumInputs). In
                cases where the input is multi-dimensional, inputVector is a
                flattened array of inputs.

          @param learn A boolean value indicating whether learning should be
                performed. Learning entails updating the permanence values of
                the synapses, duty cycles, etc. Learning is typically on but
                setting learning to 'off' is useful for analyzing the current
                state of the SP. For example, you might want to feed in various
                inputs and examine the resulting SDR's. Note that if learning
                is off, boosting is turned off and columns that have never won
                will be removed from activeVector.  TODO: we may want to keep
                boosting on even when learning is off.

          @param activeArray An array representing the winning columns after
                inhinition. The size of the array is equal to the number of
                columns (also returned by the method getNumColumns). This array
                will be populated with 1's at the indices of the active columns,
                and 0's everywhere else. In the case where the output is
                multi-dimensional, activeVector represents a flattened array
                of outputs.
           */
          virtual void compute(UInt inputVector[], bool learn,
                               UInt activeVector[]);

          /**
           * Get the version number of this spatial pooler
           * @returns Integer version number
           */
          virtual UInt version() const {
            return version_;
          };

          /**
          Save (serialize) the current state of the spatial pooler to the
          specified output stream.

          @param outStream A valid ostream.
           */
          virtual void save(ostream& outStream);

          /**
          Load (deserialize) and initialize the spatial pooler from the
          specified input stream.

          @param inStream A valid istream.
           */
          virtual void load(istream& inStream);

          /**
          Returns the number of bytes that a save operation would result in.
          Note: this method is currently somewhat inefficient as it just does
          a full save into an ostream and counts the resulting size.

          @returns Integer number of bytes
           */
          virtual UInt persistentSize();

          UInt getNumColumns();
          UInt getNumInputs();

          UInt getPotentialRadius();
          void setPotentialRadius(UInt potentialRadius);

          Real getPotentialPct();
          void setPotentialPct(Real potentialPct);

          bool getGlobalInhibition();
          void setGlobalInhibition(bool globalInhibition);

          Int getNumActiveColumnsPerInhArea();
          void setNumActiveColumnsPerInhArea(UInt numActiveColumnsPerInhArea);

          Real getLocalAreaDensity();
          void setLocalAreaDensity(Real localAreaDensity);

          UInt getStimulusThreshold();
          void setStimulusThreshold(UInt stimulusThreshold);

          UInt getInhibitionRadius();
          void setInhibitionRadius(UInt inhibitionRadius);

          UInt getDutyCyclePeriod();
          void setDutyCyclePeriod(UInt dutyCyclePeriod);

          Real getMaxBoost();
          void setMaxBoost(Real maxBoost);

          UInt getIterationNum();
          void setIterationNum(UInt iterationNum);

          UInt getIterationLearnNum();
          void setIterationLearnNum(UInt iterationLearnNum);

          UInt getSpVerbosity();
          void setSpVerbosity(UInt spVerbosity);

          UInt getUpdatePeriod();
          void setUpdatePeriod(UInt updatePeriod);

          Real getSynPermTrimThreshold();
          void setSynPermTrimThreshold(Real synPermTrimThreshold);

          Real getSynPermActiveInc();
          void setSynPermActiveInc(Real synPermActiveInc);

          Real getSynPermInactiveDec();
          void setSynPermInactiveDec(Real synPermInactiveDec);

          Real getSynPermBelowStimulusInc();
          void setSynPermBelowStimulusInc(Real synPermBelowStimulusInc);

          Real getSynPermConnected();
          void setSynPermConnected(Real setSynPermConnected);

          Real getMinPctOverlapDutyCycles();
          void setMinPctOverlapDutyCycles(Real minPctOverlapDutyCycles);

          Real getMinPctActiveDutyCycles();
          void setMinPctActiveDutyCycles(Real minPctActiveDutyCycles);

          void getBoostFactors(Real boostFactors[]);
          void setBoostFactors(Real boostFactors[]);

          void getOverlapDutyCycles(Real overlapDutyCycles[]);
          void setOverlapDutyCycles(Real overlapDutyCycles[]);

          void getActiveDutyCycles(Real activeDutyCycles[]);
          void setActiveDutyCycles(Real activeDutyCycles[]);

          void getMinOverlapDutyCycles(Real minOverlapDutyCycles[]);
          void setMinOverlapDutyCycles(Real minOverlapDutyCycles[]);

          void getMinActiveDutyCycles(Real minActiveDutyCycles[]);
          void setMinActiveDutyCycles(Real minActiveDutyCycles[]);

          void getPotential(UInt column, UInt potential[]);
          void setPotential(UInt column, UInt potential[]);

          void getPermanence(UInt column, Real permanence[]);
          void setPermanence(UInt column, Real permanence[]);

          void getConnectedSynapses(UInt column, UInt connectedSynapses[]);

          void getConnectedCounts(UInt connectedCounts[]);

          /**
          Print the main SP creation parameters to stdout.
           */
          void printParameters();

          ///////////////////////////////////////////////////////////
          //
          // Implementation methods. all methods below this line are
          // NOT part of the public API

          void stripNeverLearned_(UInt activeArray[]);

          void toDense_(vector<UInt>& sparse,
                        UInt dense[],
                        UInt n);

          void boostOverlaps_(vector<UInt>& overlaps,
                              vector<Real>& boostedOverlaps);
          void range_(Int start, Int end, UInt ubound, bool wrapAround,
                      vector<UInt>& rangeVector);

          vector<UInt> mapPotential1D_(UInt column, bool wrapAround);
          Real initPermConnected_();
          Real initPermNonConnected_();
          vector<Real> initPermanence_(vector<UInt>& potential,
                                       Real connectedPct);
          void clip_(vector<Real>& perm, bool trim);
          void updatePermanencesForColumn_(vector<Real>& perm, UInt column,
                                           bool raisePerm=true);
          UInt countConnected_(vector<Real>& perm);
          UInt raisePermanencesToThreshold_(vector<Real>& perm,
                                            vector<UInt>& potential);

          void calculateOverlap_(UInt inputVector[],
                                 vector<UInt>& overlap);
          void calculateOverlapPct_(vector<UInt>& overlaps,
                                    vector<Real>& overlapPct);

          bool isWinner_(Real score, vector<pair<UInt, Real> >& winners,
                         UInt numWinners);

          void addToWinners_(UInt index, Real score,
                             vector<pair<UInt, Real> >& winners);

          void inhibitColumns_(vector<Real>& overlaps,
                               vector<UInt>& activeColumns);
          void inhibitColumnsGlobal_(vector<Real>& overlaps, Real density,
                                     vector<UInt>& activeColumns);
          void inhibitColumnsLocal_(vector<Real>& overlaps, Real density,
                                    vector<UInt>& activeColumns);

          void getNeighbors1D_(UInt column, vector<UInt>& dimensions,
                               UInt radius, bool wrapAround,
                               vector<UInt>& neighbors);
          void getNeighbors2D_(UInt column, vector<UInt>& dimensions,
                               UInt radius, bool wrapAround,
                               vector<UInt>& neighbors);
          void cartesianProduct_(vector<vector<UInt> >& vecs,
                                 vector<vector<UInt> >& product);

          void getNeighborsND_(UInt column, vector<UInt>& dimensions,
                               UInt radius, bool wrapAround,
                               vector<UInt>& neighbors);

          void adaptSynapses_(UInt inputVector[],
                              vector<UInt>& activeColumns);
          void bumpUpWeakColumns_();

          void updateInhibitionRadius_();
          Real avgColumnsPerInput_();
          Real avgConnectedSpanForColumn1D_(UInt column);
          Real avgConnectedSpanForColumn2D_(UInt column);
          Real avgConnectedSpanForColumnND_(UInt column);
          void updateMinDutyCycles_();
          void updateMinDutyCyclesGlobal_();
          void updateMinDutyCyclesLocal_();
          static  void updateDutyCyclesHelper_(vector<Real>& dutyCycles,
                                               vector<UInt>& newValues,
                                               UInt period);
          void updateDutyCycles_(vector<UInt>& overlaps,
                                 UInt activeArray[]);
          void updateBoostFactors_();
          void updateBookeepingVars_(bool learn);

          bool isUpdateRound_();

          void seed_(UInt64 seed);

          //-------------------------------------------------------------------
          // Debugging helpers
          //-------------------------------------------------------------------

          // Print the given UInt array in a nice format
          void printState(vector<UInt> &state);

          // Print the given Real array in a nice format
          void printState(vector<Real> &state);

        protected:
          UInt numInputs_;
          UInt numColumns_;
          vector<UInt> columnDimensions_;
          vector<UInt> inputDimensions_;
          UInt potentialRadius_;
          Real potentialPct_;
          Real initConnectedPct_;
          bool globalInhibition_;
          Int numActiveColumnsPerInhArea_;
          Real localAreaDensity_;
          UInt stimulusThreshold_;
          UInt inhibitionRadius_;
          UInt dutyCyclePeriod_;
          Real maxBoost_;
          UInt iterationNum_;
          UInt iterationLearnNum_;
          UInt spVerbosity_;
          UInt updatePeriod_;

          Real synPermMin_;
          Real synPermMax_;
          Real synPermTrimThreshold_;
          Real synPermInactiveDec_;
          Real synPermActiveInc_;
          Real synPermBelowStimulusInc_;
          Real synPermConnected_;

          vector<Real> boostFactors_;
          vector<Real> overlapDutyCycles_;
          vector<Real> activeDutyCycles_;
          vector<Real> minOverlapDutyCycles_;
          vector<Real> minActiveDutyCycles_;

          Real minPctOverlapDutyCycles_;
          Real minPctActiveDutyCycles_;

          SparseMatrix<UInt,Real,Int,Real64> permanences_;
          SparseBinaryMatrix<UInt,UInt> potentialPools_;
          SparseBinaryMatrix<UInt, UInt> connectedSynapses_;
          vector<UInt> connectedCounts_;

          vector<UInt> overlaps_;
          vector<Real> overlapsPct_;
          vector<Real> boostedOverlaps_;
          vector<UInt> activeColumns_;
          vector<Real> tieBreaker_;

          UInt version_;
          Random rng_;

      };
    } // end namespace spatial_pooler
  } // end namespace algorithms
} // end namespace nta
#endif // NTA_spatial_pooler_HPP
<|endoftext|>


<commit_before>#if defined(_QT_GUI_USED_)
#include <QPainter>
#include <QDebug>
#endif

#include <math.h>
#include "zcircle.h"
#include "tz_math.h"
#include "zintpoint.h"

const ZCircle::TVisualEffect ZCircle::VE_NONE = 0;
const ZCircle::TVisualEffect ZCircle::VE_DASH_PATTERN = 1;
const ZCircle::TVisualEffect ZCircle::VE_BOUND_BOX = 2;
const ZCircle::TVisualEffect ZCircle::VE_NO_CIRCLE = 4;
const ZCircle::TVisualEffect ZCircle::VE_NO_FILL = 8;
const ZCircle::TVisualEffect ZCircle::VE_GRADIENT_FILL = 16;
const ZCircle::TVisualEffect ZCircle::VE_OUT_FOCUS_DIM = 32;

ZCircle::ZCircle() : m_visualEffect(ZCircle::VE_NONE)
{
  set(0, 0, 0, 1);
}

ZCircle::ZCircle(double x, double y, double z, double r) :
  m_visualEffect(ZCircle::VE_NONE)
{
  set(x, y, z, r);
}

void ZCircle::set(double x, double y, double z, double r)
{
  m_center.set(x, y, z);
  m_r = r;
}

void ZCircle::set(const ZIntPoint &center, double r)
{
  set(center.getX(), center.getY(), center.getZ(), r);
}

void ZCircle::set(const ZPoint &center, double r)
{
  set(center.x(), center.y(), center.z(), r);
}

//void ZCircle::display(QImage *image, int n, Display_Style style) const
//{
//#if defined(_QT_GUI_USED_)
//  QPainter painter(image);
//  painter.setPen(m_color);
//  display(&painter, n, style);
//#endif
//}

void ZCircle::display(ZPainter &painter, int n,
                      ZStackObject::Display_Style style) const
{
  if (!isVisible()) {
    return;
  }

  UNUSED_PARAMETER(style);
#if _QT_GUI_USED_
  QPen pen(m_color, getPenWidth());
  pen.setCosmetic(m_usingCosmeticPen);

  if (hasVisualEffect(VE_DASH_PATTERN)) {
    pen.setStyle(Qt::DotLine);
  }

  painter.setPen(pen);

  //qDebug() << "Internal color: " << m_color;
  const QBrush &oldBrush = painter.brush();
  if (hasVisualEffect(VE_GRADIENT_FILL)) {
    QRadialGradient gradient(50, 50, 50, 50, 50);
    gradient.setColorAt(0, QColor::fromRgbF(0, 1, 0, 1));
    gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));

    /*
    QBrush brush(gradient);
    brush.setColor(m_color);
    brush.setStyle(Qt::RadialGradientPattern);
    painter.setBrush(brush);
    */
    //painter.setBrush(m_color);
    //painter.setBrush(QBrush(m_color, Qt::RadialGradientPattern));
  } else {
    if (hasVisualEffect(VE_NO_FILL)) {
      painter.setBrush(Qt::NoBrush);
    }
  }
  displayHelper(&painter, n, style);
  painter.setBrush(oldBrush);
#endif
}

bool ZCircle::isCuttingPlane(double z, double r, double n)
{
  double h = fabs(z - n);
  if (r > h) {
    return true;
  } else if (iround(z) == iround(n)) {
    return true;
  }

  return false;
}

bool ZCircle::isCuttingPlane(double n)
{
  return isCuttingPlane(m_center.z(), m_r, n);
}

double ZCircle::getAdjustedRadius(double r) const
{
  double adjustedRadius = r;
  if (!m_usingCosmeticPen) {
    adjustedRadius += getPenWidth() * 0.5;
  }

  return adjustedRadius;
}

void ZCircle::displayHelper(ZPainter *painter, int stackFocus, Display_Style style) const
{
  UNUSED_PARAMETER(style);
#if defined(_QT_GUI_USED_)
  double adjustedRadius = getAdjustedRadius(m_r);

  double dataFocus = stackFocus - painter->getOffset().z();
  bool visible = false;

  double alpha = 1.0;
  if (stackFocus == -1) {
    visible = true;
  } else {
    if (isCuttingPlane(m_center.z(), m_r, dataFocus)) {
      double h = fabs(m_center.z() - dataFocus);
      double r = 0.0;
      if (m_r > h) {
        r = sqrt(m_r * m_r - h * h);
        adjustedRadius = getAdjustedRadius(r);
        //adjustedRadius = r + getPenWidth() * 0.5;
        visible = true;
      } else { //too small, show at least one plane
        //adjustedRadius = getPenWidth() * 0.5;
        r = 0.1;
        adjustedRadius = getAdjustedRadius(r);
        visible = true;
      }
      if (hasVisualEffect(VE_OUT_FOCUS_DIM)) {
        alpha = r / m_r;
        alpha *= alpha;
      }
    }
  }

  if (visible) {
    if (!hasVisualEffect(VE_NO_CIRCLE)) {
      //qDebug() << painter->brush().color();
      QColor color = painter->pen().color();
      color.setAlphaF(alpha);
      painter->setPen(color);
      painter->drawEllipse(QPointF(m_center.x(), m_center.y()),
                           adjustedRadius, adjustedRadius);
    }
  }

  if (hasVisualEffect(VE_BOUND_BOX)) {
    QRectF rect;
    rect.setLeft(m_center.x() - adjustedRadius);
    rect.setTop(m_center.y() - adjustedRadius);
    rect.setWidth(adjustedRadius + adjustedRadius);
    rect.setHeight(adjustedRadius + adjustedRadius);

    const QBrush &oldBrush = painter->brush();
    const QPen &oldPen = painter->pen();
    painter->setBrush(Qt::NoBrush);

    QPen pen = oldPen;
    pen.setStyle(Qt::SolidLine);
    pen.setCosmetic(m_usingCosmeticPen);
    painter->setPen(pen);

#if 0 //for future versions
    QPen pen = oldPen;
    QVector<qreal> pattern;
    pattern << 1 << 2;
    pen.setDashPattern(pattern);
    painter->setPen(pen);
    painter->drawRect(rect);

    pen.setColor(Qt::black);
    pen.setDashOffset(1.5);
    painter->setPen(pen);
#endif

    //QPainter::CompositionMode oldMode = painter->compositionMode();
    //painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination);
    painter->drawRect(rect);

    //painter->setCompositionMode(oldMode);
    painter->setBrush(oldBrush);
    painter->setPen(oldPen);
  }
#endif
}

void ZCircle::save(const char *filePath)
{
  UNUSED_PARAMETER(filePath);
}

bool ZCircle::load(const char *filePath)
{
  UNUSED_PARAMETER(filePath);

  return false;
}

ZSTACKOBJECT_DEFINE_CLASS_NAME(ZCircle)
<commit_msg>fix color bug<commit_after>#if defined(_QT_GUI_USED_)
#include <QPainter>
#include <QDebug>
#endif

#include <math.h>
#include "zcircle.h"
#include "tz_math.h"
#include "zintpoint.h"

const ZCircle::TVisualEffect ZCircle::VE_NONE = 0;
const ZCircle::TVisualEffect ZCircle::VE_DASH_PATTERN = 1;
const ZCircle::TVisualEffect ZCircle::VE_BOUND_BOX = 2;
const ZCircle::TVisualEffect ZCircle::VE_NO_CIRCLE = 4;
const ZCircle::TVisualEffect ZCircle::VE_NO_FILL = 8;
const ZCircle::TVisualEffect ZCircle::VE_GRADIENT_FILL = 16;
const ZCircle::TVisualEffect ZCircle::VE_OUT_FOCUS_DIM = 32;

ZCircle::ZCircle() : m_visualEffect(ZCircle::VE_NONE)
{
  set(0, 0, 0, 1);
}

ZCircle::ZCircle(double x, double y, double z, double r) :
  m_visualEffect(ZCircle::VE_NONE)
{
  set(x, y, z, r);
}

void ZCircle::set(double x, double y, double z, double r)
{
  m_center.set(x, y, z);
  m_r = r;
}

void ZCircle::set(const ZIntPoint &center, double r)
{
  set(center.getX(), center.getY(), center.getZ(), r);
}

void ZCircle::set(const ZPoint &center, double r)
{
  set(center.x(), center.y(), center.z(), r);
}

//void ZCircle::display(QImage *image, int n, Display_Style style) const
//{
//#if defined(_QT_GUI_USED_)
//  QPainter painter(image);
//  painter.setPen(m_color);
//  display(&painter, n, style);
//#endif
//}

void ZCircle::display(ZPainter &painter, int n,
                      ZStackObject::Display_Style style) const
{
  if (!isVisible()) {
    return;
  }

  UNUSED_PARAMETER(style);
#if _QT_GUI_USED_
  QPen pen(m_color, getPenWidth());
  pen.setCosmetic(m_usingCosmeticPen);

  if (hasVisualEffect(VE_DASH_PATTERN)) {
    pen.setStyle(Qt::DotLine);
  }

  painter.setPen(pen);

  //qDebug() << "Internal color: " << m_color;
  const QBrush &oldBrush = painter.brush();
  if (hasVisualEffect(VE_GRADIENT_FILL)) {
    QRadialGradient gradient(50, 50, 50, 50, 50);
    gradient.setColorAt(0, QColor::fromRgbF(0, 1, 0, 1));
    gradient.setColorAt(1, QColor::fromRgbF(0, 0, 0, 0));

    /*
    QBrush brush(gradient);
    brush.setColor(m_color);
    brush.setStyle(Qt::RadialGradientPattern);
    painter.setBrush(brush);
    */
    //painter.setBrush(m_color);
    //painter.setBrush(QBrush(m_color, Qt::RadialGradientPattern));
  } else {
    if (hasVisualEffect(VE_NO_FILL)) {
      painter.setBrush(Qt::NoBrush);
    }
  }
  displayHelper(&painter, n, style);
  painter.setBrush(oldBrush);
#endif
}

bool ZCircle::isCuttingPlane(double z, double r, double n)
{
  double h = fabs(z - n);
  if (r > h) {
    return true;
  } else if (iround(z) == iround(n)) {
    return true;
  }

  return false;
}

bool ZCircle::isCuttingPlane(double n)
{
  return isCuttingPlane(m_center.z(), m_r, n);
}

double ZCircle::getAdjustedRadius(double r) const
{
  double adjustedRadius = r;
  if (!m_usingCosmeticPen) {
    adjustedRadius += getPenWidth() * 0.5;
  }

  return adjustedRadius;
}

void ZCircle::displayHelper(ZPainter *painter, int stackFocus, Display_Style style) const
{
  UNUSED_PARAMETER(style);
#if defined(_QT_GUI_USED_)
  double adjustedRadius = getAdjustedRadius(m_r);

  double dataFocus = stackFocus - painter->getOffset().z();
  bool visible = false;

  const QBrush &oldBrush = painter->brush();
  const QPen &oldPen = painter->pen();
  double alpha = oldPen.color().alphaF();

  if (stackFocus == -1) {
    visible = true;
  } else {
    if (isCuttingPlane(m_center.z(), m_r, dataFocus)) {
      double h = fabs(m_center.z() - dataFocus);
      double r = 0.0;
      if (m_r > h) {
        r = sqrt(m_r * m_r - h * h);
        adjustedRadius = getAdjustedRadius(r);
        //adjustedRadius = r + getPenWidth() * 0.5;
        visible = true;
      } else { //too small, show at least one plane
        //adjustedRadius = getPenWidth() * 0.5;
        r = 0.1;
        adjustedRadius = getAdjustedRadius(r);
        visible = true;
      }
      if (hasVisualEffect(VE_OUT_FOCUS_DIM)) {
        alpha *= r * r / m_r / m_r;
        //alpha *= alpha;
      }
    }
  }

  if (visible) {
    if (!hasVisualEffect(VE_NO_CIRCLE)) {
      //qDebug() << painter->brush().color();
      QColor color = painter->pen().color();
      color.setAlphaF(alpha);
      painter->setPen(color);
      painter->drawEllipse(QPointF(m_center.x(), m_center.y()),
                           adjustedRadius, adjustedRadius);
    }
  }

  if (hasVisualEffect(VE_BOUND_BOX)) {
    QRectF rect;
    rect.setLeft(m_center.x() - adjustedRadius);
    rect.setTop(m_center.y() - adjustedRadius);
    rect.setWidth(adjustedRadius + adjustedRadius);
    rect.setHeight(adjustedRadius + adjustedRadius);

    painter->setBrush(Qt::NoBrush);

    QPen pen = oldPen;
    pen.setStyle(Qt::SolidLine);
    pen.setCosmetic(m_usingCosmeticPen);
    painter->setPen(pen);

#if 0 //for future versions
    QPen pen = oldPen;
    QVector<qreal> pattern;
    pattern << 1 << 2;
    pen.setDashPattern(pattern);
    painter->setPen(pen);
    painter->drawRect(rect);

    pen.setColor(Qt::black);
    pen.setDashOffset(1.5);
    painter->setPen(pen);
#endif

    //QPainter::CompositionMode oldMode = painter->compositionMode();
    //painter->setCompositionMode(QPainter::RasterOp_SourceXorDestination);
    painter->drawRect(rect);

    //painter->setCompositionMode(oldMode);
  }

  painter->setBrush(oldBrush);
  painter->setPen(oldPen);
#endif
}

void ZCircle::save(const char *filePath)
{
  UNUSED_PARAMETER(filePath);
}

bool ZCircle::load(const char *filePath)
{
  UNUSED_PARAMETER(filePath);

  return false;
}

ZSTACKOBJECT_DEFINE_CLASS_NAME(ZCircle)
<|endoftext|>


<commit_before>// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
//
// 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 "VkStringify.hpp"

#include "System/Debug.hpp"

#include <vulkan/vk_ext_provoking_vertex.h>
#include <vulkan/vk_google_filtering_precision.h>
#define VULKAN_HPP_NO_EXCEPTIONS
#define VULKAN_HPP_NAMESPACE vkhpp
#include <vulkan/vulkan.hpp>

#include <iostream>
#include <map>
#include <sstream>
#include <string>

namespace vk {

std::string Stringify(VkStructureType value)
{
#ifndef NDEBUG
	std::string ret = "";
	switch(static_cast<int>(value))
	{
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT:
			ret = "PhysicalDeviceProvokingVertexFeaturesEXT";
			break;
		case VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT:
			ret = "PipelineRasterizationProvokingVertexStateCreateInfoEXT";
			break;
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_PROPERTIES_EXT:
			ret = "PhysicalDeviceProvokingVertexPropertiesEXT";
			break;
		case VK_STRUCTURE_TYPE_SAMPLER_FILTERING_PRECISION_GOOGLE:
			ret = "SamplerFilteringPrecisionGOOGLE";
			break;
		default:
			ret = vkhpp::to_string(static_cast<vkhpp::StructureType>(value));
			break;
	}
	std::ostringstream stringStream;
	stringStream << ret << " (" << static_cast<int>(value) << ")";
	return stringStream.str();
#else
	return std::to_string(static_cast<int>(value));
#endif
}

}  // namespace vk
<commit_msg>Don't auto append value of stringified enums<commit_after>// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
//
// 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 "VkStringify.hpp"

#include "System/Debug.hpp"

#include <vulkan/vk_ext_provoking_vertex.h>
#include <vulkan/vk_google_filtering_precision.h>
#define VULKAN_HPP_NO_EXCEPTIONS
#define VULKAN_HPP_NAMESPACE vkhpp
#include <vulkan/vulkan.hpp>

namespace vk {

std::string Stringify(VkStructureType value)
{
#ifndef NDEBUG
	std::string ret = "";
	switch(static_cast<int>(value))
	{
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_FEATURES_EXT:
			ret = "PhysicalDeviceProvokingVertexFeaturesEXT";
			break;
		case VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_PROVOKING_VERTEX_STATE_CREATE_INFO_EXT:
			ret = "PipelineRasterizationProvokingVertexStateCreateInfoEXT";
			break;
		case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROVOKING_VERTEX_PROPERTIES_EXT:
			ret = "PhysicalDeviceProvokingVertexPropertiesEXT";
			break;
		case VK_STRUCTURE_TYPE_SAMPLER_FILTERING_PRECISION_GOOGLE:
			ret = "SamplerFilteringPrecisionGOOGLE";
			break;
		default:
			ret = vkhpp::to_string(static_cast<vkhpp::StructureType>(value));
			break;
	}

	return ret;
#else
	return std::to_string(static_cast<int>(value));
#endif
}

}  // namespace vk
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP
#define STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err/is_scal_finite.hpp>
#include <stan/math/prim/err/throw_domain_error.hpp>
#include <stan/math/prim/err/throw_domain_error_vec.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/get.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/fun/value_of_rec.hpp>
#include <cmath>

namespace stan {
namespace math {
namespace internal {
/**
 * Return true if y is finite
 *
 * @tparam T_y type of y
 * @param y parameter to check
 * @return boolean
 */
template <typename T_y>
bool is_finite(const T_y& y) {
  return is_scal_finite(y);
}

/**
 * Return true if every element of the matrix y is finite
 *
 * @tparam T_y type of elements y
 * @param y matrix to check
 * @return boolean
 */
template <typename T_y, int R, int C>
bool is_finite(const Eigen::Matrix<T_y, R, C>& y) {
  bool all = true;
  for (size_t n = 0; n < y.size(); ++n) {
    all &= is_finite(y(n));
  }
  return all;
}

/**
 * Return true if every element of the vector y is finite
 *
 * @tparam T_y type of elements y
 * @param y vector to check
 * @return boolean
 */
template <typename T_y>
bool is_finite(const std::vector<T_y>& y) {
  bool all = true;
  for (size_t n = 0; n < stan::math::size(y); ++n) {
    all &= is_finite(y[n]);
  }
  return all;
}
}  // namespace internal

/**
 * Check if y is finite.
 * This function is vectorized and will check each element of
 * y.
 * @tparam T_y Type of y
 * @param function Function name (for error messages)
 * @param name Variable name (for error messages)
 * @param y Variable to check
 * @throw domain_error if y is infinity, -infinity, or NaN
 */
template <typename T_y, require_stan_scalar_t<T_y>* = nullptr>
inline void check_finite(const char* function, const char* name, const T_y& y) {
  if (!internal::is_finite(y)) {
    throw_domain_error(function, name, y, "is ", ", but must be finite!");
  }
}

/**
 * Return true if all values in the std::vector are finite.
 *
 * @tparam T_y type of elements in the std::vector
 *
 * @param function name of function (for error messages)
 * @param name variable name (for error messages)
 * @param y std::vector to test
 * @return true if all values are finite
 **/
template <typename T_y, require_stan_scalar_t<T_y>* = nullptr>
inline void check_finite(const char* function, const char* name,
                         const std::vector<T_y>& y) {
  for (size_t n = 0; n < stan::math::size(y); n++) {
    if (!internal::is_finite(stan::get(y, n))) {
      throw_domain_error_vec(function, name, y, n, "is ",
                             ", but must be finite!");
    }
  }
}

/**
 * Return true is the specified matrix is finite.
 *
 * @tparam Derived Eigen derived type
 *
 * @param function name of function (for error messages)
 * @param name variable name (for error messages)
 * @param y matrix to test
 * @return true if the matrix is finite
 **/
template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
inline void check_finite(const char* function, const char* name,
                         const EigMat& y) {
  if (!value_of(y).allFinite()) {
    for (int n = 0; n < y.size(); ++n) {
      if (!std::isfinite(value_of_rec(y(n)))) {
        throw_domain_error_vec(function, name, y, n, "is ",
                               ", but must be finite!");
      }
    }
  }
}

/**
 * Return true if all values in the std::vector are finite.
 *
 * @tparam T_y type of elements in the std::vector
 *
 * @param function name of function (for error messages)
 * @param name variable name (for error messages)
 * @param y std::vector to test
 * @return true if all values are finite
 **/
template <typename T_y, require_not_stan_scalar_t<T_y>* = nullptr>
inline void check_finite(const char* function, const char* name,
                         const std::vector<T_y>& y) {
  for (size_t n = 0; n < stan::math::size(y); n++) {
    if (!internal::is_finite(stan::get(y, n))) {
      throw_domain_error(function, name, "", "", "is not finite!");
    }
  }
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Updated check_finite to support `var<mat>` s (Issue #2101)<commit_after>#ifndef STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP
#define STAN_MATH_PRIM_ERR_CHECK_FINITE_HPP

#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err/is_scal_finite.hpp>
#include <stan/math/prim/err/throw_domain_error.hpp>
#include <stan/math/prim/err/throw_domain_error_vec.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stan/math/prim/fun/get.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/fun/value_of_rec.hpp>
#include <cmath>

namespace stan {
namespace math {
namespace internal {
/**
 * Return true if y is finite
 *
 * @tparam T_y type of y
 * @param y parameter to check
 * @return boolean
 */
template <typename T_y>
bool is_finite(const T_y& y) {
  return is_scal_finite(y);
}

/**
 * Return true if every element of the matrix y is finite
 *
 * @tparam T_y type of elements y
 * @param y matrix to check
 * @return boolean
 */
template <typename T_y, int R, int C>
bool is_finite(const Eigen::Matrix<T_y, R, C>& y) {
  bool all = true;
  for (size_t n = 0; n < y.size(); ++n) {
    all &= is_finite(y(n));
  }
  return all;
}

/**
 * Return true if every element of the vector y is finite
 *
 * @tparam T_y type of elements y
 * @param y vector to check
 * @return boolean
 */
template <typename T_y>
bool is_finite(const std::vector<T_y>& y) {
  bool all = true;
  for (size_t n = 0; n < stan::math::size(y); ++n) {
    all &= is_finite(y[n]);
  }
  return all;
}
}  // namespace internal

/**
 * Check if y is finite.
 * This function is vectorized and will check each element of
 * y.
 * @tparam T_y Type of y
 * @param function Function name (for error messages)
 * @param name Variable name (for error messages)
 * @param y Variable to check
 * @throw domain_error if y is infinity, -infinity, or NaN
 */
template <typename T_y, require_stan_scalar_t<T_y>* = nullptr>
inline void check_finite(const char* function, const char* name, const T_y& y) {
  if (!internal::is_finite(y)) {
    throw_domain_error(function, name, y, "is ", ", but must be finite!");
  }
}

/**
 * Return true if all values in the std::vector are finite.
 *
 * @tparam T_y type of elements in the std::vector
 *
 * @param function name of function (for error messages)
 * @param name variable name (for error messages)
 * @param y std::vector to test
 * @return true if all values are finite
 **/
template <typename T_y, require_stan_scalar_t<T_y>* = nullptr>
inline void check_finite(const char* function, const char* name,
                         const std::vector<T_y>& y) {
  for (size_t n = 0; n < stan::math::size(y); n++) {
    if (!internal::is_finite(stan::get(y, n))) {
      throw_domain_error_vec(function, name, y, n, "is ",
                             ", but must be finite!");
    }
  }
}

/**
 * Return true is the specified matrix is finite.
 *
 * @tparam Derived Eigen derived type
 *
 * @param function name of function (for error messages)
 * @param name variable name (for error messages)
 * @param y matrix to test
 * @return true if the matrix is finite
 **/
template <typename Mat, require_matrix_t<Mat>* = nullptr>
inline void check_finite(const char* function, const char* name,
                         const Mat& y) {
  if (!value_of(y).allFinite()) {
    for (int n = 0; n < y.size(); ++n) {
      if (!std::isfinite(value_of_rec(y(n)))) {
        throw_domain_error_vec(function, name, value_of(y), n, "is ",
                               ", but must be finite!");
      }
    }
  }
}

/**
 * Return true if all values in the std::vector are finite.
 *
 * @tparam T_y type of elements in the std::vector
 *
 * @param function name of function (for error messages)
 * @param name variable name (for error messages)
 * @param y std::vector to test
 * @return true if all values are finite
 **/
template <typename T_y, require_not_stan_scalar_t<T_y>* = nullptr>
inline void check_finite(const char* function, const char* name,
                         const std::vector<T_y>& y) {
  for (size_t n = 0; n < stan::math::size(y); n++) {
    if (!internal::is_finite(stan::get(y, n))) {
      throw_domain_error(function, name, "", "", "is not finite!");
    }
  }
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>