text:
// __BEGIN_LICENSE__
//  Copyright (c) 2006-2013, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is 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.
// __END_LICENSE__

/// tiles2plate.cc
///
/// Converts a nested set of directories and tiles to a plate file.

#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Plate/PlateFile.h>

using namespace vw;
using namespace vw::platefile;

#include <boost/program_options.hpp>
#include <boost/filesystem/path.hpp>
namespace po = boost::program_options;
namespace fs = boost::filesystem;

struct TileLocation {
  fs::path m_path;
  int32 m_col, m_row, m_level;

  TileLocation(const fs::path &path, int32 col = -1, int32 row = -1, int32 level = -1)
    : m_path(path), m_col(col), m_row(row), m_level(level)
  { }

  inline bool valid() {
    return ( (m_row != -1 && m_col != -1 && m_level != -1) &&
             fs::exists(m_path) );
  }
};

class TilePathDecoder {
public:
  TilePathDecoder() {}
  virtual ~TilePathDecoder() {}
  virtual TileLocation decode( const fs::path &path ) = 0;
};

class ToastDecoder : public TilePathDecoder {
  fs::path m_base_path;

public:
  ToastDecoder( fs::path & base_path )
    : m_base_path(base_path) { }
  virtual ~ToastDecoder() { }

  virtual TileLocation decode( const fs::path &full_path ) {
    fs::path partial_path(full_path.string().substr(m_base_path.string().length() + 1));
    TileLocation t(full_path);

    partial_path.replace_extension();
    //std::cout << partial_path << std::endl;
    for( fs::path::iterator itr = partial_path.begin();
         itr != partial_path.end();
         ++itr ) {
      std::istringstream in(itr->string());
      t.m_level = t.m_col;
      t.m_col = t.m_row;
      if ( !(in >> t.m_row) )
        t.m_row = -1;
    }

    return t;
  }
};

class GigapanDecoder : public TilePathDecoder {
public:
  GigapanDecoder() {}
  virtual ~GigapanDecoder() {}

  virtual TileLocation decode( const fs::path &full_path ) {
    TileLocation t(full_path);
    if( full_path.extension() == ".info" )
      return t;

    std::string tile_name = fs::path(full_path).replace_extension().filename().string();

    if( tile_name[0] != 'r' )
      return t;

    tile_name.erase(0, 1);

    t.m_level = boost::numeric_cast<int32>(tile_name.length());
    if(t.m_level == 0) {
      t.m_row = t.m_col = 0;
      return t;
    }

    int32 col = 0, row = 0;
    for( std::string::iterator itr = tile_name.begin();
         itr != tile_name.end();
         ++itr ) {
      row <<= 1; col <<= 1;

      switch( *itr ) {
      case '0':
        break;
      case '1':
        col |= 1;
        break;
      case '2':
        row |= 1;
        break;
      case '3':
        row |= 1;
        col |= 1;
        break;
      default:
        return t;
      }
    }

    t.m_col = col;
    t.m_row = row;
    return t;
  }
};

class TileHandler {
public:
  TileHandler() {}
  virtual ~TileHandler() {}
  virtual bool operator() ( const TileLocation & tile ) = 0;
};

class FirstHandler : public TileHandler {
  fs::path m_path;
  bool m_have_path;

public:
  FirstHandler() : m_have_path(false) {}
  virtual ~FirstHandler() {}
  virtual bool operator() ( const TileLocation & tile ) {
    m_path = tile.m_path;
    m_have_path = true;
    return false;
  }
  bool have_path() { return m_have_path; }
  fs::path get_path() { return m_path; }
};

template <class ViewT>
class PlateHandler : public TileHandler {
  boost::shared_ptr<PlateFile> m_platefile;

public:
  PlateHandler( boost::shared_ptr<PlateFile> &platefile )
    : m_platefile(platefile) {}
  virtual ~PlateHandler() {}

  virtual bool operator() ( const TileLocation &tile ) {
    ViewT image(tile.m_path.string());
    std::cout << "\t--> Writing tile [ "
              << tile.m_col << " " << tile.m_row << " " << tile.m_level << " ] "
              << " (" << tile.m_path.filename() << ")"
              << std::endl;
    m_platefile->write_request();
    m_platefile->write_update(image, tile.m_col, tile.m_row, tile.m_level);
    m_platefile->write_complete();
    return true;
  }
};

template <class TileHandlerT>
void iterate_over_tiles( fs::path &dir_path,
                         boost::shared_ptr<TilePathDecoder> &decoder,
                         TileHandlerT &handler) {

  fs::recursive_directory_iterator end_itr;
  for( fs::recursive_directory_iterator itr( dir_path );
       itr != end_itr;
       ++itr )
  {
    if( fs::is_directory(itr->status()) )
      continue;

    TileLocation t = decoder->decode( itr->path() );
    if( t.valid() ) {
      if( !handler(t) ) return;
    }
  }
}

int main( int argc, char *argv[] ) {
  std::string tile_format;
  std::string output_file_name;
  std::string output_file_type;
  std::string tile_directory_name;

  po::options_description general_options("Turns tile trees into a plate file.\n\nGeneral Options");
  general_options.add_options()
    ("format,f", po::value<std::string>(&tile_format)->default_value("toast"), "Tile directory format: toast, gigapan")
    ("output-name,o", po::value<std::string>(&output_file_name), "Specify the output plate file name.")
    ("file-type", po::value<std::string>(&output_file_type), "Output file type (png is used by default)")
    ("help,h", "Display this help message");

  po::options_description hidden_options("");
  hidden_options.add_options()
    ("tile-directory", po::value<std::string>(&tile_directory_name));

  po::options_description options("Allowed Options");
  options.add(general_options).add(hidden_options);

  po::positional_options_description p;
  p.add("tile-directory", 1);

  std::ostringstream usage;
  usage << "Usage: " << argv[0] << " [options] <tile_directory>" << std::endl << std::endl
        << general_options << std::endl;

  po::variables_map vm;
  try {
    po::store( po::command_line_parser( argc, argv ).options(options).positional(p).run(), vm );
    po::notify( vm );
  } catch (const po::error& e) {
    std::cout << "An error occurred while parsing command line options.\n\n";
    std::cout << usage.str();
  }

  if( vm.count("help") ) {
    std::cout << usage.str();
    return 0;
  }

  if( tile_format != "toast" && tile_format != "gigapan" ) {
    vw_throw(ArgumentErr() << "Unknown fromat passed in using --format: " << tile_format);
  }

  if( vm.count("tile-directory") != 1 ) {
    std::cerr << "Error: must specify an input tile directory!" << std::endl << std::endl
              << usage.str();
    return 1;
  }

  if( !fs::exists(tile_directory_name) ) {
    std::cerr << "Error: input tile directory does not exist!" << std::endl << std::endl
              << usage.str();
    return 1;
  }

  fs::path tile_directory( tile_directory_name );

  if( !vm.count("output-name") ) {
    output_file_name = fs::path( tile_directory ).replace_extension("plate").string();
  }

  std::cout << "Reading tiles in '" << tile_format << "' format"
            << " from " << tile_directory_name
            << " into " << output_file_name << std::endl;

  boost::shared_ptr<TilePathDecoder> decoder;
  if ( tile_format == "toast" )
    decoder = boost::shared_ptr<TilePathDecoder>( new ToastDecoder(tile_directory) );
  else {
    decoder = boost::shared_ptr<TilePathDecoder>( new GigapanDecoder() );
  }

  FirstHandler first_handler;
  iterate_over_tiles( tile_directory, decoder, first_handler );

  if ( !first_handler.have_path() ) {
    std::cerr << "Error: no tiles in tile directory matching " << tile_format << " tile scheme!"
             << std::endl << std::endl
             << usage.str();
    return 1;
  }

  SrcImageResource *rsrc = DiskImageResource::open(first_handler.get_path().string());
  PixelFormatEnum pixel_format = rsrc->pixel_format();
  ChannelTypeEnum channel_type = rsrc->channel_type();
  int32 tile_size = rsrc->rows();

  if (pixel_format == VW_PIXEL_GRAY)
    pixel_format = VW_PIXEL_GRAYA;
  if (pixel_format == VW_PIXEL_RGB)
    pixel_format = VW_PIXEL_RGBA;
  delete rsrc;

  if( !vm.count("file-type") ) {
    if (channel_type == VW_CHANNEL_FLOAT32)
      output_file_type = "tif";
    else
      output_file_type = "png";
  }

  try {
    std::cout << "Opening plate file: " << output_file_name << std::endl;
    boost::shared_ptr<PlateFile> platefile =
      boost::shared_ptr<PlateFile>( new PlateFile(output_file_name, "gigapan", "",
                                                  tile_size, output_file_type,
                                                  pixel_format, channel_type) );

    std::vector<TileHeader> empty_tile_list;
    platefile->transaction_begin("Writing tiles from tile tree " + tile_directory_name, -1);

    switch(pixel_format) {
    case VW_PIXEL_GRAY:
      switch(channel_type) {
      case VW_CHANNEL_UINT8: {
          PlateHandler<DiskImageView<PixelGray<uint8> > > plate_handler(platefile);
          iterate_over_tiles( tile_directory, decoder, plate_handler );
        }
        break;
      case VW_CHANNEL_FLOAT32: {
          PlateHandler<DiskImageView<PixelGray<float> > > plate_handler(platefile);
          iterate_over_tiles( tile_directory, decoder, plate_handler );
        }
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by tiles2plate.\n");
      }
      break;

    case VW_PIXEL_GRAYA:
      switch(channel_type) {
      case VW_CHANNEL_UINT8: {
          PlateHandler<DiskImageView<PixelGrayA<uint8> > > plate_handler(platefile);
          iterate_over_tiles( tile_directory, decoder, plate_handler );
        }
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by tiles2plate.\n");
      }
      break;

    case VW_PIXEL_RGB:
      switch(channel_type) {
      case VW_CHANNEL_UINT8: {
          PlateHandler<DiskImageView<PixelRGB<uint8> > > plate_handler(platefile);
          iterate_over_tiles( tile_directory, decoder, plate_handler );
        }
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by tiles2plate.\n");
      }
      break;

    case VW_PIXEL_RGBA:
      switch(channel_type) {
      case VW_CHANNEL_UINT8: {
          PlateHandler<DiskImageView<PixelRGBA<uint8> > > plate_handler(platefile);
          iterate_over_tiles( tile_directory, decoder, plate_handler );
        }
        break;
      default:
        vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by tiles2plate.\n");
      }
      break;

    default:
      vw_throw(ArgumentErr() << "Platefile contains a pixel type not supported by tiles2plate.\n");
    }

    // update_read_cursor == true below.
    platefile->transaction_end( true );
  } catch (const vw::Exception& e) {
    std::cout << "An error occurred: " << e.what() << "\nExiting\n\n";
    return 1;
  }

  return 0;
}

