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

#include "common/rspi_io.hpp"
#include "common/spi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/flash_man.hpp"
#include "common/time.h"

#include "chip/LTC2348_16.hpp"
#include "sample.hpp"

namespace seeda {

	static const int seeda_version_ = 100;
	static const uint32_t build_id_ = B_ID;

	typedef utils::command<256> CMD;

#ifdef SEEDA
	typedef device::PORT<device::PORT6, device::bitpos::B7> SW1;
	typedef device::PORT<device::PORT6, device::bitpos::B6> SW2;
#endif

	// Soft SDC 用　SPI 定義（SPI）
#ifdef SEEDA
	typedef device::PORT<device::PORTD, device::bitpos::B6> MISO;
	typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI;
	typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK;
	typedef device::spi_io<MISO, MOSI, SPCK> SPI;

	typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT;	///< カード検出
#else
	// SDC 用　SPI 定義（RSPI）
	typedef device::rspi_io<device::RSPI> SPI;
	typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT;	///< カード検出
#endif
	typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;

#ifdef SEEDA
	// LTC2348-16 A/D 制御ポート定義
	typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN;   // P40(141)
	typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV;   // PC6(61)
	typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY;  // PD0/IRQ0(126)
	typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD;    // P53(53)
	typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI;   // P56(50)
	typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO;  // P86(41)
	typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI;  // P87(39)
	typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0;  // P20(37)
	typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2;  // P21(36)
	typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4;  // P22(35)
	typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6;  // P23(34)
	typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO;
	typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC;
#endif

	typedef device::flash_io FLASH_IO;
	typedef utils::flash_man<FLASH_IO> FLASH_MAN;

	//-----------------------------------------------------------------//
	/*!
		@brief  SDC_IO クラスへの参照
		@return SDC_IO クラス
	*/
	//-----------------------------------------------------------------//
	SDC& at_sdc();

#ifdef SEEDA
	//-----------------------------------------------------------------//
	/*!
		@brief  EADC クラスへの参照
		@return EADC クラス
	*/
	//-----------------------------------------------------------------//
	EADC& at_eadc();
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー
	*/
	//-----------------------------------------------------------------//
	void eadc_server();

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー許可
		@param[in]	ena	「false」の場合不許可
	*/
	//-----------------------------------------------------------------//
	void enable_eadc_server(bool ena = true);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の作成
		@param[in]	date	日付
		@param[in]	time	時間
	*/
	//-----------------------------------------------------------------//
	size_t make_time(const char* date, const char* time);

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の設定
		@param[in]	t	GMT 時間
	*/
	//-----------------------------------------------------------------//
	void set_time(time_t t);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の表示
		@param[in]	t		時間
		@param[in]	dst		出力文字列
		@param[in]	size	文字列の大きさ
		@return 生成された文字列の長さ
	*/
	//-----------------------------------------------------------------//
	int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0);

	//-----------------------------------------------------------------//
	/*!
		@brief  設定スイッチの状態を取得
		@return 設定スイッチの状態
	*/
	//-----------------------------------------------------------------//
	uint8_t get_switch()
	{
#ifdef SEEDA
		return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1);
#else
		return 0;  // for only develope mode
#endif
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの参照
		@param[in]	ch	チャネル（０～７）
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	sample_t& at_sample(uint8_t ch);

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの取得
		@param[in]	ch	チャネル（０～７）
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	const sample_t& get_sample(uint8_t ch);

	//-----------------------------------------------------------------//
	/*!
		@brief  内臓 A/D 変換値の取得
		@param[in]	ch	チャネル（５、６、７）
		@return A/D 変換値
	*/
	//-----------------------------------------------------------------//
	uint16_t get_adc(uint32_t ch);
}

extern "C" {

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の取得
		@return GMT 時間
	*/
	//-----------------------------------------------------------------//
	time_t get_time();

};
<commit_msg>update version number<commit_after>#pragma once
//=====================================================================//
/*! @file
    @brief  SEEDA03 (RX64M) メイン @n
			Copyright 2017 Kunihito Hiramatsu
    @author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/renesas.hpp"

#include "common/rspi_io.hpp"
#include "common/spi_io.hpp"
#include "common/sdc_io.hpp"
#include "common/command.hpp"
#include "common/fifo.hpp"
#include "common/format.hpp"
#include "common/input.hpp"
#include "common/flash_man.hpp"
#include "common/time.h"

#include "chip/LTC2348_16.hpp"
#include "sample.hpp"

namespace seeda {

	static const int seeda_version_ = 110;
	static const uint32_t build_id_ = B_ID;

	typedef utils::command<256> CMD;

#ifdef SEEDA
	typedef device::PORT<device::PORT6, device::bitpos::B7> SW1;
	typedef device::PORT<device::PORT6, device::bitpos::B6> SW2;
#endif

	// Soft SDC 用　SPI 定義（SPI）
#ifdef SEEDA
	typedef device::PORT<device::PORTD, device::bitpos::B6> MISO;
	typedef device::PORT<device::PORTD, device::bitpos::B4> MOSI;
	typedef device::PORT<device::PORTD, device::bitpos::B5> SPCK;
	typedef device::spi_io<MISO, MOSI, SPCK> SPI;

	typedef device::PORT<device::PORTD, device::bitpos::B3> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTE, device::bitpos::B6> SDC_DETECT;	///< カード検出
#else
	// SDC 用　SPI 定義（RSPI）
	typedef device::rspi_io<device::RSPI> SPI;
	typedef device::PORT<device::PORTC, device::bitpos::B4> SDC_SELECT;	///< カード選択信号
	typedef device::NULL_PORT  SDC_POWER;	///< カード電源制御（常に電源ＯＮ）
	typedef device::PORT<device::PORTB, device::bitpos::B7> SDC_DETECT;	///< カード検出
#endif
	typedef utils::sdc_io<SPI, SDC_SELECT, SDC_POWER, SDC_DETECT> SDC;

#ifdef SEEDA
	// LTC2348-16 A/D 制御ポート定義
	typedef device::PORT<device::PORT4, device::bitpos::B0> LTC_CSN;   // P40(141)
	typedef device::PORT<device::PORTC, device::bitpos::B6> LTC_CNV;   // PC6(61)
	typedef device::PORT<device::PORTD, device::bitpos::B0> LTC_BUSY;  // PD0/IRQ0(126)
	typedef device::PORT<device::PORT5, device::bitpos::B3> LTC_PD;    // P53(53)
	typedef device::PORT<device::PORT5, device::bitpos::B6> LTC_SDI;   // P56(50)
	typedef device::PORT<device::PORT8, device::bitpos::B6> LTC_SCKO;  // P86(41)
	typedef device::PORT<device::PORT8, device::bitpos::B7> LTC_SCKI;  // P87(39)
	typedef device::PORT<device::PORT2, device::bitpos::B0> LTC_SDO0;  // P20(37)
	typedef device::PORT<device::PORT2, device::bitpos::B1> LTC_SDO2;  // P21(36)
	typedef device::PORT<device::PORT2, device::bitpos::B2> LTC_SDO4;  // P22(35)
	typedef device::PORT<device::PORT2, device::bitpos::B3> LTC_SDO6;  // P23(34)
	typedef struct chip::LTC2348_SDO_t<LTC_SCKO, LTC_SDO0, LTC_SDO2, LTC_SDO4, LTC_SDO6> LTC_SDO;
	typedef chip::LTC2348_16<LTC_CSN, LTC_CNV, LTC_BUSY, LTC_PD, LTC_SDI, LTC_SCKI, LTC_SDO> EADC;
#endif

	typedef device::flash_io FLASH_IO;
	typedef utils::flash_man<FLASH_IO> FLASH_MAN;

	//-----------------------------------------------------------------//
	/*!
		@brief  SDC_IO クラスへの参照
		@return SDC_IO クラス
	*/
	//-----------------------------------------------------------------//
	SDC& at_sdc();

#ifdef SEEDA
	//-----------------------------------------------------------------//
	/*!
		@brief  EADC クラスへの参照
		@return EADC クラス
	*/
	//-----------------------------------------------------------------//
	EADC& at_eadc();
#endif

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー
	*/
	//-----------------------------------------------------------------//
	void eadc_server();

	//-----------------------------------------------------------------//
	/*!
		@brief  EADC サーバー許可
		@param[in]	ena	「false」の場合不許可
	*/
	//-----------------------------------------------------------------//
	void enable_eadc_server(bool ena = true);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の作成
		@param[in]	date	日付
		@param[in]	time	時間
	*/
	//-----------------------------------------------------------------//
	size_t make_time(const char* date, const char* time);

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の設定
		@param[in]	t	GMT 時間
	*/
	//-----------------------------------------------------------------//
	void set_time(time_t t);

	//-----------------------------------------------------------------//
	/*!
		@brief  時間の表示
		@param[in]	t		時間
		@param[in]	dst		出力文字列
		@param[in]	size	文字列の大きさ
		@return 生成された文字列の長さ
	*/
	//-----------------------------------------------------------------//
	int disp_time(time_t t, char* dst = nullptr, uint32_t size = 0);

	//-----------------------------------------------------------------//
	/*!
		@brief  設定スイッチの状態を取得
		@return 設定スイッチの状態
	*/
	//-----------------------------------------------------------------//
	uint8_t get_switch()
	{
#ifdef SEEDA
		return static_cast<uint8_t>(!SW1::P()) | (static_cast<uint8_t>(!SW2::P()) << 1);
#else
		return 0;  // for only develope mode
#endif
	}

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの参照
		@param[in]	ch	チャネル（０～７）
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	sample_t& at_sample(uint8_t ch);

	//-----------------------------------------------------------------//
	/*!
		@brief  A/D サンプルの取得
		@param[in]	ch	チャネル（０～７）
		@return A/D サンプル
	*/
	//-----------------------------------------------------------------//
	const sample_t& get_sample(uint8_t ch);

	//-----------------------------------------------------------------//
	/*!
		@brief  内臓 A/D 変換値の取得
		@param[in]	ch	チャネル（５、６、７）
		@return A/D 変換値
	*/
	//-----------------------------------------------------------------//
	uint16_t get_adc(uint32_t ch);
}

