<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX72M グループ・ペリフェラル
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2019 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ペリフェラル種別
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class peripheral : uint16_t {

		CAC,		///< クロック周波数精度測定回路

		DTC,		///< データトランスファコントローラ

		ELC,		///< イベントリンクコントローラ

		DMAC0,		///< DMA コントローラ・チャネル０
		DMAC1,		///< DMA コントローラ・チャネル１
		DMAC2,		///< DMA コントローラ・チャネル２
		DMAC3,		///< DMA コントローラ・チャネル３
		DMAC4,		///< DMA コントローラ・チャネル４
		DMAC5,		///< DMA コントローラ・チャネル５
		DMAC6,		///< DMA コントローラ・チャネル６
		DMAC7,		///< DMA コントローラ・チャネル７

		EXDMAC0,	///< EXDMA コントローラ・チャネル０
		EXDMAC1,	///< EXDMA コントローラ・チャネル１

		MTU0,		///< マルチファンクションタイマパルスユニット０
		MTU1,		///< マルチファンクションタイマパルスユニット１
		MTU2,		///< マルチファンクションタイマパルスユニット２
		MTU3,		///< マルチファンクションタイマパルスユニット３
		MTU4,		///< マルチファンクションタイマパルスユニット４
		MTU5,		///< マルチファンクションタイマパルスユニット５
		MTU6,		///< マルチファンクションタイマパルスユニット６
		MTU7,		///< マルチファンクションタイマパルスユニット７
		MTU8,		///< マルチファンクションタイマパルスユニット８

		POE,		///< ポートアウトプットイネーブル

		GPTW0,		///< 汎用 PWM タイマ０
		GPTW1,		///< 汎用 PWM タイマ１
		GPTW2,		///< 汎用 PWM タイマ２
		GPTW3,		///< 汎用 PWM タイマ３

		TPU0,		///< 16 ビットタイマパルスユニット０
		TPU1,		///< 16 ビットタイマパルスユニット１
		TPU2,		///< 16 ビットタイマパルスユニット２
		TPU3,		///< 16 ビットタイマパルスユニット３
		TPU4,		///< 16 ビットタイマパルスユニット４
		TPU5,		///< 16 ビットタイマパルスユニット５

		PPG0,		///< プログラマブルパルスジェネレータ０
		PPG1,		///< プログラマブルパルスジェネレータ１

		TMR0,		///< 8 ビットタイマ０
		TMR1,		///< 8 ビットタイマ１
		TMR2,		///< 8 ビットタイマ２
		TMR3,		///< 8 ビットタイマ３

		CMT0,		///< コンペアマッチタイマ０（CMT）
		CMT1,		///< コンペアマッチタイマ１（CMT）
		CMT2,		///< コンペアマッチタイマ２（CMT）
		CMT3,		///< コンペアマッチタイマ３（CMT）

		CMTW0,		///< コンペアマッチタイマＷ０（CMTW）
		CMTW1,		///< コンペアマッチタイマＷ１（CMTW）

		RTC,		///< リアルタイムクロック

		WDTA,		///< ウォッチドッグタイマ
		IWDT,		///< 独立ウォッチドッグタイマ

		ETHERC0,	///< イーサネットコントローラ 0
		ETHERC1,	///< イーサネットコントローラ 1
		EPTPC,		///< イーサネットコントローラ用 PTP コントローラ
		EPTPC0,		///< イーサネットコントローラ用 PTP コントローラ 0
		EPTPC1,		///< イーサネットコントローラ用 PTP コントローラ 1

		ETHERCA,	///< Ethernet 0 (PHY RMII)カスタムポート接続

		EDMAC0,		///< Ethernet DMA 0
		EDMAC1,		///< Ethernet DMA 1
		PTPEDMAC,	///< PTP Ethernet DMA

		PMGI0,		///< PHY マネジメントインタフェース 0
		PMGI1,		///< PHY マネジメントインタフェース 1

		ESC,		///< EtherCAT スレーブコントローラ

		USB0,		///< USB2.0FSホスト/ファンクションモジュール（USBb）

		SCI0,		///< シリアルコミュニケーションインタフェース (P20:TXD0, P21:RXD0)
		SCI1,		///< シリアルコミュニケーションインタフェース (PF0:TXD1, PF2:RXD1)
		SCI2,		///< シリアルコミュニケーションインタフェース (P13:TXD2, P12:RXD2)
		SCI3,		///< シリアルコミュニケーションインタフェース (P23:TXD3, P25:RXD3)
		SCI4,		///< シリアルコミュニケーションインタフェース (PB1:TXD4, PB0:RXD4)
		SCI5,		///< シリアルコミュニケーションインタフェース (PA4:TXD5, PA2:RXD5)
		SCI6,		///< シリアルコミュニケーションインタフェース (P00:TXD6, P01:RXD6)
		SCI7,		///< シリアルコミュニケーションインタフェース (P90:TXD7, P92:RXD7)
		SCI8,		///< シリアルコミュニケーションインタフェース
		SCI9,		///< シリアルコミュニケーションインタフェース
		SCI10,		///< シリアルコミュニケーションインタフェース
		SCI11,		///< シリアルコミュニケーションインタフェース
		SCI12,		///< シリアルコミュニケーションインタフェース

		RIIC0,		///< I 2 C バスインタフェース０（RIICa）
		RIIC1,		///< I 2 C バスインタフェース１（RIICa）
		RIIC2,		///< I 2 C バスインタフェース２（RIICa）

		CAN0,		///< CAN インタフェース（CAN0）
		CAN1,		///< CAN インタフェース（CAN1）
		CAN2,		///< CAN インタフェース（CAN2）

		RSPI0,		///< シリアルペリフェラルインタフェース（RSPIc）
		RSPI1,		///< シリアルペリフェラルインタフェース（RSPIc）
		RSPI2,		///< シリアルペリフェラルインタフェース（RSPIc）

		QSPI,		///< クワッドシリアルペリフェラルインタフェース（QSPI）

		CRC,		///< CRC 演算器

		SSIE0,		///< シリアルサウンドインタフェース（SSIE）
		SSIE1,		///< シリアルサウンドインタフェース（SSIE）

		SDHI,		///< SD ホストインタフェース（SDHI）

		MMCIF,		///< マルチメディアカードインタフェース（MMCIF）

		PDC,		///< パラレルデータキャプチャユニット

		GLCDC,		///< グラフィックスＬＣＤコントローラ
		DRW2D,		///< ２Ｄ描画エンジン

		DSMIF0,		///< ΔΣモジュレータインターフェース 0
		DSMIF1,		///< ΔΣモジュレータインターフェース 1

		S12AD,		///< 12 ビット A/D コンバータ（S12ADC）
		S12AD1,		///< 12 ビット A/D コンバータ（S12ADC）

		R12DA,		///< 12 ビット D/A コンバータ（R12DA）

		TEMPS,		///< 温度センサ

		DOC,		///< データ演算回路

		RAM,		///< RAM (512K)
		EXTRAM,		///< 拡張 RAM (512K)
		ECCRAM,		///< ECC RAM (32K)
		STBRAM,		///< Standby RAM (8K)

		// 仮の仕様
		IRQ0,
		IRQ1,
		IRQ2,
		IRQ3,
		IRQ4,
		IRQ5,
		IRQ6,
		IRQ7,

		ICU,		///< グループ割り込みペリフェラル
	};
}
<commit_msg>Update: cleanup<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX72M グループ・ペリフェラル
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2019 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include <cstdint>

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ペリフェラル種別
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	enum class peripheral : uint16_t {

		CAC,		///< クロック周波数精度測定回路

		DTC,		///< データトランスファコントローラ

		ELC,		///< イベントリンクコントローラ

		DMAC0,		///< DMA コントローラ・チャネル０
		DMAC1,		///< DMA コントローラ・チャネル１
		DMAC2,		///< DMA コントローラ・チャネル２
		DMAC3,		///< DMA コントローラ・チャネル３
		DMAC4,		///< DMA コントローラ・チャネル４
		DMAC5,		///< DMA コントローラ・チャネル５
		DMAC6,		///< DMA コントローラ・チャネル６
		DMAC7,		///< DMA コントローラ・チャネル７

		EXDMAC0,	///< EXDMA コントローラ・チャネル０
		EXDMAC1,	///< EXDMA コントローラ・チャネル１

		MTU0,		///< マルチファンクションタイマパルスユニット０
		MTU1,		///< マルチファンクションタイマパルスユニット１
		MTU2,		///< マルチファンクションタイマパルスユニット２
		MTU3,		///< マルチファンクションタイマパルスユニット３
		MTU4,		///< マルチファンクションタイマパルスユニット４
		MTU5,		///< マルチファンクションタイマパルスユニット５
		MTU6,		///< マルチファンクションタイマパルスユニット６
		MTU7,		///< マルチファンクションタイマパルスユニット７
		MTU8,		///< マルチファンクションタイマパルスユニット８

		POE3,		///< ポートアウトプットイネーブル

		GPTW0,		///< 汎用 PWM タイマ０
		GPTW1,		///< 汎用 PWM タイマ１
		GPTW2,		///< 汎用 PWM タイマ２
		GPTW3,		///< 汎用 PWM タイマ３

		TPU0,		///< 16 ビットタイマパルスユニット０
		TPU1,		///< 16 ビットタイマパルスユニット１
		TPU2,		///< 16 ビットタイマパルスユニット２
		TPU3,		///< 16 ビットタイマパルスユニット３
		TPU4,		///< 16 ビットタイマパルスユニット４
		TPU5,		///< 16 ビットタイマパルスユニット５

		PPG0,		///< プログラマブルパルスジェネレータ０
		PPG1,		///< プログラマブルパルスジェネレータ１

		TMR0,		///< 8 ビットタイマ０
		TMR1,		///< 8 ビットタイマ１
		TMR2,		///< 8 ビットタイマ２
		TMR3,		///< 8 ビットタイマ３

		CMT0,		///< コンペアマッチタイマ０（CMT）
		CMT1,		///< コンペアマッチタイマ１（CMT）
		CMT2,		///< コンペアマッチタイマ２（CMT）
		CMT3,		///< コンペアマッチタイマ３（CMT）

		CMTW0,		///< コンペアマッチタイマＷ０（CMTW）
		CMTW1,		///< コンペアマッチタイマＷ１（CMTW）

		RTC,		///< リアルタイムクロック

		WDTA,		///< ウォッチドッグタイマ
		IWDT,		///< 独立ウォッチドッグタイマ

		ETHERC0,	///< イーサネットコントローラ 0
		ETHERC1,	///< イーサネットコントローラ 1
		EPTPC,		///< イーサネットコントローラ用 PTP コントローラ
		EPTPC0,		///< イーサネットコントローラ用 PTP コントローラ 0
		EPTPC1,		///< イーサネットコントローラ用 PTP コントローラ 1

		ETHERCA,	///< Ethernet 0 (PHY RMII)カスタムポート接続

		EDMAC0,		///< Ethernet DMA 0
		EDMAC1,		///< Ethernet DMA 1
		PTPEDMAC,	///< PTP Ethernet DMA

		PMGI0,		///< PHY マネジメントインタフェース 0
		PMGI1,		///< PHY マネジメントインタフェース 1

		ESC,		///< EtherCAT スレーブコントローラ

		USB0,		///< USB2.0FSホスト/ファンクションモジュール（USBb）

		SCI0,		///< シリアルコミュニケーションインタフェース (P20:TXD0, P21:RXD0)
		SCI1,		///< シリアルコミュニケーションインタフェース (PF0:TXD1, PF2:RXD1)
		SCI2,		///< シリアルコミュニケーションインタフェース (P13:TXD2, P12:RXD2)
		SCI3,		///< シリアルコミュニケーションインタフェース (P23:TXD3, P25:RXD3)
		SCI4,		///< シリアルコミュニケーションインタフェース (PB1:TXD4, PB0:RXD4)
		SCI5,		///< シリアルコミュニケーションインタフェース (PA4:TXD5, PA2:RXD5)
		SCI6,		///< シリアルコミュニケーションインタフェース (P00:TXD6, P01:RXD6)
		SCI7,		///< シリアルコミュニケーションインタフェース (P90:TXD7, P92:RXD7)
		SCI8,		///< シリアルコミュニケーションインタフェース
		SCI9,		///< シリアルコミュニケーションインタフェース
		SCI10,		///< シリアルコミュニケーションインタフェース
		SCI11,		///< シリアルコミュニケーションインタフェース
		SCI12,		///< シリアルコミュニケーションインタフェース

		RIIC0,		///< I 2 C バスインタフェース０（RIICa）
		RIIC1,		///< I 2 C バスインタフェース１（RIICa）
		RIIC2,		///< I 2 C バスインタフェース２（RIICa）

		CAN0,		///< CAN インタフェース（CAN0）
		CAN1,		///< CAN インタフェース（CAN1）
		CAN2,		///< CAN インタフェース（CAN2）

		RSPI0,		///< シリアルペリフェラルインタフェース（RSPIc）
		RSPI1,		///< シリアルペリフェラルインタフェース（RSPIc）
		RSPI2,		///< シリアルペリフェラルインタフェース（RSPIc）

		QSPI,		///< クワッドシリアルペリフェラルインタフェース（QSPI）

		CRC,		///< CRC 演算器

		SSIE0,		///< シリアルサウンドインタフェース（SSIE）
		SSIE1,		///< シリアルサウンドインタフェース（SSIE）

		SDHI,		///< SD ホストインタフェース（SDHI）

		MMCIF,		///< マルチメディアカードインタフェース（MMCIF）

		PDC,		///< パラレルデータキャプチャユニット

		GLCDC,		///< グラフィックスＬＣＤコントローラ
		DRW2D,		///< ２Ｄ描画エンジン

		DSMIF0,		///< ΔΣモジュレータインターフェース 0
		DSMIF1,		///< ΔΣモジュレータインターフェース 1

		S12AD,		///< 12 ビット A/D コンバータ（S12ADC）
		S12AD1,		///< 12 ビット A/D コンバータ（S12ADC）

		R12DA,		///< 12 ビット D/A コンバータ（R12DA）

		TEMPS,		///< 温度センサ

		DOC,		///< データ演算回路

		RAM,		///< RAM (512K)
		EXTRAM,		///< 拡張 RAM (512K)
		ECCRAM,		///< ECC RAM (32K)
		STBRAM,		///< Standby RAM (8K)

		// 仮の仕様
		IRQ0,
		IRQ1,
		IRQ2,
		IRQ3,
		IRQ4,
		IRQ5,
		IRQ6,
		IRQ7,

		ICU,		///< グループ割り込みペリフェラル
	};
}
<|endoftext|>