ext: cc


text:
#include "args.h"
#include "os.h"
#include "util.h"
#include "version.h"

#include <fstream>

#include <boost/assign.hpp>

using namespace std;

DEFINE_bool(report, true, "Attempt to report errors");

namespace Glorp {
  string writeDebug() {
    string writedest = directoryTempfile();

    ofstream ofs(writedest.c_str());
    if(!ofs)
      return "";

    deque<string> &debuglog = debugLog();
    for(int i = 0; i < debuglog.size(); i++) {
      while(debuglog[i].size() && debuglog[i][debuglog[i].size() - 1] == '\n')
        debuglog[i].erase(debuglog[i].begin() + debuglog[i].size() - 1);

      ofs << debugLog()[i] << '\n';
    }

    if(ofs)
      return writedest;
    else
      return "";
  };

  void Prepare911(const char *crashfname, int crashline, const char *message) {
    if(FLAGS_report) {
      string fname = writeDebug();
      if(!fname.size()) {
        dprintf("Failed to write file, aborting with a vengeance\n");
        return; // welp
      } else {
        dprintf("Wrote debug dump to %s\n", fname.c_str());
      }

      if(!message)
      {
        message = "";
      }

      vector<string> params;
      boost::assign::push_back(params)("--report_send")("--reporter_dumpfile=" + fname)("--reporter_version=" + string(Version::gameSlug) + "-" + Version::gameVersion + "-" + Version::gamePlatform)("--reporter_file=" + std::string(crashfname))("--reporter_line=" + Format("%d", crashline))("--reporter_exesize=" + Format("%d", exeSize()));
      spawn(exeName(), params);
      sleep(1000);
    }
  };
}

ext: cpp

max_stars_repo_name: zorbathut/glorp

max_issues_repo_name: zorbathut/glorp

max_forks_repo_name: zorbathut/glorp


text:
#include "lue/utility/metadata.hpp"
#include "lue/core/aspect.hpp"
#include <boost/filesystem.hpp>
#include <fmt/format.h>
#include <exception>

namespace lue {
namespace utility {
namespace json {

bool has_key(
    JSON const& object,
    std::string const& name)
{
    return !object.is_null() && object.find(name) != object.end();
}

bool has_key(
    JSON const& object,
    JSONPointer const& pointer)
{
    return !object.is_null() && ! object.value(pointer, JSON()).is_null();
}

void assert_has_key(
    JSON const& object,
    std::string const& name)
{
    if(!has_key(object, name)) {
        throw std::runtime_error(fmt::format(
            "JSON object does not contain key {}",
            name));
    }
}

void assert_has_key(
    JSON const& object,
    JSONPointer const& pointer)
{
    if(!has_key(object, pointer)) {
        throw std::runtime_error(fmt::format(
            "JSON object does not contain key {}",
            std::string(pointer)));
    }
}

JSON object(
    JSON const& object,
    std::string const& name)
{
    assert_has_key(object, name);

    return object[name];
}

JSON object(
    JSON const& object,
    JSONPointer const& pointer)
{
    assert_has_key(object, pointer);

    return object[pointer];
}

/*!
    @brief      Find object in list
    @param      object Object to query
    @param      pointer Pointer to list
    @param      key Name of element to query
    @param      value Value of element to compare
    @exception  std::runtime_error In case the object cannot be found
*/
JSON object(
    JSON const& object,
    JSONPointer const& pointer,
    std::string const& key,
    std::string const& value)
{
    assert_has_key(object, pointer);

    auto const& list_json = json::object(object, pointer);
    auto const object_json_it = json::find(list_json, key, value);

    if(object_json_it == list_json.end()) {
        throw std::runtime_error(fmt::format(
            "No object whose key {} equals {} exists at {}",
            key, value, std::string(pointer)));

    }

    return *object_json_it;
}

std::string string(
    JSON const& object,
    std::string const& name)
{
    return json::object(object, name);
}

std::string string(
    JSON const& object,
    JSONPointer const& pointer)
{
    return json::object(object, pointer);
}

bool boolean(
    JSON const& object,
    JSONPointer const& pointer)
{
    return json::object(object, pointer);
}

JSONPointer pointer(
    JSON const& object,
    std::string const& name)
{
    return JSONPointer(string(object, name));
}

/*!
    @brief      Find an object in a list of objects
    @param      object List object to search
    @param      key Name of element to check
    @param      value Value of element to find
*/
JSONCIterator find(
    JSON const& object,
    std::string const& key,
    std::string const& value)
{
    JSONCIterator it;

    for(it = object.begin(); it != object.end(); ++it) {
        // The key must exist.
        assert_has_key(*it, key);

        if(json::string((*it), key) == value) {
            break;
        }
    }

    return it;
}

data_model::Clock clock(
    JSON const& object)
{
    return data_model::Clock{
        object.at("unit"),
        object.at("nr_units")
    };
}

}  // namespace json

/*!
    @brief      Construct an instance given a pathname to a file containing
                metadata items
    @exception  std::runtime_error In case the file does not exist
*/
Metadata::Metadata(
    std::string const& pathname)

    : _json()

{
    namespace bfs = boost::filesystem;

    if(!bfs::exists(pathname)) {
        throw std::runtime_error(fmt::format(
            "File containing metadata ({}) does not exist",
            pathname));
    }

    std::ifstream(pathname) >> _json;
}

/*!
    @brief      Construct an instance given an input stream containing
                metadata items
*/
Metadata::Metadata(
    std::istream& stream)

    : _json()

{
    stream >> _json;
}

JSON const& Metadata::object() const
{
    return _json;
}

std::string Metadata::string(
    JSONPointer const& pointer,
    std::string const& default_value) const
{
    return json::has_key(_json, pointer)
        ? json::string(_json, pointer)
        : default_value;
}

bool Metadata::boolean(
    JSONPointer const& pointer,
    bool const default_value) const
{
    return json::has_key(_json, pointer)
        ? json::boolean(_json, pointer)
        : default_value;
}

std::string Metadata::string(
    std::string const& list_name,
    std::string const& key,
    std::string const& value,
    JSONPointer const& pointer,
    std::string const& default_value) const
{
    std::string result = default_value;

    // Check whether a json element with the name of the list to search
    // exists.
    if(json::has_key(_json, list_name)) {
        // Obtain the object that should be the list.
        auto const list_json = json::object(_json, list_name);

        // Find the object that contains an element with a (key, value).
        auto const object_json_it = json::find(list_json, key, value);

        if(object_json_it != list_json.end()) {
            auto const& object_json = *object_json_it;

            // Find the string pointed to by the pointer.
            if(json::has_key(object_json, pointer)) {
                result = json::string(object_json, pointer);
            }
        }
    }

    return result;
}

std::string Metadata::string(
    std::string const& list_name,
    std::string const& key,
    std::string const& value,
    JSONPointer const& pointer,
    std::string const& value_key,
    std::string const& default_value) const
{
    std::string result = default_value;

    // Check whether a json element with the name of the list to search
    // exists.
    if(json::has_key(_json, list_name)) {
        // Obtain the object that should be the list.
        auto const list_json = json::object(_json, list_name);

        // Find the object that contains an element with a (key, value).
        auto const object_json_it = json::find(list_json, key, value);

        if(object_json_it != list_json.end()) {
            auto const& object_json = *object_json_it;

            // Find the string pointed to by the pointer.
            if(json::has_key(object_json, pointer)) {

                auto const& object2_json = json::object(object_json, pointer);

                if(json::has_key(object2_json, value_key)) {
                    result = json::string(object2_json, value_key);
                }
            }
        }
    }

    return result;
}

}  // namespace utility

namespace data_model {
namespace time {

void from_json(
    utility::JSON const& object,
    Unit& unit)
{
    unit = string_to_aspect<Unit>(object.get<std::string>());
    // unit = string_to_unit(object.get<std::string>());
}

}  // namespace data_model
}  // namespace time

}  // namespace lue

max_stars_repo_name: OliverSchmitz/lue

max_issues_repo_name: OliverSchmitz/lue

max_forks_repo_name: OliverSchmitz/lue