extern "C" {

	//-----------------------------------------------------------------//
	/*!
		@brief  GMT 時間の取得
		@return GMT 時間
	*/
	//-----------------------------------------------------------------//
	time_t get_time();

};
<|endoftext|>


<commit_before>#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <thread>
#include <utility>
#include <vector>
#include <CLI11/CLI11.hpp>

#define PROFILE_CSV_LINE_LENGTH 9

struct profile_data{
  double time_total;
  double forward_time;
  double reverse_time;
  size_t chain_stack_total;
  size_t nochain_stack_total;
  size_t no_autodiff_passes;
  size_t autodiff_passes;
  size_t n_threads;
};

using profile_data_map = std::map<std::string, profile_data>;
profile_data_map profile_map;

/**
 * Compute the summary of profiling data
 * from CSV files with Stan profiling data.
 * Command line options handled by CLI11 lib.
 *
 * @param argc Number of arguments
 * @param argv Arguments
 *
 * @return 0 for success,
 *         non-zero otherwise
 */
int main(int argc, const char *argv[]) {
  std::string usage = R"(Usage: profilesummary [OPTIONS] stan_profiling_csv_file(s)
Report summaries of the profiling data CSV files with Stan profiling data.
Example:  profilesummary profiling_chain_1.csv profiling_chain_2.csv
Options:
  -h, --help                  Produce help message, then exit.
  -s, --sig_figs [n]          Significant figures reported. Default is 2.
                              Must be an integer from (1, 18), inclusive.
)";
  if (argc < 2) {
    std::cout << usage << std::endl;
    return -1;
  }

  // Command-line arguments
  int sig_figs = 4;
  std::string csv_filename;
  std::vector<std::string> filenames;

  CLI::App app{"Allowed options"};
  app.add_option("--sig_figs,-s", sig_figs, "Significant figures, default 4.",
                 true)
      ->check(CLI::Range(1, 18));
  app.add_option("input_files", filenames, "Stan profiling CSV files.", true)
      ->required()
      ->check(CLI::ExistingFile);

  try {
    CLI11_PARSE(app, argc, argv);
  } catch (const CLI::ParseError &e) {
    std::cout << e.get_exit_code();
    return app.exit(e);
  }

  for (int i = 0; i < filenames.size(); ++i) {
    std::ifstream infile;
    infile.open(filenames[i].c_str());
    if (infile.good()) {
      infile.close();
    } else {
      std::cout << "Cannot read input csv file: " << filenames[i] << "."
                << std::endl;
      return -1;
    }
  }
  std::string delimiter = ",";

  try {
    for (int i = 0; i < filenames.size(); ++i) {
      std::string line;
      std::ifstream infile;
      infile.open(filenames[i].c_str());

      std::getline(infile, line); // ignore header
      while(std::getline(infile, line, '\n'))
      {
        std::stringstream line_stream(line);
        std::vector<std::string> line_cells;
        std::string cell;
        while(std::getline(line_stream,cell, ','))
        {
            line_cells.push_back(cell);
        }
        if(line_cells.size() != PROFILE_CSV_LINE_LENGTH) {
          std::cerr << "Expected " << PROFILE_CSV_LINE_LENGTH << " but found "
          << line_cells.size() << " columns!" << "!" << std::endl;
          return -1;
        }
        std::string name = line_cells[0];
        profile_data_map::iterator it = profile_map.find(name);
        if (it == profile_map.end()) {
          profile_map[name] = {};
        }
        profile_data& p = profile_map[name];
        p.time_total += std::stod(line_cells[2]);
        p.time_total += std::stod(line_cells[2]);
        p.forward_time += std::stod(line_cells[3]);
        p.reverse_time += std::stod(line_cells[4]);
        p.chain_stack_total += std::stoi(line_cells[5]);
        p.nochain_stack_total += std::stoi(line_cells[6]);
        p.no_autodiff_passes += std::stoi(line_cells[7]);
        p.autodiff_passes += std::stoi(line_cells[8]);
        p.n_threads += 1;
      }
      infile.close();
    }

    size_t n_files = filenames.size();

    // TODO: Iterate over all profiles and if n_threads > n_files do sum*n_files/threads

    std::cout << std::setprecision(sig_figs)
    << "Profile information combined from " << n_files << " file(s)"
    << std::endl << std::endl
    << "Timing information: " << std::endl << std::endl
    // TODO: These tabs are obviously useless
    << "\t\t" << "Total" << "\t\t" << "Forward pass" << "\t\t" << "Reverse pass" <<  std::endl;
    profile_data_map::iterator it;
    for (it = profile_map.begin(); it != profile_map.end(); it++)
    {
        std::cout << it->first
        << "\t\t" << it->second.time_total
        << "\t\t"<< it->second.forward_time
        << "\t\t"<< it->second.reverse_time << std::endl;
    }
    std::cout << "Memory information: " << std::endl << std::endl
    << "\t\t" << "ChainStack" << "\t\t" << "NoChainStack" <<  std::endl;
    for (it = profile_map.begin(); it != profile_map.end(); it++)
    {
        std::cout << it->first
        << "\t\t" << it->second.chain_stack_total
        << "\t\t"<< it->second.nochain_stack_total
        << std::endl;
    }
    std::cout << "Autodiff information: " << std::endl << std::endl
    << "\t\t" << "NoADPasses" << "\t\t" << "AdPasses" <<  std::endl;
    for (it = profile_map.begin(); it != profile_map.end(); it++)
    {
        std::cout << it->first
        << "\t\t" << it->second.no_autodiff_passes
        << "\t\t"<< it->second.autodiff_passes
        << std::endl;
    }
  } catch (const std::invalid_argument &e) {
    std::cerr << "Error during processing. " << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<commit_msg>extra newlines<commit_after>#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <thread>
#include <utility>
#include <vector>
#include <CLI11/CLI11.hpp>

#define PROFILE_CSV_LINE_LENGTH 9

struct profile_data{
  double time_total;
  double forward_time;
  double reverse_time;
  size_t chain_stack_total;
  size_t nochain_stack_total;
  size_t no_autodiff_passes;
  size_t autodiff_passes;
  size_t n_threads;
};

using profile_data_map = std::map<std::string, profile_data>;
profile_data_map profile_map;

/**
 * Compute the summary of profiling data
 * from CSV files with Stan profiling data.
 * Command line options handled by CLI11 lib.
 *
 * @param argc Number of arguments
 * @param argv Arguments
 *
 * @return 0 for success,
 *         non-zero otherwise
 */
int main(int argc, const char *argv[]) {
  std::string usage = R"(Usage: profilesummary [OPTIONS] stan_profiling_csv_file(s)
Report summaries of the profiling data CSV files with Stan profiling data.
Example:  profilesummary profiling_chain_1.csv profiling_chain_2.csv
Options:
  -h, --help                  Produce help message, then exit.
  -s, --sig_figs [n]          Significant figures reported. Default is 2.
                              Must be an integer from (1, 18), inclusive.
)";
  if (argc < 2) {
    std::cout << usage << std::endl;
    return -1;
  }

  // Command-line arguments
  int sig_figs = 4;
  std::string csv_filename;
  std::vector<std::string> filenames;

  CLI::App app{"Allowed options"};
  app.add_option("--sig_figs,-s", sig_figs, "Significant figures, default 4.",
                 true)
      ->check(CLI::Range(1, 18));
  app.add_option("input_files", filenames, "Stan profiling CSV files.", true)
      ->required()
      ->check(CLI::ExistingFile);

  try {
    CLI11_PARSE(app, argc, argv);
  } catch (const CLI::ParseError &e) {
    std::cout << e.get_exit_code();
    return app.exit(e);
  }

  for (int i = 0; i < filenames.size(); ++i) {
    std::ifstream infile;
    infile.open(filenames[i].c_str());
    if (infile.good()) {
      infile.close();
    } else {
      std::cout << "Cannot read input csv file: " << filenames[i] << "."
                << std::endl;
      return -1;
    }
  }
  std::string delimiter = ",";

  try {
    for (int i = 0; i < filenames.size(); ++i) {
      std::string line;
      std::ifstream infile;
      infile.open(filenames[i].c_str());

      std::getline(infile, line); // ignore header
      while(std::getline(infile, line, '\n'))
      {
        std::stringstream line_stream(line);
        std::vector<std::string> line_cells;
        std::string cell;
        while(std::getline(line_stream,cell, ','))
        {
            line_cells.push_back(cell);
        }
        if(line_cells.size() != PROFILE_CSV_LINE_LENGTH) {
          std::cerr << "Expected " << PROFILE_CSV_LINE_LENGTH << " but found "
          << line_cells.size() << " columns!" << "!" << std::endl;
          return -1;
        }
        std::string name = line_cells[0];
        profile_data_map::iterator it = profile_map.find(name);
        if (it == profile_map.end()) {
          profile_map[name] = {};
        }
        profile_data& p = profile_map[name];
        p.time_total += std::stod(line_cells[2]);
        p.time_total += std::stod(line_cells[2]);
        p.forward_time += std::stod(line_cells[3]);
        p.reverse_time += std::stod(line_cells[4]);
        p.chain_stack_total += std::stoi(line_cells[5]);
        p.nochain_stack_total += std::stoi(line_cells[6]);
        p.no_autodiff_passes += std::stoi(line_cells[7]);
        p.autodiff_passes += std::stoi(line_cells[8]);
        p.n_threads += 1;
      }
      infile.close();
    }

    size_t n_files = filenames.size();

    // TODO: Iterate over all profiles and if n_threads > n_files do sum*n_files/threads

    std::cout << std::setprecision(sig_figs)
    << "Profile information combined from " << n_files << " file(s)"
    << std::endl << std::endl
    << "Timing information: " << std::endl << std::endl
    // TODO: These tabs are obviously useless
    << "\t\t" << "Total" << "\t\t" << "Forward pass" << "\t\t" << "Reverse pass" <<  std::endl;
    profile_data_map::iterator it;
    for (it = profile_map.begin(); it != profile_map.end(); it++)
    {
        std::cout << it->first
        << "\t\t" << it->second.time_total
        << "\t\t"<< it->second.forward_time
        << "\t\t"<< it->second.reverse_time << std::endl;
    }
    std::cout << std::endl << "Memory information: " << std::endl << std::endl
    << "\t\t" << "ChainStack" << "\t\t" << "NoChainStack" <<  std::endl;
    for (it = profile_map.begin(); it != profile_map.end(); it++)
    {
        std::cout << it->first
        << "\t\t" << it->second.chain_stack_total
        << "\t\t"<< it->second.nochain_stack_total
        << std::endl;
    }
    std::cout << std::endl << "Autodiff information: " << std::endl << std::endl
    << "\t\t" << "NoADPasses" << "\t\t" << "AdPasses" <<  std::endl;
    for (it = profile_map.begin(); it != profile_map.end(); it++)
    {
        std::cout << it->first
        << "\t\t" << it->second.no_autodiff_passes
        << "\t\t"<< it->second.autodiff_passes
        << std::endl;
    }
  } catch (const std::invalid_argument &e) {
    std::cerr << "Error during processing. " << e.what() << std::endl;
    return -1;
  }

  return 0;
}
<|endoftext|>