<commit_before><commit_msg>2016-09-01 腾讯笔试 矩阵回形排列数字<commit_after><|endoftext|>


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

#include <iostream>
#include <memory>

#include <rclcpp/rclcpp.hpp>
#include <rclcpp/executors.hpp>
#include <rclcpp/memory_strategies.hpp>

#include <std_interfaces/msg/string.hpp>

using rclcpp::memory_strategies::static_memory_strategy::StaticMemoryStrategy;

void chatterCallback(const std_interfaces::msg::String::ConstSharedPtr & msg)
{
  std::cout << "I heard: [" << msg->data << "]" << std::endl << std::flush;
}

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy =
    rclcpp::memory_strategy::create_default_strategy();
  if (argc > 1) {
    std::string argument(argv[1]);
    if (argument == "static") {
      std::cout << "Setting memory allocation strategy to 'static'." << std::endl;
      memory_strategy = std::make_shared<StaticMemoryStrategy>(StaticMemoryStrategy());
    } else if (argument == "dynamic") {
      std::cout << "Setting memory allocation strategy to 'dynamic'." << std::endl;
    } else {
      std::cout << "Warning: unknown argument. " << std::endl;
      std::cout << "Setting memory allocation strategy to default (dynamic)." << std::endl;
    }
  }

  auto node = rclcpp::Node::make_shared("listener_exec");
  rclcpp::executors::SingleThreadedExecutor executor(memory_strategy);
  executor.add_node(node);

  auto sub = node->create_subscription<std_interfaces::msg::String>("chatter", 7, chatterCallback);

  executor.spin();

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

#include <iostream>
#include <memory>

#include <rclcpp/rclcpp.hpp>
#include <rclcpp/executors.hpp>
#include <rclcpp/memory_strategies.hpp>

#include <std_interfaces/msg/string.hpp>

using rclcpp::memory_strategies::static_memory_strategy::StaticMemoryStrategy;

void chatterCallback(const std_interfaces::msg::String::ConstSharedPtr & msg)
{
  printf("I heard: [%s]\n", msg->data.c_str());
}

int main(int argc, char * argv[])
{
  rclcpp::init(argc, argv);
  rclcpp::memory_strategy::MemoryStrategy::SharedPtr memory_strategy = nullptr;
  if (argc > 1) {
    std::string argument(argv[1]);
    if (argument == "static") {
      std::cout << "Setting memory allocation strategy to 'static'." << std::endl;
      memory_strategy = std::make_shared<StaticMemoryStrategy>(StaticMemoryStrategy());
    } else if (argument == "dynamic") {
      std::cout << "Setting memory allocation strategy to 'dynamic'." << std::endl;
    } else {
      std::cout << "Warning: unknown argument. " << std::endl;
      std::cout << "Setting memory allocation strategy to default (dynamic)." << std::endl;
    }
  }
  if (memory_strategy == nullptr) {
    memory_strategy = rclcpp::memory_strategy::create_default_strategy();
  }

  auto node = rclcpp::Node::make_shared("listener_exec");
  rclcpp::executors::SingleThreadedExecutor executor(memory_strategy);
  executor.add_node(node);

  auto sub = node->create_subscription<std_interfaces::msg::String>("chatter", 7, chatterCallback);

  executor.spin();

  return 0;
}
<|endoftext|>


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

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbSamplingRateCalculatorList.h"
#include "otbStatisticsXMLFileReader.h"

namespace otb
{
namespace Wrapper
{

class MultiImageSamplingRate : public Application
{
public:
  /** Standard class typedefs. */
  typedef MultiImageSamplingRate        Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(MultiImageSamplingRate, otb::Application);

  /** typedef */
  typedef otb::SamplingRateCalculatorList           RateCalculatorListType;

  typedef RateCalculatorListType::ClassCountMapType      ClassCountMapType;
  typedef RateCalculatorListType::MapRateType           MapRateType;

  typedef itk::VariableLengthVector<float> MeasurementType;
  typedef otb::StatisticsXMLFileReader<MeasurementType> XMLReaderType;

private:
  MultiImageSamplingRate()
    {
    m_CalculatorList = RateCalculatorListType::New();
    }

  void DoInit()
  {
    SetName("MultiImageSamplingRate");
    SetDescription("Compute sampling rate for an input set of images.");

    // Documentation
    SetDocName("Multi-image sampling rate estimation");
    SetDocLongDescription("The application computes sampling rates for a set of"
      " input images. Before calling this application, each pair of image and "
      "training vectors has to be analysed with the application "
      "PolygonClassStatistics. The statistics file is then used to compute the "
      "sampling rates for each class in each image. Several types of sampling "
      " are implemented. Each one is a combination of a mono-image strategy "
      "and a multi-image mode. The mono-image strategies are :\n"
      "  - smallest (default) : select the same number of sample in each "
      "class so that the smallest one is fully sampled.\n"
      "  - constant : select the same number of samples N in each class "
      "(with N below or equal to the size of the smallest class).\n"
      "  - byclass : set the required number for each class manually, with an "
      "input CSV file (first column is class name, second one is the required "
      "samples number).\n"
      "The multi-image modes are :\n"
      "  - proportional : we try to split proportionally the number of required"
      " samples in each image\n"
      "  - equal : we split equally the number of required samples in each "
      "image.\n"
      "  - custom : the user chooses how to split the number of required "
      "samples for each image.\n"
      );
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Learning);

    AddParameter(ParameterType_InputFilenameList,  "il",   "Input statistics");
    SetParameterDescription("il", "List of statistics files for each input image.");

    AddParameter(ParameterType_OutputFilename, "out", "Output sampling rates");
    SetParameterDescription("out","Output filename storing sampling rates (CSV "
      "format with class name, required samples, total samples, and rate). "
      "The given filename will be used with a suffix to indicate the "
      "corresponding input index (for instance: rates.csv will give rates_1.csv"
      ", rates_2.csv, ...).");

    AddParameter(ParameterType_Choice, "strategy", "Sampling strategy");

    AddChoice("strategy.byclass","Set samples count for each class");
    SetParameterDescription("strategy.byclass","Set samples count for each class");

    AddParameter(ParameterType_InputFilenameList, "strategy.byclass.in", "Number of samples by class");
    SetParameterDescription("strategy.byclass.in", "Number of samples by class "
      "(CSV format with class name in 1st column and required samples in the 2nd)."
      "In the case of the custom multi-image mode, several inputs may be given for each image.");

    AddChoice("strategy.constant","Set the same samples counts for all classes");
    SetParameterDescription("strategy.constant","Set the same samples counts for all classes");

    AddParameter(ParameterType_String, "strategy.constant.nb", "Number of samples for all classes");
    SetParameterDescription("strategy.constant.nb", "Number of samples for all classes."
      "In the case of the custom multi-image mode, several values can be given for each image.");

    AddChoice("strategy.smallest","Set same number of samples for all classes, with the smallest class fully sampled");
    SetParameterDescription("strategy.smallest","Set same number of samples for all classes, with the smallest class fully sampled");

    AddChoice("strategy.all","Take all samples");
    SetParameterDescription("strategy.all","Take all samples");

    // Default strategy : smallest
    SetParameterString("strategy","smallest");

    AddParameter(ParameterType_Choice, "mim", "Multi-Image Mode");

    AddChoice("mim.proportional", "Proportional");
    SetParameterDescription("mim.proportional","Split proportionally the required number of samples");

    AddChoice("mim.equal", "equal");
    SetParameterDescription("mim.equal","Split equally the required number of samples");

    AddChoice("mim.custom", "Custom");
    SetParameterDescription("mim.custom","Split the required number of samples following user choice.");

    // Doc example parameter settings
    SetDocExampleParameterValue("il", "stats_1.xml stats_2.xml");
    SetDocExampleParameterValue("out", "rates.csv");
    SetDocExampleParameterValue("strategy", "smallest");
    SetDocExampleParameterValue("mode","proportional");
  }

  void DoUpdateParameters()
  {
  }

