<commit_before>//=====================================================================//
/*! @file
    @brief  GR-KAEDE EFO (RX64M) メイン @n
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"

namespace {

}

extern "C" {

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字出力
		@param[in]	ch	文字
	*/
	//-----------------------------------------------------------------//
	void sci_putch(char ch)
	{
#if 0
		if(putch_lock_) {
			if((putch_tmp_.size() - putch_tmp_.length()) >= 2) {
				putch_tmp_.put(ch);
			}
			return;
		}
		putch_lock_ = true;
		core_.sci_.putch(ch);
		putch_lock_ = false;
#endif
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字列出力
		@param[in]	s	文字列
	*/
	//-----------------------------------------------------------------//
	void sci_puts(const char* s)
	{
//		core_.sci_.puts(s);
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字入力
		@return	文字
	*/
	//-----------------------------------------------------------------//
	char sci_getch(void)
	{
//		return core_.sci_.getch();
		return 0;
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字列長の取得
		@return	文字列長
	*/
	//-----------------------------------------------------------------//
	uint16_t sci_length(void)
	{
//		return core_.sci_.recv_length();
		return 0;
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
#if 0
	using namespace seeda;

	device::PORTC::PDR.B0 = 1; // output
	device::PORTC::PDR.B1 = 1; // output
	device::PORT0::PDR.B2 = 1; // output
	device::PORT0::PDR.B3 = 1; // output

	device::PORT3::PCR.B5 = 1; // P35(NMI) pull-up

	device::SYSTEM::PRCR = 0xA50B;	// クロック、低消費電力、関係書き込み許可

	device::SYSTEM::MOSCWTCR = 9;	// 1ms wait
	// メインクロック強制発振とドライブ能力設定
	device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)
						  | device::SYSTEM::MOFCR.MOFXIN.b(1);
	device::SYSTEM::MOSCCR.MOSTP = 0;		// メインクロック発振器動作
	while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");

	// Base Clock 12MHz
	device::SYSTEM::PLLCR.STC = 0b010011;		// PLL 10 倍(120MHz)
	device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
	while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");

	device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.ICK.b(0)		// 1/1 (120/1=120)
						  | device::SYSTEM::SCKCR.BCK.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.PCKA.b(0)		// 1/1 (120/1=120)
						  | device::SYSTEM::SCKCR.PCKB.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.PCKC.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.PCKD.b(1);	// 1/2 (120/2=60)
	device::SYSTEM::SCKCR2.UCK = 0b0100;  // USB Clock: 1/5 (120/5=24)
	device::SYSTEM::SCKCR3.CKSEL = 0b100;	///< PLL 選択

	main_init_();

	sample_count_ = 0;

	core_.init();

	// SD カード・クラスの初期化
	sdc_.start();

	// 設定ファイルの確認
///	config_ = sdc_.probe("seeda.cfg");
	core_.title();

	tools_.init();
	tools_.title();

	nets_.init();
	nets_.title();

	enable_eadc_server();

	uint32_t cnt = 0;
	while(1) {
		core_.sync();

		sample_data_.time_ = get_time();

		core_.service();
		tools_.service();

		sdc_.service();

		service_putch_tmp_();

		nets_.service();

		++cnt;
		if(cnt >= 32) {
			cnt = 0;
		}

		device::PORTC::PODR.B0 = (((cnt + 0)  & 31) < 8) ? 1 : 0;
		device::PORTC::PODR.B1 = (((cnt + 8)  & 31) < 8) ? 1 : 0;
		device::PORT0::PODR.B2 = (((cnt + 16) & 31) < 8) ? 1 : 0;
		device::PORT0::PODR.B3 = (((cnt + 24) & 31) < 8) ? 1 : 0;
	}
#endif
}
<commit_msg>update DAC test<commit_after>//=====================================================================//
/*! @file
    @brief  GR-KAEDE EFO (RX64M) メイン @n
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"
#include "common/cmt_io.hpp"
#include "common/fifo.hpp"
#include "common/sci_io.hpp"
#include "common/format.hpp"

namespace {

	typedef device::cmt_io<device::CMT0, utils::null_task> CMT0;
	CMT0	cmt_;

	typedef utils::fifo<uint8_t, 2048> BUFFER;
	typedef device::sci_io<device::SCI7, BUFFER, BUFFER> SCI;

	SCI		sci_;

	typedef device::dac_out	DAC;
	DAC		dac_;

}

extern "C" {

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字出力
		@param[in]	ch	文字
	*/
	//-----------------------------------------------------------------//
	void sci_putch(char ch)
	{
#if 0
		if(putch_lock_) {
			if((putch_tmp_.size() - putch_tmp_.length()) >= 2) {
				putch_tmp_.put(ch);
			}
			return;
		}
		putch_lock_ = true;
#endif
		sci_.putch(ch);
//		putch_lock_ = false;
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字列出力
		@param[in]	s	文字列
	*/
	//-----------------------------------------------------------------//
	void sci_puts(const char* s)
	{
		sci_.puts(s);
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字入力
		@return	文字
	*/
	//-----------------------------------------------------------------//
	char sci_getch(void)
	{
		return sci_.getch();
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  システム・文字列長の取得
		@return	文字列長
	*/
	//-----------------------------------------------------------------//
	uint16_t sci_length(void)
	{
		return sci_.recv_length();
	}
}

int main(int argc, char** argv);

int main(int argc, char** argv)
{
	device::PORTC::PDR.B0 = 1; // output
	device::PORTC::PDR.B1 = 1; // output
	device::PORT0::PDR.B2 = 1; // output
//	device::PORT0::PDR.B3 = 1; // output

	device::PORT3::PCR.B5 = 1; // P35(NMI) pull-up

	device::SYSTEM::PRCR = 0xA50B;	// クロック、低消費電力、関係書き込み許可

	device::SYSTEM::MOSCWTCR = 9;	// 1ms wait
	// メインクロック強制発振とドライブ能力設定
	device::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV2.b(0b10)
						  | device::SYSTEM::MOFCR.MOFXIN.b(1);
	device::SYSTEM::MOSCCR.MOSTP = 0;		// メインクロック発振器動作
	while(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm("nop");

	// Base Clock 12MHz
	device::SYSTEM::PLLCR.STC = 0b010011;		// PLL 10 倍(120MHz)
	device::SYSTEM::PLLCR2.PLLEN = 0;			// PLL 動作
	while(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm("nop");

	device::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.ICK.b(0)		// 1/1 (120/1=120)
						  | device::SYSTEM::SCKCR.BCK.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.PCKA.b(0)		// 1/1 (120/1=120)
						  | device::SYSTEM::SCKCR.PCKB.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.PCKC.b(1)		// 1/2 (120/2=60)
						  | device::SYSTEM::SCKCR.PCKD.b(1);	// 1/2 (120/2=60)
	device::SYSTEM::SCKCR2.UCK = 0b0100;  // USB Clock: 1/5 (120/5=24)
	device::SYSTEM::SCKCR3.CKSEL = 0b100;	///< PLL 選択

	{  // タイマー設定、１０００Ｈｚ（１ｍｓ）
		uint8_t int_level = 1;
		cmt_.start(1000, int_level);
	}

	{  // SCI 設定
		uint8_t int_level = 2;
		sci_.start(115200, int_level);
	}

	{  // D/A CH0, AMP enable
		dac_.start(DAC::output::CH0, true);
	}

	utils::format("\nStart KAEDE for EFO\n");

	uint32_t cnt = 0;
	uint16_t da = 0;
	while(1) {
		cmt_.sync();

		++cnt;
		if(cnt >= 32) {
			cnt = 0;
		}

		da += 1024;
		dac_.out0(da);

		auto n = cnt / 10;
		device::PORTC::PODR.B0 = (((n + 0)  & 31) < 8) ? 1 : 0;
		device::PORTC::PODR.B1 = (((n + 8)  & 31) < 8) ? 1 : 0;
		device::PORT0::PODR.B2 = (((n + 16) & 31) < 8) ? 1 : 0;
//		device::PORT0::PODR.B3 = (((cnt + 24) & 31) < 8) ? 1 : 0;
	}
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>

#include <disir/disir.h>
#include <disir/fslib/toml.h>

#include "tinytoml/toml.h"
#include "fdstream.hpp"

//! Forward declare STATIC API
static enum disir_status
toml_serialize_elements (struct disir_context *context, toml::Value* current);

//! STATIC API
static enum disir_status
toml_serialize_keyval (struct disir_context *context, toml::Value* current, const char *name)
{
    enum disir_status status;
    const char *value_string;
    int64_t value_integer;
    double value_float;
    uint8_t value_boolean;

    switch (dc_value_type (context))
    {
    case DISIR_VALUE_TYPE_ENUM:
    {
        status = dc_get_value_enum (context, &value_string, NULL);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value(value_string)));
            else
                current->setChild (name, value_string);
        }
        break;
    }
    case DISIR_VALUE_TYPE_STRING:
    {
        status = dc_get_value_string (context, &value_string, NULL);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value(value_string)));
            else
                current->setChild (name, value_string);
        }
        break;
    }
    case DISIR_VALUE_TYPE_INTEGER:
    {
        status = dc_get_value_integer (context, &value_integer);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value (value_integer)));
            else
                current->setChild (name, value_integer);
        }
        break;
    }
    case DISIR_VALUE_TYPE_FLOAT:
    {
        status = dc_get_value_float (context, &value_float);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value (value_float)));
            else
                current->setChild (name, value_float);
        }
        break;
    }
    case DISIR_VALUE_TYPE_BOOLEAN:
    {
        status = dc_get_value_boolean (context, &value_boolean);
        if (status == DISIR_STATUS_OK)
        {
            bool boolean = false;
            if (value_boolean > 0)
                boolean = true;
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value (boolean)));
            else
                current->setChild (name, boolean);
        }
        break;
    }
    default:
    {
        disir_log_user (NULL, "TOML: Unhandled value type of keyval: %s", dc_value_type_string (context));
        status = DISIR_STATUS_INTERNAL_ERROR;
    }
    }

    if (status != DISIR_STATUS_OK)
    {
        disir_log_user (NULL, "Failed to retrieve value from  %s keyval: %s",
                   dc_value_type_string (context), disir_status_string (status));
    }

    return status;
}