<commit_before>#include <binary_search_tree.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	BinarySearchTree<int> bst;
	REQUIRE(bst.root() == nullptr);
}

SCENARIO("insertElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE(bst.value_() == 7);
	REQUIRE(bst.leftNode_() == nullptr);
	REQUIRE(bst.rightNode_() == nullptr);
}

SCENARIO("findElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE( bst.isFound(7) == 1);
}

SCENARIO("infile")
{
	BinarySearchTree<int> bst;
	bst.infile("file.txt");
	REQUIRE( bst.count() == 0);
}

SCENARIO("_count")
{
	BinarySearchTree<int> bst;
	int count = 0;
	bst.insert(7);
	count = bst.count(bst.root());
	REQUIRE( count == 1);
}
<commit_msg>Update init.cpp<commit_after>#include <binary_search_tree.hpp>
#include <catch.hpp>

SCENARIO("default constructor")
{
	BinarySearchTree<int> bst;
	REQUIRE(bst.root() == nullptr);
}

SCENARIO("insertElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE(bst.value_() == 7);
	REQUIRE(bst.leftNode_() == nullptr);
	REQUIRE(bst.rightNode_() == nullptr);
}

SCENARIO("findElement")
{
	BinarySearchTree<int> bst;
	bst.insert(7);
	REQUIRE( bst.isFound(7) == 1);
}

SCENARIO("infile")
{
	BinarySearchTree<int> bst;
	bst.infile("file.txt");
	REQUIRE( bst.count() == 0);
}