text:
/*
 * Copyright (C) 2013-2014, The OpenFlint Open Source Project
 *
 * 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 <sstream>

#include <boost/bind.hpp>

#include "TCPServer.h"
#include "utils/Logging.h"

namespace flint {

TCPServer::TCPServer(boost::asio::io_service &ioService, int port) :
		IServer(), ioService_(ioService), acceptor_(ioService,
				boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(),
						port)) {
	acceptor_.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
}

TCPServer::~TCPServer() {
}

void TCPServer::onStart() {
	async_accept();
	LOG_WARN << "TCPServer is running!";
}

void TCPServer::onStop() {
	acceptor_.close();
	LOG_WARN << "TCPServer is stopped!";
}

void TCPServer::async_accept() {
	sock_ptr sock(new boost::asio::ip::tcp::socket(ioService_));
	acceptor_.async_accept(*sock,
			boost::bind(&TCPServer::accept_handler, this, sock,
					boost::asio::placeholders::error));
}

void TCPServer::accept_handler(sock_ptr sock, boost::system::error_code ec) {
	if (isRunning()) {
		std::stringstream ss;
		ss << sock->remote_endpoint().address().to_string();
		ss << ":";
		ss << sock->remote_endpoint().port();
		std::string addr = ss.str();
		LOG_INFO << "accept new connection -> " << addr;
		TcpConnection(new TCPSession(ioService_, sock, addr));
		async_accept();
	} else {
		LOG_DEBUG << "TCP server is not running, stop accept!";
	}
}

TCPSession::TCPSession(boost::asio::io_service &io_service, sock_ptr sock,
		const std::string &addr) :
		ioService_(io_service), socket_(sock), addr_(addr) {
	start();
}

TCPSession::~TCPSession() {
	LOG_DEBUG << "~TCPSession()";
}

void TCPSession::start() {
	read();
}

void TCPSession::send(const std::string &message) {
	socket_->async_send(boost::asio::buffer(message),
			boost::bind(&TCPSession::handle_send, this,
					boost::asio::placeholders::error,
					boost::asio::placeholders::bytes_transferred));
}

void TCPSession::handle_send(const boost::system::error_code& error,
		std::size_t bytes_transferred) {
	if (error) {
		LOG_ERROR << "send error";
	} else {
		LOG_DEBUG << "send success";
	}
}

void TCPSession::read() {
	socket_->async_receive(boost::asio::buffer(read_buffer_),
			boost::bind(&TCPSession::handle_read, this,
					boost::asio::placeholders::error,
					boost::asio::placeholders::bytes_transferred));
}

void TCPSession::handle_read(const boost::system::error_code& error,
		std::size_t len) {
	if (!error || error == boost::asio::error::message_size) {
		if (len > 0) {
			std::string message;
			message.assign(read_buffer_.data(), len);
			LOG_INFO << "received: \n" << message;
//			send("from test server!");
			Message(message);
			read();
		} else {
			// TODO: client closed???
			LOG_WARN << "read null data, client maybe closed!!! close session";
			onClose();
		}
	} else {
		// TODO: client closed???
		LOG_ERROR << "read error, client maybe closed!!! close session";
		onClose();
	}
}

void TCPSession::close() {
	try {
		socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
		socket_->close();
	} catch (std::exception &e) {
		LOG_ERROR << "TCP session catch: " << e.what();
	}
}

void TCPSession::onClose() {
	LOG_DEBUG << "TCP session close!";

	try {
		socket_->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
		socket_->close();
	} catch (std::exception &e) {
		LOG_ERROR << "TCP session catch: " << e.what();
	}

	Close();

	LOG_DEBUG << "TCP session delete!";
	delete this;
}

const std::string &TCPSession::getAddr() {
	return addr_;
}

} /* namespace flint */

max_stars_repo_name: jsli/flingd-cc


text:
// Copyright (c) 2020 The Picacoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
#include <random.h>
#include <uint256.h>
#include <consensus/validation.h>
#include <sync.h>
#include <test/util/setup_common.h>
#include <validation.h>

#include <vector>

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(validation_chainstate_tests, TestingSetup)

//! Test resizing coins-related CChainState caches during runtime.
//!
BOOST_AUTO_TEST_CASE(validation_chainstate_resize_caches)
{
    ChainstateManager manager;
    CTxMemPool mempool;

    //! Create and add a Coin with DynamicMemoryUsage of 80 bytes to the given view.
    auto add_coin = [](CCoinsViewCache& coins_view) -> COutPoint {
        Coin newcoin;
        uint256 txid = InsecureRand256();
        COutPoint outp{txid, 0};
        newcoin.nHeight = 1;
        newcoin.out.nValue = InsecureRand32();
        newcoin.out.scriptPubKey.assign((uint32_t)56, 1);
        coins_view.AddCoin(outp, std::move(newcoin), false);

        return outp;
    };

    CChainState& c1 = WITH_LOCK(cs_main, return manager.InitializeChainstate(mempool));
    c1.InitCoinsDB(
        /* cache_size_bytes */ 1 << 23, /* in_memory */ true, /* should_wipe */ false);
    WITH_LOCK(::cs_main, c1.InitCoinsCache(1 << 23));

    // Add a coin to the in-memory cache, upsize once, then downsize.
    {
        LOCK(::cs_main);
        auto outpoint = add_coin(c1.CoinsTip());

        // Set a meaningless bestblock value in the coinsview cache - otherwise we won't
        // flush during ResizecoinsCaches() and will subsequently hit an assertion.
        c1.CoinsTip().SetBestBlock(InsecureRand256());

        BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));

        c1.ResizeCoinsCaches(
            1 << 24,  // upsizing the coinsview cache
            1 << 22  // downsizing the coinsdb cache
        );

        // View should still have the coin cached, since we haven't destructed the cache on upsize.
        BOOST_CHECK(c1.CoinsTip().HaveCoinInCache(outpoint));

        c1.ResizeCoinsCaches(
            1 << 22,  // downsizing the coinsview cache
            1 << 23  // upsizing the coinsdb cache
        );

        // The view cache should be empty since we had to destruct to downsize.
        BOOST_CHECK(!c1.CoinsTip().HaveCoinInCache(outpoint));
    }

    // Avoid triggering the address sanitizer.
    WITH_LOCK(::cs_main, manager.Unload());
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: picacoin/picacoin

max_issues_repo_name: picacoin/picacoin

max_forks_repo_name: picacoin/picacoin


text:
/*! \file  1d_tests.cpp
  \brief Test of SVG 1D plot
  \author Jacob Voytko & Paul A. Bristow
*/

// Copyright Jacob Voytko 2007
// Copyright Paul A. Bristow 2013, 2020

// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#define BOOST_TEST_MAIN
// Must come BEFORE this include.
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>

#include <boost/svg_plot/svg_1d_plot.hpp>
  using namespace boost::svg;
#include <boost/svg_plot/svg_fwd.hpp> // forward declarations.
// Included only to check its validity.

#include <iostream>
  using std::cout;
  using std::endl;
#include <string>
  using std::string;

#include <limits>

constexpr static double few_eps = std::numeric_limits<double>::epsilon() * 5;
// using
//enum place
//{
//  left_side = -1,
//  on_axis = 0,
//  right_side = +1,
//  bottom_side = -1,
//  top_side = +1,
//};