static enum disir_status
toml_serialize_inner (struct disir_context *parent, struct disir_context *context,
                      toml::Value* current, const char *name)
{
    enum disir_status status;
    struct disir_collection *key_collection;
    struct disir_context *key_element;
    toml::Value *table;

    key_element = NULL;

    // Get all elements from the parent
    status = dc_find_elements (parent, name, &key_collection);
    if (status != DISIR_STATUS_OK)
    {
        disir_log_user (NULL, "find elements on existing name (%s) failed. Ouch. status: %s",
                   name, disir_status_string (status));
        goto out;
    }

    // Create an array storage if needed.
    if (dc_collection_size (key_collection) > 1)
    {
        current = current->setChild (name, (toml::Array()));
    }

    do
    {
        status = dc_collection_next (key_collection, &key_element);
        if (status == DISIR_STATUS_EXHAUSTED)
        {
            break;
        }
        if (status != DISIR_STATUS_OK)
        {
            disir_log_user (NULL, "collection next failed with non-OK status: %s",
                       disir_status_string (status));
            break;
        }

        switch (dc_context_type (context))
        {
        case DISIR_CONTEXT_KEYVAL:
        {
            status = toml_serialize_keyval (context, current, name);
            break;
        }
        case DISIR_CONTEXT_SECTION:
        {
            if (current->type() == toml::Value::Type::ARRAY_TYPE)
            {
                table = current->push ((toml::Table()));
            }
            else
            {
                table = current->setChild (name, (toml::Table()));
            }

            status = toml_serialize_elements (context, table);
            break;
        }
        default:
        {
            disir_log_user (NULL, "Unhandled child of elements: %s", dc_context_type_string (context));
            status = DISIR_STATUS_INTERNAL_ERROR;
            goto out;
        }
        }

        // Bail if the serialization goes awry
        if (status != DISIR_STATUS_OK)
        {
            goto out;
        }

        dc_putcontext (&key_element);

    } while (1);

    status = DISIR_STATUS_OK;
    // FALL-THROUGH
out:
    if (key_collection)
        dc_collection_finished (&key_collection);
    if (key_element)
        dc_putcontext (&key_element);
    return status;
}

//! STATIC API
static enum disir_status
toml_serialize_elements (struct disir_context *context, toml::Value* current)
{
    enum disir_status status;
    const char *name;
    struct disir_context *element;
    struct disir_collection *collection;

    collection = NULL;
    element = NULL;

    status = dc_get_elements (context, &collection);
    if (status != DISIR_STATUS_OK)
    {
        disir_log_user (NULL, "Get elements failed with status: %s", disir_status_string (status));
        goto out;
    }

    do
    {
        status = dc_collection_next (collection, &element);
        if (status == DISIR_STATUS_EXHAUSTED)
        {
            break;
        }
        if (status != DISIR_STATUS_OK)
        {
            // log error - get out of town.
            disir_log_user (NULL, "Collection returned non-OK status: %s", disir_status_string (status));
            goto out;
        }

        status = dc_get_name (element, &name, NULL);
        if (status != DISIR_STATUS_OK)
        {
            disir_log_user (NULL, "Failed to retrieve keyval name: %s", disir_status_string (status));
            goto out;
        }

        // Check if this element already exists in the current TOML value.
        // If it does, we have already added it (since there are more than one entry of it.)
        if (current->has (name))
            continue;

        status = toml_serialize_inner (context, element, current, name);
        if (status != DISIR_STATUS_OK)
            goto out;

        dc_putcontext (&element);

    } while (1);

    status = DISIR_STATUS_OK;
    // FALL-THROUGH
out:
    if (collection)
    {
        dc_collection_finished (&collection);
    }
    if (element)
    {
        dc_putcontext (&element);
    }
    return status;
}

//! FSLIB API
enum disir_status
dio_toml_serialize_config (struct disir_instance *instance,
                           struct disir_config *config, FILE *output)
{
    enum disir_status status;
    struct disir_context *context_config;

    if (config == NULL || output == NULL)
    {
        // LOG debug 0
        return DISIR_STATUS_INVALID_ARGUMENT;
    }

    disir_log_user (instance, "TRACE ENTER serialize_config");

    context_config = dc_config_getcontext (config);
    // Create a TOML document, and lets roll!!
    toml::Value root((toml::Table()));
    toml::Value* current = &root;

    // Add DISIR_CONFIG_VERSION key
    struct disir_version version;
    char buffer[512];
    status = dc_config_get_version (config, &version);
    if (status != DISIR_STATUS_OK)
    {
        // TODO: Log error
        version.sv_major = 0;
        version.sv_minor = 0;
    }
    if (dc_version_string (buffer, 512, &version) == NULL)
    {
        // TODO: Log error
        snprintf (buffer, 512, "0.0.0");
    }
    current->setChild ("@DISIR_CONFIG_VERSION", buffer);

    // Mjes
    status = toml_serialize_elements (context_config, current);

    boost::fdostream file(fileno(output));
    root.write (&file);

    disir_log_user (instance, "TRACE EXIT serialize_config");
    return DISIR_STATUS_OK;
}

<commit_msg>fix fslib: toml_serialize duplicated serialization of instances<commit_after>#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>

#include <disir/disir.h>
#include <disir/fslib/toml.h>

#include "tinytoml/toml.h"
#include "fdstream.hpp"

//! Forward declare STATIC API
static enum disir_status
toml_serialize_elements (struct disir_context *context, toml::Value* current);

//! STATIC API
static enum disir_status
toml_serialize_keyval (struct disir_context *context, toml::Value* current, const char *name)
{
    enum disir_status status;
    const char *value_string;
    int64_t value_integer;
    double value_float;
    uint8_t value_boolean;

    switch (dc_value_type (context))
    {
    case DISIR_VALUE_TYPE_ENUM:
    {
        status = dc_get_value_enum (context, &value_string, NULL);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value(value_string)));
            else
                current->setChild (name, value_string);
        }
        break;
    }
    case DISIR_VALUE_TYPE_STRING:
    {
        status = dc_get_value_string (context, &value_string, NULL);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value(value_string)));
            else
                current->setChild (name, value_string);
        }
        break;
    }
    case DISIR_VALUE_TYPE_INTEGER:
    {
        status = dc_get_value_integer (context, &value_integer);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value (value_integer)));
            else
                current->setChild (name, value_integer);
        }
        break;
    }
    case DISIR_VALUE_TYPE_FLOAT:
    {
        status = dc_get_value_float (context, &value_float);
        if (status == DISIR_STATUS_OK)
        {
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value (value_float)));
            else
                current->setChild (name, value_float);
        }
        break;
    }
    case DISIR_VALUE_TYPE_BOOLEAN:
    {
        status = dc_get_value_boolean (context, &value_boolean);
        if (status == DISIR_STATUS_OK)
        {
            bool boolean = false;
            if (value_boolean > 0)
                boolean = true;
            if (current->type () == toml::Value::Type::ARRAY_TYPE)
                current->push ((toml::Value (boolean)));
            else
                current->setChild (name, boolean);
        }
        break;
    }
    default:
    {
        disir_log_user (NULL, "TOML: Unhandled value type of keyval: %s", dc_value_type_string (context));
        status = DISIR_STATUS_INTERNAL_ERROR;
    }
    }

    if (status != DISIR_STATUS_OK)
    {
        disir_log_user (NULL, "Failed to retrieve value from  %s keyval: %s",
                   dc_value_type_string (context), disir_status_string (status));
    }

    return status;
}