SCENARIO("_count")
{
	BinarySearchTree<int> bst;
	int count = 0;
	bst.insert(7);
	count = bst.count();
	REQUIRE( count == 1);
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
#define INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX

#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <comphelper/comphelperdllapi.h>

// forward declaration
namespace com { namespace sun { namespace star { namespace accessibility {
    class XAccessible;
    class XAccessibleContext;
}}}}

namespace comphelper
{

    //= OAccessibleImplementationAccess

    typedef ::cppu::ImplHelper1 <   ::com::sun::star::lang::XUnoTunnel
                                >   OAccImpl_Base;
    struct OAccImpl_Impl;

    /** This is a helper class which allows accessing several aspects of the implementation
        of an AccessibleContext.

For instance, when you want to implement a context which can be re-parented, you:

derive your class from OAccessibleImplementationAccess

use setAccessibleParent( component, new_parent )

Another aspect which can be controlled from the outside are states. If you have a class which
        has only partial control over it's states, you may consider deriving from OAccessibleImplementationAccess.

        For instance, say you have an implementation (say component A) which is unable to know or to
        determine if the represented object is selected, but another component (say B) which uses A (and integrates
        it into a tree of accessibility components) is.

        In this case, if A is derived from OAccessibleImplementationAccess, B can manipulate this
        foreign-controlled state flag "SELECTED" by using the static helper methods on this class.

Please note that the support for foreign controlled states is rather restrictive: You can't have states
        which may be controlled by a foreign instances. This is implied by the fact that a derived
        class can ask for states which are set only, not for the ones which are reset currently.

    */
    class COMPHELPER_DLLPUBLIC OAccessibleImplementationAccess : public OAccImpl_Base
    {
    private:
        OAccImpl_Impl*  m_pImpl;

    protected:
        /// retrieves the parent previously set via <method>setAccessibleParent</method>
        ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
                implGetForeignControlledParent( ) const;

        /** retrieves the set of currently set states which are controlled by a foreign instance
        @return
            a bit mask, where a set bit 2^n means that the AccessibleStateType n has been set
        */
        sal_Int64   implGetForeignControlledStates( ) const;

        /// sets the accessible parent component
        virtual void    setAccessibleParent(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxAccParent );

        /// sets or resets a bit of the foreign controlled states
        virtual void    setStateBit( const sal_Int16 _nState, const sal_Bool _bSet );

    protected:
        OAccessibleImplementationAccess( );
        virtual ~OAccessibleImplementationAccess( );

        // XUnoTunnel
        virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rIdentifier ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

    public:
        /** tries to access the implementation of an OAccessibleImplementationAccess derivee which is known as
            interface only.

        @param _rxComponent
            is the component which should be examined.
        @return
            the pointer to the implementation, if successful. The only known error condition so far
            is an invalid context (which means it is <NULL/>, or the implementation is not derived
            from OAccessibleImplementationAccess, or retrieving the implementation failed).
        */
        static OAccessibleImplementationAccess* getImplementation(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent
        );

        /** sets the parent for a derived implementation

        @param _rxComponent
            is the component which's new parent should be set
        @param _rxNewParent
            is the new parent of the component
        @return
            <TRUE/> in case of success, <FALSE/> otherwise. For error condition please look at
            <method>getImplementation</method>.
        */
        static bool setAccessibleParent(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxNewParent
        );

    private:
        COMPHELPER_DLLPRIVATE static const ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
    };

}   // namespace comphelper

#endif // INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>No need for these functions to be virtual<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#ifndef INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX
#define INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX

#include <cppuhelper/implbase1.hxx>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <comphelper/comphelperdllapi.h>

// forward declaration
namespace com { namespace sun { namespace star { namespace accessibility {
    class XAccessible;
    class XAccessibleContext;
}}}}

namespace comphelper
{

    //= OAccessibleImplementationAccess

    typedef ::cppu::ImplHelper1 <   ::com::sun::star::lang::XUnoTunnel
                                >   OAccImpl_Base;
    struct OAccImpl_Impl;

    /** This is a helper class which allows accessing several aspects of the implementation
        of an AccessibleContext.

For instance, when you want to implement a context which can be re-parented, you:

derive your class from OAccessibleImplementationAccess

use setAccessibleParent( component, new_parent )

Another aspect which can be controlled from the outside are states. If you have a class which
        has only partial control over it's states, you may consider deriving from OAccessibleImplementationAccess.

        For instance, say you have an implementation (say component A) which is unable to know or to
        determine if the represented object is selected, but another component (say B) which uses A (and integrates
        it into a tree of accessibility components) is.

        In this case, if A is derived from OAccessibleImplementationAccess, B can manipulate this
        foreign-controlled state flag "SELECTED" by using the static helper methods on this class.

Please note that the support for foreign controlled states is rather restrictive: You can't have states
        which may be controlled by a foreign instances. This is implied by the fact that a derived
        class can ask for states which are set only, not for the ones which are reset currently.

    */
    class COMPHELPER_DLLPUBLIC OAccessibleImplementationAccess : public OAccImpl_Base
    {
    private:
        OAccImpl_Impl*  m_pImpl;

    protected:
        /// retrieves the parent previously set via <method>setAccessibleParent</method>
        ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >
                implGetForeignControlledParent( ) const;

        /** retrieves the set of currently set states which are controlled by a foreign instance
        @return
            a bit mask, where a set bit 2^n means that the AccessibleStateType n has been set
        */
        sal_Int64   implGetForeignControlledStates( ) const;

        /// sets the accessible parent component
        void setAccessibleParent(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxAccParent );

        /// sets or resets a bit of the foreign controlled states
        void setStateBit( const sal_Int16 _nState, const sal_Bool _bSet );

    protected:
        OAccessibleImplementationAccess( );
        virtual ~OAccessibleImplementationAccess( );

        // XUnoTunnel
        virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& _rIdentifier ) throw (::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;

    public:
        /** tries to access the implementation of an OAccessibleImplementationAccess derivee which is known as
            interface only.

        @param _rxComponent
            is the component which should be examined.
        @return
            the pointer to the implementation, if successful. The only known error condition so far
            is an invalid context (which means it is <NULL/>, or the implementation is not derived
            from OAccessibleImplementationAccess, or retrieving the implementation failed).
        */
        static OAccessibleImplementationAccess* getImplementation(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent
        );

        /** sets the parent for a derived implementation

        @param _rxComponent
            is the component which's new parent should be set
        @param _rxNewParent
            is the new parent of the component
        @return
            <TRUE/> in case of success, <FALSE/> otherwise. For error condition please look at
            <method>getImplementation</method>.
        */
        static bool setAccessibleParent(
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext >& _rxComponent,
            const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible >& _rxNewParent
        );

    private:
        COMPHELPER_DLLPRIVATE static const ::com::sun::star::uno::Sequence< sal_Int8 > getUnoTunnelImplementationId();
    };

}   // namespace comphelper

#endif // INCLUDED_COMPHELPER_ACCIMPLACCESS_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin-explorer.
 *
 * libbitcoin-explorer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/explorer/commands/ek-to-address.hpp>

#include <iostream>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/primitives/address.hpp>

using namespace bc;
using namespace bc::explorer;
using namespace bc::explorer::commands;
using namespace bc::explorer::primitives;
using namespace bc::wallet;

console_result ek_to_address::invoke(std::ostream& output, std::ostream& error)
{
#ifdef WITH_ICU
    const auto& passphrase = get_passphrase_argument();
    const auto& key = get_ek_private_key_argument();

    bool compressed;
    uint8_t version;
    ec_private secret;
    if (!decrypt(secret.data(), version, compressed, key, passphrase))
    {
        error << BX_EK_TO_ADDRESS_INVALID_PASSPHRASE << std::endl;
        return console_result::failure;
    }

    const auto point = secret_to_public_key(secret, compressed);
    const address payment_address(version, point);

    output << secret << std::endl;
    return console_result::okay;
#else
    error << BX_EK_TO_ADDRESS_REQUIRES_ICU << std::endl;
    return console_result::failure;
#endif
}
<commit_msg>fix: ek-to-address was returning the ec private key instead of the address.<commit_after>/**
 * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin-explorer.
 *
 * libbitcoin-explorer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/explorer/commands/ek-to-address.hpp>

#include <iostream>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/primitives/address.hpp>

using namespace bc;
using namespace bc::explorer;
using namespace bc::explorer::commands;
using namespace bc::explorer::primitives;
using namespace bc::wallet;

console_result ek_to_address::invoke(std::ostream& output, std::ostream& error)
{
#ifdef WITH_ICU
    const auto& passphrase = get_passphrase_argument();
    const auto& key = get_ek_private_key_argument();

    bool compressed;
    uint8_t version;
    ec_private secret;
    if (!decrypt(secret.data(), version, compressed, key, passphrase))
    {
        error << BX_EK_TO_ADDRESS_INVALID_PASSPHRASE << std::endl;
        return console_result::failure;
    }

    const auto point = secret_to_public_key(secret, compressed);
    const address payment_address(version, point);

    output << payment_address << std::endl;
    return console_result::okay;
#else
    error << BX_EK_TO_ADDRESS_REQUIRES_ICU << std::endl;
    return console_result::failure;
#endif
}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <chrono>  // NOLINT(build/c++11)
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

#include "absl/time/time.h"
#include "tensorflow/lite/delegates/gpu/cl/gpu_api_delegate.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/testing/tflite_model_reader.h"
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/register.h"

namespace {

void FillInputTensor(tflite::Interpreter* interpreter) {
  for (int k = 0; k < interpreter->inputs().size(); ++k) {
    TfLiteTensor* tensor_ptr = interpreter->tensor(interpreter->inputs()[k]);
    const auto tensor_elements_count = tflite::NumElements(tensor_ptr);
    if (tensor_ptr->type == kTfLiteFloat32) {
      float* p = interpreter->typed_input_tensor<float>(k);
      for (int i = 0; i < tensor_elements_count; ++i) {
        p[i] = std::sin(i);
      }
    }
    if (tensor_ptr->type == kTfLiteInt32) {
      int* p = interpreter->typed_input_tensor<int>(k);
      for (int i = 0; i < tensor_elements_count; ++i) {
        p[i] = i % 2;
      }
    }
  }
}

void CompareCPUGPUResults(tflite::Interpreter* cpu, tflite::Interpreter* gpu,
                          float eps) {
  for (int i = 0; i < cpu->outputs().size(); ++i) {
    const float* cpu_out = cpu->typed_output_tensor<float>(i);
    const float* gpu_out = gpu->typed_output_tensor<float>(i);
    auto out_n = tflite::NumElements(cpu->tensor(cpu->outputs()[i]));
    const int kMaxPrint = 10;
    int printed = 0;
    int total_different = 0;
    for (int k = 0; k < out_n; ++k) {
      const float abs_diff = fabs(cpu_out[k] - gpu_out[k]);
      if (abs_diff > eps) {
        total_different++;
        if (printed < kMaxPrint) {
          std::cout << "Output #" << i << ": element #" << k << ": CPU value - "
                    << cpu_out[k] << ", GPU value - " << gpu_out[k]
                    << ", abs diff - " << abs_diff << std::endl;
          printed++;
        }
        if (printed == kMaxPrint) {
          std::cout << "Printed " << kMaxPrint
                    << " different elements, threshhold - " << eps
                    << ", next different elements skipped" << std::endl;
          printed++;
        }
      }
    }
    std::cout << "Total " << total_different
              << " different elements, for output #" << i << ", threshhold - "
              << eps << std::endl;
  }
}

}  // namespace

int main(int argc, char** argv) {
  if (argc <= 1) {
    std::cerr << "Expected model path as second argument." << std::endl;
    return -1;
  }

  auto model = tflite::FlatBufferModel::BuildFromFile(argv[1]);
  if (!model) {
    std::cerr << "FlatBufferModel::BuildFromFile failed, model path - "
              << argv[1] << std::endl;
    return -1;
  }
  tflite::ops::builtin::BuiltinOpResolver op_resolver;
  tflite::InterpreterBuilder builder(*model, op_resolver);

  // CPU.
  std::unique_ptr<tflite::Interpreter> cpu_inference;
  builder(&cpu_inference);
  if (!cpu_inference) {
    std::cerr << "Failed to build CPU inference." << std::endl;
    return -1;
  }
  auto status = cpu_inference->AllocateTensors();
  if (status != kTfLiteOk) {
    std::cerr << "Failed to AllocateTensors for CPU inference." << std::endl;
    return -1;
  }
  FillInputTensor(cpu_inference.get());
  status = cpu_inference->Invoke();
  if (status != kTfLiteOk) {
    std::cerr << "Failed to Invoke CPU inference." << std::endl;
    return -1;
  }

  // GPU.
  std::unique_ptr<tflite::Interpreter> gpu_inference;
  builder(&gpu_inference);
  if (!gpu_inference) {
    std::cerr << "Failed to build GPU inference." << std::endl;
    return -1;
  }
  TfLiteGpuDelegateOptionsV2 options;
  options.is_precision_loss_allowed = -1;
  options.inference_preference =
      TFLITE_GPU_INFERENCE_PREFERENCE_FAST_SINGLE_ANSWER;
  options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
  options.inference_priority2 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_MEMORY_USAGE;
  options.inference_priority3 = TFLITE_GPU_INFERENCE_PRIORITY_MAX_PRECISION;
  options.max_delegated_partitions = 1;
  auto* gpu_delegate = TfLiteGpuDelegateV2Create(&options);
  status = gpu_inference->ModifyGraphWithDelegate(gpu_delegate);
  if (status != kTfLiteOk) {
    std::cerr << "ModifyGraphWithDelegate failed." << std::endl;
    return -1;
  }
  FillInputTensor(gpu_inference.get());
  status = gpu_inference->Invoke();
  if (status != kTfLiteOk) {
    std::cerr << "Failed to Invoke GPU inference." << std::endl;
    return -1;
  }

  CompareCPUGPUResults(cpu_inference.get(), gpu_inference.get(), 1e-4f);

  // CPU inference latency.
  auto start = std::chrono::high_resolution_clock::now();
  cpu_inference->Invoke();
  auto end = std::chrono::high_resolution_clock::now();
  std::cout << "CPU time - " << (end - start).count() * 1e-6f << "ms"
            << std::endl;

  // GPU inference latency.
  start = std::chrono::high_resolution_clock::now();
  gpu_inference->Invoke();
  end = std::chrono::high_resolution_clock::now();
  std::cout << "GPU time(CPU->GPU->CPU) - " << (end - start).count() * 1e-6f
            << "ms" << std::endl;

  TfLiteGpuDelegateV2Delete(gpu_delegate);
  return EXIT_SUCCESS;
}
<commit_msg>Added initialization of new field.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <algorithm>
#include <chrono>  // NOLINT(build/c++11)
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <memory>
#include <string>

#include "absl/time/time.h"
#include "tensorflow/lite/delegates/gpu/cl/gpu_api_delegate.h"
#include "tensorflow/lite/delegates/gpu/common/status.h"
#include "tensorflow/lite/delegates/gpu/common/testing/tflite_model_reader.h"
#include "tensorflow/lite/delegates/gpu/delegate.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/register.h"

namespace {

void FillInputTensor(tflite::Interpreter* interpreter) {
  for (int k = 0; k < interpreter->inputs().size(); ++k) {
    TfLiteTensor* tensor_ptr = interpreter->tensor(interpreter->inputs()[k]);
    const auto tensor_elements_count = tflite::NumElements(tensor_ptr);
    if (tensor_ptr->type == kTfLiteFloat32) {
      float* p = interpreter->typed_input_tensor<float>(k);
      for (int i = 0; i < tensor_elements_count; ++i) {
        p[i] = std::sin(i);
      }
    }
    if (tensor_ptr->type == kTfLiteInt32) {
      int* p = interpreter->typed_input_tensor<int>(k);
      for (int i = 0; i < tensor_elements_count; ++i) {
        p[i] = i % 2;
      }
    }
  }
}

void CompareCPUGPUResults(tflite::Interpreter* cpu, tflite::Interpreter* gpu,
                          float eps) {
  for (int i = 0; i < cpu->outputs().size(); ++i) {
    const float* cpu_out = cpu->typed_output_tensor<float>(i);
    const float* gpu_out = gpu->typed_output_tensor<float>(i);
    auto out_n = tflite::NumElements(cpu->tensor(cpu->outputs()[i]));
    const int kMaxPrint = 10;
    int printed = 0;
    int total_different = 0;
    for (int k = 0; k < out_n; ++k) {
      const float abs_diff = fabs(cpu_out[k] - gpu_out[k]);
      if (abs_diff > eps) {
        total_different++;
        if (printed < kMaxPrint) {
          std::cout << "Output #" << i << ": element #" << k << ": CPU value - "
                    << cpu_out[k] << ", GPU value - " << gpu_out[k]
                    << ", abs diff - " << abs_diff << std::endl;
          printed++;
        }
        if (printed == kMaxPrint) {
          std::cout << "Printed " << kMaxPrint
                    << " different elements, threshhold - " << eps
                    << ", next different elements skipped" << std::endl;
          printed++;
        }
      }
    }
    std::cout << "Total " << total_different
              << " different elements, for output #" << i << ", threshhold - "
              << eps << std::endl;
  }
}

}  // namespace

int main(int argc, char** argv) {
  if (argc <= 1) {
    std::cerr << "Expected model path as second argument." << std::endl;
    return -1;
  }

  auto model = tflite::FlatBufferModel::BuildFromFile(argv[1]);
  if (!model) {
    std::cerr << "FlatBufferModel::BuildFromFile failed, model path - "
              << argv[1] << std::endl;
    return -1;
  }
  tflite::ops::builtin::BuiltinOpResolver op_resolver;
  tflite::InterpreterBuilder builder(*model, op_resolver);

  // CPU.
  std::unique_ptr<tflite::Interpreter> cpu_inference;
  builder(&cpu_inference);
  if (!cpu_inference) {
    std::cerr << "Failed to build CPU inference." << std::endl;
    return -1;
  }
  auto status = cpu_inference->AllocateTensors();
  if (status != kTfLiteOk) {
    std::cerr << "Failed to AllocateTensors for CPU inference." << std::endl;
    return -1;
  }
  FillInputTensor(cpu_inference.get());
  status = cpu_inference->Invoke();
  if (status != kTfLiteOk) {
    std::cerr << "Failed to Invoke CPU inference." << std::endl;
    return -1;
  }

  // GPU.
  std::unique_ptr<tflite::Interpreter> gpu_inference;
  builder(&gpu_inference);
  if (!gpu_inference) {
    std::cerr << "Failed to build GPU inference." << std::endl;
    return -1;
  }
  TfLiteGpuDelegateOptionsV2 options;
  options.is_precision_loss_allowed = -1;
  options.inference_preference =
      TFLITE_GPU_INFERENCE_PREFERENCE_FAST_SINGLE_ANSWER;
  options.inference_priority1 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_LATENCY;
  options.inference_priority2 = TFLITE_GPU_INFERENCE_PRIORITY_MIN_MEMORY_USAGE;
  options.inference_priority3 = TFLITE_GPU_INFERENCE_PRIORITY_MAX_PRECISION;
  options.experimental_flags = TFLITE_GPU_EXPERIMENTAL_FLAGS_NONE;
  options.max_delegated_partitions = 1;
  auto* gpu_delegate = TfLiteGpuDelegateV2Create(&options);
  status = gpu_inference->ModifyGraphWithDelegate(gpu_delegate);
  if (status != kTfLiteOk) {
    std::cerr << "ModifyGraphWithDelegate failed." << std::endl;
    return -1;
  }
  FillInputTensor(gpu_inference.get());
  status = gpu_inference->Invoke();
  if (status != kTfLiteOk) {
    std::cerr << "Failed to Invoke GPU inference." << std::endl;
    return -1;
  }

  CompareCPUGPUResults(cpu_inference.get(), gpu_inference.get(), 1e-4f);

  // CPU inference latency.
  auto start = std::chrono::high_resolution_clock::now();
  cpu_inference->Invoke();
  auto end = std::chrono::high_resolution_clock::now();
  std::cout << "CPU time - " << (end - start).count() * 1e-6f << "ms"
            << std::endl;

  // GPU inference latency.
  start = std::chrono::high_resolution_clock::now();
  gpu_inference->Invoke();
  end = std::chrono::high_resolution_clock::now();
  std::cout << "GPU time(CPU->GPU->CPU) - " << (end - start).count() * 1e-6f
            << "ms" << std::endl;

  TfLiteGpuDelegateV2Delete(gpu_delegate);
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

#include <vtkObjectFactory.h>

// MRML includes
#include "vtkMRMLSpatialObjectsStorageNode.h"
#include "vtkMRMLSpatialObjectsNode.h"
#include "vtkMRMLSpatialObjectsDisplayNode.h"

// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCellArray.h>
#include <vtkCleanPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyLine.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkStringArray.h>

// ITK includes
#include <itkTubeSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>

//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSpatialObjectsStorageNode);

//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//------------------------------------------------------------------------------
bool vtkMRMLSpatialObjectsStorageNode::
CanReadInReferenceNode(vtkMRMLNode *refNode)
{
  return refNode->IsA("vtkMRMLSpatialObjectsNode");
}

//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::ReadDataInternal(vtkMRMLNode *refNode)
{
  vtkMRMLSpatialObjectsNode* spatialObjectsNode =
    vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);

  if(Superclass::ReadDataInternal(refNode) != 0)
    {
    return 0;
    }

  std::string fullName = this->GetFullNameFromFileName();
  if(fullName == std::string(""))
    {
    vtkErrorMacro("ReadData: File name not specified");
    return 0;
    }

  // compute file prefix
  std::string name(fullName);
  std::string::size_type loc = name.find_last_of(".");
  if( loc == std::string::npos )
    {
    vtkErrorMacro("ReadData: no file extension specified: " << name.c_str());
    return 0;
    }
  std::string extension = name.substr(loc);
  vtkDebugMacro("ReadData: extension = " << extension.c_str());

  int result = 1;
  try
  {
    if(extension == std::string(".tre"))
      {
      ReaderType::Pointer reader = ReaderType::New();
      reader->SetFileName(fullName);
      reader->Update();
      // WARNING : Should we check if the tube contains less than 2 points...

      char childName[] = "Tube";
      TubeNetType::ChildrenListType* tubeList =
        reader->GetGroup()->GetChildren(tubeList->GetMaximumDepth(), childName);

      // -----------------------------------------------------------------------
      // Copy skeleton points from vessels into polydata structure
      // -----------------------------------------------------------------------

      // Initialize the SpatialObject
      // Count number of points && remove dupplicate
      int totalNumberOfPoints = 0;
      for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
           tubeIT != tubeList->end();
           ++tubeIT )
        {
        TubeType* currTube =
          static_cast<TubeType*>((*tubeIT).GetPointer());

        currTube->RemoveDuplicatePoints();

        if(currTube->GetNumberOfPoints() < 2)
          continue;

        totalNumberOfPoints += currTube->GetNumberOfPoints();
        }

      // Create the points
      vtkNew<vtkPoints> vesselsPoints;
      vesselsPoints->SetNumberOfPoints(totalNumberOfPoints);

      // Create the Lines
      vtkNew<vtkCellArray> vesselLinesCA;

      // Create scalar array that indicates the radius at each
      // centerline point.
      vtkNew<vtkDoubleArray> tubeRadius;
      tubeRadius->SetName("TubeRadius");
      tubeRadius->SetNumberOfTuples(totalNumberOfPoints);

      // Create scalar array that indicates TubeID.
      vtkNew<vtkDoubleArray> tubeIDs;
      tubeIDs->SetName("TubeIDs");
      tubeIDs->SetNumberOfTuples(totalNumberOfPoints);

      // Create scalar array that indicates both tangeantes at each
      // centerline point.
      vtkNew<vtkDoubleArray> tan1;
      tan1->SetName("Tan1");
      tan1->SetNumberOfTuples(3 * totalNumberOfPoints);
      tan1->SetNumberOfComponents(3);

      vtkNew<vtkDoubleArray> tan2;
      tan2->SetName("Tan2");
      tan2->SetNumberOfTuples(3 * totalNumberOfPoints);
      tan2->SetNumberOfComponents(3);

      // Create scalar array that indicates Ridgness and medialness at each
      // centerline point.
      bool containsMidialnessInfo = false;
      vtkNew<vtkDoubleArray> medialness;
      medialness->SetName("Medialness");
      medialness->SetNumberOfTuples(totalNumberOfPoints);

      bool containsRidgnessInfo = false;
      vtkNew<vtkDoubleArray> ridgeness;
      ridgeness->SetName("Ridgeness");
      ridgeness->SetNumberOfTuples(totalNumberOfPoints);

      int pointID = 0;
      for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
           tubeIT != tubeList->end(); ++tubeIT )
        {
        TubeType* currTube =
          static_cast<TubeType*>((*tubeIT).GetPointer());

        currTube->RemoveDuplicatePoints();

        int tubeSize = currTube->GetNumberOfPoints();
        if(tubeSize < 2)
          continue;

        currTube->ComputeTangentAndNormals();

        // Create a pointID list [linear for a polyline]
        vtkIdType* pointIDs = new vtkIdType[tubeSize];
        vtkNew<vtkPolyLine> vesselLine;

        // Get the tube element spacing information.
        const double* axesRatio = currTube->GetSpacing();

        int index = 0;
        std::vector<TubePointType>::iterator  tubePointIterator;
        for(tubePointIterator = currTube->GetPoints().begin();
             tubePointIterator != currTube->GetPoints().end();
             ++tubePointIterator, ++pointID, ++index)
          {
          PointType inputPoint = tubePointIterator->GetPosition();
          pointIDs[index] = pointID;

          // Insert points using the element spacing information.
          vesselsPoints->SetPoint(pointID,
                                  inputPoint[0],
                                  inputPoint[1] * axesRatio[1] / axesRatio[0],
                                  inputPoint[2] * axesRatio[2] / axesRatio[0]);

          // TubeID
          tubeIDs->SetTuple1(pointID, currTube->GetId());

          // Radius
          tubeRadius->SetTuple1(pointID, tubePointIterator->GetRadius());

          // Tangeantes
          tan1->SetTuple3(pointID,
                          (*tubePointIterator).GetNormal1()[0],
                          (*tubePointIterator).GetNormal1()[1],
                          (*tubePointIterator).GetNormal1()[2]);

          tan2->SetTuple3(pointID,
                          (*tubePointIterator).GetNormal2()[0],
                          (*tubePointIterator).GetNormal2()[1],
                          (*tubePointIterator).GetNormal2()[2]);

          // Medialness & Ridgness
          if(tubePointIterator->GetMedialness() != 0)
            {
            containsMidialnessInfo = true;
            }
          medialness->SetTuple1(pointID, tubePointIterator->GetMedialness());

          if(tubePointIterator->GetRidgeness() != 0)
            {
            containsRidgnessInfo = true;
            }
          ridgeness->SetTuple1(pointID, tubePointIterator->GetRidgeness());
          }

        vesselLine->Initialize(tubeSize,
                               pointIDs,
                               vesselsPoints.GetPointer());
        vesselLinesCA->InsertNextCell(vesselLine.GetPointer());
        delete [] pointIDs;
        }

      // Convert spatial objects to a PolyData
      vtkNew<vtkPolyData> vesselsPD;
      vesselsPD->SetLines(vesselLinesCA.GetPointer());
      vesselsPD->SetPoints(vesselsPoints.GetPointer());

      // Add the Radius information
      vesselsPD->GetPointData()->AddArray(tubeRadius.GetPointer());
      vesselsPD->GetPointData()->SetActiveScalars("TubeRadius");

      // Add the TudeID information
      vesselsPD->GetPointData()->AddArray(tubeIDs.GetPointer());

      // Add Tangeantes information
      vesselsPD->GetPointData()->AddArray(tan1.GetPointer());
      vesselsPD->GetPointData()->AddArray(tan2.GetPointer());

      // Add Medialness & Ridgness if contains information
      if(containsMidialnessInfo == true)
        {
        vesselsPD->GetPointData()->AddArray(medialness.GetPointer());
        }

      if(containsRidgnessInfo == true)
        {
        vesselsPD->GetPointData()->AddArray(ridgeness.GetPointer());
        }

      // Remove any duplicate points from polydata.
      // The tubes generation will fails if any duplicates points are present.
      // Cleaned before, could create degeneration problems with the cells
      //vtkNew<vtkCleanPolyData> cleanedVesselPD;
      //cleanedVesselPD->SetInput(vesselsPD.GetPointer());

      vtkDebugMacro("Points: " << totalNumberOfPoints);

      spatialObjectsNode->SetAndObservePolyData(vesselsPD.GetPointer());
      spatialObjectsNode->SetSpatialObject(reader->GetGroup());
      delete tubeList;
    }
  }
  catch(...)
  {
    result = 0;
  }

  if(spatialObjectsNode->GetPolyData() != NULL)
    {
    // is there an active scalar array?
    if(spatialObjectsNode->GetDisplayNode())
      {
      double *scalarRange = spatialObjectsNode->GetPolyData()->GetScalarRange();
      if(scalarRange)
        {
        vtkDebugMacro("ReadData: setting scalar range " << scalarRange[0]
                      << ", " << scalarRange[1]);
        spatialObjectsNode->GetDisplayNode()->SetScalarRange(scalarRange);
        }
      }

    spatialObjectsNode->GetPolyData()->Modified();
    }

  return result;
}

//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::WriteDataInternal(vtkMRMLNode *refNode)
{
  vtkMRMLSpatialObjectsNode* spatialObjects =
    vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);

  std::string fullName = this->GetFullNameFromFileName();
  if(fullName == std::string(""))
    {
    vtkErrorMacro("vtkMRMLModelNode: File name not specified");
    return 0;
    }

  std::string extension =
    itksys::SystemTools::GetFilenameLastExtension(fullName);

  int result = 1;
  if(extension == ".tre")
    {
    try
      {
      WriterType::Pointer writer = WriterType::New();
      writer->SetFileName(fullName.c_str());
      writer->SetInput(spatialObjects->GetSpatialObject());
      writer->Update();
      }
    catch(...)
      {
      result = 0;
      vtkErrorMacro("Error occured writing Spatial Objects: "
                    << fullName.c_str());
      }
    }
  else
    {
    result = 0;
    vtkErrorMacro( << "No file extension recognized: " << fullName.c_str());
    }

  return result;
}

//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedReadFileTypes( void )
{
  this->SupportedReadFileTypes->InsertNextValue("SpatialObject (.tre)");
}

//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedWriteFileTypes( void )
{
  this->SupportedWriteFileTypes->InsertNextValue("SpatialObject (.tre)");
}

//------------------------------------------------------------------------------
const char* vtkMRMLSpatialObjectsStorageNode::GetDefaultWriteFileExtension( void )
{
  return "tre";
}
<commit_msg>PATCH: Maximum depth of group<commit_after>/*=========================================================================

Library:   TubeTK

Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.

All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=========================================================================*/

#include <vtkObjectFactory.h>

// MRML includes
#include "vtkMRMLSpatialObjectsStorageNode.h"
#include "vtkMRMLSpatialObjectsNode.h"
#include "vtkMRMLSpatialObjectsDisplayNode.h"

// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCellArray.h>
#include <vtkCleanPolyData.h>
#include <vtkDoubleArray.h>
#include <vtkNew.h>
#include <vtkPointData.h>
#include <vtkPolyLine.h>
#include <vtkSmartPointer.h>
#include <vtkSphereSource.h>
#include <vtkStringArray.h>

// ITK includes
#include <itkTubeSpatialObject.h>
#include <itkSpatialObjectReader.h>
#include <itkSpatialObjectWriter.h>

//------------------------------------------------------------------------------
vtkMRMLNodeNewMacro(vtkMRMLSpatialObjectsStorageNode);

//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}

//------------------------------------------------------------------------------
bool vtkMRMLSpatialObjectsStorageNode::
CanReadInReferenceNode(vtkMRMLNode *refNode)
{
  return refNode->IsA("vtkMRMLSpatialObjectsNode");
}

//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::ReadDataInternal(vtkMRMLNode *refNode)
{
  vtkMRMLSpatialObjectsNode* spatialObjectsNode =
    vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);

  if(Superclass::ReadDataInternal(refNode) != 0)
    {
    return 0;
    }

  std::string fullName = this->GetFullNameFromFileName();
  if(fullName == std::string(""))
    {
    vtkErrorMacro("ReadData: File name not specified");
    return 0;
    }

  // compute file prefix
  std::string name(fullName);
  std::string::size_type loc = name.find_last_of(".");
  if( loc == std::string::npos )
    {
    vtkErrorMacro("ReadData: no file extension specified: " << name.c_str());
    return 0;
    }
  std::string extension = name.substr(loc);
  vtkDebugMacro("ReadData: extension = " << extension.c_str());

  int result = 1;
  try
  {
    if(extension == std::string(".tre"))
      {
      ReaderType::Pointer reader = ReaderType::New();
      reader->SetFileName(fullName);
      reader->Update();
      // WARNING : Should we check if the tube contains less than 2 points...

      char childName[] = "Tube";
      TubeNetType::ChildrenListType* tubeList =
        reader->GetGroup()->GetChildren(reader->GetGroup()->GetMaximumDepth(), childName);

      // -----------------------------------------------------------------------
      // Copy skeleton points from vessels into polydata structure
      // -----------------------------------------------------------------------

      // Initialize the SpatialObject
      // Count number of points && remove dupplicate
      int totalNumberOfPoints = 0;
      for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
           tubeIT != tubeList->end();
           ++tubeIT )
        {
        TubeType* currTube =
          static_cast<TubeType*>((*tubeIT).GetPointer());

        currTube->RemoveDuplicatePoints();

        if(currTube->GetNumberOfPoints() < 2)
          continue;

        totalNumberOfPoints += currTube->GetNumberOfPoints();
        }

      // Create the points
      vtkNew<vtkPoints> vesselsPoints;
      vesselsPoints->SetNumberOfPoints(totalNumberOfPoints);

      // Create the Lines
      vtkNew<vtkCellArray> vesselLinesCA;

      // Create scalar array that indicates the radius at each
      // centerline point.
      vtkNew<vtkDoubleArray> tubeRadius;
      tubeRadius->SetName("TubeRadius");
      tubeRadius->SetNumberOfTuples(totalNumberOfPoints);

      // Create scalar array that indicates TubeID.
      vtkNew<vtkDoubleArray> tubeIDs;
      tubeIDs->SetName("TubeIDs");
      tubeIDs->SetNumberOfTuples(totalNumberOfPoints);

      // Create scalar array that indicates both tangeantes at each
      // centerline point.
      vtkNew<vtkDoubleArray> tan1;
      tan1->SetName("Tan1");
      tan1->SetNumberOfTuples(3 * totalNumberOfPoints);
      tan1->SetNumberOfComponents(3);

      vtkNew<vtkDoubleArray> tan2;
      tan2->SetName("Tan2");
      tan2->SetNumberOfTuples(3 * totalNumberOfPoints);
      tan2->SetNumberOfComponents(3);

      // Create scalar array that indicates Ridgness and medialness at each
      // centerline point.
      bool containsMidialnessInfo = false;
      vtkNew<vtkDoubleArray> medialness;
      medialness->SetName("Medialness");
      medialness->SetNumberOfTuples(totalNumberOfPoints);

      bool containsRidgnessInfo = false;
      vtkNew<vtkDoubleArray> ridgeness;
      ridgeness->SetName("Ridgeness");
      ridgeness->SetNumberOfTuples(totalNumberOfPoints);

      int pointID = 0;
      for(TubeNetType::ChildrenListType::iterator tubeIT = tubeList->begin();
           tubeIT != tubeList->end(); ++tubeIT )
        {
        TubeType* currTube =
          static_cast<TubeType*>((*tubeIT).GetPointer());

        currTube->RemoveDuplicatePoints();

        int tubeSize = currTube->GetNumberOfPoints();
        if(tubeSize < 2)
          continue;

        currTube->ComputeTangentAndNormals();

        // Create a pointID list [linear for a polyline]
        vtkIdType* pointIDs = new vtkIdType[tubeSize];
        vtkNew<vtkPolyLine> vesselLine;

        // Get the tube element spacing information.
        const double* axesRatio = currTube->GetSpacing();

        int index = 0;
        std::vector<TubePointType>::iterator  tubePointIterator;
        for(tubePointIterator = currTube->GetPoints().begin();
             tubePointIterator != currTube->GetPoints().end();
             ++tubePointIterator, ++pointID, ++index)
          {
          PointType inputPoint = tubePointIterator->GetPosition();
          pointIDs[index] = pointID;

          // Insert points using the element spacing information.
          vesselsPoints->SetPoint(pointID,
                                  inputPoint[0],
                                  inputPoint[1] * axesRatio[1] / axesRatio[0],
                                  inputPoint[2] * axesRatio[2] / axesRatio[0]);

          // TubeID
          tubeIDs->SetTuple1(pointID, currTube->GetId());

          // Radius
          tubeRadius->SetTuple1(pointID, tubePointIterator->GetRadius());

          // Tangeantes
          tan1->SetTuple3(pointID,
                          (*tubePointIterator).GetNormal1()[0],
                          (*tubePointIterator).GetNormal1()[1],
                          (*tubePointIterator).GetNormal1()[2]);

          tan2->SetTuple3(pointID,
                          (*tubePointIterator).GetNormal2()[0],
                          (*tubePointIterator).GetNormal2()[1],
                          (*tubePointIterator).GetNormal2()[2]);

          // Medialness & Ridgness
          if(tubePointIterator->GetMedialness() != 0)
            {
            containsMidialnessInfo = true;
            }
          medialness->SetTuple1(pointID, tubePointIterator->GetMedialness());

          if(tubePointIterator->GetRidgeness() != 0)
            {
            containsRidgnessInfo = true;
            }
          ridgeness->SetTuple1(pointID, tubePointIterator->GetRidgeness());
          }

        vesselLine->Initialize(tubeSize,
                               pointIDs,
                               vesselsPoints.GetPointer());
        vesselLinesCA->InsertNextCell(vesselLine.GetPointer());
        delete [] pointIDs;
        }

      // Convert spatial objects to a PolyData
      vtkNew<vtkPolyData> vesselsPD;
      vesselsPD->SetLines(vesselLinesCA.GetPointer());
      vesselsPD->SetPoints(vesselsPoints.GetPointer());

      // Add the Radius information
      vesselsPD->GetPointData()->AddArray(tubeRadius.GetPointer());
      vesselsPD->GetPointData()->SetActiveScalars("TubeRadius");

      // Add the TudeID information
      vesselsPD->GetPointData()->AddArray(tubeIDs.GetPointer());

      // Add Tangeantes information
      vesselsPD->GetPointData()->AddArray(tan1.GetPointer());
      vesselsPD->GetPointData()->AddArray(tan2.GetPointer());

      // Add Medialness & Ridgness if contains information
      if(containsMidialnessInfo == true)
        {
        vesselsPD->GetPointData()->AddArray(medialness.GetPointer());
        }

      if(containsRidgnessInfo == true)
        {
        vesselsPD->GetPointData()->AddArray(ridgeness.GetPointer());
        }

      // Remove any duplicate points from polydata.
      // The tubes generation will fails if any duplicates points are present.
      // Cleaned before, could create degeneration problems with the cells
      //vtkNew<vtkCleanPolyData> cleanedVesselPD;
      //cleanedVesselPD->SetInput(vesselsPD.GetPointer());

      vtkDebugMacro("Points: " << totalNumberOfPoints);

      spatialObjectsNode->SetAndObservePolyData(vesselsPD.GetPointer());
      spatialObjectsNode->SetSpatialObject(reader->GetGroup());
      delete tubeList;
    }
  }
  catch(...)
  {
    result = 0;
  }

  if(spatialObjectsNode->GetPolyData() != NULL)
    {
    // is there an active scalar array?
    if(spatialObjectsNode->GetDisplayNode())
      {
      double *scalarRange = spatialObjectsNode->GetPolyData()->GetScalarRange();
      if(scalarRange)
        {
        vtkDebugMacro("ReadData: setting scalar range " << scalarRange[0]
                      << ", " << scalarRange[1]);
        spatialObjectsNode->GetDisplayNode()->SetScalarRange(scalarRange);
        }
      }

    spatialObjectsNode->GetPolyData()->Modified();
    }

  return result;
}