BOOST_AUTO_TEST_CASE( test1 )
{
  // Check on default values and all set and get functions.
  // (Note: changes to default will mean tests must change too!)
  // Note that constants for comparison must be exactly the right type.
  // to avoid a warning from within Boost.Test.
  // use of unsigned int means that test value must also be unsigned,
  // for example 12U rather 12,
  // double must be 1. rather than 1...

  // Test the text_element class.
  // text_element::text_element(double x, double y,
  //  const std::string&,
  //  int,
  //  const std::string& font,
  //  const std::string& style, const std::string& weight,
  //  const std::string& stretch, const std::string& decoration,
  //  int align, int rotate);

  BOOST_TEST_MESSAGE("SVG 1D Test");

  text_element text;
  BOOST_CHECK_EQUAL(text.x(), 0);
  text.x(10);
  BOOST_CHECK_EQUAL(text.x(), 10);
  BOOST_CHECK_EQUAL(text.y(), 0);
  text.y(20);
  BOOST_CHECK_EQUAL(text.y(), 20);

  BOOST_CHECK_EQUAL(text.text(), "");
  text.text("X");
  BOOST_CHECK_EQUAL(text.text(), "X");

  BOOST_CHECK_EQUAL(text.textstyle().font_size(), 12);
  text.textstyle().font_size(10);
  BOOST_CHECK_EQUAL(text.textstyle().font_size(), 10);

  BOOST_CHECK_EQUAL(text.textstyle().font_family(), "Lucida Sans Unicode");

  text.textstyle().font_family("Verdana");
  BOOST_CHECK_EQUAL(text.textstyle().font_family(), "Verdana");

  BOOST_CHECK_EQUAL(text.textstyle().font_style(), "");
  text.textstyle().font_style("X");
  BOOST_CHECK_EQUAL(text.textstyle().font_style(), "X");

  BOOST_CHECK_EQUAL(text.textstyle().font_weight(), "");
  text.textstyle().font_weight("X");
  BOOST_CHECK_EQUAL(text.textstyle().font_weight(), "X");

  BOOST_CHECK_EQUAL(text.textstyle().font_stretch(), "");
  text.textstyle().font_stretch("X");
  BOOST_CHECK_EQUAL(text.textstyle().font_stretch(), "X");

  BOOST_CHECK_EQUAL(text.textstyle().font_decoration(), "");
  text.textstyle().font_decoration("X");
  BOOST_CHECK_EQUAL(text.textstyle().font_decoration(), "X");

  double boost::svg::string_svg_length(const std::string& s, const text_style& style);

  text_style t(1); // font size / aspect_ratio = unity for tests.
  // double aspect_ratio = 0.7; declared in svg_style.hpp

  using boost::svg::string_svg_length;
  double boost::svg::string_svg_length(const std::string& s, const text_style& style);

  const string s0("");
  double l = string_svg_length(s0, t);
  BOOST_CHECK_EQUAL(l, 0);
  const string s1("1");
  BOOST_CHECK_EQUAL(string_svg_length(s1, t) /aspect_ratio, 1);

  string s10("1234567890");
  l = string_svg_length(s10, t);
   BOOST_CHECK_CLOSE_FRACTION(l / aspect_ratio, 10, few_eps); // Normal chars
  const string g1("±"); // One greek.
  BOOST_CHECK_EQUAL(string_svg_length(g1, t)/ aspect_ratio, 1);
   const string g2("√±"); // 2 greek only.
  l = string_svg_length(g2, t);
  BOOST_CHECK_EQUAL( l / aspect_ratio, 2);
  const string g3("√ ±"); // 2 greek plus a space.
  const string x0("<>");
  BOOST_CHECK_EQUAL( string_svg_length(x0, t)/ aspect_ratio, 0);
  const string xn("<    >"); // Should ignore all inside.
  BOOST_CHECK_EQUAL( string_svg_length(xn, t)/ aspect_ratio, 0);

  const std::string s = "Demo 1D plot <sup>-α </sup> Ω Φ √ ∞ ζ ±";
  BOOST_CHECK_EQUAL( boost::svg::string_svg_length(s, t)/ aspect_ratio, 28);

  // Test the svg_element class.

  svg_1d_plot my_plot;
  // Check the default image sizes:
  BOOST_CHECK_EQUAL(my_plot.x_size(), 500U);
  BOOST_CHECK_EQUAL(my_plot.y_size(), 200U);

  my_plot.size(200U, 100U);
  BOOST_CHECK_EQUAL(my_plot.x_size(), 200U);
  my_plot.size(500U, 100U); // update x
  BOOST_CHECK_EQUAL(my_plot.x_size(), 500U); // & check
  my_plot.size(500U, 300U); // update y
  BOOST_CHECK_EQUAL(my_plot.y_size(), 300U); // & check

  // cout <<  my_plot.x_size() << endl; // 500
  BOOST_CHECK_EQUAL(my_plot.x_size(), 500U);
 // Check that test really works by checking the wrong answer!
//  BOOST_CHECK_EQUAL(my_plot.x_size(), 400U);
 // // check my_plot.x_size() == 400U failed [500 != 400]

  std::pair<double, double> const def(-1., -1.); // needs operator<<
  std::pair<double, double> tl(my_plot.legend_top_left()); //

  BOOST_CHECK_EQUAL(tl.first, def.first); // default position unassigned = -1..
  BOOST_CHECK_EQUAL(tl.second, def.second); // default position unassigned = -1..
  my_plot.legend_top_left(10., 20.);
  std::pair<double, double> tl2(my_plot.legend_top_left()); //
  BOOST_CHECK_EQUAL(tl2.first, 10.);
  BOOST_CHECK_EQUAL(tl2.second, 20.);

  BOOST_CHECK_EQUAL(my_plot.title(), ""); // Default NO title of plot.
  my_plot.title("test title");
  BOOST_CHECK_EQUAL(my_plot.title(), "test title");

  BOOST_CHECK_EQUAL(my_plot.legend_title(), ""); // Default no legend title.
  my_plot.legend_title("");
  BOOST_CHECK_EQUAL(my_plot.legend_title(), "");

  BOOST_CHECK_EQUAL(my_plot.document_title(), ""); // Default no document title
  my_plot.document_title("Document Title");
  BOOST_CHECK_EQUAL(my_plot.document_title(), "Document Title");

  BOOST_CHECK_EQUAL(my_plot.description(), ""); // Default no document description.
  my_plot.description("Document Description");
  BOOST_CHECK_EQUAL(my_plot.description(), "Document Description");

  BOOST_CHECK_EQUAL(my_plot.copyright_holder(), ""); // Default no copyright_holder.
  my_plot.copyright_holder("Jake Voytko");
  BOOST_CHECK_EQUAL(my_plot.copyright_holder(), "Jake Voytko");

  BOOST_CHECK_EQUAL(my_plot.copyright_date(), ""); // Default no copyright_date.
  my_plot.copyright_date("2007");
  BOOST_CHECK_EQUAL(my_plot.copyright_date(), "2007");

  // Plot Title & font.

   BOOST_CHECK_EQUAL(my_plot.title_font_family(), "Verdana");// Check default.
  my_plot.title_font_family("Times New Roman"); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_family(),"Times New Roman"); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_font_style(), ""); // Check default.
  my_plot.title_font_style("bold"); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_style(), "bold"); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_font_weight(), ""); // Check default.
  my_plot.title_font_weight("400"); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_weight(), "400"); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_font_stretch(), ""); // Check default.
  my_plot.title_font_stretch("wider"); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_stretch(), "wider"); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_font_decoration(), ""); // Check default.
  my_plot.title_font_decoration("underline"); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_decoration(), "underline"); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_font_rotation(), 0);// Check default.
  my_plot.title_font_rotation(uphill); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_rotation(), uphill); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_font_alignment(), align_style::center_align);// Check default.
  my_plot.title_font_alignment(align_style::left_align); // Set
   BOOST_CHECK_EQUAL(my_plot.title_font_alignment(), align_style::left_align); // & check.

  // legend title & font

   BOOST_CHECK_EQUAL(my_plot.legend_on(), false); // Check default.
  my_plot.legend_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.legend_on(), true); // & check.

  BOOST_CHECK_EQUAL(my_plot.legend_title_font_size(), 14U);// Check default.
  my_plot.legend_title_font_size(15); // Set
   BOOST_CHECK_EQUAL(my_plot.legend_title_font_size(), 15U); // & check.

   BOOST_CHECK_EQUAL(my_plot.plot_window_on(), true); // Check default.
  my_plot.plot_window_on(false); // Set
   BOOST_CHECK_EQUAL(my_plot.plot_window_on(), false); // & check.

  BOOST_CHECK_EQUAL(my_plot.x_ticks_up_on(), false); // Check default.
  my_plot.x_ticks_up_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.x_ticks_up_on(), true); // & check.

  BOOST_CHECK_EQUAL(my_plot.x_ticks_down_on(), true); // Check default.
  my_plot.x_ticks_down_on(false); // Set
   BOOST_CHECK_EQUAL(my_plot.x_ticks_down_on(), false); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_label_on(), true); // Check default.
  my_plot.x_label_on(false); // Set false // & check.

   BOOST_CHECK_EQUAL(my_plot.x_label_units_on(), false); // Check default.
  my_plot.x_label_units_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.x_label_units_on(), true); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_labels_side(), boost::svg::left_side); // Check default.
  my_plot.x_major_labels_side(0); // Set
   BOOST_CHECK_EQUAL(my_plot.x_major_labels_side(), boost::svg::none); // & check.
  my_plot.x_major_labels_side(+1); // Set
   BOOST_CHECK_EQUAL(my_plot.x_major_labels_side(), boost::svg::right_side); // & check.

   BOOST_CHECK_EQUAL(my_plot.title_on(), true); // Check default.
  my_plot.title_on(false); // Set
   BOOST_CHECK_EQUAL(my_plot.title_on(), false); // & check.
   BOOST_CHECK_EQUAL(my_plot.title_on(), false); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_grid_on(), false); // Check default.
  my_plot.x_major_grid_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.x_major_grid_on(), true); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_minor_grid_on(), false); // Check default.
  my_plot.x_minor_grid_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.x_minor_grid_on(), true); // & check.

  // Varies for 1D and 2D
  BOOST_CHECK_EQUAL(my_plot.axes_on(), false); // Check default (only x for 1d).
  my_plot.axes_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.axes_on(), true); // & check.
  my_plot.axes_on(false); // Set false revert to default.

   BOOST_CHECK_EQUAL(my_plot.x_axis_on(), false); // & check.
  my_plot.x_axis_on(true); // Set
   BOOST_CHECK_EQUAL(my_plot.x_axis_on(), true); // & check.

  BOOST_CHECK_EQUAL(my_plot.y_axis_on(), false); // Check default.
  my_plot.y_axis_on(true); // But leave false - as always should be for 1D?
   BOOST_CHECK_EQUAL(my_plot.y_axis_on(), true); // & check.
  my_plot.y_axis_on(false); // Set
   BOOST_CHECK_EQUAL(my_plot.y_axis_on(), false); // & check.

   BOOST_CHECK_EQUAL(my_plot.axes_on(), false); //
  my_plot.axes_on(true); //
   BOOST_CHECK_EQUAL(my_plot.axes_on(), true); // Only x axis on
  my_plot.axes_on(false); // Both on
   BOOST_CHECK_EQUAL(my_plot.axes_on(), false); //

  // ticks left and right only for 2-D

  my_plot.y_axis_on(false); // But leave false - as always should be for 1D?

   BOOST_CHECK_EQUAL(svg_color(red), svg_color(red)); // OK
  // But problem when try to check that svg_color is blank!
   //BOOST_CHECK_EQUAL(svg_color(blank), false); // check svg_color(blank) == false failed [blank != false]
   BOOST_CHECK_EQUAL(svg_color(blank), svg_color(255, 255, 255)); // but this is OK.

   //BOOST_CHECK_EQUAL(my_plot.title_color(), svg_color(blank)); //  Check default color is blank.
  // check my_plot.title_color() == svg_color(blank) failed [blank != blank]
   BOOST_CHECK_EQUAL(my_plot.title_color(), svg_color(255, 255, 255)); //  Check default color is blank.
  my_plot.title_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.title_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.background_color(), svg_color(255, 255, 255)); //  Check default color.
  my_plot.background_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.background_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.legend_background_color(), svg_color(255, 255, 255)); //  Check default color.
  my_plot.legend_background_color( svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.legend_background_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.legend_border_color(), svg_color(255, 255, 0)); //  Check default color.
  my_plot.legend_border_color( svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.legend_border_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.background_border_color(), svg_color(255,255,0)); //  Check default color.
  my_plot.background_border_color( svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.background_border_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.plot_background_color(), svg_color(255, 255, 255)); //  Check default color.
  my_plot.plot_background_color( svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.plot_background_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_axis_color(), svg_color(black)); //  Check default color.
  my_plot.x_axis_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.x_axis_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.y_axis_color(), svg_color(black)); //  Check default color.
  my_plot.y_axis_color( svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.y_axis_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_label_color(), svg_color(255, 255, 255)); //  Check default color.
  my_plot.x_label_color( svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.x_label_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.y_label_color(), svg_color(255, 255, 255)); //  Check default color.
  my_plot.y_label_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.y_label_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_tick_color(), svg_color(black)); //  Check default color.
  my_plot.x_major_tick_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.x_major_tick_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_minor_tick_color(), svg_color(black)); //  Check default color.
  my_plot.x_minor_tick_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.x_minor_tick_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_grid_color(), svg_color(200, 220, 255)); //  Check default color.
  my_plot.x_major_grid_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.x_major_grid_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_grid_width(), 1U); //  Check default width.
  my_plot.x_major_grid_width(10U); //
   BOOST_CHECK_EQUAL(my_plot.x_major_grid_width(), 10U); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_minor_grid_width(), 0.5); //  Check default width.
  my_plot.x_minor_grid_width(10); //
   BOOST_CHECK_EQUAL(my_plot.x_minor_grid_width(), 10); // & check.

  my_plot.x_minor_grid_color(svg_color(red)); //
   BOOST_CHECK_EQUAL(my_plot.x_minor_grid_color(), svg_color(red)); // & check.
   BOOST_CHECK_EQUAL(my_plot.x_minor_grid_color(), svg_color(red)); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_axis_width(), 1); //  Check default width.
  my_plot.x_axis_width(2); // change
   BOOST_CHECK_EQUAL(my_plot.x_axis_width(), 2); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_label(), ""); //  Check NO default label.
  my_plot.x_label("X Axis"); //
   BOOST_CHECK_EQUAL(my_plot.x_label(), "X Axis"); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_label_units(), ""); //  Check NO default label.
  my_plot.x_label_units(" (meter)"); //
   BOOST_CHECK_EQUAL(my_plot.x_label_units()," (meter)"); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_interval(), 2.); //  Check default.
  my_plot.x_major_interval(1.); //
   BOOST_CHECK_EQUAL(my_plot.x_major_interval(), 1.); // & check.

   BOOST_CHECK_EQUAL(my_plot.x_major_tick_length(), 5);
  my_plot.x_major_tick_length(10); //
   BOOST_CHECK_EQUAL(my_plot.x_major_tick_length(), 10);

   BOOST_CHECK_EQUAL(my_plot.x_major_tick_width(), 2);
  my_plot.x_major_tick_width(5); //
   BOOST_CHECK_EQUAL(my_plot.x_major_tick_width(), 5);

   BOOST_CHECK_EQUAL(my_plot.x_minor_tick_width(), 1);
  my_plot.x_minor_tick_width(5); //
   BOOST_CHECK_EQUAL(my_plot.x_minor_tick_width(), 5);

   BOOST_CHECK_EQUAL(my_plot.x_num_minor_ticks(), 4U);
  my_plot.x_num_minor_ticks(9U); //
   BOOST_CHECK_EQUAL(my_plot.x_num_minor_ticks(), 9U);

   BOOST_CHECK_EQUAL(my_plot.x_major_interval(), 1.);
  my_plot.x_major_interval(2.); //
   BOOST_CHECK_EQUAL(my_plot.x_major_interval(), 2.);

   BOOST_CHECK_EQUAL(my_plot.x_min(), -10.); //  Check default xmin.
   BOOST_CHECK_EQUAL(my_plot.x_max(), +10.); //  Check default xmax.
  my_plot.x_range(-1., +1.); //
   BOOST_CHECK_EQUAL(my_plot.x_min(), -1.); // & check.
   BOOST_CHECK_EQUAL(my_plot.x_max(), +1.); // & check.

  std::pair<double, double> r = my_plot.x_range();
   BOOST_CHECK_EQUAL(r.first, -1.); // & check.
   BOOST_CHECK_EQUAL(r.second, +1.); // & check.

  std::pair<double, double> xr = my_plot.x_range();
   BOOST_CHECK_EQUAL(xr.first, -1.); // & check.

   BOOST_CHECK_EQUAL(xr.second, +1.); // & check.

  const string style = "test_style.css";
  //my_plot.load_stylesheet(style); // TODO -  Error opening file test_style.css
  //BOOST_CHECK(validate_stylesheet(style));

  my_plot
  .background_border_color(svg_color(0, 0, 1))
  .background_color(svg_color(0, 0, 2))
  .legend_background_color(svg_color(0, 0, 3))
  .legend_border_color(svg_color(0, 0, 4))
  .plot_background_color(svg_color(0, 0, 5))
  .title_color(svg_color(0, 0, 6))
  .x_axis_color(svg_color(0, 0, 7))
  .x_label_color(svg_color(0, 0, 8))
  .x_major_grid_color(svg_color(0, 0, 9))
  .x_major_tick_color(svg_color(0, 0, 10))
  .x_minor_grid_color(svg_color(0, 0, 11))
  .x_minor_tick_color(svg_color(0, 0, 12));

  BOOST_CHECK(my_plot.background_border_color() == svg_color(0, 0, 1));
  BOOST_CHECK(my_plot.background_color() == svg_color(0, 0, 2));
  BOOST_CHECK(my_plot.legend_background_color() == svg_color(0, 0, 3));
  BOOST_CHECK(my_plot.legend_border_color() == svg_color(0, 0, 4));
  BOOST_CHECK(my_plot.plot_background_color() == svg_color(0, 0, 5));
  BOOST_CHECK(my_plot.title_color() == svg_color(0, 0, 6));
  BOOST_CHECK(my_plot.x_axis_color() == svg_color(0, 0, 7));
  BOOST_CHECK(my_plot.x_label_color() == svg_color(0, 0, 8));
  //BOOST_CHECK_EQUAL(svg_color(1, 1, 1), svg_color(0, 0, 0));
  // check svg_color(1, 1, 1) == svg_color(0, 0, 0) failed [RGB(1,1,1) != RGB(0,0,0)]

  BOOST_CHECK_EQUAL(red, red);  // OK
  // BOOST_CHECK_EQUAL(white, black);
  // check white == black failed [143 != 7]
  // Note that named colors are enums!

  BOOST_CHECK_EQUAL(svg_color(0, 0, 8), svg_color(0, 0, 8));
  BOOST_CHECK_EQUAL(my_plot.x_label_color(), svg_color(0, 0, 8));
  // using BOOST_CHECK_EQUAL is more convenient because it shows the difference!
  // provided operator== and operator >> is provided.

  BOOST_CHECK(my_plot.x_major_grid_color() == svg_color(0, 0, 9));
  BOOST_CHECK(my_plot.x_major_tick_color() == svg_color(0, 0, 10));
  BOOST_CHECK(my_plot.x_minor_grid_color() == svg_color(0, 0, 11));
  BOOST_CHECK(my_plot.x_minor_tick_color() == svg_color(0, 0, 12));

  // Repeat - intentional? - would different values be a better test?
  my_plot
  .x_minor_tick_color(svg_color(0, 0, 12))
  .x_minor_grid_color(svg_color(0, 0, 11))
  .x_major_tick_color(svg_color(0, 0, 10))
  .x_major_grid_color(svg_color(0, 0, 9))
  .x_label_color(svg_color(0, 0, 8))
  .x_axis_color(svg_color(0, 0, 7))
  .title_color(svg_color(0, 0, 6))
  .plot_background_color(svg_color(0, 0, 5))
  .legend_border_color(svg_color(0, 0, 4))
  .legend_background_color(svg_color(0, 0, 3))
  .background_color(svg_color(0, 0, 2))
  .background_border_color(svg_color(0, 0, 1));

  BOOST_CHECK(my_plot.x_minor_tick_color() == svg_color(0, 0, 12));
  BOOST_CHECK(my_plot.x_minor_grid_color() == svg_color(0, 0, 11));
  BOOST_CHECK(my_plot.x_major_tick_color() == svg_color(0, 0, 10));
  BOOST_CHECK(my_plot.x_major_grid_color() == svg_color(0, 0, 9));
  BOOST_CHECK(my_plot.x_label_color() == svg_color(0, 0, 8));
  BOOST_CHECK(my_plot.x_axis_color() == svg_color(0, 0, 7));
  BOOST_CHECK(my_plot.title_color() == svg_color(0, 0, 6));
  BOOST_CHECK(my_plot.plot_background_color() == svg_color(0, 0, 5));
  BOOST_CHECK(my_plot.legend_border_color() == svg_color(0, 0, 4));
  BOOST_CHECK(my_plot.legend_background_color() == svg_color(0, 0, 3));
  BOOST_CHECK(my_plot.background_color() == svg_color(0, 0, 2));
  BOOST_CHECK(my_plot.background_border_color() == svg_color(0, 0, 1));

} // BOOST_AUTO_TEST_CASE( test1 )