static enum disir_status
toml_serialize_inner (struct disir_context *parent,
                      toml::Value* current, const char *name)
{
    enum disir_status status;
    struct disir_collection *key_collection;
    struct disir_context *key_element;
    toml::Value *table;

    key_element = NULL;

    // Get all elements from the parent
    status = dc_find_elements (parent, name, &key_collection);
    if (status != DISIR_STATUS_OK)
    {
        disir_log_user (NULL, "find elements on existing name (%s) failed. Ouch. status: %s",
                   name, disir_status_string (status));
        goto out;
    }

    // Create an array storage if needed.
    if (dc_collection_size (key_collection) > 1)
    {
        current = current->setChild (name, (toml::Array()));
    }

    do
    {
        status = dc_collection_next (key_collection, &key_element);
        if (status == DISIR_STATUS_EXHAUSTED)
        {
            break;
        }
        if (status != DISIR_STATUS_OK)
        {
            disir_log_user (NULL, "collection next failed with non-OK status: %s",
                       disir_status_string (status));
            break;
        }

        switch (dc_context_type (key_element))
        {
        case DISIR_CONTEXT_KEYVAL:
        {
            status = toml_serialize_keyval (key_element, current, name);
            break;
        }
        case DISIR_CONTEXT_SECTION:
        {
            if (current->type() == toml::Value::Type::ARRAY_TYPE)
            {
                table = current->push ((toml::Table()));
            }
            else
            {
                table = current->setChild (name, (toml::Table()));
            }

            status = toml_serialize_elements (key_element, table);
            break;
        }
        default:
        {
            disir_log_user (NULL, "Unhandled child of elements: %s", dc_context_type_string (key_element));
            status = DISIR_STATUS_INTERNAL_ERROR;
            goto out;
        }
        }

        // Bail if the serialization goes awry
        if (status != DISIR_STATUS_OK)
        {
            goto out;
        }

        dc_putcontext (&key_element);

    } while (1);

    status = DISIR_STATUS_OK;
    // FALL-THROUGH
out:
    if (key_collection)
        dc_collection_finished (&key_collection);
    if (key_element)
        dc_putcontext (&key_element);
    return status;
}

//! STATIC API
static enum disir_status
toml_serialize_elements (struct disir_context *context, toml::Value* current)
{
    enum disir_status status;
    const char *name;
    struct disir_context *element;
    struct disir_collection *collection;

    collection = NULL;
    element = NULL;

    status = dc_get_elements (context, &collection);
    if (status != DISIR_STATUS_OK)
    {
        disir_log_user (NULL, "Get elements failed with status: %s", disir_status_string (status));
        goto out;
    }

    do
    {
        status = dc_collection_next (collection, &element);
        if (status == DISIR_STATUS_EXHAUSTED)
        {
            break;
        }
        if (status != DISIR_STATUS_OK)
        {
            // log error - get out of town.
            disir_log_user (NULL, "Collection returned non-OK status: %s", disir_status_string (status));
            goto out;
        }

        status = dc_get_name (element, &name, NULL);
        if (status != DISIR_STATUS_OK)
        {
            disir_log_user (NULL, "Failed to retrieve keyval name: %s", disir_status_string (status));
            goto out;
        }

        // Check if this element already exists in the current TOML value.
        // If it does, we have already added it (since there are more than one entry of it.)
        if (current->has (name))
            continue;

        status = toml_serialize_inner (context, current, name);
        if (status != DISIR_STATUS_OK)
            goto out;

        dc_putcontext (&element);

    } while (1);

    status = DISIR_STATUS_OK;
    // FALL-THROUGH
out:
    if (collection)
    {
        dc_collection_finished (&collection);
    }
    if (element)
    {
        dc_putcontext (&element);
    }
    return status;
}

//! FSLIB API
enum disir_status
dio_toml_serialize_config (struct disir_instance *instance,
                           struct disir_config *config, FILE *output)
{
    enum disir_status status;
    struct disir_context *context_config;

    if (config == NULL || output == NULL)
    {
        // LOG debug 0
        return DISIR_STATUS_INVALID_ARGUMENT;
    }

    disir_log_user (instance, "TRACE ENTER serialize_config");

    context_config = dc_config_getcontext (config);
    // Create a TOML document, and lets roll!!
    toml::Value root((toml::Table()));
    toml::Value* current = &root;

    // Add DISIR_CONFIG_VERSION key
    struct disir_version version;
    char buffer[512];
    status = dc_config_get_version (config, &version);
    if (status != DISIR_STATUS_OK)
    {
        // TODO: Log error
        version.sv_major = 0;
        version.sv_minor = 0;
    }
    if (dc_version_string (buffer, 512, &version) == NULL)
    {
        // TODO: Log error
        snprintf (buffer, 512, "0.0.0");
    }
    current->setChild ("@DISIR_CONFIG_VERSION", buffer);

    // Mjes
    status = toml_serialize_elements (context_config, current);

    boost::fdostream file(fileno(output));
    root.write (&file);

    disir_log_user (instance, "TRACE EXIT serialize_config");
    return DISIR_STATUS_OK;
}

<|endoftext|>


<commit_before>/*  This file is part of libDAI - http://www.libdai.org/
 *
 *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
 */

#include <dai/dai_config.h>
#ifdef DAI_WITH_BP

#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <algorithm>
#include <dai/bp.h>
#include <dai/util.h>
#include <dai/properties.h>

//#define DAI_VERBOSE
#ifdef DAI_VERBOSE
#   define DAI_LOG(MESSAGE) do { std::cout << MESSAGE << std::endl; } while(0)
#else
#   define DAI_LOG(MESSAGE)
#endif

namespace dai {

using namespace std;

void BP::setProperties( const PropertySet &opts ) {
    DAI_ASSERT( opts.hasKey("tol") );
    DAI_ASSERT( opts.hasKey("updates") );

    props.tol = opts.getStringAs<Real>("tol");

    if( opts.hasKey("maxiter") )
        props.maxiter = opts.getStringAs<size_t>("maxiter");
    else
        props.maxiter = 10000;
    if( opts.hasKey("maxtime") )
        props.maxtime = opts.getStringAs<Real>("maxtime");
    else
        props.maxtime = INFINITY;
    if( opts.hasKey("verbose") )
        props.verbose = opts.getStringAs<size_t>("verbose");
    else
        props.verbose = 0;
    if( opts.hasKey("damping") )
        props.damping = opts.getStringAs<Real>("damping");
    else
        props.damping = 0.0;
}

PropertySet BP::getProperties() const {
    PropertySet opts;
    opts.set( "tol", props.tol );
    opts.set( "maxiter", props.maxiter );
    opts.set( "maxtime", props.maxtime );
    opts.set( "verbose", props.verbose );
    opts.set( "damping", props.damping );
    return opts;
}

string BP::printProperties() const {
    stringstream s( stringstream::out );
    s << "[";
    s << "tol=" << props.tol << ",";
    s << "maxiter=" << props.maxiter << ",";
    s << "maxtime=" << props.maxtime << ",";
    s << "verbose=" << props.verbose << ",";
    s << "damping=" << props.damping << "]";
    return s.str();
}

void BP::construct() {
    // create edge properties
    _edges.clear();
    _edges.reserve( nrVars() );
    _oldProd.clear();
    _edge2lutNew.clear();
    _edge2lutNew.reserve( nrVars() );
    for( size_t i = 0; i < nrVars(); ++i ) {
        _edges.push_back( vector<EdgeProp>() );
        _edges[i].reserve( nbV(i).size() );
        _oldProd.push_back(vector<double>(var(i).states(), 1));
        _edge2lutNew.push_back( vector<heap_data_handle>() );
        _edge2lutNew[i].reserve( nbV(i).size() );
        for( const Neighbor &I : nbV(i) ) {
            EdgeProp newEP;
            newEP.message = Prob( var(i).states() );
            newEP.newMessage = Prob( var(i).states() );

            newEP.index.reserve( factor(I).nrStates() );
            for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k )
                newEP.index.push_back( k );

            newEP.residual = 0.0;
            _edges[i].push_back( newEP );
            _edge2lutNew[i].push_back( _lutNew.push( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))));
        }
    }

    // create old beliefs
    _oldBeliefsV.clear();
    _oldBeliefsV.reserve( nrVars() );
    for( size_t i = 0; i < nrVars(); ++i )
        _oldBeliefsV.push_back( Factor( var(i) ) );
    _oldBeliefsF.clear();
    _oldBeliefsF.reserve( nrFactors() );
    for( size_t I = 0; I < nrFactors(); ++I )
        _oldBeliefsF.push_back( Factor( factor(I).vars() ) );

    // create update sequence
    _updateSeq.clear();
    _updateSeq.reserve( nrEdges() );
    for( size_t I = 0; I < nrFactors(); I++ )
        for( const Neighbor &i : nbF(I) )
            _updateSeq.push_back( Edge( i, i.dual ) );
}