//------------------------------------------------------------------------------
int vtkMRMLSpatialObjectsStorageNode::WriteDataInternal(vtkMRMLNode *refNode)
{
  vtkMRMLSpatialObjectsNode* spatialObjects =
    vtkMRMLSpatialObjectsNode::SafeDownCast(refNode);

  std::string fullName = this->GetFullNameFromFileName();
  if(fullName == std::string(""))
    {
    vtkErrorMacro("vtkMRMLModelNode: File name not specified");
    return 0;
    }

  std::string extension =
    itksys::SystemTools::GetFilenameLastExtension(fullName);

  int result = 1;
  if(extension == ".tre")
    {
    try
      {
      WriterType::Pointer writer = WriterType::New();
      writer->SetFileName(fullName.c_str());
      writer->SetInput(spatialObjects->GetSpatialObject());
      writer->Update();
      }
    catch(...)
      {
      result = 0;
      vtkErrorMacro("Error occured writing Spatial Objects: "
                    << fullName.c_str());
      }
    }
  else
    {
    result = 0;
    vtkErrorMacro( << "No file extension recognized: " << fullName.c_str());
    }

  return result;
}

//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedReadFileTypes( void )
{
  this->SupportedReadFileTypes->InsertNextValue("SpatialObject (.tre)");
}