  void DoExecute()
    {
    // Clear state
    m_CalculatorList->Clear();
    std::vector<std::string> inputs = this->GetParameterStringList("il");
    unsigned int nbInputs = inputs.size();
    XMLReaderType::Pointer statReader = XMLReaderType::New();
    for (unsigned int i=0 ; i<nbInputs ; i++ )
      {
      m_CalculatorList->PushBack(otb::SamplingRateCalculator::New());
      statReader->SetFileName(inputs[i]);
      ClassCountMapType classCount = statReader->GetStatisticMapByName<ClassCountMapType>("samplesPerClass");
      m_CalculatorList->SetNthClassCount(i,classCount);
      }

    // Cautions : direct mapping between the enum PartitionType and the choice order
    RateCalculatorListType::PartitionType partitionMode =
      static_cast<RateCalculatorListType::PartitionType>(this->GetParameterInt("mim"));

    unsigned int minParamSize = 1;
    if (partitionMode == RateCalculatorListType::CUSTOM)
      {
      // Check we have enough inputs for the custom mode
      minParamSize = nbInputs;
      }

    switch (this->GetParameterInt("strategy"))
      {
      // byclass
      case 0:
        {
        std::vector<std::string> requiredFiles = this->GetParameterStringList("strategy.byclass.in");
        std::vector<ClassCountMapType> requiredCounts;
        if (requiredFiles.size() < minParamSize)
          {
          otbAppLogFATAL("Missing arguments in strategy.byclass.in to process sampling rates");
          }
        otbAppLogINFO("Sampling strategy : set number of samples for each class");
        for (unsigned int i=0 ; i<minParamSize ; i++)
          {
          requiredCounts.push_back(otb::SamplingRateCalculator::ReadRequiredSamples(requiredFiles[i]));
          }
        m_CalculatorList->SetNbOfSamplesByClass(requiredCounts, partitionMode);
        }
      break;
      // constant
      case 1:
        {
        std::vector<itksys::String> parts = itksys::SystemTools::SplitString(this->GetParameterString("strategy.constant.nb"),' ');
        std::vector<unsigned long> countList;
        for (unsigned int i=0 ; i<parts.size() ; i++)
          {
          if (!parts[i].empty())
            {
            std::string::size_type pos1 = parts[i].find_first_not_of(" \t");
            std::string::size_type pos2 = parts[i].find_last_not_of(" \t");
            std::string value(parts[i].substr(pos1, pos2 - pos1 + 1));
            countList.push_back(boost::lexical_cast<unsigned long>(parts[i]));
            }
          }
        if (countList.size() < minParamSize)
          {
          otbAppLogFATAL("Missing arguments in strategy.constant.nb to process sampling rates");
          }
        otbAppLogINFO("Sampling strategy : set a constant number of samples for all classes");
        m_CalculatorList->SetNbOfSamplesAllClasses(countList, partitionMode);
        }
      break;
      // smallest class
      case 2:
        {
        otbAppLogINFO("Sampling strategy : fit the number of samples based on the smallest class");
        m_CalculatorList->SetMinimumNbOfSamplesByClass(partitionMode);
        }
      break;
      // all samples
      case 3:
        {
        otbAppLogINFO("Sampling strategy : take all samples");
        m_CalculatorList->SetAllSamples(partitionMode);
        }
      break;
      default:
        otbAppLogFATAL("Strategy mode unknown :"<<this->GetParameterString("strategy"));
      break;
      }

    std::ostringstream oss;
    std::string outputPath(this->GetParameterString("out"));
    std::string outputBase = outputPath.substr(0, outputPath.find_last_of('.'));
    std::string outputExt = outputPath.substr(outputPath.find_last_of('.'), std::string::npos);
    unsigned int overflowCount = 0;
    for (unsigned int i=0 ; i<nbInputs ; i++ )
      {
      // Print results
      oss.str(std::string(""));
      oss << " className  requiredSamples  totalSamples  rate" << std::endl;
      MapRateType rates = m_CalculatorList->GetRatesByClass(i);
      MapRateType::const_iterator itRates = rates.begin();
      for(; itRates != rates.end(); ++itRates)
        {
        otb::SamplingRateCalculator::TripletType tpt = itRates->second;
        oss << itRates->first << "\t" << tpt.Required << "\t" << tpt.Tot << "\t" << tpt.Rate;
        if (tpt.Required > tpt.Tot)
          {
          overflowCount++;
          oss << "\t[OVERFLOW]";
          }
        oss << std::endl;
        }
      otbAppLogINFO("Sampling rates for image "<< i+1 <<" : " << oss.str());
      // Output results to disk
      oss.str(std::string(""));
      oss << outputBase << "_" << i+1 << outputExt;
      m_CalculatorList->GetNthElement(i)->Write(oss.str());
      }
    if (overflowCount)
      {
      std::string plural(overflowCount>1?"s":"");
      otbAppLogWARNING(<< overflowCount << " case"<<plural<<" of overflow detected! (requested number of samples higher than total available samples)");
      }
  }

  RateCalculatorListType::Pointer m_CalculatorList;
};

} // end namespace Wrapper
} // end namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::MultiImageSamplingRate)
<commit_msg>DOC: improve documentation of MultiImageSamplingRate<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbSamplingRateCalculatorList.h"
#include "otbStatisticsXMLFileReader.h"

namespace otb
{
namespace Wrapper
{

class MultiImageSamplingRate : public Application
{
public:
  /** Standard class typedefs. */
  typedef MultiImageSamplingRate        Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(MultiImageSamplingRate, otb::Application);

  /** typedef */
  typedef otb::SamplingRateCalculatorList           RateCalculatorListType;

  typedef RateCalculatorListType::ClassCountMapType      ClassCountMapType;
  typedef RateCalculatorListType::MapRateType           MapRateType;

  typedef itk::VariableLengthVector<float> MeasurementType;
  typedef otb::StatisticsXMLFileReader<MeasurementType> XMLReaderType;

private:
  MultiImageSamplingRate()
    {
    m_CalculatorList = RateCalculatorListType::New();
    }

  void DoInit()
  {
    SetName("MultiImageSamplingRate");
    SetDescription("Compute sampling rate for an input set of images.");

    // Documentation
    SetDocName("Multi-image sampling rate estimation");
    SetDocLongDescription("The application computes sampling rates for a set of"
      " input images. Before calling this application, each pair of image and "
      "training vectors has to be analysed with the application "
      "PolygonClassStatistics. The statistics file is then used to compute the "
      "sampling rates for each class in each image. Several types of sampling "
      " are implemented. Each one is a combination of a mono-image strategy "
      "and a multi-image mode. The mono-image strategies are :\n"
      "  - smallest (default) : select the same number of sample in each "
      "class so that the smallest one is fully sampled.\n"
      "  - constant : select the same number of samples N in each class "
      "(with N below or equal to the size of the smallest class).\n"
      "  - byclass : set the required number for each class manually, with an "
      "input CSV file (first column is class name, second one is the required "
      "samples number).\n"
      "The multi-image modes (mim) are : proportional, equal and custom. The custom "
      "mode lets the users choose the distribution of samples among the "
      "images. The different behaviours are described below. Ti(c) and Ni(c) "
      " refers resp. to the total number and needed number of samples in "
      "image i for class c. Let's call L the total number of images.\n"
      "  > strategy = all\n"
      "    + Same behaviour for all modes : take all samples\n"
      "  > strategy = constant\n"
      "    (let's call M the global number of samples required per class)\n"
      "    + mim = proportional : For each image i and each class c,\n"
      "       Ni( c ) = M * Ti( c ) / sum_k( Tk(c) )\n"
      "    + mim = equal : For each image i and each class c,\n"
      "       Ni( c ) = M / L\n"
      "    + mim = custom : For each image i and each class c,\n"
      "       Ni( c ) = Mi where Mi is the custom requested number of samples for image i\n"
      "  > strategy = byClass\n"
      "    (let's call M(c) the global number of samples for class c)\n"
      "    + mim = proportional : For each image i and each class c\n"
      "       Ni( c ) = M(c) * Ti( c ) / sum_k( Tk(c) )\n"
      "    + mim = equal : For each image i and each class c,\n"
      "       Ni( c ) = M(c) / L\n"
      "    + mim = custom : For each image i and each class c,\n"
      "       Ni( c ) = Mi(c) where Mi(c) is the custom requested number of samples for image i and class c\n"
      "  > strategy = smallest class\n"
      "    + mim = proportional :\n"
      "       The smallest class size (computed globally) is used for the strategy constant+proportional\n"
      "    + mim = equal :\n"
      "       The smallest class size (computed globally) is used for the strategy constant+equal\n"
      "    + mim = custom :\n"
      "       The smallest class is computed and used for each image separately\n"
      );
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Learning);

    AddParameter(ParameterType_InputFilenameList,  "il",   "Input statistics");
    SetParameterDescription("il", "List of statistics files for each input image.");

    AddParameter(ParameterType_OutputFilename, "out", "Output sampling rates");
    SetParameterDescription("out","Output filename storing sampling rates (CSV "
      "format with class name, required samples, total samples, and rate). "
      "The given filename will be used with a suffix to indicate the "
      "corresponding input index (for instance: rates.csv will give rates_1.csv"
      ", rates_2.csv, ...).");

    AddParameter(ParameterType_Choice, "strategy", "Sampling strategy");

    AddChoice("strategy.byclass","Set samples count for each class");
    SetParameterDescription("strategy.byclass","Set samples count for each class");

    AddParameter(ParameterType_InputFilenameList, "strategy.byclass.in", "Number of samples by class");
    SetParameterDescription("strategy.byclass.in", "Number of samples by class "
      "(CSV format with class name in 1st column and required samples in the 2nd)."
      "In the case of the custom multi-image mode, several inputs may be given for each image.");

    AddChoice("strategy.constant","Set the same samples counts for all classes");
    SetParameterDescription("strategy.constant","Set the same samples counts for all classes");

    AddParameter(ParameterType_String, "strategy.constant.nb", "Number of samples for all classes");
    SetParameterDescription("strategy.constant.nb", "Number of samples for all classes."
      "In the case of the custom multi-image mode, several values can be given for each image.");

    AddChoice("strategy.smallest","Set same number of samples for all classes, with the smallest class fully sampled");
    SetParameterDescription("strategy.smallest","Set same number of samples for all classes, with the smallest class fully sampled");

    AddChoice("strategy.all","Take all samples");
    SetParameterDescription("strategy.all","Take all samples");

    // Default strategy : smallest
    SetParameterString("strategy","smallest");

    AddParameter(ParameterType_Choice, "mim", "Multi-Image Mode");

    AddChoice("mim.proportional", "Proportional");
    SetParameterDescription("mim.proportional","Split proportionally the required number of samples");

    AddChoice("mim.equal", "equal");
    SetParameterDescription("mim.equal","Split equally the required number of samples");

    AddChoice("mim.custom", "Custom");
    SetParameterDescription("mim.custom","Split the required number of samples following user choice.");

    // Doc example parameter settings
    SetDocExampleParameterValue("il", "stats_1.xml stats_2.xml");
    SetDocExampleParameterValue("out", "rates.csv");
    SetDocExampleParameterValue("strategy", "smallest");
    SetDocExampleParameterValue("mode","proportional");
  }

  void DoUpdateParameters()
  {
  }

  void DoExecute()
    {
    // Clear state
    m_CalculatorList->Clear();
    std::vector<std::string> inputs = this->GetParameterStringList("il");
    unsigned int nbInputs = inputs.size();
    XMLReaderType::Pointer statReader = XMLReaderType::New();
    for (unsigned int i=0 ; i<nbInputs ; i++ )
      {
      m_CalculatorList->PushBack(otb::SamplingRateCalculator::New());
      statReader->SetFileName(inputs[i]);
      ClassCountMapType classCount = statReader->GetStatisticMapByName<ClassCountMapType>("samplesPerClass");
      m_CalculatorList->SetNthClassCount(i,classCount);
      }

    // Cautions : direct mapping between the enum PartitionType and the choice order
    RateCalculatorListType::PartitionType partitionMode =
      static_cast<RateCalculatorListType::PartitionType>(this->GetParameterInt("mim"));

    unsigned int minParamSize = 1;
    if (partitionMode == RateCalculatorListType::CUSTOM)
      {
      // Check we have enough inputs for the custom mode
      minParamSize = nbInputs;
      }

    switch (this->GetParameterInt("strategy"))
      {
      // byclass
      case 0:
        {
        std::vector<std::string> requiredFiles = this->GetParameterStringList("strategy.byclass.in");
        std::vector<ClassCountMapType> requiredCounts;
        if (requiredFiles.size() < minParamSize)
          {
          otbAppLogFATAL("Missing arguments in strategy.byclass.in to process sampling rates");
          }
        otbAppLogINFO("Sampling strategy : set number of samples for each class");
        for (unsigned int i=0 ; i<minParamSize ; i++)
          {
          requiredCounts.push_back(otb::SamplingRateCalculator::ReadRequiredSamples(requiredFiles[i]));
          }
        m_CalculatorList->SetNbOfSamplesByClass(requiredCounts, partitionMode);
        }
      break;
      // constant
      case 1:
        {
        std::vector<itksys::String> parts = itksys::SystemTools::SplitString(this->GetParameterString("strategy.constant.nb"),' ');
        std::vector<unsigned long> countList;
        for (unsigned int i=0 ; i<parts.size() ; i++)
          {
          if (!parts[i].empty())
            {
            std::string::size_type pos1 = parts[i].find_first_not_of(" \t");
            std::string::size_type pos2 = parts[i].find_last_not_of(" \t");
            std::string value(parts[i].substr(pos1, pos2 - pos1 + 1));
            countList.push_back(boost::lexical_cast<unsigned long>(parts[i]));
            }
          }
        if (countList.size() < minParamSize)
          {
          otbAppLogFATAL("Missing arguments in strategy.constant.nb to process sampling rates");
          }
        otbAppLogINFO("Sampling strategy : set a constant number of samples for all classes");
        m_CalculatorList->SetNbOfSamplesAllClasses(countList, partitionMode);
        }
      break;
      // smallest class
      case 2:
        {
        otbAppLogINFO("Sampling strategy : fit the number of samples based on the smallest class");
        m_CalculatorList->SetMinimumNbOfSamplesByClass(partitionMode);
        }
      break;
      // all samples
      case 3:
        {
        otbAppLogINFO("Sampling strategy : take all samples");
        m_CalculatorList->SetAllSamples(partitionMode);
        }
      break;
      default:
        otbAppLogFATAL("Strategy mode unknown :"<<this->GetParameterString("strategy"));
      break;
      }

    std::ostringstream oss;
    std::string outputPath(this->GetParameterString("out"));
    std::string outputBase = outputPath.substr(0, outputPath.find_last_of('.'));
    std::string outputExt = outputPath.substr(outputPath.find_last_of('.'), std::string::npos);
    unsigned int overflowCount = 0;
    for (unsigned int i=0 ; i<nbInputs ; i++ )
      {
      // Print results
      oss.str(std::string(""));
      oss << " className  requiredSamples  totalSamples  rate" << std::endl;
      MapRateType rates = m_CalculatorList->GetRatesByClass(i);
      MapRateType::const_iterator itRates = rates.begin();
      for(; itRates != rates.end(); ++itRates)
        {
        otb::SamplingRateCalculator::TripletType tpt = itRates->second;
        oss << itRates->first << "\t" << tpt.Required << "\t" << tpt.Tot << "\t" << tpt.Rate;
        if (tpt.Required > tpt.Tot)
          {
          overflowCount++;
          oss << "\t[OVERFLOW]";
          }
        oss << std::endl;
        }
      otbAppLogINFO("Sampling rates for image "<< i+1 <<" : " << oss.str());
      // Output results to disk
      oss.str(std::string(""));
      oss << outputBase << "_" << i+1 << outputExt;
      m_CalculatorList->GetNthElement(i)->Write(oss.str());
      }
    if (overflowCount)
      {
      std::string plural(overflowCount>1?"s":"");
      otbAppLogWARNING(<< overflowCount << " case"<<plural<<" of overflow detected! (requested number of samples higher than total available samples)");
      }
  }