/*

Build started 20-Dec-2013 18:49:02.
InitializeBuildStatus:
  Creating "Release\1d_tests.unsuccessfulbuild" because "AlwaysCreate" was specified.
ClCompile:
  1d_tests.cpp
Link:
  Generating code
  Finished generating code
  1d_tests.vcxproj -> J:\Cpp\SVG\Release\1d_tests.exe
CustomBuildStep:
  Description: Autorun "J:\Cpp\SVG\Release\1d_tests.exe"
  Running 1 test case...
  Platform: Win32
  Compiler: Microsoft Visual C++ version 10.0
  STL     : Dinkumware standard library version 520
  Boost   : 1.55.0

  Test module "Master Test Suite" passed with:
    1 test case out of 1 passed
    182 assertions out of 182 passed

    Test case "test1" passed with:
      182 assertions out of 182 passed

FinalizeBuildStatus:
  Deleting file "Release\1d_tests.unsuccessfulbuild".
  Touching "Release\1d_tests.lastbuildstate".

Build succeeded.

Time Elapsed 00:00:06.88

*/


text:
// This file is part of:
// gnss-sim: A GNSS Signal Simulator
//
// Copyright (c) 2020 Damien Dusha
// SPDX-License-Identifier: MIT
//
// Derived from https://github.com/osqzss/gps-sdr-sim (MIT Licence):
// Copyright (c) 2015-2020 Takuji Ebinuma