void BP::init() {
    Real c = 1.0;
    for( size_t i = 0; i < nrVars(); ++i ) {
        for( const Neighbor &I : nbV(i) ) {
            message( i, I.iter ).fill( c );
            newMessage( i, I.iter ).fill( c );
            updateResidual( i, I.iter, 0.0 );
        }
    }
    _iters = 0;
}

void BP::findMaxResidual( size_t &i, size_t &_I ) {
    DAI_ASSERT( !_lutNew.empty() );
    i  = _lutNew.top().second.first;
    _I = _lutNew.top().second.second;
}

// TODO: Optimize (in progress)
void BP::calcIncomingMessageProduct(Prob &prod, size_t I, bool without_i, size_t i) const {

    // Calculate product of incoming messages and factor I
    for(const Neighbor &j: nbF(I)) {
        if( !(without_i && (j == i)) ) {
            // _prod_j will contain the product of messages coming into j
            // This will be a no-op if size() is smaller than the current capacity.
            // Clear won't free any memory for std::vector<Real>.
            _prod_j.reserve(_oldProd[j.node].size());
            _prod_j.clear();

            // The message that should not go into the product is the one from that
            // node that that message will be sent to. Conveniently, the value is
            // already available: j.dual.
            size_t Iiter = j.dual;

            // Now let us divide by that message.
            for (size_t k=0; k<_oldProd[j.node].size(); ++k) {
                _prod_j.push_back(_oldProd[j.node][k] / _edges[j][Iiter].message._p[k]);
            }

            DAI_LOG("Product of incoming messages into " << j << " is " << _prod_j);

            // TODO: If we understand this we might be able to get rid of this whole function call and use _oldProd directly.
            // multiply prod with _prod_j
            size_t _I = j.dual;
            // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
            const ind_t &ind = index(j, _I);
            for(size_t r = 0; r < prod.size(); ++r) {
                prod._p[r] *= _prod_j[ind[r]];
            }
        }
    }
}

void BP::calcNewMessage( size_t i, size_t _I) {

    // load
    size_t I = _G.nb1(i)[_I].node;
    Prob marg;

    // The following applies only rarely  (uV2New1: 50x, uNew1 and u1: 135x)
    // TODO: investigate further, can this still be useful?
#if 0
    if( factor(I).vars().size() == 1 ) // optimization
        marg = factor(I).p();
    else {
#endif

    // calculate updated message I->i
    Prob prod = Prob(_factors[I].p());
    calcIncomingMessageProduct(prod, I, true, i);
    DAI_LOG("calcNewMessage " << I << " <-> " << i);

    // Marginalize onto i
    marg = Prob( var(i).states(), 0.0 );
    // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
    const ind_t ind = index(i,_I);
    for( size_t r = 0; r < prod.size(); ++r )
        marg.set( ind[r], marg[ind[r]] + prod[r] );
    marg.normalizeFast();

    // Store result
    newMessage(i,_I) = marg;

    // Update the residual if necessary
    updateResidual( i, _I , dist( newMessage( i, _I ), message( i, _I ), DISTLINF ) );
}

// BP::run does not check for NANs for performance reasons
// Somehow NaNs do not often occur in BP...
Real BP::run() {
    if( props.verbose >= 1 )
        cerr << "Starting " << identify() << "...";
    if( props.verbose >= 3)
        cerr << endl;

    double tic = toc();

    // do several passes over the network until maximum number of iterations has
    // been reached or until the maximum belief difference is smaller than tolerance
    Real maxDiff = INFINITY;
    for( ; _iters < props.maxiter && maxDiff > props.tol && (toc() - tic) < props.maxtime; _iters++ ) {
        if( _iters == 0 ) {
            // do the first pass
            for( size_t i = 0; i < nrVars(); ++i )
                for( const Neighbor &I : nbV(i) ) {
                    calcNewMessage( i, I.iter);
                }
        }
        // Maximum-Residual BP [\ref EMK06]
        for( size_t t = 0; t < _updateSeq.size(); ++t ) {
            // update the message with the largest residual
            size_t i, _I;
            findMaxResidual( i, _I );
            DAI_LOG("updating message from " << i << " to " << _I);
            updateMessage( i, _I );

            // I->i has been updated, which means that residuals for all
            // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
            for( const Neighbor &J: nbV(i) ) {
                if( J.iter != _I ) {
                    for( const Neighbor &j: nbF(J) ) {
                        size_t _J = j.dual;
                        if( j != i )
                            calcNewMessage( j, _J);
                    }
                }
            }
        }

        // calculate new beliefs and compare with old ones
        maxDiff = -INFINITY;
        for( size_t i = 0; i < nrVars(); ++i ) {
            Factor b( beliefV(i) );
            maxDiff = std::max( maxDiff, dist( b, _oldBeliefsV[i], DISTLINF ) );
            _oldBeliefsV[i] = b;
        }
        for( size_t I = 0; I < nrFactors(); ++I ) {
            Factor b( beliefF(I) );
            maxDiff = std::max( maxDiff, dist( b, _oldBeliefsF[I], DISTLINF ) );
            _oldBeliefsF[I] = b;
        }

        if( props.verbose >= 3 )
            cerr << name() << "::run:  maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
    }

    if( maxDiff > _maxdiff )
        _maxdiff = maxDiff;

    if( props.verbose >= 1 ) {
        if( maxDiff > props.tol ) {
            if( props.verbose == 1 )
                cerr << endl;
                cerr << name() << "::run:  WARNING: not converged after " << _iters << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
        } else {
            if( props.verbose >= 3 )
                cerr << name() << "::run:  ";
                cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
        }
    }

    return maxDiff;
}

void BP::calcBeliefV( size_t i, Prob &p ) const {
    p = Prob( var(i).states(), 1.0);
    for ( const Neighbor &I : nbV(i) )
            p *= newMessage( i, I.iter );
}

Factor BP::beliefV( size_t i ) const {
    Prob p;
    calcBeliefV( i, p );
    p.normalize();

    return( Factor( var(i), p ) );
}

Factor BP::beliefF( size_t I ) const {
    Factor Fprod( factor(I) );
    Prob &p = Fprod.p();
    calcBeliefF( I, p );
    p.normalize();

    return( Factor( factor(I).vars(), p ) );
}

vector<Factor> BP::beliefs() const {
    vector<Factor> result;
    for( size_t i = 0; i < nrVars(); ++i )
        result.push_back( beliefV(i) );
    for( size_t I = 0; I < nrFactors(); ++I )
        result.push_back( beliefF(I) );
    return result;
}

Factor BP::belief( const VarSet &ns ) const {
    if( ns.size() == 0 )
        return Factor();
    else if( ns.size() == 1 )
        return beliefV( findVar( *(ns.begin() ) ) );
    else {
        size_t I;
        for( I = 0; I < nrFactors(); I++ )
            if( factor(I).vars() >> ns )
                break;
        if( I == nrFactors() )
            DAI_THROW(BELIEF_NOT_AVAILABLE);
        return beliefF(I).marginal(ns);
    }
}

Real BP::logZ() const {
    Real sum = 0.0;
    for( size_t i = 0; i < nrVars(); ++i )
        sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
    for( size_t I = 0; I < nrFactors(); ++I )
        sum -= dist( beliefF(I), factor(I), DISTKL );
    return sum;
}

void BP::init( const VarSet &ns ) {
    for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
        size_t ni = findVar( *n );
        for( const Neighbor &I : nbV( ni ) ) {
            Real val = 1.0;
            message( ni, I.iter ).fill( val );
            newMessage( ni, I.iter ).fill( val );
            updateResidual( ni, I.iter, 0.0 );
        }
    }
    _iters = 0;
}

void BP::updateMessage( size_t i, size_t _I ) {
    for (size_t j=0; j<_oldProd[i].size(); ++j) {
        _oldProd[i][j] =  _edges[i][_I].newMessage._p[j] * _oldProd[i][j] / _edges[i][_I].message._p[j];
    }

    if( recordSentMessages )
        _sentMessages.push_back(make_pair(i,_I));
    if( props.damping == 0.0 ) {
        message(i,_I) = newMessage(i,_I);
        updateResidual( i, _I, 0.0 );
    } else {
        message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
        updateResidual( i, _I, dist( newMessage(i,_I), message(i,_I), DISTLINF ) );
    }
}