  RateCalculatorListType::Pointer m_CalculatorList;
};

} // end namespace Wrapper
} // end namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::MultiImageSamplingRate)
<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkContourModelLiveWireInteractor.h"

#include "mitkToolManager.h"

#include "mitkBaseRenderer.h"
#include "mitkRenderingManager.h"

#include <mitkPositionEvent.h>
#include <mitkStateEvent.h>

#include <mitkInteractionConst.h>

mitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor(DataNode* dataNode)
:ContourModelInteractor(dataNode)
{
  m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New();

  mitk::ContourModel::Pointer m_ContourLeft = mitk::ContourModel::New();
  mitk::ContourModel::Pointer m_ContourRight = mitk::ContourModel::New();
  m_NextActiveVertexDown.Fill(0);
  m_NextActiveVertexUp.Fill(0);
}

mitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor()
{
}

bool mitk::ContourModelLiveWireInteractor::OnCheckPointClick( Action* action, const StateEvent* stateEvent)
{
  const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
  if (!positionEvent) {
    this->HandleEvent( new mitk::StateEvent(EIDNO, stateEvent->GetEvent()) );
    return false;
  }

  mitk::StateEvent* newStateEvent = NULL;

  int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep();

  mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>(
    m_DataNode->GetData() );

  contour->Deselect();

  /*
  * Check distance to any vertex.
  * Transition YES if click close to a vertex
  */
  mitk::Point3D click = positionEvent->GetWorldPosition();

  if (contour->SelectVertexAt(click, 1.5, timestep) )
  {
    contour->SetSelectedVertexAsControlPoint();

    assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );
    mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );
    newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent());
    m_lastMousePosition = click;

    mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>( m_DataNode->GetData() );

    //
    m_ContourLeft = mitk::ContourModel::New();

    //get coordinates of next active vertex downwards from selected vertex
    int downIndex = SplitContourFromSelectedVertex( contour, m_ContourLeft, false, timestep);

    mitk::ContourModel::VertexIterator itDown = contour->IteratorBegin() + downIndex;
    m_NextActiveVertexDown = (*itDown)->Coordinates;

    //
    m_ContourRight = mitk::ContourModel::New();

    //get coordinates of next active vertex upwards from selected vertex
    int upIndex = SplitContourFromSelectedVertex( contour, m_ContourRight, true, timestep);

    mitk::ContourModel::VertexIterator itUp = contour->IteratorBegin() + upIndex;
    m_NextActiveVertexUp = (*itUp)->Coordinates;

  }
  else
  {
    newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent());
  }

  this->HandleEvent( newStateEvent );

  return true;
}

bool mitk::ContourModelLiveWireInteractor::OnDeletePoint( Action* action, const StateEvent* stateEvent)
{

  int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep();

  mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>( m_DataNode->GetData() );

  if(contour->GetSelectedVertex())
  {

    mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();
    newContour->Expand(contour->GetTimeSteps());
    newContour->Concatenate( m_ContourLeft, timestep );

    //recompute contour between neighbored two active control points
    this->m_LiveWireFilter->SetStartPoint( m_NextActiveVertexDown );
    this->m_LiveWireFilter->SetEndPoint( m_NextActiveVertexUp );
    this->m_LiveWireFilter->Update();

    mitk::ContourModel::Pointer liveWireContour = mitk::ContourModel::New();
    liveWireContour = this->m_LiveWireFilter->GetOutput();

    //insert new liveWire computed points
    newContour->Concatenate( liveWireContour, timestep );

    newContour->Concatenate( m_ContourRight, timestep );

    newContour->SetIsClosed(contour->IsClosed(timestep), timestep);

    m_DataNode->SetData(newContour);

    assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );
    mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );

  }
  return true;
}

bool mitk::ContourModelLiveWireInteractor::OnMovePoint( Action* action, const StateEvent* stateEvent)
{
  const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
  if (!positionEvent) return false;

  int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep();

  mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>( m_DataNode->GetData() );

  mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();
  newContour->Expand(contour->GetTimeSteps());

  /*++++++++++++++ concatenate LEFT ++++++++++++++++++++++++++++++*/
  newContour->Concatenate( m_ContourLeft, timestep );

  mitk::Point3D currentPosition = positionEvent->GetWorldPosition();

  /*+++++++++++++++ start computation ++++++++++++++++++++*/
  //recompute contour between previous active vertex and selected vertex
  this->m_LiveWireFilter->SetStartPoint( m_NextActiveVertexDown );
  this->m_LiveWireFilter->SetEndPoint( currentPosition );
  this->m_LiveWireFilter->Update();

  mitk::ContourModel::Pointer liveWireContour = mitk::ContourModel::New();
  liveWireContour = this->m_LiveWireFilter->GetOutput();

  //remove point at current position because it is included in next livewire segment too.
  liveWireContour->RemoveVertexAt( liveWireContour->GetNumberOfVertices(timestep) - 1, timestep);

  /*++++++++++++++ concatenate LIVEWIRE ++++++++++++++++++++++++++++++*/
  //insert new liveWire computed points
  newContour->Concatenate( liveWireContour, timestep );

  //recompute contour between selected vertex and next active vertex
  this->m_LiveWireFilter->SetStartPoint( currentPosition );
  this->m_LiveWireFilter->SetEndPoint( m_NextActiveVertexUp );
  this->m_LiveWireFilter->Update();

  liveWireContour = this->m_LiveWireFilter->GetOutput();

  //make point at mouse position active again, so it is drawn
  const_cast<mitk::ContourModel::VertexType*>( liveWireContour->GetVertexAt(0, timestep) )->IsControlPoint = true;

  /*++++++++++++++ concatenate RIGHT ++++++++++++++++++++++++++++++*/
  //insert new liveWire computed points
  newContour->Concatenate( liveWireContour, timestep );
  /*------------------------------------------------*/

  newContour->Concatenate( m_ContourRight, timestep );

  newContour->SetIsClosed(contour->IsClosed(timestep), timestep);
  newContour->Deselect();//just to make sure
  m_DataNode->SetData(newContour);

  this->m_lastMousePosition = positionEvent->GetWorldPosition();

  assert( positionEvent->GetSender()->GetRenderWindow() );
  mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );

  return true;
}

int mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel* sourceContour, mitk::ContourModel* destinationContour, bool fromSelectedUpwards, int timestep)
{

  mitk::ContourModel::VertexIterator end =sourceContour->IteratorEnd();
  mitk::ContourModel::VertexIterator begin =sourceContour->IteratorBegin();

  //search next active control point to left and rigth and set as start and end point for filter
  mitk::ContourModel::VertexIterator itSelected = sourceContour->IteratorBegin();

  //move iterator to position
  while((*itSelected) != sourceContour->GetSelectedVertex())
  {
    itSelected++;
  }

  //CASE search upwards for next control point
  if(fromSelectedUpwards)
  {
    mitk::ContourModel::VertexIterator itUp = itSelected;

    if(itUp != end)
    {
      itUp++;//step once up otherwise the the loop breaks immediately
    }

    while( itUp != end && !((*itUp)->IsControlPoint)){ itUp++; }

    mitk::ContourModel::VertexIterator it = itUp;

    if(itSelected != begin)
    {
      //copy the rest of the original contour
      while(it != end)
      {
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
    }
    //else do not copy the contour

    //return the offset of iterator at one before next-vertex-upwards
    if(itUp != begin)
    {
      return itUp._Myoff - 1;
    }
    else
    {
      return itUp._Myoff;
    }

  }
  else //CASE search downwards for next control point
  {
    mitk::ContourModel::VertexIterator itDown = itSelected;
    mitk::ContourModel::VertexIterator it = sourceContour->IteratorBegin();

    if( itSelected != begin )
    {
      if(itDown != begin)
      {
        itDown--;//step once down otherwise the the loop breaks immediately
      }

      while( itDown != begin && !((*itDown)->IsControlPoint)){ itDown--; }

      if(it != end)//if not empty
      {
        //always add the first vertex
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
      //copy from begin to itDown
      while(it <= itDown)
      {
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
    }
    else
    {
      //if selected vertex is the first element search from end of contour downwards
      itDown = end;
      itDown--;
      while(!((*itDown)->IsControlPoint)){itDown--;}

      //move one forward as we don't want the first control point
      it++;
      //move iterator to second control point
      while( (it!=end) && !((*it)->IsControlPoint) ){it++;}
      //copy from begin to itDown
      while(it <= itDown)
      {
        //copy the contour from second control point to itDown
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
    }

    //add vertex at itDown - it's not considered during while loop
    if( it != begin && it != end)
    {
      //destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
    }

    //return the offset of iterator at one after next-vertex-downwards
    if( itDown != end)
    {
      return itDown._Myoff;// + 1;//index of next vertex
    }
    else
    {
      return itDown._Myoff - 1;
    }
  }
}
<commit_msg>Fix compiler errors on mac.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

#include "mitkContourModelLiveWireInteractor.h"

#include "mitkToolManager.h"

#include "mitkBaseRenderer.h"
#include "mitkRenderingManager.h"

#include <mitkPositionEvent.h>
#include <mitkStateEvent.h>

#include <mitkInteractionConst.h>

mitk::ContourModelLiveWireInteractor::ContourModelLiveWireInteractor(DataNode* dataNode)
:ContourModelInteractor(dataNode)
{
  m_LiveWireFilter = mitk::ImageLiveWireContourModelFilter::New();

  mitk::ContourModel::Pointer m_ContourLeft = mitk::ContourModel::New();
  mitk::ContourModel::Pointer m_ContourRight = mitk::ContourModel::New();
  m_NextActiveVertexDown.Fill(0);
  m_NextActiveVertexUp.Fill(0);
}

mitk::ContourModelLiveWireInteractor::~ContourModelLiveWireInteractor()
{
}

bool mitk::ContourModelLiveWireInteractor::OnCheckPointClick( Action* action, const StateEvent* stateEvent)
{
  const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
  if (!positionEvent) {
    this->HandleEvent( new mitk::StateEvent(EIDNO, stateEvent->GetEvent()) );
    return false;
  }

  mitk::StateEvent* newStateEvent = NULL;

  int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep();

  mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>(
    m_DataNode->GetData() );

  contour->Deselect();

  /*
  * Check distance to any vertex.
  * Transition YES if click close to a vertex
  */
  mitk::Point3D click = positionEvent->GetWorldPosition();

  if (contour->SelectVertexAt(click, 1.5, timestep) )
  {
    contour->SetSelectedVertexAsControlPoint();

    assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );
    mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );
    newStateEvent = new mitk::StateEvent(EIDYES, stateEvent->GetEvent());
    m_lastMousePosition = click;

    mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>( m_DataNode->GetData() );

    //
    m_ContourLeft = mitk::ContourModel::New();

    //get coordinates of next active vertex downwards from selected vertex
    int downIndex = SplitContourFromSelectedVertex( contour, m_ContourLeft, false, timestep);

    mitk::ContourModel::VertexIterator itDown = contour->IteratorBegin() + downIndex;
    m_NextActiveVertexDown = (*itDown)->Coordinates;

    //
    m_ContourRight = mitk::ContourModel::New();

    //get coordinates of next active vertex upwards from selected vertex
    int upIndex = SplitContourFromSelectedVertex( contour, m_ContourRight, true, timestep);

    mitk::ContourModel::VertexIterator itUp = contour->IteratorBegin() + upIndex;
    m_NextActiveVertexUp = (*itUp)->Coordinates;

  }
  else
  {
    newStateEvent = new mitk::StateEvent(EIDNO, stateEvent->GetEvent());
  }

  this->HandleEvent( newStateEvent );

  return true;
}

bool mitk::ContourModelLiveWireInteractor::OnDeletePoint( Action* action, const StateEvent* stateEvent)
{

  int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep();

  mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>( m_DataNode->GetData() );

  if(contour->GetSelectedVertex())
  {

    mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();
    newContour->Expand(contour->GetTimeSteps());
    newContour->Concatenate( m_ContourLeft, timestep );

    //recompute contour between neighbored two active control points
    this->m_LiveWireFilter->SetStartPoint( m_NextActiveVertexDown );
    this->m_LiveWireFilter->SetEndPoint( m_NextActiveVertexUp );
    this->m_LiveWireFilter->Update();

    mitk::ContourModel::Pointer liveWireContour = mitk::ContourModel::New();
    liveWireContour = this->m_LiveWireFilter->GetOutput();

    //insert new liveWire computed points
    newContour->Concatenate( liveWireContour, timestep );

    newContour->Concatenate( m_ContourRight, timestep );

    newContour->SetIsClosed(contour->IsClosed(timestep), timestep);

    m_DataNode->SetData(newContour);

    assert( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );
    mitk::RenderingManager::GetInstance()->RequestUpdate( stateEvent->GetEvent()->GetSender()->GetRenderWindow() );

  }
  return true;
}

bool mitk::ContourModelLiveWireInteractor::OnMovePoint( Action* action, const StateEvent* stateEvent)
{
  const PositionEvent* positionEvent = dynamic_cast<const PositionEvent*>(stateEvent->GetEvent());
  if (!positionEvent) return false;

  int timestep = stateEvent->GetEvent()->GetSender()->GetTimeStep();

  mitk::ContourModel *contour = dynamic_cast<mitk::ContourModel *>( m_DataNode->GetData() );

  mitk::ContourModel::Pointer newContour = mitk::ContourModel::New();
  newContour->Expand(contour->GetTimeSteps());

  /*++++++++++++++ concatenate LEFT ++++++++++++++++++++++++++++++*/
  newContour->Concatenate( m_ContourLeft, timestep );

  mitk::Point3D currentPosition = positionEvent->GetWorldPosition();

  /*+++++++++++++++ start computation ++++++++++++++++++++*/
  //recompute contour between previous active vertex and selected vertex
  this->m_LiveWireFilter->SetStartPoint( m_NextActiveVertexDown );
  this->m_LiveWireFilter->SetEndPoint( currentPosition );
  this->m_LiveWireFilter->Update();

  mitk::ContourModel::Pointer liveWireContour = mitk::ContourModel::New();
  liveWireContour = this->m_LiveWireFilter->GetOutput();

  //remove point at current position because it is included in next livewire segment too.
  liveWireContour->RemoveVertexAt( liveWireContour->GetNumberOfVertices(timestep) - 1, timestep);

  /*++++++++++++++ concatenate LIVEWIRE ++++++++++++++++++++++++++++++*/
  //insert new liveWire computed points
  newContour->Concatenate( liveWireContour, timestep );

  //recompute contour between selected vertex and next active vertex
  this->m_LiveWireFilter->SetStartPoint( currentPosition );
  this->m_LiveWireFilter->SetEndPoint( m_NextActiveVertexUp );
  this->m_LiveWireFilter->Update();

  liveWireContour = this->m_LiveWireFilter->GetOutput();

  //make point at mouse position active again, so it is drawn
  const_cast<mitk::ContourModel::VertexType*>( liveWireContour->GetVertexAt(0, timestep) )->IsControlPoint = true;

  /*++++++++++++++ concatenate RIGHT ++++++++++++++++++++++++++++++*/
  //insert new liveWire computed points
  newContour->Concatenate( liveWireContour, timestep );
  /*------------------------------------------------*/

  newContour->Concatenate( m_ContourRight, timestep );

  newContour->SetIsClosed(contour->IsClosed(timestep), timestep);
  newContour->Deselect();//just to make sure
  m_DataNode->SetData(newContour);

  this->m_lastMousePosition = positionEvent->GetWorldPosition();

  assert( positionEvent->GetSender()->GetRenderWindow() );
  mitk::RenderingManager::GetInstance()->RequestUpdate( positionEvent->GetSender()->GetRenderWindow() );

  return true;
}

int mitk::ContourModelLiveWireInteractor::SplitContourFromSelectedVertex(mitk::ContourModel* sourceContour, mitk::ContourModel* destinationContour, bool fromSelectedUpwards, int timestep)
{

  mitk::ContourModel::VertexIterator end =sourceContour->IteratorEnd();
  mitk::ContourModel::VertexIterator begin =sourceContour->IteratorBegin();

  //search next active control point to left and rigth and set as start and end point for filter
  mitk::ContourModel::VertexIterator itSelected = sourceContour->IteratorBegin();

  //move iterator to position
  while((*itSelected) != sourceContour->GetSelectedVertex())
  {
    itSelected++;
  }

  //CASE search upwards for next control point
  if(fromSelectedUpwards)
  {
    mitk::ContourModel::VertexIterator itUp = itSelected;

    if(itUp != end)
    {
      itUp++;//step once up otherwise the the loop breaks immediately
    }

    while( itUp != end && !((*itUp)->IsControlPoint)){ itUp++; }

    mitk::ContourModel::VertexIterator it = itUp;

    if(itSelected != begin)
    {
      //copy the rest of the original contour
      while(it != end)
      {
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
    }
    //else do not copy the contour

    //return the offset of iterator at one before next-vertex-upwards
    if(itUp != begin)
    {
      return std::distance( begin, itUp) - 1;
    }
    else
    {
      return std::distance( begin, itUp);
    }

  }
  else //CASE search downwards for next control point
  {
    mitk::ContourModel::VertexIterator itDown = itSelected;
    mitk::ContourModel::VertexIterator it = sourceContour->IteratorBegin();

    if( itSelected != begin )
    {
      if(itDown != begin)
      {
        itDown--;//step once down otherwise the the loop breaks immediately
      }

      while( itDown != begin && !((*itDown)->IsControlPoint)){ itDown--; }

      if(it != end)//if not empty
      {
        //always add the first vertex
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
      //copy from begin to itDown
      while(it <= itDown)
      {
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
    }
    else
    {
      //if selected vertex is the first element search from end of contour downwards
      itDown = end;
      itDown--;
      while(!((*itDown)->IsControlPoint)){itDown--;}

      //move one forward as we don't want the first control point
      it++;
      //move iterator to second control point
      while( (it!=end) && !((*it)->IsControlPoint) ){it++;}
      //copy from begin to itDown
      while(it <= itDown)
      {
        //copy the contour from second control point to itDown
        destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
        it++;
      }
    }

    //add vertex at itDown - it's not considered during while loop
    if( it != begin && it != end)
    {
      //destinationContour->AddVertex( (*it)->Coordinates, (*it)->IsControlPoint, timestep);
    }

    //return the offset of iterator at one after next-vertex-downwards
    if( itDown != end)
    {
      return std::distance( begin, itDown);// + 1;//index of next vertex
    }
    else
    {
      return std::distance( begin, itDown) - 1;
    }
  }
}
<|endoftext|>


<commit_before>#include "Common.h"
#include <iostream>
#include <float.h>

#ifdef __linux__
#include <dlfcn.h>

bool sqaod::isCUDAAvailable() {
#ifndef SQAODC_CUDA_ENABLED
    return false;
#else
    void *h = dlopen("libcuda.so", RTLD_NOW);
    if (h == NULL)
        return false;
    /* shared library found */
    typedef int (*cuDeviceGetCountType)(int *);
    cuDeviceGetCountType cuDeviceGetCount = (cuDeviceGetCountType)dlsym(h, "cuDeviceGetCount");
    int count = 0;
    int res = cuDeviceGetCount(&count);
    bool deviceFound = (res == 0) && (count != 0);
    dlclose(h);
    return deviceFound;
#endif
    return false;
}

#endif

template<class real>
void sqaod::createBitsSequence(real *bits, int nBits, PackedBits bBegin, PackedBits bEnd) {
    for (PackedBits b = bBegin; b < bEnd; ++b) {
        for (int pos = 0; pos < nBits; ++pos)
            bits[pos] = real((b >> (nBits - 1 - pos)) & 1);
        bits += nBits;
    }
}

void sqaod::unpackBits(Bits *unpacked, const PackedBits packed, int N) {
    unpacked->resize(N);
    for (int pos = 0; pos < N; ++pos) {
        (*unpacked)(pos) = (packed >> (N - 1 - pos)) & 1;
    }
}

template<class real>
bool sqaod::isSymmetric(const MatrixType<real> &W) {
    for (SizeType j = 0; j < W.rows; ++j) {
        for (SizeType i = 0; i < j + 1; ++i)
            if (W(i, j) != W(j, i))
                return false;
    }
    return true;
}

// template<class real>
// sqaod::MatrixType<real> sqaod::bitsToMat(const BitMatrix &bits) {
//     MatrixType<real> mat(bits.dim());
//     mat.map() = bits.map().cast<real>();
//     return mat;
// }

template
void ::sqaod::createBitsSequence<double>(double *bits, int nBits, PackedBits bBegin, PackedBits bEnd);
template
void ::sqaod::createBitsSequence<float>(float *bits, int nBits, PackedBits bBegin, PackedBits bEnd);
template
void ::sqaod::createBitsSequence<char>(char *bits, int nBits, PackedBits bBegin, PackedBits bEnd);

template
bool ::sqaod::isSymmetric<float>(const sqaod::MatrixType<float> &W);
template
bool ::sqaod::isSymmetric<double>(const sqaod::MatrixType<double> &W);

// template
// sqaod::MatrixType<double> sqaod::bitsToMat<double>(const BitMatrix &bits);
// template
// sqaod::MatrixType<float> sqaod::bitsToMat<float>(const BitMatrix &bits);
<commit_msg>isCUDAAvailable() updated on Windows. Fix: cuInit() not called.<commit_after>#include "Common.h"
#include <iostream>
#include <float.h>

#ifndef SQAODC_CUDA_ENABLED
bool sqaod::isCUDAAvailable() {
    return false;
}

#else

#ifdef __linux__
#include <dlfcn.h>
bool sqaod::isCUDAAvailable() {
    void *h = dlopen("libcuda.so", RTLD_NOW);
    if (h == NULL)
        return false;
     /* shared library found */
    typedef int(*cuInitType)(unsigned int);
    typedef int(*cuDeviceGetCountType)(int *);
    cuInitType cuInit = (cuInitType)dlsym(h, "cuInit");
    cuDeviceGetCountType cuDeviceGetCount = (cuDeviceGetCountType)dlsym(h, "cuDeviceGetCount");

    bool deviceFound = false;
    int res = cuInit(0);
    if (res == 0) {
        int count = 0;
        res = cuDeviceGetCount(&count);
        deviceFound = (res == 0) && (count != 0);
    }
    dlclose(h);
    return deviceFound;
}

#endif

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

bool sqaod::isCUDAAvailable() {
    HMODULE h = LoadLibrary(L"nvcuda.dll");
    if (h == NULL)
        return false;
    /* shared library found */
    typedef int(*cuInitType)(unsigned int);
    typedef int (*cuDeviceGetCountType)(int *);
    cuInitType cuInit = (cuInitType)GetProcAddress(h, "cuInit");
    cuDeviceGetCountType cuDeviceGetCount = (cuDeviceGetCountType)GetProcAddress(h, "cuDeviceGetCount");
    bool deviceFound = false;
    int res = cuInit(0);
    if (res == 0) {
        int count = 0;
        res = cuDeviceGetCount(&count);
        deviceFound = (res == 0) && (count != 0);
    }
    FreeLibrary(h);
    return deviceFound;
}
#endif

#endif

template<class real>
void sqaod::createBitsSequence(real *bits, int nBits, PackedBits bBegin, PackedBits bEnd) {
    for (PackedBits b = bBegin; b < bEnd; ++b) {
        for (int pos = 0; pos < nBits; ++pos)
            bits[pos] = real((b >> (nBits - 1 - pos)) & 1);
        bits += nBits;
    }
}

void sqaod::unpackBits(Bits *unpacked, const PackedBits packed, int N) {
    unpacked->resize(N);
    for (int pos = 0; pos < N; ++pos) {
        (*unpacked)(pos) = (packed >> (N - 1 - pos)) & 1;
    }
}

template<class real>
bool sqaod::isSymmetric(const MatrixType<real> &W) {
    for (SizeType j = 0; j < W.rows; ++j) {
        for (SizeType i = 0; i < j + 1; ++i)
            if (W(i, j) != W(j, i))
                return false;
    }
    return true;
}

// template<class real>
// sqaod::MatrixType<real> sqaod::bitsToMat(const BitMatrix &bits) {
//     MatrixType<real> mat(bits.dim());
//     mat.map() = bits.map().cast<real>();
//     return mat;
// }

template
void ::sqaod::createBitsSequence<double>(double *bits, int nBits, PackedBits bBegin, PackedBits bEnd);
template
void ::sqaod::createBitsSequence<float>(float *bits, int nBits, PackedBits bBegin, PackedBits bEnd);
template
void ::sqaod::createBitsSequence<char>(char *bits, int nBits, PackedBits bBegin, PackedBits bEnd);

template
bool ::sqaod::isSymmetric<float>(const sqaod::MatrixType<float> &W);
template
bool ::sqaod::isSymmetric<double>(const sqaod::MatrixType<double> &W);

// template
// sqaod::MatrixType<double> sqaod::bitsToMat<double>(const BitMatrix &bits);
// template
// sqaod::MatrixType<float> sqaod::bitsToMat<float>(const BitMatrix &bits);
<|endoftext|>


<commit_before>#ifndef GUARD_identity_map_hpp
#define GUARD_identity_map_hpp

#include "handle.hpp"
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <cassert>
#include <map>
#include <stdexcept>

// For debugging
	#include <jewel/debug_log.hpp>
	#include <iostream>
	#include <typeinfo>
	using std::endl;

namespace sqloxx
{

template <typename T, typename Connection>
class IdentityMap
{
public:

	typedef typename T::Id Id;
	typedef typename T::Id ProxyKey;

	IdentityMap(Connection& p_connection);

	/**
	 * Provide handle to object of T, representing a newly created object
	 * that has not yet been persisted to the database
	 */
	Handle<T> provide_object();

	/**
	 * Provide handle to object of type T, representing an object
	 * already stored in the database, with id p_id.
	 */
	Handle<T> provide_object(Id p_id);

	/**
	 * Register id of newly saved T.
	 */
	void register_id(ProxyKey proxy_key, Id allocated_id);

	void erase_object_proxied(ProxyKey proxy_key);

	/**
	 * Notify the IdentityMap that there are no handles left that are
	 * pointing to this object.
	 */
	void notify_nil_handles(ProxyKey proxy_key);

	void enable_caching();

	void disable_caching();

	/**
	 * @returns a reference to the database connection with which
	 * this IdentityMap is associated.
	 *
	 * Exception safety: nothrow guarantee.
	 *
	 * @todo Testing.
	 */
	Connection& connection();

	IdentityMap& operator=(IdentityMap const& rhs);

private:

	// Find the next available proxy key
	// WARNING Move the implementation out of the class body.
	ProxyKey next_proxy_key();
	typedef typename boost::shared_ptr<T> Record;
	typedef boost::unordered_map<Id, Record> IdMap;
	typedef std::map<ProxyKey, Record> ProxyKeyMap;

	ProxyKeyMap& proxy_map() const
	{
		return m_map_data->proxy_map;
	}

	IdMap& id_map() const
	{
		return m_map_data->id_map;
	}

	bool& caching() const
	{
		return m_map_data->caching;
	}

	// Data members

	struct MapData
	{
		MapData(Connection& p_connection):
			connection(p_connection),
			caching(false)
		{
		}
		ProxyKeyMap proxy_map;  // For all objects.
		IdMap id_map;        // For objects that exist in the database.
		// Indicates whether the IdentityMap is currently
		// holding objects indefinitely in the cache (m_caching == true),
		// or whether it is
		// clearing each object out when there are no longer handles
		// pointing to it (m_caching == false).
		Connection& connection;
		bool caching;
	};
	boost::shared_ptr<MapData> m_map_data;
};

template <typename T, typename Connection>
IdentityMap<T, Connection>::IdentityMap(Connection& p_connection):
	m_map_data(new MapData(p_connection))
{
}

template <typename T, typename Connection>
Handle<T>
IdentityMap<T, Connection>::provide_object()
{

	Record obj_ptr((new T(*this)));
	ProxyKey const proxy_key = next_proxy_key();
	obj_ptr->set_proxy_key(proxy_key);
	proxy_map()[proxy_key] = obj_ptr;
	return Handle<T>(obj_ptr.get());
}

template <typename T, typename Connection>
Handle<T>
IdentityMap<T, Connection>::provide_object(Id p_id)
{
	typename IdMap::iterator it = id_map().find(p_id);
	if (it == id_map().end())
	{
		// Then we need to create this object.
		Record obj_ptr(new T(*this, p_id));
		id_map()[p_id] = obj_ptr;
		ProxyKey proxy_key = next_proxy_key();
		proxy_map()[proxy_key] = obj_ptr;
		obj_ptr->set_proxy_key(proxy_key);
		return Handle<T>(obj_ptr.get());
	}
	assert (it != id_map().end());
	return Handle<T>(it->second.get());
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::register_id(ProxyKey proxy_key, Id allocated_id)
{
	id_map()[allocated_id] = proxy_map()[proxy_key];
	return;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::erase_object_proxied(ProxyKey proxy_key)
{
	Record const record = proxy_map().find(proxy_key)->second;
	if (record->has_id())
	{
		assert (id_map().find(record->id()) != id_map().end());
		id_map().erase(record->id());
	}
	proxy_map().erase(proxy_key);
	return;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::notify_nil_handles(ProxyKey proxy_key)
{
	if (!caching())
	{
		erase_object_proxied(proxy_key);
	}
	return;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::enable_caching()
{
	caching() = true;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::disable_caching()
{
	if (caching())
	{
		typename ProxyKeyMap::iterator const endpoint = proxy_map().end();
		for
		(	typename ProxyKeyMap::iterator it = proxy_map().begin();
			it != endpoint;
			++it
		)
		{
			if (it->second->is_orphaned())
			{
				erase_object_proxied(it->first);
			}
		}
		caching() = false;
	}
	return;
}

template <typename T, typename Connection>
Connection&
IdentityMap<T, Connection>::connection()
{
	return m_map_data->connection;
}

template <typename T, typename Connection>
IdentityMap<T, Connection>&
IdentityMap<T, Connection>::operator=(IdentityMap const& rhs)
{
	m_map_data = rhs.m_map_data;
	return *this;
}

template <typename T, typename Connection>
typename IdentityMap<T, Connection>::ProxyKey
IdentityMap<T, Connection>::next_proxy_key()
{
	// TODO Change this so that vacated slots are filled, rather
	// than just always taking least - 1. Currently there is
	// a danger that we will just forever move towards min, until
	// we overflow.

	// Using negative numbers to avoid any possible confusion
	// with Id.
	// Relies on this being a std::map, in which the first
	// key is less than any other key.
	ProxyKey const least = proxy_map().begin()->first;
	if (least == std::numeric_limits<ProxyKey>::min())
	{
		throw OverflowException("Proxy key has reached numeric limit.");
	}
	return least - 1;
}

}  // namespace sqloxx

#endif  // GUARD_identity_map_hpp
<commit_msg>Provided explicit copy constructor, destructor and assignment operator for sqloxx::IdentityMap.<commit_after>#ifndef GUARD_identity_map_hpp
#define GUARD_identity_map_hpp

#include "handle.hpp"
#include <boost/noncopyable.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/unordered_map.hpp>
#include <cassert>
#include <map>
#include <stdexcept>

// For debugging
	#include <jewel/debug_log.hpp>
	#include <iostream>
	#include <typeinfo>
	using std::endl;

namespace sqloxx
{

template <typename T, typename Connection>
class IdentityMap
{
public:

	typedef typename T::Id Id;
	typedef typename T::Id ProxyKey;

	IdentityMap(Connection& p_connection);
	IdentityMap(IdentityMap const& rhs);
	~IdentityMap;
	IdentityMap& operator=(IdentityMap const& rhs);
	/**
	 * Provide handle to object of T, representing a newly created object
	 * that has not yet been persisted to the database
	 */
	Handle<T> provide_object();

	/**
	 * Provide handle to object of type T, representing an object
	 * already stored in the database, with id p_id.
	 */
	Handle<T> provide_object(Id p_id);

	/**
	 * Register id of newly saved T.
	 */
	void register_id(ProxyKey proxy_key, Id allocated_id);

	void erase_object_proxied(ProxyKey proxy_key);

	/**
	 * Notify the IdentityMap that there are no handles left that are
	 * pointing to this object.
	 */
	void notify_nil_handles(ProxyKey proxy_key);

	void enable_caching();

	void disable_caching();

	/**
	 * @returns a reference to the database connection with which
	 * this IdentityMap is associated.
	 *
	 * Exception safety: nothrow guarantee.
	 *
	 * @todo Testing.
	 */
	Connection& connection();

	IdentityMap& operator=(IdentityMap const& rhs);

private:

	// Find the next available proxy key
	// WARNING Move the implementation out of the class body.
	ProxyKey next_proxy_key();
	typedef typename boost::shared_ptr<T> Record;
	typedef boost::unordered_map<Id, Record> IdMap;
	typedef std::map<ProxyKey, Record> ProxyKeyMap;

	ProxyKeyMap& proxy_map() const
	{
		return m_map_data->proxy_map;
	}

	IdMap& id_map() const
	{
		return m_map_data->id_map;
	}

	bool& caching() const
	{
		return m_map_data->caching;
	}

	// Data members

	// Hold in a struct to facilitate safe, shallow copying.
	struct MapData
	{
		MapData(Connection& p_connection):
			connection(p_connection),
			caching(false)
		{
		}
		ProxyKeyMap proxy_map;  // For all objects.
		IdMap id_map;        // For objects that exist in the database.
		// Indicates whether the IdentityMap is currently
		// holding objects indefinitely in the cache (m_caching == true),
		// or whether it is
		// clearing each object out when there are no longer handles
		// pointing to it (m_caching == false).
		Connection& connection;
		bool caching;
	};
	boost::shared_ptr<MapData> m_map_data;
};

template <typename T, typename Connection>
inline
IdentityMap<T, Connection>::IdentityMap(Connection& p_connection):
	m_map_data(new MapData(p_connection))
{
}

template <typename T, typename Connection>
inline
IdentityMap<T, Connection>::IdentityMap(IdentityMap const& rhs):
	m_map_data(rhs.m_map_data)
{
}

template <typename T, typename Connection>
inline
IdentityMap<T, Connection>::~IdentityMap()
{
}

template <typename T, typename Connection>
inline
IdentityMap<T, Connection>&
IdentityMap<T, Connection>::operator=(IdentityMap const& rhs)
{
	m_map_data = rhs.m_map_data;
	return *this;
}

template <typename T, typename Connection>
Handle<T>
IdentityMap<T, Connection>::provide_object()
{

	Record obj_ptr((new T(*this)));
	ProxyKey const proxy_key = next_proxy_key();
	obj_ptr->set_proxy_key(proxy_key);
	proxy_map()[proxy_key] = obj_ptr;
	return Handle<T>(obj_ptr.get());
}

template <typename T, typename Connection>
Handle<T>
IdentityMap<T, Connection>::provide_object(Id p_id)
{
	typename IdMap::iterator it = id_map().find(p_id);
	if (it == id_map().end())
	{
		// Then we need to create this object.
		Record obj_ptr(new T(*this, p_id));
		id_map()[p_id] = obj_ptr;
		ProxyKey proxy_key = next_proxy_key();
		proxy_map()[proxy_key] = obj_ptr;
		obj_ptr->set_proxy_key(proxy_key);
		return Handle<T>(obj_ptr.get());
	}
	assert (it != id_map().end());
	return Handle<T>(it->second.get());
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::register_id(ProxyKey proxy_key, Id allocated_id)
{
	id_map()[allocated_id] = proxy_map()[proxy_key];
	return;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::erase_object_proxied(ProxyKey proxy_key)
{
	Record const record = proxy_map().find(proxy_key)->second;
	if (record->has_id())
	{
		assert (id_map().find(record->id()) != id_map().end());
		id_map().erase(record->id());
	}
	proxy_map().erase(proxy_key);
	return;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::notify_nil_handles(ProxyKey proxy_key)
{
	if (!caching())
	{
		erase_object_proxied(proxy_key);
	}
	return;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::enable_caching()
{
	caching() = true;
}

template <typename T, typename Connection>
void
IdentityMap<T, Connection>::disable_caching()
{
	if (caching())
	{
		typename ProxyKeyMap::iterator const endpoint = proxy_map().end();
		for
		(	typename ProxyKeyMap::iterator it = proxy_map().begin();
			it != endpoint;
			++it
		)
		{
			if (it->second->is_orphaned())
			{
				erase_object_proxied(it->first);
			}
		}
		caching() = false;
	}
	return;
}

template <typename T, typename Connection>
inline
Connection&
IdentityMap<T, Connection>::connection()
{
	return m_map_data->connection;
}

template <typename T, typename Connection>
typename IdentityMap<T, Connection>::ProxyKey
IdentityMap<T, Connection>::next_proxy_key()
{
	// TODO Change this so that vacated slots are filled, rather
	// than just always taking least - 1. Currently there is
	// a danger that we will just forever move towards min, until
	// we overflow.

	// Using negative numbers to avoid any possible confusion
	// with Id.
	// Relies on this being a std::map, in which the first
	// key is less than any other key.
	ProxyKey const least = proxy_map().begin()->first;
	if (least == std::numeric_limits<ProxyKey>::min())
	{
		throw OverflowException("Proxy key has reached numeric limit.");
	}
	return least - 1;
}

}  // namespace sqloxx

#endif  // GUARD_identity_map_hpp
<|endoftext|>


<commit_before>/*
    <one line to give the library's name and an idea of what it does.>
    Copyright (C) 2012  Hong Jen Yee (PCMan) <pcman.tw@gmail.com>

    This library 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 2.1 of the License, or (at your option) any later version.

    This library 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 this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "icontheme.h"
#include <libfm/fm.h>
#include <QList>
#include <QIcon>
#include <QtGlobal>

using namespace Fm;

static IconTheme* theIconTheme = NULL; // the global single instance of IconTheme.

static void fmIconDataDestroy(gpointer data) {
  QIcon* picon = reinterpret_cast<QIcon*>(data);
  delete picon;
}

IconTheme::IconTheme():
  fallbackIcon(QIcon::fromTheme("application-octet-stream")) {
  // NOTE: only one instance is allowed
  Q_ASSERT(theIconTheme == NULL);

  theIconTheme = this;
  fm_icon_set_user_data_destroy(reinterpret_cast<GDestroyNotify>(fmIconDataDestroy));
}

IconTheme::~IconTheme() {
}

void IconTheme::setThemeName(QString name) {
  QIcon::setThemeName(name);
  if(theIconTheme) {
    // set fallback icon
    theIconTheme->fallbackIcon = QIcon::fromTheme("unknown");
  }
}

QIcon IconTheme::convertFromGIcon(GIcon* gicon) {
  if(G_IS_THEMED_ICON(gicon)) {
    const gchar * const * names = g_themed_icon_get_names(G_THEMED_ICON(gicon));
    const gchar * const * name;
    for(name = names; *name; ++name) {
      // qDebug("icon name=%s", *name);
      QString qname = *name;
      QIcon qicon = QIcon::fromTheme(qname);
      if(!qicon.isNull()) {
	return qicon;
      }
    }
  }
  else if(G_IS_FILE_ICON(gicon)) {
    GFile* file = g_file_icon_get_file(G_FILE_ICON(gicon));
    char* fpath = g_file_get_path(file);
    QString path = fpath;
    g_free(fpath);
    return QIcon(path);
  }
  return theIconTheme->fallbackIcon;
}

//static
QIcon IconTheme::icon(FmIcon* fmicon) {
  // check if we have a cached version
  QIcon* picon = reinterpret_cast<QIcon*>(fm_icon_get_user_data(fmicon));
  if(!picon) { // we don't have a cache yet
    picon = new QIcon(); // what a waste!
    *picon = convertFromGIcon(G_ICON(fmicon));
    fm_icon_set_user_data(fmicon, picon); // store it in FmIcon
  }
  return *picon;
}

//static
QIcon IconTheme::icon(GIcon* gicon) {
  if(G_IS_THEMED_ICON(gicon)) {
    FmIcon* fmicon = fm_icon_from_gicon(gicon);
    QIcon qicon = icon(fmicon);
    fm_icon_unref(fmicon);
    return qicon;
  }
  else if(G_IS_FILE_ICON(gicon)) {
    // we do not map GFileIcon to FmIcon deliberately.
    return convertFromGIcon(gicon);
  }
  return theIconTheme->fallbackIcon;
}

<commit_msg>Fix the icon for files of unknown mime types, again.<commit_after>/*
    <one line to give the library's name and an idea of what it does.>
    Copyright (C) 2012  Hong Jen Yee (PCMan) <pcman.tw@gmail.com>

    This library 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 2.1 of the License, or (at your option) any later version.

    This library 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 this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "icontheme.h"
#include <libfm/fm.h>
#include <QList>
#include <QIcon>
#include <QtGlobal>

using namespace Fm;

static IconTheme* theIconTheme = NULL; // the global single instance of IconTheme.

static void fmIconDataDestroy(gpointer data) {
  QIcon* picon = reinterpret_cast<QIcon*>(data);
  delete picon;
}

IconTheme::IconTheme():
  fallbackIcon(QIcon::fromTheme("application-octet-stream")) {
  // NOTE: only one instance is allowed
  Q_ASSERT(theIconTheme == NULL);

  theIconTheme = this;
  fm_icon_set_user_data_destroy(reinterpret_cast<GDestroyNotify>(fmIconDataDestroy));
}

IconTheme::~IconTheme() {
}

void IconTheme::setThemeName(QString name) {
  QIcon::setThemeName(name);
  if(theIconTheme) {
    // set fallback icon
    theIconTheme->fallbackIcon = QIcon::fromTheme("application-octet-stream");
  }
}

QIcon IconTheme::convertFromGIcon(GIcon* gicon) {
  if(G_IS_THEMED_ICON(gicon)) {
    const gchar * const * names = g_themed_icon_get_names(G_THEMED_ICON(gicon));
    const gchar * const * name;
    for(name = names; *name; ++name) {
      // qDebug("icon name=%s", *name);
      QString qname = *name;
      QIcon qicon = QIcon::fromTheme(qname);
      if(!qicon.isNull()) {
	return qicon;
      }
    }
  }
  else if(G_IS_FILE_ICON(gicon)) {
    GFile* file = g_file_icon_get_file(G_FILE_ICON(gicon));
    char* fpath = g_file_get_path(file);
    QString path = fpath;
    g_free(fpath);
    return QIcon(path);
  }
  return theIconTheme->fallbackIcon;
}

//static
QIcon IconTheme::icon(FmIcon* fmicon) {
  // check if we have a cached version
  QIcon* picon = reinterpret_cast<QIcon*>(fm_icon_get_user_data(fmicon));
  if(!picon) { // we don't have a cache yet
    picon = new QIcon(); // what a waste!
    *picon = convertFromGIcon(G_ICON(fmicon));
    fm_icon_set_user_data(fmicon, picon); // store it in FmIcon
  }
  return *picon;
}

//static
QIcon IconTheme::icon(GIcon* gicon) {
  if(G_IS_THEMED_ICON(gicon)) {
    FmIcon* fmicon = fm_icon_from_gicon(gicon);
    QIcon qicon = icon(fmicon);
    fm_icon_unref(fmicon);
    return qicon;
  }
  else if(G_IS_FILE_ICON(gicon)) {
    // we do not map GFileIcon to FmIcon deliberately.
    return convertFromGIcon(gicon);
  }
  return theIconTheme->fallbackIcon;
}

<|endoftext|>


<commit_before>#include "FitResultPrinter.h"

// STL
#include <iomanip>

// from Boost
#include <boost/format.hpp>

// from ROOT
#include <TIterator.h>

// from RooFit
#include <RooFitResult.h>
#include <RooArgList.h>
#include <RooAbsArg.h>
#include <RooRealVar.h>

// from DooCore
#include <doocore/statistics/general.h>

doofit::plotting::fitresult::FitResultPrinter::FitResultPrinter(const RooFitResult& fit_result)
: fit_result_(fit_result),
  full_precision_printout_(false),
  print_pulls_(true)
{
}

void doofit::plotting::fitresult::FitResultPrinter::PlotHandler() const {
  using namespace doocore::statistics::general;
  using namespace doocore::io;
  using boost::format;
  using boost::io::group;

  std::cout << std::endl;

	RooArgList par_list_float_final = fit_result_.floatParsFinal();
  RooArgList par_list_float_init  = fit_result_.floatParsInit();

  TIterator* it_float = par_list_float_final.createIterator();
  RooAbsArg* arg = NULL;

  std::cout << format("%-30s %15s %15s +/- %-15s ") % "          Parameter          " % "   InitValue   " % "    Fit result" % "Error         ";
  if (print_pulls_) {
    std::cout << format("%15s") % "      Pull     ";
  }
  std::cout << std::endl;

  std::cout << format("%-30s %15s %15s-----%-15s ") % "-----------------------------" % "---------------" % "--------------" % "--------------";
  if (print_pulls_) {
    std::cout << format("%15s") % "---------------";
  }
  std::cout << std::endl;

  while ((arg = dynamic_cast<RooAbsArg*>(it_float->Next()))) {
    RooRealVar* var = dynamic_cast<RooRealVar*>(arg);
    if (var != NULL) {
      ValueWithError<double> val(var->getVal(), var->getError());
      val.set_full_precision_printout(full_precision_printout_);
      RooRealVar* var_init = dynamic_cast<RooRealVar*>(par_list_float_init.find(var->GetName()));
      double val_init = 0.0, pull = 0.0;
      if (var_init != NULL) {
        val_init = var_init->getVal();
        pull = (val_init-val.value)/val.error;
      }

      std::string str_color, str_term;
      if (!doocore::io::TerminalIsRedirected()) {
        if (std::abs(pull) < 2.0) {
          str_color = "\033[1;32m";
        } else if (std::abs(pull) > 2.0 && std::abs(pull) <= 3.0) {
          str_color = "\033[1;33m";
        } else if (std::abs(pull) > 3.0) {
          str_color = "\033[1;31m";
        }
        str_term = "\033[0m";
      }

      val.FormatString();

      std::cout << format("%-30s %15g %15s +/- %-15s ") % var->GetName() % val_init % val.str_value() % val.str_error();
      if (print_pulls_) {
        std::cout << format("%s%15g%s") % str_color % pull % str_term;
      }
      std::cout << std::endl;
    }
  }

  std::cout << std::endl;
}
<commit_msg>FitResultPrinter: more colors, more good<commit_after>#include "FitResultPrinter.h"

// STL
#include <iomanip>
#include <string>
#include <vector>

// from Boost
#include <boost/format.hpp>

// from ROOT
#include <TIterator.h>

// from RooFit
#include <RooFitResult.h>
#include <RooArgList.h>
#include <RooAbsArg.h>
#include <RooRealVar.h>

// from DooCore
#include <doocore/statistics/general.h>

doofit::plotting::fitresult::FitResultPrinter::FitResultPrinter(const RooFitResult& fit_result)
: fit_result_(fit_result),
  full_precision_printout_(false),
  print_pulls_(true)
{
}

void doofit::plotting::fitresult::FitResultPrinter::PlotHandler() const {
  using namespace doocore::statistics::general;
  using namespace doocore::io;
  using boost::format;
  using boost::io::group;

  std::vector<std::string> str_colors;
  str_colors.push_back("\033[1;32m");
  str_colors.push_back("\033[1;33m");
  str_colors.push_back("\033[1;31m");

  std::cout << std::endl;
  std::cout << "FitResultPrinter: NLL = " << fit_result_.minNll() << ", EDM = " << fit_result_.edm() << std::endl;
  std::cout << "                  covariance matrix quality: ";
  switch(fit_result_.covQual()) {
    case -1:
      std::cout << str_colors.at(2) << fit_result_.covQual() << ": Unknown, matrix was externally provided \033[0m" << std::endl;
      break;
    case 0:
      std::cout << str_colors.at(2) << fit_result_.covQual() << ": Not calculated at all \033[0m" << std::endl;
      break;
    case 1:
      std::cout << str_colors.at(2) << fit_result_.covQual() << ": Approximation only, not accurate \033[0m" << std::endl;
      break;
    case 2:
      std::cout << str_colors.at(1) << fit_result_.covQual() << ": Full matrix, but forced positive-definite \033[0m" << std::endl;
      break;
    case 3:
      std::cout << str_colors.at(0) << fit_result_.covQual() << ": Full, accurate covariance matrix \033[0m" << std::endl;
      break;
  }

  std::cout << "                  Fit status: ";
  for (unsigned int i=0; i<fit_result_.numStatusHistory(); ++i) {
    if (fit_result_.statusCodeHistory(i) == 0) {
      std::cout << str_colors.at(0);
    } else if (fit_result_.statusCodeHistory(i) == 1) {
      std::cout << str_colors.at(1);
    } else {
      std::cout << str_colors.at(2);
    }
    std::cout << fit_result_.statusLabelHistory(i) << "=" << fit_result_.statusCodeHistory(i) << "\033[0m";
    if (i<(fit_result_.numStatusHistory()-1)) {
      std::cout << ", ";
    }
  }
  std::cout << std::endl;
  std::cout << std::endl;

	RooArgList par_list_float_final = fit_result_.floatParsFinal();
  RooArgList par_list_float_init  = fit_result_.floatParsInit();

  TIterator* it_float = par_list_float_final.createIterator();
  RooAbsArg* arg = NULL;

  std::cout << format("%-30s %15s %15s +/- %-15s ") % "          Parameter          " % "   InitValue   " % "    Fit result" % "Error         ";
  if (print_pulls_) {
    std::cout << format("%15s") % "      Pull     ";
  }
  std::cout << std::endl;

  std::cout << format("%-30s %15s %15s-----%-15s ") % "-----------------------------" % "---------------" % "--------------" % "--------------";
  if (print_pulls_) {
    std::cout << format("%15s") % "---------------";
  }
  std::cout << std::endl;

  while ((arg = dynamic_cast<RooAbsArg*>(it_float->Next()))) {
    RooRealVar* var = dynamic_cast<RooRealVar*>(arg);
    if (var != NULL) {
      ValueWithError<double> val(var->getVal(), var->getError());
      val.set_full_precision_printout(full_precision_printout_);
      RooRealVar* var_init = dynamic_cast<RooRealVar*>(par_list_float_init.find(var->GetName()));
      double val_init = 0.0, pull = 0.0;
      if (var_init != NULL) {
        val_init = var_init->getVal();
        pull = (val_init-val.value)/val.error;
      }

      std::string str_color, str_term;
      if (!doocore::io::TerminalIsRedirected()) {
        if (std::abs(pull) < 2.0) {
          str_color = "\033[1;32m";
        } else if (std::abs(pull) > 2.0 && std::abs(pull) <= 3.0) {
          str_color = "\033[1;33m";
        } else if (std::abs(pull) > 3.0) {
          str_color = "\033[1;31m";
        }
        str_term = "\033[0m";
      }

      val.FormatString();

      std::cout << format("%-30s %15g %15s +/- %-15s ") % var->GetName() % val_init % val.str_value() % val.str_error();
      if (print_pulls_) {
        std::cout << format("%s%15g%s") % str_color % pull % str_term;
      }
      std::cout << std::endl;
    }
  }

  std::cout << std::endl;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
// FILE:          ASITiger.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION:   ASI Tiger MODULE_API items and ASIUtility class
//                Note this is for the "Tiger" MM set of adapters, which should
//                  work for more than just the TG-1000 "Tiger" controller
//
// COPYRIGHT:     Applied Scientific Instrumentation, Eugene OR
//
// LICENSE:       This file is distributed under the BSD license.
//
//                This file 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.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR:        Jon Daniels (jon@asiimaging.com) 09/2013
//
// BASED ON:      ASIStage.cpp, ASIFW1000.cpp, Arduino.cpp, and DemoCamera.cpp
//
//

#ifdef WIN32
#define snprintf _snprintf
#pragma warning(disable: 4355)
#endif

#include "ASITiger.h"
#include "ASITigerComm.h"
#include "ASIXYStage.h"
#include "ASIZStage.h"
#include "ASIClocked.h"
#include "ASIFWheel.h"
#include "ASIScanner.h"
#include "ASIPiezo.h"
#include "ASICRISP.h"
#include "ASILED.h"
#include <cstdio>
#include <string>
#include "../../MMDevice/MMDevice.h"
#include "../../MMDevice/DeviceBase.h"
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

// TODO add in support for other devices, each time modifying these places
//    name constant declarations in the corresponding .h file
//    MODULE_API MM::Device* CreateDevice(const char* deviceName) in this file
//    DetectInstalledDevices in TigerComm (or other hub)

///////////////////////////////////////////////////////////////////////////////
// Exported MMDevice API
///////////////////////////////////////////////////////////////////////////////

MODULE_API void InitializeModuleData()
{
   RegisterDevice(g_TigerCommHubName, MM::HubDevice, g_TigerCommHubDescription);
   RegisterDevice(g_ZStageDeviceName, MM::StageDevice, g_ZStageDeviceDescription);
   RegisterDevice(g_XYStageDeviceName, MM::XYStageDevice, g_XYStageDeviceDescription);
   RegisterDevice(g_FSliderDeviceName, MM::StateDevice, g_FSliderDeviceDescription);
   RegisterDevice(g_TurretDeviceName, MM::StateDevice, g_TurretDeviceDescription);
   RegisterDevice(g_FWheelDeviceName, MM::StateDevice, g_FWheelDeviceDescription);
   RegisterDevice(g_ScannerDeviceName, MM::GalvoDevice, g_ScannerDeviceDescription);
   RegisterDevice(g_PiezoDeviceName, MM::StageDevice, g_PiezoDeviceDescription);
   RegisterDevice(g_CRISPDeviceName, MM::AutoFocusDevice, g_CRISPDeviceDescription);
   RegisterDevice(g_LEDDeviceName, MM::ShutterDevice, g_LEDDeviceDescription);
}

MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
   string deviceStr = deviceName;
   if (deviceName == 0)
      return 0;
   else if (strcmp(deviceName, g_TigerCommHubName) == 0)
      return new CTigerCommHub;
   else if (deviceStr.compare(0, strlen(g_XYStageDeviceName), (string)g_XYStageDeviceName) == 0)
         return new CXYStage(deviceName);
   else if (deviceStr.compare(0, strlen(g_ZStageDeviceName), (string)g_ZStageDeviceName) == 0)
         return new CZStage(deviceName);
   else if (deviceStr.compare(0, strlen(g_FSliderDeviceName), (string)g_FSliderDeviceName) == 0)
      return new CFSlider(deviceName);
   else if (deviceStr.compare(0, strlen(g_TurretDeviceName), (string)g_TurretDeviceName) == 0)
      return new CTurret(deviceName);
   else if (deviceStr.compare(0, strlen(g_FWheelDeviceName), (string)g_FWheelDeviceName) == 0)
      return new CFWheel(deviceName);
   else if (deviceStr.compare(0, strlen(g_ScannerDeviceName), (string)g_ScannerDeviceName) == 0)
      return new CScanner(deviceName);
   else if (deviceStr.compare(0, strlen(g_MMirrorDeviceName), (string)g_MMirrorDeviceName) == 0)
         return new CScanner(deviceName);  // this for compatibility with old config files
   else if (deviceStr.compare(0, strlen(g_PiezoDeviceName), (string)g_PiezoDeviceName) == 0)
      return new CPiezo(deviceName);
   else if (deviceStr.compare(0, strlen(g_CRISPDeviceName), (string)g_CRISPDeviceName) == 0)
      return new CCRISP(deviceName);
   else if (deviceStr.compare(0, strlen(g_LEDDeviceName), (string)g_LEDDeviceName) == 0)
      return new CLED(deviceName);
   else
      return 0;
}

MODULE_API void DeleteDevice(MM::Device* pDevice)
{
   delete pDevice;
}

<commit_msg>ASITiger: Avoid registering 'fake' peripherals.<commit_after>///////////////////////////////////////////////////////////////////////////////
// FILE:          ASITiger.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION:   ASI Tiger MODULE_API items and ASIUtility class
//                Note this is for the "Tiger" MM set of adapters, which should
//                  work for more than just the TG-1000 "Tiger" controller
//
// COPYRIGHT:     Applied Scientific Instrumentation, Eugene OR
//
// LICENSE:       This file is distributed under the BSD license.
//
//                This file 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.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.
//
// AUTHOR:        Jon Daniels (jon@asiimaging.com) 09/2013
//
// BASED ON:      ASIStage.cpp, ASIFW1000.cpp, Arduino.cpp, and DemoCamera.cpp
//
//

#ifdef WIN32
#define snprintf _snprintf
#pragma warning(disable: 4355)
#endif

#include "ASITiger.h"
#include "ASITigerComm.h"
#include "ASIXYStage.h"
#include "ASIZStage.h"
#include "ASIClocked.h"
#include "ASIFWheel.h"
#include "ASIScanner.h"
#include "ASIPiezo.h"
#include "ASICRISP.h"
#include "ASILED.h"
#include <cstdio>
#include <string>
#include "../../MMDevice/MMDevice.h"
#include "../../MMDevice/DeviceBase.h"
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

// TODO add in support for other devices, each time modifying these places
//    name constant declarations in the corresponding .h file
//    MODULE_API MM::Device* CreateDevice(const char* deviceName) in this file
//    DetectInstalledDevices in TigerComm (or other hub)

///////////////////////////////////////////////////////////////////////////////
// Exported MMDevice API
///////////////////////////////////////////////////////////////////////////////

MODULE_API void InitializeModuleData()
{
   RegisterDevice(g_TigerCommHubName, MM::HubDevice, g_TigerCommHubDescription);
}

MODULE_API MM::Device* CreateDevice(const char* deviceName)
{
   string deviceStr = deviceName;
   if (deviceName == 0)
      return 0;
   else if (strcmp(deviceName, g_TigerCommHubName) == 0)
      return new CTigerCommHub;
   else if (deviceStr.compare(0, strlen(g_XYStageDeviceName), (string)g_XYStageDeviceName) == 0)
         return new CXYStage(deviceName);
   else if (deviceStr.compare(0, strlen(g_ZStageDeviceName), (string)g_ZStageDeviceName) == 0)
         return new CZStage(deviceName);
   else if (deviceStr.compare(0, strlen(g_FSliderDeviceName), (string)g_FSliderDeviceName) == 0)
      return new CFSlider(deviceName);
   else if (deviceStr.compare(0, strlen(g_TurretDeviceName), (string)g_TurretDeviceName) == 0)
      return new CTurret(deviceName);
   else if (deviceStr.compare(0, strlen(g_FWheelDeviceName), (string)g_FWheelDeviceName) == 0)
      return new CFWheel(deviceName);
   else if (deviceStr.compare(0, strlen(g_ScannerDeviceName), (string)g_ScannerDeviceName) == 0)
      return new CScanner(deviceName);
   else if (deviceStr.compare(0, strlen(g_MMirrorDeviceName), (string)g_MMirrorDeviceName) == 0)
         return new CScanner(deviceName);  // this for compatibility with old config files
   else if (deviceStr.compare(0, strlen(g_PiezoDeviceName), (string)g_PiezoDeviceName) == 0)
      return new CPiezo(deviceName);
   else if (deviceStr.compare(0, strlen(g_CRISPDeviceName), (string)g_CRISPDeviceName) == 0)
      return new CCRISP(deviceName);
   else if (deviceStr.compare(0, strlen(g_LEDDeviceName), (string)g_LEDDeviceName) == 0)
      return new CLED(deviceName);
   else
      return 0;
}

MODULE_API void DeleteDevice(MM::Device* pDevice)
{
   delete pDevice;
}

<|endoftext|>