#include "geodesy.h"
#include "gpssim.h"
#include "gps_math.h"

#include <Eigen/Core>

#include <cmath>

GeodeticPosition xyz2llh(const Eigen::Vector3d &ecef)
{
	constexpr double a = WGS84_RADIUS;
	constexpr double e = WGS84_ECCENTRICITY;
	constexpr double e2 = e*e;

    constexpr double eps = 1.0e-3;
	if (ecef.norm() < eps)
	{
        // Invalid ECEF vector
        return GeodeticPosition::FromRadians(0.0, 0.0, -a);
	}

	const double x = ecef.x();
	const double y = ecef.y();
	const double z = ecef.z();

	const double rho2 = x*x + y*y;
	double dz = e2*z;

    double n, zdz, nh;
	while (1)
	{
		zdz = z + dz;
		nh = std::sqrt(rho2 + zdz*zdz);
		const double slat = zdz / nh;
		n = a / std::sqrt(1.0-e2*slat*slat);
		const double dz_new = n*e2*slat;

		if (std::fabs(dz-dz_new) < eps)
			break;

		dz = dz_new;
	}

    const double lat_rad = std::atan2(zdz, std::sqrt(rho2));
    const double lon_rad = std::atan2(y, x);
    const double height_m = nh - n;

    return GeodeticPosition::FromRadians(lat_rad, lon_rad, height_m);
}

Eigen::Vector3d llh2xyz(const GeodeticPosition &llh)
{
	constexpr double a = WGS84_RADIUS;
	constexpr double e = WGS84_ECCENTRICITY;
	constexpr double e2 = e*e;

	const double clat = std::cos(llh.latitude_rad());
	const double slat = std::sin(llh.latitude_rad());
	const double clon = std::cos(llh.longitude_rad());
	const double slon = std::sin(llh.longitude_rad());
	const double d = e*slat;

	const double n = a / std::sqrt(1.0-d*d);
	const double nph = n + llh.height_m();

	const double tmp = nph*clat;
	const double x = tmp*clon;
	const double y = tmp*slon;
	const double z = ((1.0-e2)*n + llh.height_m())*slat;

	return Eigen::Vector3d(x, y, z);
}

void ltcmat(const GeodeticPosition &llh, double t[3][3])
{
	const double slat = std::sin(llh.latitude_rad());
	const double clat = std::cos(llh.latitude_rad());
	const double slon = std::sin(llh.longitude_rad());
	const double clon = std::cos(llh.longitude_rad());

	t[0][0] = -slat*clon;
	t[0][1] = -slat*slon;
	t[0][2] = clat;
	t[1][0] = -slon;
	t[1][1] = clon;
	t[1][2] = 0.0;
	t[2][0] = clat*clon;
	t[2][1] = clat*slon;
	t[2][2] = slat;
}

void ecef2neu(const double *xyz, double t[3][3], double *neu)
{
	neu[0] = t[0][0]*xyz[0] + t[0][1]*xyz[1] + t[0][2]*xyz[2];
	neu[1] = t[1][0]*xyz[0] + t[1][1]*xyz[1] + t[1][2]*xyz[2];
	neu[2] = t[2][0]*xyz[0] + t[2][1]*xyz[1] + t[2][2]*xyz[2];

	return;
}

AzimuthElevation neu2azel(const double *neu)
{
	double azimuth_rad = std::atan2(neu[1],neu[0]);
	if (azimuth_rad < 0.0)
		azimuth_rad += 2.0*PI;

	const double ne = std::hypot(neu[0], neu[1]);
	const double elevation_rad = std::atan2(neu[2], ne);

    return AzimuthElevation::FromRadians(azimuth_rad, elevation_rad);
}

max_stars_repo_name: damiendusha/gnss-sim

max_issues_repo_name: damiendusha/gnss-sim

max_forks_repo_name: damiendusha/gnss-sim


text:
/*
 * baseMeasure.hpp
 *
 *  Created on: Feb 1, 2013
 *      Author: jstraub
 */

#ifndef BASEMEASURE_HPP_
#define BASEMEASURE_HPP_

#include "probabilityHelpers.hpp"

#include <boost/math/special_functions/gamma.hpp>
#include <armadillo>

#include <stddef.h>
#include <stdint.h>
#include <typeinfo>

using namespace std;
using namespace arma;

/*
 * templated on the unit
 */
template<class U>
class BaseMeasure
{
public:
  BaseMeasure()
    : mRowDim(0)
  {
    //cout<<"Creating "<<typeid(this).name()<<endl;
  };

  BaseMeasure(const BaseMeasure<U>& other)
    : mRowDim(0)
  { };

  virtual ~BaseMeasure()
  {};

  virtual double predictiveProb(const Col<U>& x_q, const Mat<U>& x_given) const
  {
    cerr<<"BaseMeasure:: Something gone wrong with virtual functions"<<endl;
    exit(0);
    return 0.0;
  };
  virtual double predictiveProb(const Col<U>& x_q) const
  {
    cerr<<"BaseMeasure:: Something gone wrong with virtual functions"<<endl;
    exit(0);
    return 0.0;
  };

  virtual BaseMeasure<U>* getCopy() const
  {
    cerr<<"BaseMeasure:: getCopy()"<<endl;
    exit(0);
    return new BaseMeasure<U>(*this);
  };

  virtual Row<double> asRow() const
  {
    cerr<<"BaseMeasure:: asRow()"<<endl;
    exit(0); return Row<double>();
  };

  uint32_t rowDim() const
  {
    return mRowDim;
  };

  virtual void fromRow(const Row<double>& r)
  {
    cerr<<"BaseMeasure:: fromRow()"<<endl;
    exit(0);
  };

  virtual BaseMeasure<U>* mode() const
  {
    cerr<<"BaseMeasure:: mode()"<<endl;
    exit(0);};

  virtual double Elog(const Col<U>& x) const
  {
    cerr<<"BaseMeasure:: Elog()"<<endl;
    exit(0);};

  virtual void posteriorHDP_var(const Col<double>& zeta, const Mat<double>& phi, uint32_t D, const Mat<U>& x)
  {
    cerr<<"BaseMeasure:: posteriorHDP_var()"<<endl;
    exit(0);};

  virtual void posterior(const Mat<U>& x)
  {
    cerr<<"BaseMeasure:: posterior()"<<endl;
    exit(0);};

  virtual double logP(const Col<U>& x) const
  {
    cerr<<"BaseMeasure:: logP()"<<endl;
    exit(0);}

protected:
  uint32_t mRowDim;

};

/*
 * Multinomial distribution
 */
class Mult : public BaseMeasure<uint32_t>
{
  public:

    Mult(const Mult& mult)
      : mP(mult.mP)
    {
      mRowDim = mP.n_cols;
    };

    Mult(const Row<double>& p)
      : mP(p)
    {
      mRowDim = mP.n_cols;
    };

  virtual BaseMeasure<uint32_t>* getCopy() const
  {
    return new Mult(*this);
  };

  virtual Row<double> asRow() const
  {
    return mP;
  };

  virtual void fromRow(const Row<double>& r)
  {
    mP = r;
    mRowDim = r.n_cols;
  };

  virtual double logP(const Col<uint32_t>& x) const
  {
    return log(mP[x(0)]);
  };

  Row<double> mP;
private:
};

/*
 * Mutlivariate Gaussian distribution
 */
class Gauss : public BaseMeasure<double>
{
  public:
    Gauss(const Gauss& gauss)
      : mMu(gauss.mMu), mSig(gauss.mSig)
    {
      uint32_t d=mMu.n_rows;
      mRowDim = d*d+d;
    };

    Gauss(const Col<double>& mu, const Mat<double>& sig)
      : mMu(mu), mSig(sig)
    {
      uint32_t d=mMu.n_rows;
      mRowDim = d*d+d;
    };

  virtual BaseMeasure<double>* getCopy() const
  {
    return new Gauss(*this);
  };

  /*
   * puts all parameters, mu and Sig into one vector
   * (0 to d^2-1) Sig
   * (d^2 to d^2+d-1) mu
   */
  virtual Row<double> asRow() const
  {
    uint32_t d = mMu.n_elem;
    Row<double> row(d*d+d);
    for (uint32_t i=0; i<d; ++i)
      for (uint32_t j=0; j<d; ++j)
       row(j+i*d) = mSig(j,i); // column major
    for (uint32_t i=0; i<d; ++i)
      row(d*d+i) = mMu(i);
    return row;
  };