// TODO: Optimize: We are using a heap now but this is not faster then the multimap solution. So we might have to revert to it.
void BP::updateResidual( size_t i, size_t _I, Real r ) {
    EdgeProp* pEdge = &_edges[i][_I];
    pEdge->residual = r;

    // rearrange look-up table (delete and reinsert new key)
    _lutNew.update(_edge2lutNew[i][_I], make_pair( r, make_pair(i, _I) ));
}

} // end of namespace dai

#endif
<commit_msg>Swap the order of clear and reserve (first clear it then reserve, not the other way around).<commit_after>/*  This file is part of libDAI - http://www.libdai.org/
 *
 *  Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
 */

#include <dai/dai_config.h>
#ifdef DAI_WITH_BP

#include <iostream>
#include <sstream>
#include <map>
#include <set>
#include <algorithm>
#include <dai/bp.h>
#include <dai/util.h>
#include <dai/properties.h>

//#define DAI_VERBOSE
#ifdef DAI_VERBOSE
#   define DAI_LOG(MESSAGE) do { std::cout << MESSAGE << std::endl; } while(0)
#else
#   define DAI_LOG(MESSAGE)
#endif

namespace dai {

using namespace std;

void BP::setProperties( const PropertySet &opts ) {
    DAI_ASSERT( opts.hasKey("tol") );
    DAI_ASSERT( opts.hasKey("updates") );

    props.tol = opts.getStringAs<Real>("tol");

    if( opts.hasKey("maxiter") )
        props.maxiter = opts.getStringAs<size_t>("maxiter");
    else
        props.maxiter = 10000;
    if( opts.hasKey("maxtime") )
        props.maxtime = opts.getStringAs<Real>("maxtime");
    else
        props.maxtime = INFINITY;
    if( opts.hasKey("verbose") )
        props.verbose = opts.getStringAs<size_t>("verbose");
    else
        props.verbose = 0;
    if( opts.hasKey("damping") )
        props.damping = opts.getStringAs<Real>("damping");
    else
        props.damping = 0.0;
}

PropertySet BP::getProperties() const {
    PropertySet opts;
    opts.set( "tol", props.tol );
    opts.set( "maxiter", props.maxiter );
    opts.set( "maxtime", props.maxtime );
    opts.set( "verbose", props.verbose );
    opts.set( "damping", props.damping );
    return opts;
}

string BP::printProperties() const {
    stringstream s( stringstream::out );
    s << "[";
    s << "tol=" << props.tol << ",";
    s << "maxiter=" << props.maxiter << ",";
    s << "maxtime=" << props.maxtime << ",";
    s << "verbose=" << props.verbose << ",";
    s << "damping=" << props.damping << "]";
    return s.str();
}

void BP::construct() {
    // create edge properties
    _edges.clear();
    _edges.reserve( nrVars() );
    _oldProd.clear();
    _edge2lutNew.clear();
    _edge2lutNew.reserve( nrVars() );
    for( size_t i = 0; i < nrVars(); ++i ) {
        _edges.push_back( vector<EdgeProp>() );
        _edges[i].reserve( nbV(i).size() );
        _oldProd.push_back(vector<double>(var(i).states(), 1));
        _edge2lutNew.push_back( vector<heap_data_handle>() );
        _edge2lutNew[i].reserve( nbV(i).size() );
        for( const Neighbor &I : nbV(i) ) {
            EdgeProp newEP;
            newEP.message = Prob( var(i).states() );
            newEP.newMessage = Prob( var(i).states() );

            newEP.index.reserve( factor(I).nrStates() );
            for( IndexFor k( var(i), factor(I).vars() ); k.valid(); ++k )
                newEP.index.push_back( k );

            newEP.residual = 0.0;
            _edges[i].push_back( newEP );
            _edge2lutNew[i].push_back( _lutNew.push( make_pair( newEP.residual, make_pair( i, _edges[i].size() - 1 ))));
        }
    }

    // create old beliefs
    _oldBeliefsV.clear();
    _oldBeliefsV.reserve( nrVars() );
    for( size_t i = 0; i < nrVars(); ++i )
        _oldBeliefsV.push_back( Factor( var(i) ) );
    _oldBeliefsF.clear();
    _oldBeliefsF.reserve( nrFactors() );
    for( size_t I = 0; I < nrFactors(); ++I )
        _oldBeliefsF.push_back( Factor( factor(I).vars() ) );

    // create update sequence
    _updateSeq.clear();
    _updateSeq.reserve( nrEdges() );
    for( size_t I = 0; I < nrFactors(); I++ )
        for( const Neighbor &i : nbF(I) )
            _updateSeq.push_back( Edge( i, i.dual ) );
}

void BP::init() {
    Real c = 1.0;
    for( size_t i = 0; i < nrVars(); ++i ) {
        for( const Neighbor &I : nbV(i) ) {
            message( i, I.iter ).fill( c );
            newMessage( i, I.iter ).fill( c );
            updateResidual( i, I.iter, 0.0 );
        }
    }
    _iters = 0;
}

void BP::findMaxResidual( size_t &i, size_t &_I ) {
    DAI_ASSERT( !_lutNew.empty() );
    i  = _lutNew.top().second.first;
    _I = _lutNew.top().second.second;
}

// TODO: Optimize (in progress)
void BP::calcIncomingMessageProduct(Prob &prod, size_t I, bool without_i, size_t i) const {

    // Calculate product of incoming messages and factor I
    for(const Neighbor &j: nbF(I)) {
        if( !(without_i && (j == i)) ) {
            // _prod_j will contain the product of messages coming into j
            // This will be a no-op if size() is smaller than the current capacity.
            // Clear won't free any memory for std::vector<Real>.
            _prod_j.clear();
            _prod_j.reserve(_oldProd[j.node].size());
            // The message that should not go into the product is the one from that
            // node that that message will be sent to. Conveniently, the value is
            // already available: j.dual.
            size_t Iiter = j.dual;

            // Now let us divide by that message.
            for (size_t k=0; k<_oldProd[j.node].size(); ++k) {
                _prod_j.push_back(_oldProd[j.node][k] / _edges[j][Iiter].message._p[k]);
            }

            DAI_LOG("Product of incoming messages into " << j << " is " << _prod_j);

            // TODO: If we understand this we might be able to get rid of this whole function call and use _oldProd directly.
            // multiply prod with _prod_j
            size_t _I = j.dual;
            // ind is the precalculated IndexFor(j,I) i.e. to x_I == k corresponds x_j == ind[k]
            const ind_t &ind = index(j, _I);
            for(size_t r = 0; r < prod.size(); ++r) {
                prod._p[r] *= _prod_j[ind[r]];
            }
        }
    }
}

void BP::calcNewMessage( size_t i, size_t _I) {

    // load
    size_t I = _G.nb1(i)[_I].node;
    Prob marg;

    // The following applies only rarely  (uV2New1: 50x, uNew1 and u1: 135x)
    // TODO: investigate further, can this still be useful?
#if 0
    if( factor(I).vars().size() == 1 ) // optimization
        marg = factor(I).p();
    else {
#endif

    // calculate updated message I->i
    Prob prod = Prob(_factors[I].p());
    calcIncomingMessageProduct(prod, I, true, i);
    DAI_LOG("calcNewMessage " << I << " <-> " << i);

    // Marginalize onto i
    marg = Prob( var(i).states(), 0.0 );
    // ind is the precalculated IndexFor(i,I) i.e. to x_I == k corresponds x_i == ind[k]
    const ind_t ind = index(i,_I);
    for( size_t r = 0; r < prod.size(); ++r )
        marg.set( ind[r], marg[ind[r]] + prod[r] );
    marg.normalizeFast();

    // Store result
    newMessage(i,_I) = marg;

    // Update the residual if necessary
    updateResidual( i, _I , dist( newMessage( i, _I ), message( i, _I ), DISTLINF ) );
}

// BP::run does not check for NANs for performance reasons
// Somehow NaNs do not often occur in BP...
Real BP::run() {
    if( props.verbose >= 1 )
        cerr << "Starting " << identify() << "...";
    if( props.verbose >= 3)
        cerr << endl;

    double tic = toc();

    // do several passes over the network until maximum number of iterations has
    // been reached or until the maximum belief difference is smaller than tolerance
    Real maxDiff = INFINITY;
    for( ; _iters < props.maxiter && maxDiff > props.tol && (toc() - tic) < props.maxtime; _iters++ ) {
        if( _iters == 0 ) {
            // do the first pass
            for( size_t i = 0; i < nrVars(); ++i )
                for( const Neighbor &I : nbV(i) ) {
                    calcNewMessage( i, I.iter);
                }
        }
        // Maximum-Residual BP [\ref EMK06]
        for( size_t t = 0; t < _updateSeq.size(); ++t ) {
            // update the message with the largest residual
            size_t i, _I;
            findMaxResidual( i, _I );
            DAI_LOG("updating message from " << i << " to " << _I);
            updateMessage( i, _I );

            // I->i has been updated, which means that residuals for all
            // J->j with J in nb[i]\I and j in nb[J]\i have to be updated
            for( const Neighbor &J: nbV(i) ) {
                if( J.iter != _I ) {
                    for( const Neighbor &j: nbF(J) ) {
                        size_t _J = j.dual;
                        if( j != i )
                            calcNewMessage( j, _J);
                    }
                }
            }
        }

        // calculate new beliefs and compare with old ones
        maxDiff = -INFINITY;
        for( size_t i = 0; i < nrVars(); ++i ) {
            Factor b( beliefV(i) );
            maxDiff = std::max( maxDiff, dist( b, _oldBeliefsV[i], DISTLINF ) );
            _oldBeliefsV[i] = b;
        }
        for( size_t I = 0; I < nrFactors(); ++I ) {
            Factor b( beliefF(I) );
            maxDiff = std::max( maxDiff, dist( b, _oldBeliefsF[I], DISTLINF ) );
            _oldBeliefsF[I] = b;
        }

        if( props.verbose >= 3 )
            cerr << name() << "::run:  maxdiff " << maxDiff << " after " << _iters+1 << " passes" << endl;
    }

    if( maxDiff > _maxdiff )
        _maxdiff = maxDiff;

    if( props.verbose >= 1 ) {
        if( maxDiff > props.tol ) {
            if( props.verbose == 1 )
                cerr << endl;
                cerr << name() << "::run:  WARNING: not converged after " << _iters << " passes (" << toc() - tic << " seconds)...final maxdiff:" << maxDiff << endl;
        } else {
            if( props.verbose >= 3 )
                cerr << name() << "::run:  ";
                cerr << "converged in " << _iters << " passes (" << toc() - tic << " seconds)." << endl;
        }
    }

    return maxDiff;
}

void BP::calcBeliefV( size_t i, Prob &p ) const {
    p = Prob( var(i).states(), 1.0);
    for ( const Neighbor &I : nbV(i) )
            p *= newMessage( i, I.iter );
}

Factor BP::beliefV( size_t i ) const {
    Prob p;
    calcBeliefV( i, p );
    p.normalize();

    return( Factor( var(i), p ) );
}

Factor BP::beliefF( size_t I ) const {
    Factor Fprod( factor(I) );
    Prob &p = Fprod.p();
    calcBeliefF( I, p );
    p.normalize();

    return( Factor( factor(I).vars(), p ) );
}

vector<Factor> BP::beliefs() const {
    vector<Factor> result;
    for( size_t i = 0; i < nrVars(); ++i )
        result.push_back( beliefV(i) );
    for( size_t I = 0; I < nrFactors(); ++I )
        result.push_back( beliefF(I) );
    return result;
}

Factor BP::belief( const VarSet &ns ) const {
    if( ns.size() == 0 )
        return Factor();
    else if( ns.size() == 1 )
        return beliefV( findVar( *(ns.begin() ) ) );
    else {
        size_t I;
        for( I = 0; I < nrFactors(); I++ )
            if( factor(I).vars() >> ns )
                break;
        if( I == nrFactors() )
            DAI_THROW(BELIEF_NOT_AVAILABLE);
        return beliefF(I).marginal(ns);
    }
}

Real BP::logZ() const {
    Real sum = 0.0;
    for( size_t i = 0; i < nrVars(); ++i )
        sum += (1.0 - nbV(i).size()) * beliefV(i).entropy();
    for( size_t I = 0; I < nrFactors(); ++I )
        sum -= dist( beliefF(I), factor(I), DISTKL );
    return sum;
}

void BP::init( const VarSet &ns ) {
    for( VarSet::const_iterator n = ns.begin(); n != ns.end(); ++n ) {
        size_t ni = findVar( *n );
        for( const Neighbor &I : nbV( ni ) ) {
            Real val = 1.0;
            message( ni, I.iter ).fill( val );
            newMessage( ni, I.iter ).fill( val );
            updateResidual( ni, I.iter, 0.0 );
        }
    }
    _iters = 0;
}

void BP::updateMessage( size_t i, size_t _I ) {
    for (size_t j=0; j<_oldProd[i].size(); ++j) {
        _oldProd[i][j] =  _edges[i][_I].newMessage._p[j] * _oldProd[i][j] / _edges[i][_I].message._p[j];
    }

    if( recordSentMessages )
        _sentMessages.push_back(make_pair(i,_I));
    if( props.damping == 0.0 ) {
        message(i,_I) = newMessage(i,_I);
        updateResidual( i, _I, 0.0 );
    } else {
        message(i,_I) = (message(i,_I) ^ props.damping) * (newMessage(i,_I) ^ (1.0 - props.damping));
        updateResidual( i, _I, dist( newMessage(i,_I), message(i,_I), DISTLINF ) );
    }
}

// TODO: Optimize: We are using a heap now but this is not faster then the multimap solution. So we might have to revert to it.
void BP::updateResidual( size_t i, size_t _I, Real r ) {
    EdgeProp* pEdge = &_edges[i][_I];
    pEdge->residual = r;

    // rearrange look-up table (delete and reinsert new key)
    _lutNew.update(_edge2lutNew[i][_I], make_pair( r, make_pair(i, _I) ));
}

} // end of namespace dai

#endif
<|endoftext|>


<commit_before>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <alpaka/mem/view/Traits.hpp>   // dev::traits::DevType, DimType, GetExtent,Copy, GetOffset, ...

#include <alpaka/vec/Vec.hpp>           // Vec<N>

namespace alpaka
{
    namespace mem
    {
        namespace view
        {
            //#############################################################################
            //! The memory view to wrap plain pointers.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            class ViewPlainPtr final
            {
            public:
                //-----------------------------------------------------------------------------
                //! Constructor
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TExtent>
                ALPAKA_FN_HOST_ACC ViewPlainPtr(
                    TElem * pMem,
                    TDev const & dev,
                    TExtent const & extent = TExtent()) :
                        m_pMem(pMem),
                        m_dev(dev),
                        m_extentElements(extent::getExtentVecEnd<TDim>(extent)),
                        m_pitchBytes(Vec<TDim, TSize>::all(0))
                {
                    // Calculate the pitches by hand.
                    m_pitchBytes[TDim::value - 1u] = extent[TDim::value - 1u] * sizeof(TElem);
                    for(TSize i = TDim::value - 1u; i > static_cast<TSize>(0u); --i)
                    {
                        m_pitchBytes[i-1] = extent[i-1] * m_pitchBytes[i];
                    }
                }

                //-----------------------------------------------------------------------------
                //! Constructor
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TExtent,
                    typename TPitch>
                ALPAKA_FN_HOST_ACC ViewPlainPtr(
                    TElem * pMem,
                    TDev const dev,
                    TExtent const & extent,
                    TPitch const & pitchBytes) :
                        m_pMem(pMem),
                        m_dev(dev),
                        m_extentElements(extent::getExtentVecEnd<TDim>(extent)),
                        m_pitchBytes(vec::subVecEnd<TDim>(pitchBytes))
                {}

                //-----------------------------------------------------------------------------
                //! Copy constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC ViewPlainPtr(ViewPlainPtr const &) = delete;
                //-----------------------------------------------------------------------------
                //! Move constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC ViewPlainPtr(ViewPlainPtr &&) = default;
                //-----------------------------------------------------------------------------
                //! Copy assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC auto operator=(ViewPlainPtr const &) -> ViewPlainPtr & = delete;
                //-----------------------------------------------------------------------------
                //! Move assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC auto operator=(ViewPlainPtr &&) -> ViewPlainPtr & = default;
                //-----------------------------------------------------------------------------
                //! Destructor.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC ~ViewPlainPtr() = default;

            public:
                TElem * m_pMem;
                TDev m_dev;
                Vec<TDim, TSize> m_extentElements;
                Vec<TDim, TSize> m_pitchBytes;
            };
        }
    }

    //-----------------------------------------------------------------------------
    // Trait specializations for ViewPlainPtr.
    //-----------------------------------------------------------------------------
    namespace dev
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr device type trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct DevType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TDev;
            };

            //#############################################################################
            //! The ViewPlainPtr device get trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct GetDev<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC static auto getDev(
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & view)
                    -> TDev
                {
                    return view.m_dev;
                }
            };
        }
    }
    namespace dim
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr dimension getter trait.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct DimType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TDim;
            };
        }
    }
    namespace elem
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr memory element type get trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct ElemType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TElem;
            };
        }
    }
    namespace extent
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr width get trait specialization.
            //#############################################################################
            template<
                typename TIdx,
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct GetExtent<
                TIdx,
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>,
                typename std::enable_if<(TDim::value > TIdx::value)>::type>
            {
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC static auto getExtent(
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & extent)
                -> TSize
                {
                    return extent.m_extentElements[TIdx::value];
                }
            };
        }
    }
    namespace mem
    {
        namespace view
        {
            namespace traits
            {
                //#############################################################################
                //! The ViewPlainPtr native pointer get trait specialization.
                //#############################################################################
                template<
                    typename TDev,
                    typename TElem,
                    typename TDim,
                    typename TSize>
                struct GetPtrNative<
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
                {
                    ALPAKA_NO_HOST_ACC_WARNING
                    ALPAKA_FN_HOST_ACC static auto getPtrNative(
                        mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & view)
                    -> TElem const *
                    {
                        return view.m_pMem;
                    }
                    ALPAKA_NO_HOST_ACC_WARNING
                    ALPAKA_FN_HOST_ACC static auto getPtrNative(
                        mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> & view)
                    -> TElem *
                    {
                        return view.m_pMem;
                    }
                };

                //#############################################################################
                //! The ViewPlainPtr memory pitch get trait specialization.
                //#############################################################################
                template<
                    typename TIdx,
                    typename TDev,
                    typename TElem,
                    typename TDim,
                    typename TSize>
                struct GetPitchBytes<
                    TIdx,
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>,
                    typename std::enable_if<TIdx::value < TDim::value>::type>
                {
                    ALPAKA_NO_HOST_ACC_WARNING
                    ALPAKA_FN_HOST_ACC static auto getPitchBytes(
                        mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & view)
                    -> TSize
                    {
                        return view.m_pitchBytes[TIdx::value];
                    }
                };
            }
        }
    }
    namespace offset
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr offset get trait specialization.
            //#############################################################################
            template<
                typename TIdx,
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct GetOffset<
                TIdx,
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                //-----------------------------------------------------------------------------
                //!
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC static auto getOffset(
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const &)
                -> TSize
                {
                    return 0u;
                }
            };
        }
    }
    namespace size
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr size type trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct SizeType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TSize;
            };
        }
    }
}<commit_msg>fix invalid call of `vec::subVecEnd<>()`<commit_after>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/