//------------------------------------------------------------------------------
void vtkMRMLSpatialObjectsStorageNode::InitializeSupportedWriteFileTypes( void )
{
  this->SupportedWriteFileTypes->InsertNextValue("SpatialObject (.tre)");
}

//------------------------------------------------------------------------------
const char* vtkMRMLSpatialObjectsStorageNode::GetDefaultWriteFileExtension( void )
{
  return "tre";
}
<|endoftext|>


<commit_before>#include <QGraphicsView>

#include "fish_annotator/common/annotation_scene.h"

namespace fish_annotator {

AnnotationScene::AnnotationScene(QObject *parent)
  : QGraphicsScene(parent)
  , mode_(kDoNothing)
  , type_(kBox)
  , start_pos_()
  , rect_item_(nullptr)
  , line_item_(nullptr)
  , dot_item_(nullptr) {
}

void AnnotationScene::setToolWidget(AnnotationWidget *widget) {
  QObject::connect(widget, &AnnotationWidget::setAnnotation,
      this, &AnnotationScene::setAnnotationType);
}

void AnnotationScene::setMode(Mode mode) {
  mode_ = mode;
  QGraphicsView::DragMode drag;
  if(mode == kDraw) {
    makeItemsControllable(false);
    drag = QGraphicsView::NoDrag;
  }
  else if(mode == kSelect) {
    makeItemsControllable(true);
    drag = QGraphicsView::RubberBandDrag;
  }
  auto view = views().at(0);
  if(view != nullptr) view->setDragMode(drag);
}

void AnnotationScene::setAnnotationType(AnnotationType type) {
  type_ = type;
}

namespace {
// Define pen width in anonymous namespace.
static const int pen_width = 7;
}

void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
  if(mode_ == kDraw && sceneRect().contains(event->scenePos()) == true) {
    start_pos_ = event->scenePos();
    switch(type_) {
      case kBox:
        rect_item_ = new QGraphicsRectItem(
              start_pos_.x(), start_pos_.y(), 0, 0);
        rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
        addItem(rect_item_);
        break;
      case kLine:
        line_item_ = new QGraphicsLineItem(QLineF(
              start_pos_, start_pos_));
        line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
        addItem(line_item_);
        break;
      case kDot:
        dot_item_ = new QGraphicsEllipseItem(
              start_pos_.x() - pen_width,
              start_pos_.y() - pen_width,
              2 * pen_width, 2 * pen_width);
        dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
        addItem(dot_item_);
        break;
    }
  }
  QGraphicsScene::mousePressEvent(event);
}