  virtual void fromRow(const Row<double>& row)
  {
    uint32_t d = mMu.n_elem; // we already have a Vtheta from the init;
    for (uint32_t i=0; i<d; ++i)
      for (uint32_t j=0; j<d; ++j)
        mSig(j,i) = row(j+i*d); // column major
    for (uint32_t i=0; i<d; ++i)
      mMu(i) = row(d*d+i);
  };

  virtual double logP(const Col<double>& x) const
  {
    return -0.5*(double(mSig.n_rows)*1.8378770664093453 + log(det(mSig)) +  as_scalar((x-mMu).t()*solve(mSig,x-mMu)));
  };

  Col<double> mMu;
  Mat<double> mSig;
private:
};

class Dir : public BaseMeasure<uint32_t>
{
public:
  Dir(const Row<double>& alphas)
  : mAlphas(alphas), mAlpha0(sum(alphas))
  {
    mRowDim = mAlphas.n_elem;
  };

  Dir(const Dir& dir)
    : mAlphas(dir.mAlphas), mAlpha0(sum(dir.mAlphas))
  {
    mRowDim = mAlphas.n_elem;
  };

  /*
   * return a copy of this object - this uses the concept of covariance
   */
  virtual Dir* getCopy() const
  {
    return new Dir(*this);
  };

  virtual Row<double> asRow() const
  {
    return mAlphas;
  };

  virtual void fromRow(const Row<double>& r)
  {
    mAlphas = r;
    mAlpha0 = sum(r);
  };

  virtual BaseMeasure<uint32_t>* mode() const
//  virtual BaseMeasure<uint32_t> mode() const
  {
    Row<double> mode(mAlphas.size());
    dirMode(mode,mAlphas);
    return new Mult(mode);
  };

  virtual double Elog(const Col<uint32_t>& x) const
  {
    // TODO: assumes that x is 1D word
    return digamma(mAlphas(x(0))) - digamma(mAlpha0);
  };

  /*
   * update parameters using observations x to form posterior for stochastic variational HDP
   */
  virtual void posteriorHDP_var(const Col<double>& zeta, const Mat<double>& phi, uint32_t D, const Mat<uint32_t>& x)
  {

    uint32_t N = x.n_cols;
    uint32_t T = zeta.n_rows;
    uint32_t Nw = mAlphas.n_elem;

    Row<double> lambda(Nw);
    lambda.zeros();
    for (uint32_t i=0; i<T; ++i)
    {
      Row<double> _lambda(Nw);
      _lambda.zeros();
      for (uint32_t n=0; n<N; ++n){
        _lambda(x(n)) += phi(n,i);
      }
      lambda += zeta(i) * _lambda;
    }
    mAlphas += D*lambda;
    //cout<<"lambda-nu="<<d_lambda[k].t()<<endl;
    //cout<<"lambda="<<d_lambda[k].t()<<endl;
  };

  virtual void posterior(const Mat<uint32_t>& x)
  {
    uint32_t N = x.n_cols;
    for (uint32_t i=0; i< N; ++i)
      mAlphas[x[i]] ++;
    mAlpha0= sum(mAlphas);
  };

  /*
   * used for gibbs sampling - seems to assume a categorical distribution
   */
  double predictiveProb(const Col<uint32_t>& x_q, const Mat<uint32_t>& x_given) const
  {
    // TODO: assumes x_q is 1D! (so actually just a uint32_t

    // compute posterior under x_given
    uint32_t k=x_q(0);
    Row<uint32_t> ids=(x_given.row(0)==k);
    uint32_t C_k=sum(ids);
    uint32_t L=x_given.n_cols;
    //    cout<<"k="<<k<<" C_k="<<C_k<<" L="<<L<<" alpha0="<<mAlpha0
    //      <<" alpha_k="<<mAlphas(k)
    //      <<" log(p)="<< log((C_k + mAlphas(k))/(L + mAlpha0))<<endl;
    //    cout<<x_q<<" -" <<x_given.t()<<endl;
    return log((C_k + mAlphas(k))/(L + mAlpha0));
  };
  double predictiveProb(const Col<uint32_t>& x_q) const
  {
    const uint32_t k=x_q(0);
    return log(mAlphas(k)/mAlpha0);
  };

  Row<double> mAlphas;
  double mAlpha0;
private:
};

class NIW : public BaseMeasure<double>
{
public:
  // make a copy of vtheta and Delta (that should only be a copy of the header anyway
  NIW(colvec vtheta, double kappa, mat Delta, double nu)
  : mVtheta(vtheta), mKappa(kappa), mDelta(Delta), mNu(nu)
  {
//    cout<<"Creating "<<typeid(this).name()<<endl;

    mRowDim = mVtheta.n_elem;
    mRowDim = mRowDim*mRowDim + mRowDim +2;
  };

  NIW(const NIW& niw)
  : mVtheta(niw.mVtheta), mKappa(niw.mKappa), mDelta(niw.mDelta), mNu(niw.mNu)
  {
    mRowDim = mVtheta.n_elem;
    mRowDim = mRowDim*mRowDim + mRowDim +2;
  };

  virtual NIW* getCopy() const
  {
    return new NIW(*this);
  };

  /*
   * puts all parameters, Vtheta, kappa, delta, and nu into one vector
   * (0 to d^2-1) Delta
   * (d^2 to d^2+d-1) Vtheta
   * (d^2+d) nu
   * (d^2+d+1) kappa
   */
  virtual Row<double> asRow() const
  {
    uint32_t d = mVtheta.n_elem;
    Row<double> row(d*d+d+2);

    for (uint32_t i=0; i<d; ++i)
      for (uint32_t j=0; j<d; ++j)
        row(j+i*d) = mDelta(j,i); // column major
    for (uint32_t i=0; i<d; ++i)
      row(d*d+i) = mVtheta(i);
    row(d*d+d) = mNu;
    row(d*d+d+1) = mKappa;
    return row;
  };

  virtual void fromRow(const Row<double>& row)
  {
    uint32_t d = mVtheta.n_elem; // we already have a Vtheta from the init;
    for (uint32_t i=0; i<d; ++i)
      for (uint32_t j=0; j<d; ++j)
        mDelta(j,i) = row(j+i*d); // column major
    for (uint32_t i=0; i<d; ++i)
      mVtheta(i) = row(d*d+i);
    mNu = row(d*d+d);
    mKappa = row(d*d+d+1);
  };

  virtual BaseMeasure<double>* mode() const
  {
    uint32_t d = mVtheta.n_elem; // we already have a Vtheta from the init;
    Mat<double> sig = mDelta/(mNu+d+2);
//    cout<<"mu: "<<mVtheta;
//    cout<<"sig:"<<sig;

    return new Gauss(mVtheta,sig);

//    mode.set_size(d*d+d);
//    //TODO: not sure about covariance...
//    for (uint32_t i=0; i<d; ++i)
//      for (uint32_t j=0; j<d; ++j)
//        mode(j+i*d) = mDelta(j,i)/(mNu+d+1); // column major
//    for (uint32_t i=0; i<d; ++i)
//      mode(d*d+i) = mVtheta(i); // sure about the mean
  };

  virtual double Elog(const Col<double>& x) const
  {
    //TODO: make it log from the beginning
    double d = mVtheta.n_elem; // we already have a Vtheta from the init;

//    double b = as_scalar((x-mVtheta).t()*solve(mDelta,x-mVtheta));
//    double logA=boost::math::lgamma((mNu+1.0)/2.0) - (d/2.0)*log((mNu-d+1.0)*datum::pi) - boost::math::lgamma((mNu-d+1.0)/2.0) - 0.5*(log(mKappa+1.0)-log(mKappa*(mNu-d+1.0))) - 0.5*log(det(mDelta));
//    double logC=log (1.0+(mKappa/(mKappa+1.0))*b)*((mNu+1.0)/2.0);

//    cout<<boost::math::tgamma((mNu+1.0)/2.0)<<" "<<sqrt(det(mDelta))<<" "<<boost::math::tgamma((mNu-d+1.0)/2.0)<<" "<<(mNu-d+1.0)<<endl;

//    cout<<"vtheta: "<<mVtheta;
//    cout<<"delta: "<<mDelta;
//    cout<<"kappa: "<<mKappa<<" nu="<<mNu<<endl;
    double sq = as_scalar((x+mVtheta).t()*solve(mDelta,x+mVtheta));

    double eLog= -0.5*d*log(datum::pi) -0.5*log(det(mDelta)) +0.5*digamma_mult(-0.5*mNu,uint32_t(d)) -0.5*(d/mKappa) -0.5*mNu*sq;

    if(!is_finite(mVtheta)|| !is_finite(eLog))
    {
      cout<<"vtheta: "<<mVtheta;
      cout<<"delta: "<<mDelta;
      cout<<"kappa: "<<mKappa<<" nu="<<mNu<<endl;
      cout<<"Elog="<<eLog<<" sq="<<sq<<" digamma_mult="<<digamma_mult(-0.5*mNu,uint32_t(d))<<endl;
      exit(0);
    }
    return eLog;
  };