#pragma once

#include <alpaka/mem/view/Traits.hpp>   // dev::traits::DevType, DimType, GetExtent,Copy, GetOffset, ...

#include <alpaka/vec/Vec.hpp>           // Vec<N>

namespace alpaka
{
    namespace mem
    {
        namespace view
        {
            //#############################################################################
            //! The memory view to wrap plain pointers.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            class ViewPlainPtr final
            {
            public:
                //-----------------------------------------------------------------------------
                //! Constructor
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TExtent>
                ALPAKA_FN_HOST_ACC ViewPlainPtr(
                    TElem * pMem,
                    TDev const & dev,
                    TExtent const & extent = TExtent()) :
                        m_pMem(pMem),
                        m_dev(dev),
                        m_extentElements(extent::getExtentVecEnd<TDim>(extent)),
                        m_pitchBytes(Vec<TDim, TSize>::all(0))
                {
                    // Calculate the pitches by hand.
                    m_pitchBytes[TDim::value - 1u] = extent[TDim::value - 1u] * sizeof(TElem);
                    for(TSize i = TDim::value - 1u; i > static_cast<TSize>(0u); --i)
                    {
                        m_pitchBytes[i-1] = extent[i-1] * m_pitchBytes[i];
                    }
                }

                //-----------------------------------------------------------------------------
                //! Constructor
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                template<
                    typename TExtent,
                    typename TPitch>
                ALPAKA_FN_HOST_ACC ViewPlainPtr(
                    TElem * pMem,
                    TDev const dev,
                    TExtent const & extent,
                    TPitch const & pitchBytes) :
                        m_pMem(pMem),
                        m_dev(dev),
                        m_extentElements(extent::getExtentVecEnd<TDim>(extent)),
                        m_pitchBytes(
                            vec::subVecEnd<TDim>(
                               static_cast<
                                    Vec<TDim, TSize> >(pitchBytes)
                            )
                        )
                {}

                //-----------------------------------------------------------------------------
                //! Copy constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC ViewPlainPtr(ViewPlainPtr const &) = delete;
                //-----------------------------------------------------------------------------
                //! Move constructor.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC ViewPlainPtr(ViewPlainPtr &&) = default;
                //-----------------------------------------------------------------------------
                //! Copy assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC auto operator=(ViewPlainPtr const &) -> ViewPlainPtr & = delete;
                //-----------------------------------------------------------------------------
                //! Move assignment operator.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC auto operator=(ViewPlainPtr &&) -> ViewPlainPtr & = default;
                //-----------------------------------------------------------------------------
                //! Destructor.
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC ~ViewPlainPtr() = default;

            public:
                TElem * m_pMem;
                TDev m_dev;
                Vec<TDim, TSize> m_extentElements;
                Vec<TDim, TSize> m_pitchBytes;
            };
        }
    }

    //-----------------------------------------------------------------------------
    // Trait specializations for ViewPlainPtr.
    //-----------------------------------------------------------------------------
    namespace dev
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr device type trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct DevType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TDev;
            };

            //#############################################################################
            //! The ViewPlainPtr device get trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct GetDev<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC static auto getDev(
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & view)
                    -> TDev
                {
                    return view.m_dev;
                }
            };
        }
    }
    namespace dim
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr dimension getter trait.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct DimType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TDim;
            };
        }
    }
    namespace elem
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr memory element type get trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct ElemType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TElem;
            };
        }
    }
    namespace extent
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr width get trait specialization.
            //#############################################################################
            template<
                typename TIdx,
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct GetExtent<
                TIdx,
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>,
                typename std::enable_if<(TDim::value > TIdx::value)>::type>
            {
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC static auto getExtent(
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & extent)
                -> TSize
                {
                    return extent.m_extentElements[TIdx::value];
                }
            };
        }
    }
    namespace mem
    {
        namespace view
        {
            namespace traits
            {
                //#############################################################################
                //! The ViewPlainPtr native pointer get trait specialization.
                //#############################################################################
                template<
                    typename TDev,
                    typename TElem,
                    typename TDim,
                    typename TSize>
                struct GetPtrNative<
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
                {
                    ALPAKA_NO_HOST_ACC_WARNING
                    ALPAKA_FN_HOST_ACC static auto getPtrNative(
                        mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & view)
                    -> TElem const *
                    {
                        return view.m_pMem;
                    }
                    ALPAKA_NO_HOST_ACC_WARNING
                    ALPAKA_FN_HOST_ACC static auto getPtrNative(
                        mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> & view)
                    -> TElem *
                    {
                        return view.m_pMem;
                    }
                };

                //#############################################################################
                //! The ViewPlainPtr memory pitch get trait specialization.
                //#############################################################################
                template<
                    typename TIdx,
                    typename TDev,
                    typename TElem,
                    typename TDim,
                    typename TSize>
                struct GetPitchBytes<
                    TIdx,
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>,
                    typename std::enable_if<TIdx::value < TDim::value>::type>
                {
                    ALPAKA_NO_HOST_ACC_WARNING
                    ALPAKA_FN_HOST_ACC static auto getPitchBytes(
                        mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const & view)
                    -> TSize
                    {
                        return view.m_pitchBytes[TIdx::value];
                    }
                };
            }
        }
    }
    namespace offset
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr offset get trait specialization.
            //#############################################################################
            template<
                typename TIdx,
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct GetOffset<
                TIdx,
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                //-----------------------------------------------------------------------------
                //!
                //-----------------------------------------------------------------------------
                ALPAKA_NO_HOST_ACC_WARNING
                ALPAKA_FN_HOST_ACC static auto getOffset(
                    mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize> const &)
                -> TSize
                {
                    return 0u;
                }
            };
        }
    }
    namespace size
    {
        namespace traits
        {
            //#############################################################################
            //! The ViewPlainPtr size type trait specialization.
            //#############################################################################
            template<
                typename TDev,
                typename TElem,
                typename TDim,
                typename TSize>
            struct SizeType<
                mem::view::ViewPlainPtr<TDev, TElem, TDim, TSize>>
            {
                using type = TSize;
            };
        }
    }
}<|endoftext|>


<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_LAGARITH_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Video/File_Lagarith.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Lagarith::File_Lagarith()
:File__Analyze()
{
    //Configuration
    ParserName=__T("Lagarith");
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Lagarith::Streams_Fill()
{
    Stream_Prepare(Stream_Video);
    Fill(Stream_Video, 0, Video_Format, "Lagarith");
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_Lagarith::Read_Buffer_Continue()
{
    //Parsing
    int8u version;
    Get_L1 (version,                                            "version");
    Skip_XX(Element_Size-Element_Offset,                        "data");

    FILLING_BEGIN();
        Accept();
        Fill();
        switch (version)
        {
            case 0x02 : Fill(Stream_Video, 0, Video_ColorSpace, "RGB"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            case 0x03 : Fill(Stream_Video, 0, Video_ColorSpace, "YUV"); Fill(Stream_Video, 0, Video_ChromaSubsampling, "4:2:2"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            case 0x04 : Fill(Stream_Video, 0, Video_ColorSpace, "RGB"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            case 0x05 : Fill(Stream_Video, 0, Video_ColorSpace, "Grey"); break;
            case 0x06 : Fill(Stream_Video, 0, Video_ColorSpace, "RGB"); break;
            case 0x07 : Fill(Stream_Video, 0, Video_ColorSpace, "RGB"); break;
            case 0x08 : Fill(Stream_Video, 0, Video_ColorSpace, "RGBA"); break;
            case 0x09 : Fill(Stream_Video, 0, Video_ColorSpace, "RGBA"); break;
            case 0x0A : Fill(Stream_Video, 0, Video_ColorSpace, "YUV"); Fill(Stream_Video, 0, Video_ChromaSubsampling, "4:2:0"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            case 0x0B : Fill(Stream_Video, 0, Video_ColorSpace, "YUV"); Fill(Stream_Video, 0, Video_ChromaSubsampling, "4:2:0"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            default   : ;
        }

    FILLING_END();
    Finish();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_LAGARITH_YES
<commit_msg>x Some cleanup<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_LAGARITH_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Video/File_Lagarith.h"
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Lagarith::File_Lagarith()
:File__Analyze()
{
    //Configuration
    ParserName=__T("Lagarith");
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Lagarith::Streams_Fill()
{
    Stream_Prepare(Stream_Video);
    Fill(Stream_Video, 0, Video_Format, "Lagarith");
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
void File_Lagarith::Read_Buffer_Continue()
{
    //Parsing
    int8u version;
    Get_L1 (version,                                            "version");
    Skip_XX(Element_Size-Element_Offset,                        "data");

    FILLING_BEGIN();
        Accept();
        Fill();
        switch (version)
        {
            case 0x02 :
            case 0x04 : Fill(Stream_Video, 0, Video_ColorSpace, "RGB"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            case 0x03 : Fill(Stream_Video, 0, Video_ColorSpace, "YUV"); Fill(Stream_Video, 0, Video_ChromaSubsampling, "4:2:2"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            case 0x05 : Fill(Stream_Video, 0, Video_ColorSpace, "Y"); break;
            case 0x06 :
            case 0x07 : Fill(Stream_Video, 0, Video_ColorSpace, "RGB"); break;
            case 0x08 :
            case 0x09 : Fill(Stream_Video, 0, Video_ColorSpace, "RGBA"); break;
            case 0x0A :
            case 0x0B : Fill(Stream_Video, 0, Video_ColorSpace, "YUV"); Fill(Stream_Video, 0, Video_ChromaSubsampling, "4:2:0"); Fill(Stream_Video, 0, Video_BitDepth, 8); break;
            default   : ;
        }

    FILLING_END();
    Finish();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_LAGARITH_YES
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 <iostream>
#include "itkCastImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkPipelineMonitorImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkTestingMacros.h"

int itkShrinkImageStreamingTest(int, char* [] )
{

  const unsigned int numberOfStreamDivisions = 4;

  // typedefs to simplify the syntax
  typedef itk::Image<short, 2>   ShortImage;
  ShortImage::Pointer sourceImage = ShortImage::New();

  typedef itk::PipelineMonitorImageFilter<ShortImage> MonitorFilter;

  // fill in an image
  ShortImage::IndexType  index = {{100, 100}};
  ShortImage::SizeType   size = {{8, 12}};
  ShortImage::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );
  sourceImage->SetRegions( region );
  sourceImage->Allocate();

  itk::ImageRegionIterator<ShortImage> iterator(sourceImage, region);

  short i=0;
  for (; !iterator.IsAtEnd(); ++iterator, ++i)
    {
    iterator.Set( i );
    }

  // use caster to copy source to intermediate image of only the
  // requested region
  itk::CastImageFilter<ShortImage, ShortImage>::Pointer caster;
  caster = itk::CastImageFilter<ShortImage, ShortImage>::New();
  caster->SetInput( sourceImage );

  MonitorFilter::Pointer monitor1 = MonitorFilter::New();
  monitor1->SetInput( caster->GetOutput() );

  // Create a filter, shrink by 2,3
  itk::ShrinkImageFilter< ShortImage, ShortImage >::Pointer shrink;
  shrink = itk::ShrinkImageFilter< ShortImage, ShortImage >::New();
  shrink->SetInput( monitor1->GetOutput() );

  unsigned int factors[2] = { 2, 3 };
  shrink->SetShrinkFactors(factors);

  MonitorFilter::Pointer monitor2 = MonitorFilter::New();
  monitor2->SetInput(shrink->GetOutput());

  itk::StreamingImageFilter<ShortImage, ShortImage>::Pointer streamer;
  streamer = itk::StreamingImageFilter<ShortImage, ShortImage>::New();
  streamer->SetInput( monitor2->GetOutput() );
  streamer->SetNumberOfStreamDivisions( numberOfStreamDivisions );
  streamer->Update();

  // this verifies that the pipeline was executed as expected allong
  // with correct region propagation and output information
  if (!monitor2->VerifyAllInputCanStream(numberOfStreamDivisions))
    {
    std::cout << "Filter failed to execute as expected!" << std::endl;
    std::cout << monitor2;
    return EXIT_FAILURE;
    }

  // Verify that only the data needed is requested;
  MonitorFilter::RegionVectorType rr = monitor1->GetOutputRequestedRegions();
  for (unsigned int j = 0; j < rr.size(); ++j )
    {
    TEST_EXPECT_TRUE(rr[j].GetSize(1)%factors[1]== 1);
    }

  return EXIT_SUCCESS;

}
<commit_msg>STYLE: Fix ShrinkImageStreamingTest style<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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 <iostream>
#include "itkCastImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkPipelineMonitorImageFilter.h"
#include "itkStreamingImageFilter.h"
#include "itkTestingMacros.h"

int itkShrinkImageStreamingTest(int, char* [] )
{

  const unsigned int numberOfStreamDivisions = 4;

  // typedefs to simplify the syntax
  typedef itk::Image<short, 2>   ShortImage;
  ShortImage::Pointer sourceImage = ShortImage::New();

  typedef itk::PipelineMonitorImageFilter<ShortImage> MonitorFilter;

  // fill in an image
  ShortImage::IndexType  index = {{100, 100}};
  ShortImage::SizeType   size = {{8, 12}};
  ShortImage::RegionType region;
  region.SetSize( size );
  region.SetIndex( index );
  sourceImage->SetRegions( region );
  sourceImage->Allocate();

  itk::ImageRegionIterator<ShortImage> iterator(sourceImage, region);

  short i=0;
  for (; !iterator.IsAtEnd(); ++iterator, ++i)
    {
    iterator.Set( i );
    }

  // use caster to copy source to intermediate image of only the
  // requested region
  itk::CastImageFilter<ShortImage, ShortImage>::Pointer caster;
  caster = itk::CastImageFilter<ShortImage, ShortImage>::New();
  caster->SetInput( sourceImage );

  MonitorFilter::Pointer monitor1 = MonitorFilter::New();
  monitor1->SetInput( caster->GetOutput() );

  // Create a filter, shrink by 2,3
  itk::ShrinkImageFilter< ShortImage, ShortImage >::Pointer shrink;
  shrink = itk::ShrinkImageFilter< ShortImage, ShortImage >::New();
  shrink->SetInput( monitor1->GetOutput() );

  unsigned int factors[2] = { 2, 3 };
  shrink->SetShrinkFactors(factors);

  MonitorFilter::Pointer monitor2 = MonitorFilter::New();
  monitor2->SetInput(shrink->GetOutput());

  itk::StreamingImageFilter<ShortImage, ShortImage>::Pointer streamer;
  streamer = itk::StreamingImageFilter<ShortImage, ShortImage>::New();
  streamer->SetInput( monitor2->GetOutput() );
  streamer->SetNumberOfStreamDivisions( numberOfStreamDivisions );
  streamer->Update();

  // this verifies that the pipeline was executed as expected allong
  // with correct region propagation and output information
  if (!monitor2->VerifyAllInputCanStream(numberOfStreamDivisions))
    {
    std::cout << "Filter failed to execute as expected!" << std::endl;
    std::cout << monitor2;
    return EXIT_FAILURE;
    }

  // Verify that only the data needed is requested;
  MonitorFilter::RegionVectorType rr = monitor1->GetOutputRequestedRegions();
  for (unsigned int j = 0; j < rr.size(); ++j )
    {
    TEST_EXPECT_TRUE(rr[j].GetSize(1)%factors[1] == 1);
    }

  return EXIT_SUCCESS;

}
<|endoftext|>