void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
  if(mode_ == kDraw) {
    auto update_pos = event->scenePos();
    qreal margin;
    switch(type_) {
      case kBox:
        margin = pen_width / 2.0;
        break;
      case kLine:
        margin = pen_width;
        break;
      case kDot:
        margin = 2.0 * pen_width;
        break;
    }
    update_pos.setX(qMin(update_pos.x(), sceneRect().right() - margin));
    update_pos.setX(qMax(update_pos.x(), sceneRect().left() + margin));
    update_pos.setY(qMin(update_pos.y(), sceneRect().bottom() - margin));
    update_pos.setY(qMax(update_pos.y(), sceneRect().top() + margin));
    switch(type_) {
      case kBox:
        if(rect_item_ != nullptr) {
          auto left = qMin(start_pos_.x(), update_pos.x());
          auto top = qMin(start_pos_.y(), update_pos.y());
          auto width = qAbs(start_pos_.x() - update_pos.x());
          auto height = qAbs(start_pos_.y() - update_pos.y());
          rect_item_->setRect(QRectF(left, top, width, height));
        }
        break;
      case kLine:
        if(line_item_ != nullptr) {
          line_item_->setLine(QLineF(start_pos_, update_pos));
        }
        break;
      case kDot:
        if(dot_item_ != nullptr) {
          dot_item_->setRect(QRectF(
                update_pos.x() - pen_width,
                update_pos.y() - pen_width,
                2 * pen_width, 2 * pen_width));
        }
        break;
    }
  }
  QGraphicsScene::mouseMoveEvent(event);
}

void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
  if(mode_ == kDraw) {
    switch(type_) {
      case kBox:
        if(rect_item_ != nullptr) {
          emit boxFinished(rect_item_->rect());
          removeItem(rect_item_);
          rect_item_ = nullptr;
        }
        break;
      case kLine:
        if(line_item_ != nullptr) {
          emit lineFinished(line_item_->line());
          removeItem(line_item_);
          line_item_ = nullptr;
        }
        break;
      case kDot:
        if(dot_item_ != nullptr) {
          emit dotFinished(QPointF(
              dot_item_->rect().topLeft().x() + pen_width,
              dot_item_->rect().topLeft().y() + pen_width));
          removeItem(dot_item_);
          dot_item_ = nullptr;
        }
        break;
    }
    mode_ = kSelect;
  }
  QGraphicsScene::mouseReleaseEvent(event);
}

void AnnotationScene::makeItemsControllable(bool controllable) {
  foreach(QGraphicsItem *item, items()) {
    item->setFlag(QGraphicsItem::ItemIsSelectable, controllable);
    item->setFlag(QGraphicsItem::ItemIsMovable, controllable);
  }
}

#include "../../include/fish_annotator/common/moc_annotation_scene.cpp"

} // namespace fish_annotator
<commit_msg>Change to cursor when drawing is enabled.  This closes #25.<commit_after>#include <QGraphicsView>

#include "fish_annotator/common/annotation_scene.h"

namespace fish_annotator {

AnnotationScene::AnnotationScene(QObject *parent)
  : QGraphicsScene(parent)
  , mode_(kDoNothing)
  , type_(kBox)
  , start_pos_()
  , rect_item_(nullptr)
  , line_item_(nullptr)
  , dot_item_(nullptr) {
}

void AnnotationScene::setToolWidget(AnnotationWidget *widget) {
  QObject::connect(widget, &AnnotationWidget::setAnnotation,
      this, &AnnotationScene::setAnnotationType);
}

void AnnotationScene::setMode(Mode mode) {
  mode_ = mode;
  QGraphicsView::DragMode drag;
  if(mode == kDraw) {
    QApplication::setOverrideCursor(QCursor(Qt::CrossCursor));
    makeItemsControllable(false);
    drag = QGraphicsView::NoDrag;
  }
  else if(mode == kSelect) {
    makeItemsControllable(true);
    drag = QGraphicsView::RubberBandDrag;
  }
  auto view = views().at(0);
  if(view != nullptr) view->setDragMode(drag);
}

void AnnotationScene::setAnnotationType(AnnotationType type) {
  type_ = type;
}

namespace {
// Define pen width in anonymous namespace.
static const int pen_width = 7;
}

void AnnotationScene::mousePressEvent(QGraphicsSceneMouseEvent *event) {
  if(mode_ == kDraw && sceneRect().contains(event->scenePos()) == true) {
    start_pos_ = event->scenePos();
    switch(type_) {
      case kBox:
        rect_item_ = new QGraphicsRectItem(
              start_pos_.x(), start_pos_.y(), 0, 0);
        rect_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
        addItem(rect_item_);
        break;
      case kLine:
        line_item_ = new QGraphicsLineItem(QLineF(
              start_pos_, start_pos_));
        line_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
        addItem(line_item_);
        break;
      case kDot:
        dot_item_ = new QGraphicsEllipseItem(
              start_pos_.x() - pen_width,
              start_pos_.y() - pen_width,
              2 * pen_width, 2 * pen_width);
        dot_item_->setPen(QPen(Qt::black, pen_width, Qt::SolidLine));
        addItem(dot_item_);
        break;
    }
  }
  QGraphicsScene::mousePressEvent(event);
}

void AnnotationScene::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
  if(mode_ == kDraw) {
    auto update_pos = event->scenePos();
    qreal margin;
    switch(type_) {
      case kBox:
        margin = pen_width / 2.0;
        break;
      case kLine:
        margin = pen_width;
        break;
      case kDot:
        margin = 2.0 * pen_width;
        break;
    }
    update_pos.setX(qMin(update_pos.x(), sceneRect().right() - margin));
    update_pos.setX(qMax(update_pos.x(), sceneRect().left() + margin));
    update_pos.setY(qMin(update_pos.y(), sceneRect().bottom() - margin));
    update_pos.setY(qMax(update_pos.y(), sceneRect().top() + margin));
    switch(type_) {
      case kBox:
        if(rect_item_ != nullptr) {
          auto left = qMin(start_pos_.x(), update_pos.x());
          auto top = qMin(start_pos_.y(), update_pos.y());
          auto width = qAbs(start_pos_.x() - update_pos.x());
          auto height = qAbs(start_pos_.y() - update_pos.y());
          rect_item_->setRect(QRectF(left, top, width, height));
        }
        break;
      case kLine:
        if(line_item_ != nullptr) {
          line_item_->setLine(QLineF(start_pos_, update_pos));
        }
        break;
      case kDot:
        if(dot_item_ != nullptr) {
          dot_item_->setRect(QRectF(
                update_pos.x() - pen_width,
                update_pos.y() - pen_width,
                2 * pen_width, 2 * pen_width));
        }
        break;
    }
  }
  QGraphicsScene::mouseMoveEvent(event);
}

void AnnotationScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
  if(mode_ == kDraw) {
    switch(type_) {
      case kBox:
        if(rect_item_ != nullptr) {
          emit boxFinished(rect_item_->rect());
          removeItem(rect_item_);
          rect_item_ = nullptr;
        }
        break;
      case kLine:
        if(line_item_ != nullptr) {
          emit lineFinished(line_item_->line());
          removeItem(line_item_);
          line_item_ = nullptr;
        }
        break;
      case kDot:
        if(dot_item_ != nullptr) {
          emit dotFinished(QPointF(
              dot_item_->rect().topLeft().x() + pen_width,
              dot_item_->rect().topLeft().y() + pen_width));
          removeItem(dot_item_);
          dot_item_ = nullptr;
        }
        break;
    }
    mode_ = kSelect;
    QApplication::restoreOverrideCursor();
  }
  QGraphicsScene::mouseReleaseEvent(event);
}

void AnnotationScene::makeItemsControllable(bool controllable) {
  foreach(QGraphicsItem *item, items()) {
    item->setFlag(QGraphicsItem::ItemIsSelectable, controllable);
    item->setFlag(QGraphicsItem::ItemIsMovable, controllable);
  }
}

#include "../../include/fish_annotator/common/moc_annotation_scene.cpp"

} // namespace fish_annotator
<|endoftext|>


<commit_before>#include "log.h"
#include "InstructionQueue.h"
#include "SegmentAccessor.h"
#include "JobReport.h"
#include "Assembler.h"

#define  DEFAULT_INST_TIMEOUT_MS     (100000)

using namespace liber;
using namespace liber::rsync;

//-----------------------------------------------------------------------------
Assembler::Assembler( SegmentAccessor& segment_accessor )
: assembler_state_        ( segment_accessor )
, instruction_timeout_ms_ ( DEFAULT_INST_TIMEOUT_MS )
{
}

//-----------------------------------------------------------------------------
Assembler::~Assembler()
{
}

//-----------------------------------------------------------------------------
bool Assembler::process(
  JobDescriptor& job_descriptor,
  InstructionQueue& instruction_queue,
  AssemblyReport&   report
)
{
  assembler_state_.reset();
  assembler_state_.jobDescriptor() = job_descriptor;

  while ( ( assembler_state_.done() == false ) &&
          ( assembler_state_.failed() == false ) )
  {
    Instruction* instruction_ptr = instruction_queue.pop(
      instruction_timeout_ms_
    );

    if ( instruction_ptr )
    {
      switch ( instruction_ptr->type() )
      {
        case BeginInstruction::Type:
          report.begin.sample();
          break;

        case SegmentInstruction::Type:
          report.segmentCount++;
          break;

        case ChunkInstruction::Type:
          report.chunkCount++;
          break;

        case EndInstruction::Type:
          report.end.sample();
          break;

        default:
          log::error("Assembler - Invalid instruction type %d\n",
                     instruction_ptr->type());
          break;
      }

      instruction_ptr->execute(
        assembler_state_
      );

      if ( assembler_state_.failed() )
      {
        log::error(
          "Assembler::process - "
          "Instruction (type=%d) failed with status %d\n",
          instruction_ptr->type(),
          assembler_state_.status_
        );
      }

      delete instruction_ptr;
    }
    else
    {
      log::error("Assembler - NULL instruction.\n");
    }
  }

  report.status = assembler_state_.status_;

  return ( assembler_state_.failed() == false );
}

//-----------------------------------------------------------------------------
std::ofstream& Assembler::outputStream()
{
  return assembler_state_.stream();
}

<commit_msg>Fixed bad spelling in include.<commit_after>#include "Log.h"
#include "InstructionQueue.h"
#include "SegmentAccessor.h"
#include "JobReport.h"
#include "Assembler.h"

#define  DEFAULT_INST_TIMEOUT_MS     (100000)

using namespace liber;
using namespace liber::rsync;

//-----------------------------------------------------------------------------
Assembler::Assembler( SegmentAccessor& segment_accessor )
: assembler_state_        ( segment_accessor )
, instruction_timeout_ms_ ( DEFAULT_INST_TIMEOUT_MS )
{
}

//-----------------------------------------------------------------------------
Assembler::~Assembler()
{
}

//-----------------------------------------------------------------------------
bool Assembler::process(
  JobDescriptor& job_descriptor,
  InstructionQueue& instruction_queue,
  AssemblyReport&   report
)
{
  assembler_state_.reset();
  assembler_state_.jobDescriptor() = job_descriptor;

  while ( ( assembler_state_.done() == false ) &&
          ( assembler_state_.failed() == false ) )
  {
    Instruction* instruction_ptr = instruction_queue.pop(
      instruction_timeout_ms_
    );

    if ( instruction_ptr )
    {
      switch ( instruction_ptr->type() )
      {
        case BeginInstruction::Type:
          report.begin.sample();
          break;

        case SegmentInstruction::Type:
          report.segmentCount++;
          break;

        case ChunkInstruction::Type:
          report.chunkCount++;
          break;

        case EndInstruction::Type:
          report.end.sample();
          break;

        default:
          log::error("Assembler - Invalid instruction type %d\n",
                     instruction_ptr->type());
          break;
      }

      instruction_ptr->execute(
        assembler_state_
      );

      if ( assembler_state_.failed() )
      {
        log::error(
          "Assembler::process - "
          "Instruction (type=%d) failed with status %d\n",
          instruction_ptr->type(),
          assembler_state_.status_
        );
      }

      delete instruction_ptr;
    }
    else
    {
      log::error("Assembler - NULL instruction.\n");
    }
  }

  report.status = assembler_state_.status_;

  return ( assembler_state_.failed() == false );
}

//-----------------------------------------------------------------------------
std::ofstream& Assembler::outputStream()
{
  return assembler_state_.stream();
}

<|endoftext|>