  virtual void posteriorHDP_var(const Col<double>& zeta, const Mat<double>& phi, uint32_t D, const Mat<double>& x)
  {
    uint32_t N = x.n_cols;
    uint32_t T = zeta.n_rows;

//    cout<<" -----------------"<<endl;
//    cout<<"N="<<N<<" T="<<T<<endl;
    double counts=0.0;
    for (uint32_t i=0; i<T; ++i){
//      cout<<"counts= "<<counts<<" zeta="<<zeta(i)<<" sumphi="<<sum(phi.col(i))<<endl;
      counts += zeta(i)*sum(phi.col(i));
    }
    counts*=D;

    Col<double> x_hat(x.n_rows);
    x_hat.zeros();
    for (uint32_t i=0; i<T; ++i){
      Col<double> x_sum(x.n_rows);
      x_sum.zeros();
      for (uint32_t n=0; n<N; ++n){
        x_sum += phi(n,i)*x.col(n);
      }
      x_hat += zeta(i) * x_sum;
    }
    x_hat *= D/counts;

    Mat<double> S(mDelta);
    S.zeros();
    for (uint32_t i=0; i<T; ++i){
      Mat<double> S_sum(mDelta);
      S_sum.zeros();
      for (uint32_t n=0; n<N; ++n){
        S_sum += phi(n,i)*(x.col(n)-x_hat)*(x.col(n)-x_hat).t();
      }
      S += zeta(i) * S_sum;
    }

    // TODO: use zeta and Phi!!
//    uint32_t n = x.n_cols;
//    Col<double> x_hat=sum(x,1)/n;
//    Mat<double> S(mDelta)
//    S.zeros();
//    for (uint32_t i=0; i<n; ++i)
//      S += (x.col(i) - x_hat) * (x.col(i) - x_hat).t();

      cout<<" -----------------"<<endl;
      cout<<"vtheta(before): "<<mVtheta;
//    cout<<"delta: "<<mDelta;
//    cout<<"kappa: "<<mKappa<<" nu="<<mNu<<endl;
//    cout<<"S="<<S;
//    cout<<"x_hat="<<x_hat<< " sum/N="<<sum(x,1)/N;
//    cout<<"counts="<<counts<<endl;

    mDelta += D*S + (mKappa*counts)/(mKappa+counts)*(x_hat - mVtheta)*(x_hat - mVtheta).t();
    mVtheta = mKappa/(mKappa+counts)* mVtheta + counts/(mKappa+counts)*x_hat;
    mKappa += counts;
    mNu += counts;

//    if(!is_finite(mVtheta) || accu(mDelta<0.0)>0)
    {
//      cout<<"zeta="<<zeta.t();
//      cout<<"phi="<<phi;
//      cout<<"N="<<N<<" T="<<T<<endl;
//      cout<<"x="<<x;
      cout<<"S="<<S;
      cout<<"x_hat="<<x_hat<< " sum/N="<<sum(x,1)/N;
      cout<<"counts="<<counts<<endl;
      cout<<"-> vtheta: "<<mVtheta;
      cout<<"-> delta: "<<mDelta;
      cout<<"-> kappa: "<<mKappa<<" nu="<<mNu<<endl;
//      exit(0);
    }
  };

  virtual void posterior(const NIW& niw)
  {
    mDelta +=;
  };

  virtual void posterior(const Mat<double>& x)
  {
    uint32_t n = x.n_cols;
    Col<double> x_hat=sum(x,1)/n;
    Mat<double> S(mDelta);
    S.zeros();
    for (uint32_t i=0; i<n; ++i)
      S += (x.col(i) - x_hat) * (x.col(i) - x_hat).t();

    mDelta = mDelta + S + (mKappa*n)/(mKappa+n)*(x_hat - mVtheta)*(x_hat - mVtheta).t();
    mVtheta = mKappa/(mKappa+n)* mVtheta + n/(mKappa+n)*x_hat;
    mKappa += x.n_cols;
    mNu += x.n_cols;
  };

  double predictiveProb(const Col<double>& x_q, const Mat<double>& x_given) const
  {
    // compute posterior under x_given
    // M0: number of data points in the cluster
    // M1: sum over all data points in the cluster
    // M2: x*x.T over all data points in the cluster
    double M0=x_given.n_cols;
    colvec M1=sum(x_given,1);
    mat M2=x_given.t()*x_given;
    double kappa = mKappa+M0;
    double nu = mNu+M0;
    colvec vtheta = (mKappa*mVtheta + M1)/kappa;
    //    cout<<"vtheta="<<vtheta<<endl;
    //    cout<<"mVtheta="<<mVtheta<<endl;
    //    cout<<"M2="<<M2<<endl;
    //    cout<<"mDelta="<<mDelta<<endl;
    mat Delta = (mNu*mDelta + M2 + mKappa*(mVtheta*mVtheta.t()) - kappa*(vtheta*vtheta.t()))/nu;

    // compute the likelihood of x_q under the posterior
    // This can be approximated by using a moment matched gaussian
    // to the multivariate student-t distribution which arises in
    // when integrating over the parameters of the normal inverse
    // wishart
    mat C_matched=(((kappa+1.0)*nu)/(kappa*(nu-vtheta.n_rows-1.0)))*Delta;

    return logGaus(x_q, vtheta, C_matched);
  };

  double predictiveProb(const Col<double>& x_q) const
  {
    // compute the likelihood of x_q under the posterior
    // This can be approximated by using a moment matched gaussian
    // to the multivariate student-t distribution which arises in
    // when integrating over the parameters of the normal inverse
    // wishart
    mat C_matched=(((mKappa+1.0)*mNu)/(mKappa*(mNu-mVtheta.n_rows-1.0)))*mDelta;

    return logGaus(x_q, mVtheta, C_matched);
  };

  static double logGaus(const colvec& x, const colvec& mu, const mat& C)
  {
    //    cout<<"C"<<C<<endl;
    //    cout<<"mu"<<mu<<endl;
    //    cout<<"x"<<x<<endl;
    double detC=det(C);
    if(!is_finite(detC))
      return 0.0;
    mat CinvXMu=solve(C,x-mu);
    mat logXCX = (x-mu).t() * CinvXMu;
    //    cout<<"rows="<<C.n_rows<<" log(det(C))="<<log(det(C*0.001))-double(C.n_rows)*1000.0<<" logXC="<<logXCX(0)<<" p="<<-0.5*(double(C.n_rows)*1.8378770664093453 + log(det(C)) + logXCX(0))<<endl;

    return -0.5*(double(C.n_rows)*1.8378770664093453 + log(detC) + logXCX(0));
  };

  colvec mVtheta;
  double mKappa;
  mat mDelta;
  double mNu;
};

/*
 * Container for base measure pointers
 */
template <class U>
class DistriContainer
{
public:

  DistriContainer(uint32_t d=0)
    : mDistris(d,NULL)
  {};

  DistriContainer(const BaseMeasure<U>& a, uint32_t d)
    : mDistris(d,NULL)
  {
    for (uint32_t i=0; i<d; ++i)
      mDistris[i] = a.getCopy();
  };

  DistriContainer(const vector<BaseMeasure<U>* >& a)
    : mDistris(a.size(),NULL)
  {
    for (uint32_t i=0; i<a.size(); ++i)
      mDistris[i] = a[i]->getCopy();
  };

  DistriContainer(const DistriContainer<U>& a)
    : mDistris(a.size(),NULL)
  {
    for (uint32_t i=0; i<a.size(); ++i)
      mDistris[i] = a[i]->getCopy();
  };

  ~DistriContainer()
  {
    for (uint32_t i=0; i<mDistris.size(); ++i)
    {
      //cout<<"deleting "<<mDistris.size()<<" "<<i<<" :"<<mDistris[i]<<endl;
      delete mDistris[i];
    }
  };

  void init(const BaseMeasure<U>& a, uint32_t d)
  {
    for (uint32_t i=0; i<mDistris.size(); ++i)
      delete mDistris[i];

    mDistris.resize(d,NULL);
    for (uint32_t i=0; i<d; ++i)
      mDistris[i] = a.getCopy();
  };

  BaseMeasure<U>* operator[](const uint32_t i) const
  {
    assert(i<mDistris.size());
    return mDistris[i];
  };

  BaseMeasure<U>*& operator[](const uint32_t i)
  {
    assert(i<mDistris.size());
    return mDistris[i];
  };

  uint32_t size() const
  {
    return mDistris.size();
  };

  void resize(uint32_t i)
  {
    mDistris.resize(i,NULL);
  };

  void toMat( Mat<double>& mat) const
  {
    mat.set_size(this->size(), mDistris[0]->rowDim() );
    for (uint32_t i=0; i< this->size(); ++i)
      mat.row(i) = mDistris[i]->asRow();
  };

  Mat<double> toMat() const
  {
    Mat<double> mat;
    toMat(mat);
    return mat;
  };

private:
  vector<BaseMeasure<U>* > mDistris;
};

/*
 * Mixture of probabiliti distributions
 */
template <class U>
class Mixture
{
  public:
    Mixture()
      : mDistris()
    { };

    Mixture(const Mixture<U>& mix)
      : mDistris(mix.mDistris), mP(mix.mP)
    {};

    Mixture(const DistriContainer<U>& distris, const Row<double>& ps)
      : mDistris(distris), mP(ps)
    {};

    double logP(const Col<U>& x) const
    {
      double p=0.0 ;
      for (uint32_t i=0; i<mDistris.size(); ++i)
        p += mP[i]*exp(mDistris[i]->logP(x));
      return log(p);
    };

    DistriContainer<U> mDistris;
    Row<double> mP;

  private:
};

#endif /* BASEMEASURE_HPP_ */

ext: hpp

max_stars_repo_name: jstraub/bnp

max_issues_repo_name: jstraub/bnp

max_forks_repo_name: jstraub/bnp


text: #include <boost/callable_traits/remove_member_const.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino