<commit_before>//---------------------------------------------------------------------------
//      $Id$
//    Version: $Name$
//
//    Copyright (C) 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/path_search.h>
#include <base/logstream.h>

#include <iostream>
#include <algorithm>

//TODO:[GK] Clean up open functions, reuse code!

std::map<std::string, std::vector<std::string> > PathSearch::path_lists;
std::map<std::string, std::vector<std::string> > PathSearch::suffix_lists;
std::string PathSearch::empty("");

void
PathSearch::initialize_classes()
{
  std::vector<std::string> v;
  v.push_back(empty);
  path_lists.insert(map_type(std::string("PARAMETER"), v));

  v.push_back(std::string(DEAL_II_PATH "/lib/meshes/"));
  path_lists.insert(map_type(std::string("MESH"), v));

  v.clear();
  v.push_back(empty);
  v.push_back(std::string(".prm"));
  suffix_lists.insert(map_type(std::string("PARAMETER"), v));

  v.clear();
  v.push_back(empty);
  v.push_back(std::string(".inp"));
  v.push_back(std::string(".xda"));
  v.push_back(std::string(".dbmesh"));
  suffix_lists.insert(map_type(std::string("MESH"), v));
}

std::vector<std::string>&
PathSearch::get_path_list(const std::string& cls)
{
  if (path_lists.empty())
    initialize_classes();

  Assert(path_lists.count(cls) != 0, ExcNoClass(cls));

  return path_lists.find(cls)->second;
}

std::vector<std::string>&
PathSearch::get_suffix_list(const std::string& cls)
{
  Assert(suffix_lists.count(cls) != 0, ExcNoClass(cls));

  return suffix_lists.find(cls)->second;
}

PathSearch::PathSearch(const std::string& cls,
		       const unsigned int debug)
		:
		cls(cls),
		my_path_list(get_path_list(cls)),
		my_suffix_list(get_suffix_list(cls)),
		debug(debug)
{}

std::istream&
PathSearch::open (const std::string& filename,
		  const std::string& suffix)
{
  std::vector<std::string>::const_iterator path;
  const std::vector<std::string>::const_iterator endp = my_path_list.end();

  if (debug > 2)
    deallog << "PathSearch[" << cls << "] "
	    << my_path_list.size() << " directories "
	    << std::endl;

				   // Try without suffix first
  for (path = my_path_list.begin(); path != endp; ++path)
    {
      real_name = *path + filename;
      if (debug > 1)
	deallog << "PathSearch[" << cls << "] trying "
		<< real_name << std::endl;
      stream.reset(new std::ifstream(real_name.c_str()));
      if (stream->is_open())
	{
	  if (debug > 0)
	    deallog << "PathSearch[" << cls << "] opened "
		    << real_name << std::endl;
	  return *stream;
	}
    }

				   // Now try with given suffix
  for (path = my_path_list.begin(); path != endp; ++path)
    {
      real_name = *path + filename + suffix;
      if (debug > 1)
	deallog << "PathSearch[" << cls << "] trying "
		<< real_name << std::endl;
      stream.reset(new std::ifstream(real_name.c_str()));
      if (stream->is_open())
	{
	  if (debug > 0)
	    deallog << "PathSearch[" << cls << "] opened "
		    << real_name << std::endl;
	  return *stream;
	}
    }
  AssertThrow(false, ExcFileNotFound(filename, cls));
  return *stream;
}

std::istream&
PathSearch::open (const std::string& filename)
{
  std::vector<std::string>::const_iterator suffix;
  std::vector<std::string>::const_iterator path;
  const std::vector<std::string>::const_iterator ends = my_suffix_list.end();
  const std::vector<std::string>::const_iterator endp = my_path_list.end();

  if (debug > 2)
    deallog << "PathSearch[" << cls << "] "
	    << my_path_list.size() << " directories "
	    << my_suffix_list.size() << " suffixes"
	    << std::endl;

  for (suffix = my_suffix_list.begin(); suffix != ends; ++suffix)
    {
      for (path = my_path_list.begin(); path != endp; ++path)
	{
	  real_name = *path + filename + *suffix;
	  if (debug > 1)
	    deallog << "PathSearch[" << cls << "] trying "
		    << real_name << std::endl;
	  stream.reset(new std::ifstream(real_name.c_str()));
	  if (stream->is_open())
	    {
	      if (debug > 0)
		deallog << "PathSearch[" << cls << "] opened "
			<< real_name << std::endl;
	      return *stream;
	    }
	}
    }
  AssertThrow(false, ExcFileNotFound(filename, cls));
  return *stream;
}

void
PathSearch::add_class (const std::string& cls)
{
				   // Make sure standard classes are
				   // initialized first
  if (path_lists.empty())
    initialize_classes();
				   // Add empty path and empty suffix
				   // for new class
  std::vector<std::string> v;
  v.push_back(empty);
  path_lists.insert(map_type(cls, v));
  suffix_lists.insert(map_type(cls, v));
}

void
PathSearch::add_path (const std::string& path,
		      Position pos)
{
  if (pos == back)
    my_path_list.push_back(path);
  else if (pos == front)
    my_path_list.insert(my_path_list.begin(), path);
  else if (pos == after_none)
    {
      std::vector<std::string>::iterator
	i = std::find(my_path_list.begin(), my_path_list.end(), empty);
      if (i != my_path_list.end())
	++i;
      my_path_list.insert(i, path);
    }
}

void
PathSearch::add_suffix (const std::string& suffix,
		      Position pos)
{
  if (pos == back)
    my_suffix_list.push_back(suffix);
  else if (pos == front)
    my_suffix_list.insert(my_suffix_list.begin(), suffix);
  else if (pos == after_none)
    {
      std::vector<std::string>::iterator
	i = std::find(my_suffix_list.begin(), my_suffix_list.end(), empty);
      if (i != my_suffix_list.end())
	++i;
      my_suffix_list.insert(i, suffix);
    }
}

<commit_msg>Add a TODO.<commit_after>//---------------------------------------------------------------------------
//      $Id$
//    Version: $Name$
//
//    Copyright (C) 2005 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

#include <base/path_search.h>
#include <base/logstream.h>

#include <iostream>
#include <algorithm>

//TODO:[GK] Clean up open functions, reuse code!

std::map<std::string, std::vector<std::string> > PathSearch::path_lists;
std::map<std::string, std::vector<std::string> > PathSearch::suffix_lists;
std::string PathSearch::empty("");

void
PathSearch::initialize_classes()
{
  std::vector<std::string> v;
  v.push_back(empty);
  path_lists.insert(map_type(std::string("PARAMETER"), v));

  v.push_back(std::string(DEAL_II_PATH "/lib/meshes/"));
  path_lists.insert(map_type(std::string("MESH"), v));

  v.clear();
  v.push_back(empty);
  v.push_back(std::string(".prm"));
  suffix_lists.insert(map_type(std::string("PARAMETER"), v));

//TODO[GK]: instead of listing by hand here, query the GridIn class which formats it can presently read
  v.clear();
  v.push_back(empty);
  v.push_back(std::string(".inp"));
  v.push_back(std::string(".xda"));
  v.push_back(std::string(".dbmesh"));
  suffix_lists.insert(map_type(std::string("MESH"), v));
}

std::vector<std::string>&
PathSearch::get_path_list(const std::string& cls)
{
  if (path_lists.empty())
    initialize_classes();

  Assert(path_lists.count(cls) != 0, ExcNoClass(cls));

  return path_lists.find(cls)->second;
}

std::vector<std::string>&
PathSearch::get_suffix_list(const std::string& cls)
{
  Assert(suffix_lists.count(cls) != 0, ExcNoClass(cls));

  return suffix_lists.find(cls)->second;
}

PathSearch::PathSearch(const std::string& cls,
		       const unsigned int debug)
		:
		cls(cls),
		my_path_list(get_path_list(cls)),
		my_suffix_list(get_suffix_list(cls)),
		debug(debug)
{}

std::istream&
PathSearch::open (const std::string& filename,
		  const std::string& suffix)
{
  std::vector<std::string>::const_iterator path;
  const std::vector<std::string>::const_iterator endp = my_path_list.end();

  if (debug > 2)
    deallog << "PathSearch[" << cls << "] "
	    << my_path_list.size() << " directories "
	    << std::endl;

				   // Try without suffix first
  for (path = my_path_list.begin(); path != endp; ++path)
    {
      real_name = *path + filename;
      if (debug > 1)
	deallog << "PathSearch[" << cls << "] trying "
		<< real_name << std::endl;
      stream.reset(new std::ifstream(real_name.c_str()));
      if (stream->is_open())
	{
	  if (debug > 0)
	    deallog << "PathSearch[" << cls << "] opened "
		    << real_name << std::endl;
	  return *stream;
	}
    }

				   // Now try with given suffix
  for (path = my_path_list.begin(); path != endp; ++path)
    {
      real_name = *path + filename + suffix;
      if (debug > 1)
	deallog << "PathSearch[" << cls << "] trying "
		<< real_name << std::endl;
      stream.reset(new std::ifstream(real_name.c_str()));
      if (stream->is_open())
	{
	  if (debug > 0)
	    deallog << "PathSearch[" << cls << "] opened "
		    << real_name << std::endl;
	  return *stream;
	}
    }
  AssertThrow(false, ExcFileNotFound(filename, cls));
  return *stream;
}

std::istream&
PathSearch::open (const std::string& filename)
{
  std::vector<std::string>::const_iterator suffix;
  std::vector<std::string>::const_iterator path;
  const std::vector<std::string>::const_iterator ends = my_suffix_list.end();
  const std::vector<std::string>::const_iterator endp = my_path_list.end();

  if (debug > 2)
    deallog << "PathSearch[" << cls << "] "
	    << my_path_list.size() << " directories "
	    << my_suffix_list.size() << " suffixes"
	    << std::endl;

  for (suffix = my_suffix_list.begin(); suffix != ends; ++suffix)
    {
      for (path = my_path_list.begin(); path != endp; ++path)
	{
	  real_name = *path + filename + *suffix;
	  if (debug > 1)
	    deallog << "PathSearch[" << cls << "] trying "
		    << real_name << std::endl;
	  stream.reset(new std::ifstream(real_name.c_str()));
	  if (stream->is_open())
	    {
	      if (debug > 0)
		deallog << "PathSearch[" << cls << "] opened "
			<< real_name << std::endl;
	      return *stream;
	    }
	}
    }
  AssertThrow(false, ExcFileNotFound(filename, cls));
  return *stream;
}

void
PathSearch::add_class (const std::string& cls)
{
				   // Make sure standard classes are
				   // initialized first
  if (path_lists.empty())
    initialize_classes();
				   // Add empty path and empty suffix
				   // for new class
  std::vector<std::string> v;
  v.push_back(empty);
  path_lists.insert(map_type(cls, v));
  suffix_lists.insert(map_type(cls, v));
}

void
PathSearch::add_path (const std::string& path,
		      Position pos)
{
  if (pos == back)
    my_path_list.push_back(path);
  else if (pos == front)
    my_path_list.insert(my_path_list.begin(), path);
  else if (pos == after_none)
    {
      std::vector<std::string>::iterator
	i = std::find(my_path_list.begin(), my_path_list.end(), empty);
      if (i != my_path_list.end())
	++i;
      my_path_list.insert(i, path);
    }
}

void
PathSearch::add_suffix (const std::string& suffix,
		      Position pos)
{
  if (pos == back)
    my_suffix_list.push_back(suffix);
  else if (pos == front)
    my_suffix_list.insert(my_suffix_list.begin(), suffix);
  else if (pos == after_none)
    {
      std::vector<std::string>::iterator
	i = std::find(my_suffix_list.begin(), my_suffix_list.end(), empty);
      if (i != my_suffix_list.end())
	++i;
      my_suffix_list.insert(i, suffix);
    }
}

<|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2014 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  field/test/container.cpp                                                        */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

// includes, system

#include <glm/gtx/io.hpp> // glm::operator<<

// includes, project

#include <scene/objects.hpp>

// internal unnamed namespace

namespace {

  // types, internal (class, enum, struct, union, typedef)

  // variables, internal

  // functions, internal

} // namespace {

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(test_scene_object_light_base_rep)
{
  scene::object::light::base::rep const lr;

  BOOST_CHECK(false == lr.active);
  BOOST_MESSAGE("object_light_source_rep:" << lr << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_directional)
{
  scene::object::light::directional const l;

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_positional)
{
  scene::object::light::positional const l;

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_spot)
{
  scene::object::light::spot const l;

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_area)
{
  scene::object::light::area l;

  l.exponent.set(1);
  l.cutoff.  set(12.5);

  l.size.    set(glm::uvec2(1, 2));
  l.samples. set(glm::uvec2(1, 4));

  l.size.    set(glm::uvec2(2, 1));
  l.samples. set(glm::uvec2(4, 1));

  l.size.    set(glm::uvec2(2, 2));
  l.samples. set(glm::uvec2(4, 4));

  l.size.    set(glm::uvec2( 6, 3));
  l.samples. set(glm::uvec2(10, 5));

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}
<commit_msg>fixed: typo<commit_after>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2014 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  field/test/objects_light.cpp                                                    */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

// includes, system

#include <glm/gtx/io.hpp> // glm::operator<<

// includes, project

#include <scene/objects.hpp>

// internal unnamed namespace

namespace {

  // types, internal (class, enum, struct, union, typedef)

  // variables, internal

  // functions, internal

} // namespace {

#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(test_scene_object_light_base_rep)
{
  scene::object::light::base::rep const lr;

  BOOST_CHECK(false == lr.active);
  BOOST_MESSAGE("object_light_source_rep:" << lr << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_directional)
{
  scene::object::light::directional const l;

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_positional)
{
  scene::object::light::positional const l;

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_spot)
{
  scene::object::light::spot const l;

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}

BOOST_AUTO_TEST_CASE(test_scene_object_light_area)
{
  scene::object::light::area l;

  l.exponent.set(1);
  l.cutoff.  set(12.5);

  l.size.    set(glm::uvec2(1, 2));
  l.samples. set(glm::uvec2(1, 4));

  l.size.    set(glm::uvec2(2, 1));
  l.samples. set(glm::uvec2(4, 1));

  l.size.    set(glm::uvec2(2, 2));
  l.samples. set(glm::uvec2(4, 4));

  l.size.    set(glm::uvec2( 6, 3));
  l.samples. set(glm::uvec2(10, 5));

  BOOST_CHECK(false == l.active);
  BOOST_MESSAGE(l << '\n');
}
<|endoftext|>


<commit_before>/*
 * BaseProbe.h
 *
 *      Author: slundquist
 */

#ifndef BASEPROBE_HPP_
#define BASEPROBE_HPP_

#include <stdio.h>
#include <vector>
#include "../io/fileio.hpp"

namespace PV {

class HyPerCol;
class HyPerLayer;

//typedef enum {
//   BufV,
//   BufActivity
//} PVBufType;

/**
 * An abstract base class for the common functionality of layer probes and connection probes.
 */
class BaseProbe {

// Methods
public:
   //BaseProbe(const char * probeName, HyPerCol * hc);
   virtual ~BaseProbe();

   int ioParams(enum ParamsIOFlag ioFlag);

   /**
    * A pure virtual function called during HyPerCol::run, during the communicateInitInfo stage.
    * BaseProbe::communicateInitInfo sets up the triggering layer and attaches to the energy probe,
    * if either triggerFlag or energyProbe are set.
    */
   virtual int communicateInitInfo() = 0;

   /**
    * Called during HyPerCol::run, during the allocateDataStructures stage.
    * BaseProbe::allocateDataStructures returns immediately, but derived classes that
    * need to allocate storage should override this method.
    */
   virtual int allocateDataStructures();

   /**
    * If there is a triggering layer, needUpdate returns true when the triggering layer's
    * nextUpdateTime, modified by the probe's triggerOffset parameter, occurs.
    * If there is not a triggering layer, needUpdate returns false.
    * This behavior can be overridden if a probe uses some criterion other than triggering
    * to choose when output its state.
    */
   virtual bool needUpdate(double time, double dt);

   /**
    * Returns the number of value indices the probe can compute (typically the value
    * of the parent HyPerCol's nBatch parameter).
    * BaseProbe::getNumValues() returns the parent HyPerCol's getNBatch(), which can be overridden.
    * Probes derived from BaseProbe can set numValues to zero or a negative number to indicate that
    * getValues() and getNumValues()
    * are not fully implemented for that probe.
    */
   int getNumValues() { return numValues; }

   /**
    * The public interface for calling the outputState method.
    * BaseConnection::outputStateWrapper calls outputState() if needUpdate() returns true.
    * This behavior is intended to be general, but the method can be overridden if needed.
    */
   virtual int outputStateWrapper(double timef, double dt);

   /**
    * A pure virtual method for writing output to the output file.
    */
   virtual int outputState(double timef) = 0;
   virtual int writeTimer(FILE* stream) {return PV_SUCCESS;}

   /**
    * Returns the keyword of the params group associated with this probe.
    */
   char const * getKeyword();

   /**
    * Returns the name of the probe, specified in the public constructor.
    */
   const char * getName() {return name;}

   /**
    * Returns the name of the targetName parameter for this probe.
    * LayerProbe uses targetName to specify the layer to attach to;
    * BaseConnectionProbe uses it to specify the connection to attach to.
    */
   const char * getTargetName() {return targetName;}

   /**
    * Specifies the object responsible calling the probe's destructor.
    * BaseProbe sets owner to the parent HyPerCol during initialization.
    * During the communicateInitInfo stage, layer probes and connection probes
    * change their owner to the layer or connection they attach to.
    */
   void const * getOwner() { return owner;}

   /**
    * getValues(double timevalue, double * values) sets the buffer 'values' with the probe's calculated values.
    * It assumes that the values buffer is large enough to hold getNumValues()
    * double-precision values.
    * If 'values' is NULL, the values are still updated internally if needed, but
    * those values are not returned.
    * Internally, getValues() calls calcValues() if needRecalc() is true.  It then
    * copies the probeValues buffer to the input argument buffer 'values'.
    * Derived classes should not override or hide this method.  Instead, they should override calcValues.
    */
   int getValues(double timevalue, double * valuesVector);
   /**
    * getValues(double timevalue, vector<double> * valuesVector) is a wrapper around
    * getValues(double, double *) that uses C++ vectors.  It resizes valuesVector
    * to size getNumValues() and then fills the vector with the values returned by getValues.
    */
   int getValues(double timevalue, std::vector<double> * valuesVector);
   /**
    * getValue() is meant for situations where the caller needs one value
    * that would be returned by getValues(), not the whole buffer.
    * getValue() returns a signaling NaN if index is out of bounds.  If index is valid,
    * getValue() calls calcValues() if needRecalc() returns true, and then
    * returns probeValues[index].
    * Derived classes should not override or hide this method.  Instead, they should override calcValues.
    */
   double getValue(double timevalue, int index);

protected:
   BaseProbe();
   int initialize(const char * probeName, HyPerCol * hc);
   virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag);

   /**
    * List of parameters for the BaseProbe class
    * @name BaseProbe Parameters
    * @{
    */

   /**
    * @brief targetName: the name of the object that the probe attaches to.
    * In LayerProbe, targetName is used to define the targetLayer, and in
    * BaseConnectionProbe, targetName is used to define the targetConn.
    */
   virtual void ioParam_targetName(enum ParamsIOFlag ioFlag);

   /**
    * @brief message: A string parameter that is typically included in the lines output by the outputState method
    */
   virtual void ioParam_message(enum ParamsIOFlag ioFlag);

   /**
    * @brief probeOutputFile: the name of the file that the outputState method writes to.
    * If blank, the output is sent to stdout.
    */
   virtual void ioParam_probeOutputFile(enum ParamsIOFlag ioFlag);

   /**
    * @brief triggerFlag: If false, the needUpdate method always returns true,
    * so that outputState is called every timestep.  If false, the needUpdate
    * method uses triggerLayerName and triggerOffset to determine if the probe
    * should be triggered.
    */
   virtual void ioParam_triggerFlag(enum ParamsIOFlag ioFlag);

   /**
    * @brief triggerLayerName: If triggerFlag is true, triggerLayerName specifies the layer
    * to check for triggering.
    */
   virtual void ioParam_triggerLayerName(enum ParamsIOFlag ioFlag);

   /**
    * @brief triggerOffset: If triggerFlag is true, triggerOffset specifies the
    * time interval *before* the triggerLayer's nextUpdate time that needUpdate() returns true.
    */
   virtual void ioParam_triggerOffset(enum ParamsIOFlag ioFlag);

   /**
    * @brief energyProbe: If nonblank, specifies the name of a ColumnEnergyProbe
    * that this probe contributes an energy term to.
    */
   virtual void ioParam_energyProbe(enum ParamsIOFlag ioFlag);

   /**
    * @brief coefficient: If energyProbe is set, the coefficient parameter specifies
    * that ColumnEnergyProbe multiplies the result of this probe's getValues() method
    * by coefficient when computing the error.
    * @details Note that coefficient does not affect the value returned by the getValue() or
    * getValues() method.
    */
   virtual void ioParam_coefficient(enum ParamsIOFlag ioFlag);
   /** @} */

   virtual int initOutputStream(const char * filename);

   /**
    * A pure virtual method for that should return true if the quantities being measured
    * by the probe have changed since the last time the quantities were calculated.
    * Typically, an implementation of needRecalc() will check the lastUpdateTime of
    * the object being probed, and return true if that value is greater than the
    * lastUpdateTime member variable.
    * needRecalc() is called by getValues(double) (and hence by getValue() and the other
    * flavors of getValues).
    * Note that there is a single needRecalc that applies to all getNumValues() quantities.
    */
   virtual bool needRecalc(double timevalue) = 0;

   /**
    * A pure virtual method to calculate the values of the probe.  calcValues() can
    * assume that needRecalc() has been called and returned true.
    * It should write the computed values into the buffer of member variable 'probeValues'.
    */
   virtual int calcValues(double timevalue) = 0;

   /**
    * If needRecalc() returns true, getValues(double) updates the probeValues buffer
    * (by calling calcValues) and sets lastUpdateTime to the timevalue input argument.
    */
   int getValues(double timevalue);

   /**
    * Returns a pointer to parent HyPerCol.
    */
   HyPerCol * getParent() {return parent;}

   /**
    * Returns a pointer to the message parameter.
    */
   const char * getMessage() {return msgstring;}

   /**
    * The method called by BaseProbe::initialize() to set the message used by
    * the probe's outputState method.
    */
   virtual int initMessage(const char * msg);

   /**
    * Returns a pointer to the PV_Stream used by outputState.
    */
   PV_Stream * getStream() {return outputstream;}

   /**
    * initNumValues is called by initialize.
    * BaseProbe::initNumValues sets numValues to the parent HyPerCol's getNBatch().
    * Derived classes can override initNumValues to initialize numValues to a different
    * value.
    */
   virtual int initNumValues();

   /**
    * Sets the numValues member variable (returned by getNumValues()) and reallocates
    * the probeValues member variable to hold numValues double-precision values.
    * If the reallocation fails, the probeValues buffer is left unchanged, errno is
    * set (by a realloc() call), and PV_FAILURE is returned.
    * Otherwise, PV_SUCCESS is returned.
    */
   int setNumValues(int n);

   /**
    * Returns a pointer to the buffer containing the probeValues.
    */
   double * getValuesBuffer() { return probeValues; }

   /**
    * Returns the time that calcValues was last called.
    * BaseProbe updates the last update time in getValues() and getValue(),
    * based on the result of needRecalc.
    */
   double getLastUpdateTime() { return lastUpdateTime; }

private:
   int initialize_base();
   void setParentCol(HyPerCol * hc) {parent = hc;}
   int setProbeName(const char * probeName);

// Member variables
protected:
   PV_Stream * outputstream;
   bool triggerFlag;
   char* triggerLayerName;
   HyPerLayer * triggerLayer;
   double triggerOffset;
   HyPerCol * parent;
   void * owner; // the object responsible for calling the probe's destructor
   char * name;
   char * targetName;
   char * energyProbe; // the name of the ColumnEnergyProbe to attach to, if any.
   double coefficient;

private:
   char * msgparams; // the message parameter in the params
   char * msgstring; // the string that gets printed by outputState ("" if message is empty or null; message + ":" if nonempty
   char * probeOutputFilename;
   int numValues;
   double * probeValues;
   double lastUpdateTime; // The time of the last time calcValues was called.
};

}

#endif /* BASEPROBE_HPP_ */
<commit_msg>Fixes comment to ioParam_triggerFlag in BaseProbe<commit_after>/*
 * BaseProbe.h
 *
 *      Author: slundquist
 */

#ifndef BASEPROBE_HPP_
#define BASEPROBE_HPP_

#include <stdio.h>
#include <vector>
#include "../io/fileio.hpp"

namespace PV {

class HyPerCol;
class HyPerLayer;

//typedef enum {
//   BufV,
//   BufActivity
//} PVBufType;

/**
 * An abstract base class for the common functionality of layer probes and connection probes.
 */
class BaseProbe {

// Methods
public:
   //BaseProbe(const char * probeName, HyPerCol * hc);
   virtual ~BaseProbe();

   int ioParams(enum ParamsIOFlag ioFlag);

   /**
    * A pure virtual function called during HyPerCol::run, during the communicateInitInfo stage.
    * BaseProbe::communicateInitInfo sets up the triggering layer and attaches to the energy probe,
    * if either triggerFlag or energyProbe are set.
    */
   virtual int communicateInitInfo() = 0;

   /**
    * Called during HyPerCol::run, during the allocateDataStructures stage.
    * BaseProbe::allocateDataStructures returns immediately, but derived classes that
    * need to allocate storage should override this method.
    */
   virtual int allocateDataStructures();

   /**
    * If there is a triggering layer, needUpdate returns true when the triggering layer's
    * nextUpdateTime, modified by the probe's triggerOffset parameter, occurs.
    * If there is not a triggering layer, needUpdate returns false.
    * This behavior can be overridden if a probe uses some criterion other than triggering
    * to choose when output its state.
    */
   virtual bool needUpdate(double time, double dt);

   /**
    * Returns the number of value indices the probe can compute (typically the value
    * of the parent HyPerCol's nBatch parameter).
    * BaseProbe::getNumValues() returns the parent HyPerCol's getNBatch(), which can be overridden.
    * Probes derived from BaseProbe can set numValues to zero or a negative number to indicate that
    * getValues() and getNumValues()
    * are not fully implemented for that probe.
    */
   int getNumValues() { return numValues; }

   /**
    * The public interface for calling the outputState method.
    * BaseConnection::outputStateWrapper calls outputState() if needUpdate() returns true.
    * This behavior is intended to be general, but the method can be overridden if needed.
    */
   virtual int outputStateWrapper(double timef, double dt);

   /**
    * A pure virtual method for writing output to the output file.
    */
   virtual int outputState(double timef) = 0;
   virtual int writeTimer(FILE* stream) {return PV_SUCCESS;}

   /**
    * Returns the keyword of the params group associated with this probe.
    */
   char const * getKeyword();

   /**
    * Returns the name of the probe, specified in the public constructor.
    */
   const char * getName() {return name;}

   /**
    * Returns the name of the targetName parameter for this probe.
    * LayerProbe uses targetName to specify the layer to attach to;
    * BaseConnectionProbe uses it to specify the connection to attach to.
    */
   const char * getTargetName() {return targetName;}

   /**
    * Specifies the object responsible calling the probe's destructor.
    * BaseProbe sets owner to the parent HyPerCol during initialization.
    * During the communicateInitInfo stage, layer probes and connection probes
    * change their owner to the layer or connection they attach to.
    */
   void const * getOwner() { return owner;}

   /**
    * getValues(double timevalue, double * values) sets the buffer 'values' with the probe's calculated values.
    * It assumes that the values buffer is large enough to hold getNumValues()
    * double-precision values.
    * If 'values' is NULL, the values are still updated internally if needed, but
    * those values are not returned.
    * Internally, getValues() calls calcValues() if needRecalc() is true.  It then
    * copies the probeValues buffer to the input argument buffer 'values'.
    * Derived classes should not override or hide this method.  Instead, they should override calcValues.
    */
   int getValues(double timevalue, double * valuesVector);
   /**
    * getValues(double timevalue, vector<double> * valuesVector) is a wrapper around
    * getValues(double, double *) that uses C++ vectors.  It resizes valuesVector
    * to size getNumValues() and then fills the vector with the values returned by getValues.
    */
   int getValues(double timevalue, std::vector<double> * valuesVector);
   /**
    * getValue() is meant for situations where the caller needs one value
    * that would be returned by getValues(), not the whole buffer.
    * getValue() returns a signaling NaN if index is out of bounds.  If index is valid,
    * getValue() calls calcValues() if needRecalc() returns true, and then
    * returns probeValues[index].
    * Derived classes should not override or hide this method.  Instead, they should override calcValues.
    */
   double getValue(double timevalue, int index);

protected:
   BaseProbe();
   int initialize(const char * probeName, HyPerCol * hc);
   virtual int ioParamsFillGroup(enum ParamsIOFlag ioFlag);

   /**
    * List of parameters for the BaseProbe class
    * @name BaseProbe Parameters
    * @{
    */

   /**
    * @brief targetName: the name of the object that the probe attaches to.
    * In LayerProbe, targetName is used to define the targetLayer, and in
    * BaseConnectionProbe, targetName is used to define the targetConn.
    */
   virtual void ioParam_targetName(enum ParamsIOFlag ioFlag);

   /**
    * @brief message: A string parameter that is typically included in the lines output by the outputState method
    */
   virtual void ioParam_message(enum ParamsIOFlag ioFlag);

   /**
    * @brief probeOutputFile: the name of the file that the outputState method writes to.
    * If blank, the output is sent to stdout.
    */
   virtual void ioParam_probeOutputFile(enum ParamsIOFlag ioFlag);

   /**
    * @brief triggerFlag: If false, the needUpdate method always returns true,
    * so that outputState is called every timestep.  If true, the needUpdate
    * method uses triggerLayerName and triggerOffset to determine if the probe
    * should be triggered.
    */
   virtual void ioParam_triggerFlag(enum ParamsIOFlag ioFlag);

   /**
    * @brief triggerLayerName: If triggerFlag is true, triggerLayerName specifies the layer
    * to check for triggering.
    */
   virtual void ioParam_triggerLayerName(enum ParamsIOFlag ioFlag);

   /**
    * @brief triggerOffset: If triggerFlag is true, triggerOffset specifies the
    * time interval *before* the triggerLayer's nextUpdate time that needUpdate() returns true.
    */
   virtual void ioParam_triggerOffset(enum ParamsIOFlag ioFlag);

   /**
    * @brief energyProbe: If nonblank, specifies the name of a ColumnEnergyProbe
    * that this probe contributes an energy term to.
    */
   virtual void ioParam_energyProbe(enum ParamsIOFlag ioFlag);

   /**
    * @brief coefficient: If energyProbe is set, the coefficient parameter specifies
    * that ColumnEnergyProbe multiplies the result of this probe's getValues() method
    * by coefficient when computing the error.
    * @details Note that coefficient does not affect the value returned by the getValue() or
    * getValues() method.
    */
   virtual void ioParam_coefficient(enum ParamsIOFlag ioFlag);
   /** @} */

   virtual int initOutputStream(const char * filename);

   /**
    * A pure virtual method for that should return true if the quantities being measured
    * by the probe have changed since the last time the quantities were calculated.
    * Typically, an implementation of needRecalc() will check the lastUpdateTime of
    * the object being probed, and return true if that value is greater than the
    * lastUpdateTime member variable.
    * needRecalc() is called by getValues(double) (and hence by getValue() and the other
    * flavors of getValues).
    * Note that there is a single needRecalc that applies to all getNumValues() quantities.
    */
   virtual bool needRecalc(double timevalue) = 0;

   /**
    * A pure virtual method to calculate the values of the probe.  calcValues() can
    * assume that needRecalc() has been called and returned true.
    * It should write the computed values into the buffer of member variable 'probeValues'.
    */
   virtual int calcValues(double timevalue) = 0;

   /**
    * If needRecalc() returns true, getValues(double) updates the probeValues buffer
    * (by calling calcValues) and sets lastUpdateTime to the timevalue input argument.
    */
   int getValues(double timevalue);

   /**
    * Returns a pointer to parent HyPerCol.
    */
   HyPerCol * getParent() {return parent;}

   /**
    * Returns a pointer to the message parameter.
    */
   const char * getMessage() {return msgstring;}

   /**
    * The method called by BaseProbe::initialize() to set the message used by
    * the probe's outputState method.
    */
   virtual int initMessage(const char * msg);

   /**
    * Returns a pointer to the PV_Stream used by outputState.
    */
   PV_Stream * getStream() {return outputstream;}

   /**
    * initNumValues is called by initialize.
    * BaseProbe::initNumValues sets numValues to the parent HyPerCol's getNBatch().
    * Derived classes can override initNumValues to initialize numValues to a different
    * value.
    */
   virtual int initNumValues();

   /**
    * Sets the numValues member variable (returned by getNumValues()) and reallocates
    * the probeValues member variable to hold numValues double-precision values.
    * If the reallocation fails, the probeValues buffer is left unchanged, errno is
    * set (by a realloc() call), and PV_FAILURE is returned.
    * Otherwise, PV_SUCCESS is returned.
    */
   int setNumValues(int n);

   /**
    * Returns a pointer to the buffer containing the probeValues.
    */
   double * getValuesBuffer() { return probeValues; }

   /**
    * Returns the time that calcValues was last called.
    * BaseProbe updates the last update time in getValues() and getValue(),
    * based on the result of needRecalc.
    */
   double getLastUpdateTime() { return lastUpdateTime; }

private:
   int initialize_base();
   void setParentCol(HyPerCol * hc) {parent = hc;}
   int setProbeName(const char * probeName);

// Member variables
protected:
   PV_Stream * outputstream;
   bool triggerFlag;
   char* triggerLayerName;
   HyPerLayer * triggerLayer;
   double triggerOffset;
   HyPerCol * parent;
   void * owner; // the object responsible for calling the probe's destructor
   char * name;
   char * targetName;
   char * energyProbe; // the name of the ColumnEnergyProbe to attach to, if any.
   double coefficient;

private:
   char * msgparams; // the message parameter in the params
   char * msgstring; // the string that gets printed by outputState ("" if message is empty or null; message + ":" if nonempty
   char * probeOutputFilename;
   int numValues;
   double * probeValues;
   double lastUpdateTime; // The time of the last time calcValues was called.
};

}

#endif /* BASEPROBE_HPP_ */
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgstreamercameraexposurecontrol_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include <gst/interfaces/photography.h>

#include <QDebug>

QGstreamerCameraExposureControl::QGstreamerCameraExposureControl(GstElement &camerabin, QGstreamerCaptureSession *session)
    :QCameraExposureControl(session),
     m_camerabin(camerabin),
     m_session(session)
{
}

QGstreamerCameraExposureControl::~QGstreamerCameraExposureControl()
{
}

QCamera::FlashModes QGstreamerCameraExposureControl::flashMode() const
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    GstFlashMode flashMode = config.flash_mode;

    QCamera::FlashModes modes;
    switch (flashMode) {
    case GST_PHOTOGRAPHY_FLASH_MODE_AUTO: modes |= QCamera::FlashAuto; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_OFF: modes |= QCamera::FlashOff; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_ON: modes |= QCamera::FlashOn; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN: modes |= QCamera::FlashFill; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE: modes |= QCamera::FlashRedEyeReduction; break;
    default:
        modes |= QCamera::FlashManual;
        break;
    }
    return modes;
}

void QGstreamerCameraExposureControl::setFlashMode(QCamera::FlashModes mode)
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);

    GstFlashMode flashMode = config.flash_mode;
    if (mode.testFlag(QCamera::FlashAuto)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_AUTO;
    else if (mode.testFlag(QCamera::FlashOff)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_OFF;
    else if (mode.testFlag(QCamera::FlashOn)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_ON;
    else if (mode.testFlag(QCamera::FlashFill)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN;
    else if (mode.testFlag(QCamera::FlashRedEyeReduction)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE;

    config.flash_mode = flashMode;
    gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
}

QCamera::FlashModes QGstreamerCameraExposureControl::supportedFlashModes() const
{
    QCamera::FlashModes modes;
    modes |= QCamera::FlashOff;
    modes |= QCamera::FlashOn;
    modes |= QCamera::FlashAuto;
    modes |= QCamera::FlashRedEyeReduction;
    modes |= QCamera::FlashFill;

    return modes;
}

qreal QGstreamerCameraExposureControl::flashCompensation() const
{
    return 0;
}

void QGstreamerCameraExposureControl::setFlashCompensation(qreal ev)
{
}

qreal QGstreamerCameraExposureControl::flashPower() const
{
}

void QGstreamerCameraExposureControl::setFlashPower(qreal power)
{
}

bool QGstreamerCameraExposureControl::isFlashReady() const
{
}

QCamera::ExposureMode QGstreamerCameraExposureControl::exposureMode() const
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    GstSceneMode sceneMode = config.scene_mode;

    switch (sceneMode) {
    case GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT: return QCamera::ExposurePortrait;
    case GST_PHOTOGRAPHY_SCENE_MODE_SPORT: return QCamera::ExposureSports;
    case GST_PHOTOGRAPHY_SCENE_MODE_NIGHT: return QCamera::ExposureNight;
    case GST_PHOTOGRAPHY_SCENE_MODE_AUTO: return QCamera::ExposureAuto;
    case GST_PHOTOGRAPHY_SCENE_MODE_MANUAL:
    case GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP:    //no direct mapping available so mapping to manual mode
    case GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE:  //no direct mapping available so mapping to manual mode
    default:
         return QCamera::ExposureManual;
    }
}

void QGstreamerCameraExposureControl::setExposureMode(QCamera::ExposureMode mode)
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    GstSceneMode sceneMode = config.scene_mode;

    if (mode == QCamera::ExposureManual) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_MANUAL;
    else if (mode == QCamera::ExposurePortrait) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT;
    else if (mode == QCamera::ExposureSports) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_SPORT;
    else if (mode == QCamera::ExposureNight) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_NIGHT;
    else if (mode == QCamera::ExposureAuto) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_AUTO;

    config.scene_mode = sceneMode;
    gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
}

QCamera::ExposureModes QGstreamerCameraExposureControl::supportedExposureModes() const
{
    //Similar mode names can be found in gst as GstSceneMode
    QCamera::ExposureModes modes;
    modes |= QCamera::ExposureManual;
    modes |= QCamera::ExposurePortrait;
    modes |= QCamera::ExposureSports;
    modes |= QCamera::ExposureNight;
    modes |= QCamera::ExposureAuto;

    //No direct mapping available for GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP and
    //GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE

    return modes;
}

qreal QGstreamerCameraExposureControl::exposureCompensation() const
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    return config.ev_compensation;
}

void QGstreamerCameraExposureControl::setExposureCompensation(qreal ev)
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    config.ev_compensation = ev;
    gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
}

QCamera::MeteringMode QGstreamerCameraExposureControl::meteringMode() const
{
}

void QGstreamerCameraExposureControl::setMeteringMode(QCamera::MeteringMode mode)
{
}

QCamera::MeteringModes QGstreamerCameraExposureControl::supportedMeteringModes() const
{
}

int QGstreamerCameraExposureControl::isoSensitivity() const
{
}

QList<int> QGstreamerCameraExposureControl::supportedIsoSensitivities(bool *continuous) const
{
}

void QGstreamerCameraExposureControl::setManualIsoSensitivity(int iso)
{
}

void QGstreamerCameraExposureControl::setAutoIsoSensitivity()
{
}

qreal QGstreamerCameraExposureControl::aperture() const
{
}

QList<qreal> QGstreamerCameraExposureControl::supportedApertures(bool *continuous) const
{
}

void QGstreamerCameraExposureControl::setManualAperture(qreal aperture)
{
}

void QGstreamerCameraExposureControl::setAutoAperture()
{
}

qreal QGstreamerCameraExposureControl::shutterSpeed() const
{
}

QList<qreal> QGstreamerCameraExposureControl::supportedShutterSpeeds(bool *continuous) const
{
}

void QGstreamerCameraExposureControl::setManualShutterSpeed(qreal seconds)
{
}

void QGstreamerCameraExposureControl::setAutoShutterSpeed()
{
}

bool QGstreamerCameraExposureControl::isExposureLocked() const
{
}

void QGstreamerCameraExposureControl::lockExposure()
{
}

void QGstreamerCameraExposureControl::unlockExposure()
{
}

<commit_msg>Returning MeteringAverage as an only supported mode<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qgstreamercameraexposurecontrol_maemo.h"
#include "qgstreamercapturesession_maemo.h"
#include <gst/interfaces/photography.h>

#include <QDebug>

QGstreamerCameraExposureControl::QGstreamerCameraExposureControl(GstElement &camerabin, QGstreamerCaptureSession *session)
    :QCameraExposureControl(session),
     m_camerabin(camerabin),
     m_session(session)
{
}

QGstreamerCameraExposureControl::~QGstreamerCameraExposureControl()
{
}

QCamera::FlashModes QGstreamerCameraExposureControl::flashMode() const
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    GstFlashMode flashMode = config.flash_mode;

    QCamera::FlashModes modes;
    switch (flashMode) {
    case GST_PHOTOGRAPHY_FLASH_MODE_AUTO: modes |= QCamera::FlashAuto; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_OFF: modes |= QCamera::FlashOff; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_ON: modes |= QCamera::FlashOn; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN: modes |= QCamera::FlashFill; break;
    case GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE: modes |= QCamera::FlashRedEyeReduction; break;
    default:
        modes |= QCamera::FlashManual;
        break;
    }
    return modes;
}

void QGstreamerCameraExposureControl::setFlashMode(QCamera::FlashModes mode)
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);

    GstFlashMode flashMode = config.flash_mode;
    if (mode.testFlag(QCamera::FlashAuto)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_AUTO;
    else if (mode.testFlag(QCamera::FlashOff)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_OFF;
    else if (mode.testFlag(QCamera::FlashOn)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_ON;
    else if (mode.testFlag(QCamera::FlashFill)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_FILL_IN;
    else if (mode.testFlag(QCamera::FlashRedEyeReduction)) flashMode = GST_PHOTOGRAPHY_FLASH_MODE_RED_EYE;

    config.flash_mode = flashMode;
    gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
}

QCamera::FlashModes QGstreamerCameraExposureControl::supportedFlashModes() const
{
    QCamera::FlashModes modes;
    modes |= QCamera::FlashOff;
    modes |= QCamera::FlashOn;
    modes |= QCamera::FlashAuto;
    modes |= QCamera::FlashRedEyeReduction;
    modes |= QCamera::FlashFill;

    return modes;
}

qreal QGstreamerCameraExposureControl::flashCompensation() const
{
    return 0;
}

void QGstreamerCameraExposureControl::setFlashCompensation(qreal ev)
{
}

qreal QGstreamerCameraExposureControl::flashPower() const
{
}

void QGstreamerCameraExposureControl::setFlashPower(qreal power)
{
}

bool QGstreamerCameraExposureControl::isFlashReady() const
{
}

QCamera::ExposureMode QGstreamerCameraExposureControl::exposureMode() const
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    GstSceneMode sceneMode = config.scene_mode;

    switch (sceneMode) {
    case GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT: return QCamera::ExposurePortrait;
    case GST_PHOTOGRAPHY_SCENE_MODE_SPORT: return QCamera::ExposureSports;
    case GST_PHOTOGRAPHY_SCENE_MODE_NIGHT: return QCamera::ExposureNight;
    case GST_PHOTOGRAPHY_SCENE_MODE_AUTO: return QCamera::ExposureAuto;
    case GST_PHOTOGRAPHY_SCENE_MODE_MANUAL:
    case GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP:    //no direct mapping available so mapping to manual mode
    case GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE:  //no direct mapping available so mapping to manual mode
    default:
         return QCamera::ExposureManual;
    }
}

void QGstreamerCameraExposureControl::setExposureMode(QCamera::ExposureMode mode)
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    GstSceneMode sceneMode = config.scene_mode;

    if (mode == QCamera::ExposureManual) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_MANUAL;
    else if (mode == QCamera::ExposurePortrait) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_PORTRAIT;
    else if (mode == QCamera::ExposureSports) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_SPORT;
    else if (mode == QCamera::ExposureNight) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_NIGHT;
    else if (mode == QCamera::ExposureAuto) sceneMode = GST_PHOTOGRAPHY_SCENE_MODE_AUTO;

    config.scene_mode = sceneMode;
    gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
}

QCamera::ExposureModes QGstreamerCameraExposureControl::supportedExposureModes() const
{
    //Similar mode names can be found in gst as GstSceneMode
    QCamera::ExposureModes modes;
    modes |= QCamera::ExposureManual;
    modes |= QCamera::ExposurePortrait;
    modes |= QCamera::ExposureSports;
    modes |= QCamera::ExposureNight;
    modes |= QCamera::ExposureAuto;

    //No direct mapping available for GST_PHOTOGRAPHY_SCENE_MODE_CLOSEUP and
    //GST_PHOTOGRAPHY_SCENE_MODE_LANDSCAPE

    return modes;
}

qreal QGstreamerCameraExposureControl::exposureCompensation() const
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    return config.ev_compensation;
}

void QGstreamerCameraExposureControl::setExposureCompensation(qreal ev)
{
    GstPhotoSettings config;
    gst_photography_get_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
    config.ev_compensation = ev;
    gst_photography_set_config(GST_PHOTOGRAPHY(&m_camerabin), &config);
}

QCamera::MeteringMode QGstreamerCameraExposureControl::meteringMode() const
{
    return QCamera::MeteringAverage;
}

void QGstreamerCameraExposureControl::setMeteringMode(QCamera::MeteringMode mode)
{
    //pass
}

QCamera::MeteringModes QGstreamerCameraExposureControl::supportedMeteringModes() const
{
    QCamera::MeteringModes modes;
    modes |= QCamera::MeteringAverage;
    return modes;
}

int QGstreamerCameraExposureControl::isoSensitivity() const
{
}

QList<int> QGstreamerCameraExposureControl::supportedIsoSensitivities(bool *continuous) const
{
}

void QGstreamerCameraExposureControl::setManualIsoSensitivity(int iso)
{
}

void QGstreamerCameraExposureControl::setAutoIsoSensitivity()
{
}

qreal QGstreamerCameraExposureControl::aperture() const
{
}

QList<qreal> QGstreamerCameraExposureControl::supportedApertures(bool *continuous) const
{
}

void QGstreamerCameraExposureControl::setManualAperture(qreal aperture)
{
}

void QGstreamerCameraExposureControl::setAutoAperture()
{
}

qreal QGstreamerCameraExposureControl::shutterSpeed() const
{
}

QList<qreal> QGstreamerCameraExposureControl::supportedShutterSpeeds(bool *continuous) const
{
}

void QGstreamerCameraExposureControl::setManualShutterSpeed(qreal seconds)
{
}

void QGstreamerCameraExposureControl::setAutoShutterSpeed()
{
}

bool QGstreamerCameraExposureControl::isExposureLocked() const
{
}

void QGstreamerCameraExposureControl::lockExposure()
{
}

void QGstreamerCameraExposureControl::unlockExposure()
{
}

<|endoftext|>


<commit_before><commit_msg>Обновление библиотек<commit_after><|endoftext|>


<commit_before>// ==========================================================================
//                   NGS: Regions of Interest Analysis
// ==========================================================================
// Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Bernd Jagla <bernd.jagla@pasteur.fr>
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================

#include "project_interval.h"

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::pushBed()
// ----------------------------------------------------------------------------

void IntersectBed::pushBed(TBedRecord const & bedRecord)
{
    if (options.verbosity >= 2)
    {
        std::cerr << "pushBed()\n"
                  << "  ";
        writeRecord(std::cerr, bedRecord, seqan::Bed());
    }

    // Handle contig transition, we can unconditionally update rId.
    if (bedRecord.ref != ref)
        finishContig();
    ref = bedRecord.ref;

    // Register new BED record.
    bedRecords.push_back(bedRecord);
}

// ----------------------------------------------------------------------------
// Member Function IntersectBed::writeEmptyBed()
// ----------------------------------------------------------------------------

void IntersectBed::writeEmptyBed(seqan::BedRecord<seqan::Bed6> const & bedRecord)
{
    seqan::RoiRecord roiRecord;
    roiRecord.ref = bedRecord.ref;
    roiRecord.beginPos = bedRecord.beginPos;
    roiRecord.endPos = bedRecord.endPos;
    roiRecord.strand = bedRecord.strand;
    roiRecord.name = bedRecord.name;
    roiRecord.len = roiRecord.endPos - roiRecord.beginPos;
    roiRecord.countMax = 0;
    for (int i = 0; i < (int)roiRecord.len; ++i)
        appendValue(roiRecord.count, 0);

    writeRecord(roiFileOut, roiRecord);
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::processFirstBedRecord()
// ----------------------------------------------------------------------------

// Return true iff lhs and rhs overlap (both are BED or ROI records).
template <typename TLeft, typename TRight>
bool overlap(TLeft const & lhs, TRight const & rhs)
{
    return (rhs.beginPos < lhs.endPos) && (lhs.beginPos < rhs.endPos);
}

void IntersectBed::processFirstBedRecord()
{
    if (options.verbosity >= 2)
    {
        std::cerr << "processFirstBedRecord()\n";
        if (!bedRecords.empty())
        {
            std::cerr << "  ";
            writeRecord(std::cerr, bedRecords.front(), seqan::Bed());
        }
    }

    // When computing symmetric difference, we write out the BED record as ROI if there is no overlapping ROI record.
    if (options.mode == IntersectBedOptions::DIFF)
    {
        if (roiRecords.empty() || roiRecords.front().beginPos >= bedRecords.front().endPos)
        {
            writeEmptyBed(bedRecords.front());
            return;
        }
    }

    if (roiRecords.empty())
        return;

    // When in DIFF mode:  Mark all ROI records overlapping with current front BED record as such and stop.
    typedef std::list<TRoiRecord>::/*const_*/iterator TRoiIter;
    if (options.mode == IntersectBedOptions::DIFF)
    {
        for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it)
            if (overlap(*it, bedRecords.front()))
                back(it->data)[0] = '*';  // Mark as overlapping with BED.
        return;
    }

    // Get range of ROI records overlapping with BED record.
    TRoiIter rangeBegin = roiRecords.begin();
    TRoiIter rangeEnd = rangeBegin;
    for (; rangeEnd != roiRecords.end() && overlap(*rangeEnd, bedRecords.front()); ++rangeEnd)
    {
        if (options.verbosity >= 2)
        {
            std::cerr << "ROI RECORD\t";
            writeRecord(std::cerr, *rangeEnd, seqan::Roi());
        }
        continue;
    }

    // ------------------------------------------------------------------------
    // Create a result ROI from that depending on the configuration.
    // ------------------------------------------------------------------------

    // Compute the smallest begin position and the largest end position of BED and all ROI objects.
    TBedRecord const & bedRecord = bedRecords.front();
    int beginPos = bedRecord.beginPos;
    int endPos = bedRecord.endPos;
    if (options.verbosity >= 2)
        std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n";
    for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)
    {
        if (options.verbosity >= 2)
            std::cerr << "it->beginPos, it->endPos == " << it->beginPos << ", " << it->endPos << "\n";
        beginPos = std::min(it->beginPos, beginPos);
        endPos = std::max(it->endPos, endPos);
        if (options.verbosity >= 2)
            std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n";
    }

    // Create bitmap marking positions as connected/covered.
    seqan::String<bool> connected;
    resize(connected, endPos - beginPos, false);
    updateConnectivity(connected, beginPos, bedRecord, rangeBegin, rangeEnd);

    // Create array with counts.
    seqan::String<int> counts;
    resize(counts, endPos - beginPos, 0);
    for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)
        for (unsigned j = it->beginPos - beginPos, i = 0; i < length(it->count); ++i, ++j)
            counts[j] += it->count[i];  // TODO(holtgrew): Increment or simply set?

    // Write resulting intervals to output file.
    writeRois(connected, counts, beginPos, bedRecord);
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::cleanRoiRecords()
// ----------------------------------------------------------------------------

void IntersectBed::cleanRoiRecords()
{
    if (options.verbosity >= 2)
    {
        std::cerr << "cleanRoiRecords()\n";
    }

    while (!roiRecords.empty() && (bedRecords.empty() || roiRecords.front().endPos <= bedRecords.front().beginPos))
    {
        // Remove data from front ROI, write it out, remove it.
        if (options.mode == IntersectBedOptions::DIFF && back(roiRecords.front().data)[0] == '.')
        {
            clear(roiRecords.front().data);
            writeRecord(roiFileOut, roiRecords.front());
        }
        roiRecords.pop_front();
    }
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::pushRoi()
// ----------------------------------------------------------------------------

void IntersectBed::pushRoi(TRoiRecord const & roiRecord)
{
    if (options.verbosity >= 2)
    {
        std::cerr << "pushRoi()\n"
                  << "  ";
        writeRecord(std::cerr, roiRecord, seqan::Roi());
    }

    // Handle contig transition, we can unconditionally update ref.
    if (roiRecord.ref != ref)
        finishContig();
    ref = roiRecord.ref;

    // Complete processing all BED records that cannot overlap with roiRecord.  After removing each BED record, remove
    // all ROI records that do not overlap with first BED record any more.
    while (!empty(bedRecords) && bedRecords.front().endPos <= roiRecord.beginPos)
    {
        processFirstBedRecord();
        bedRecords.pop_front();
        cleanRoiRecords();
    }

    // Finally, register ROI records.
    roiRecords.push_back(roiRecord);
    // Mark ROI record as not touched yet.  We do this using the data entry.
    appendValue(roiRecords.back().data, ".");
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::finishContig()
// ----------------------------------------------------------------------------

void IntersectBed::finishContig()
{
    if (options.verbosity >= 2)
        std::cerr << "finishContig()\n";

    while (!empty(bedRecords))
    {
        processFirstBedRecord();
        bedRecords.pop_front();
    }

    cleanRoiRecords();
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::updateConnectivity()
// ----------------------------------------------------------------------------

void IntersectBed::updateConnectivity(seqan::String<bool> & bitmap,
                                      int beginPos,  // position of bitmap[0]
                                      seqan::BedRecord<seqan::Bed6> const & bedRecord,
                                      std::list<TRoiRecord>::const_iterator const & rangeBegin,
                                      std::list<TRoiRecord>::const_iterator const & rangeEnd)
{
    if (options.verbosity >= 2)
        std::cerr << "updateConnectivity()\n";

    typedef std::list<TRoiRecord>::const_iterator TRoiIter;

    switch (options.mode)
    {
        case IntersectBedOptions::PROJECTION:
            // Mark whole BED record range as covered.
            for (int pos = bedRecord.beginPos; pos != bedRecord.endPos; ++pos)
                bitmap[pos - beginPos] = true;
            break;
        case IntersectBedOptions::INTERSECTION:
            // Mark intersection of BED record and ROI records as covered.
            for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)
            {
                for (int pos = it->beginPos; pos != it->endPos; ++pos)
                    if (pos >= bedRecord.beginPos && pos < bedRecord.endPos)
                        bitmap[pos - beginPos] = true;
            }
            break;
        case IntersectBedOptions::UNION:
            // Mark union of BED and ROI intervals as being covered.
            for (unsigned i = 0; i < length(bitmap); ++i)
                bitmap[i] = true;
            break;
        case IntersectBedOptions::DIFF:
        default:
            SEQAN_FAIL("Cannot reach here!");
    }
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::writeRois()
// ----------------------------------------------------------------------------

void IntersectBed::writeRois(seqan::String<bool> const & bitmap,
                             seqan::String<int> const & counts,
                             int beginPos,  // position of bitmap[0] and counts[0]
                             seqan::BedRecord<seqan::Bed6> const & bedRecord)
{
    // We will build a string of ranges in bitmap/counts for writing out.  The bitmap is used depending on the
    // combination mode.
    typedef seqan::Pair<int, int> TIntPair;
    seqan::String<TIntPair> pairs;
    // We also generate the names of the new regions.
    seqan::StringSet<seqan::CharString> names;

    switch (options.mode)
    {
        case IntersectBedOptions::PROJECTION:
            // Use BED range only.
            appendValue(pairs, TIntPair(bedRecord.beginPos - beginPos, bedRecord.endPos - beginPos));
            break;
        case IntersectBedOptions::INTERSECTION:
            // Search for 0/1 and 1/0 flanks.
            {
                bool state = bitmap[0];
                int lastFlank = 0;
                for (unsigned i = 1; i < length(bitmap); ++i)
                {
                    if (state)
                    {
                        if (!bitmap[i])  // Found a 1/0 flank.
                        {
                            appendValue(pairs, TIntPair(lastFlank, i));
                            state = false;
                            lastFlank = i;
                        }
                    }
                    else
                    {
                        if (bitmap[i])  // Found a 0/1 flank.
                        {
                            state = true;
                            lastFlank = i;
                        }
                    }
                }
                if (state)
                    appendValue(pairs, TIntPair(lastFlank, length(bitmap)));
            }
            break;
        case IntersectBedOptions::UNION:
            // Use whole range, including overlaps to the left of right.
            appendValue(pairs, TIntPair(0, length(counts)));
            break;
        case IntersectBedOptions::DIFF:
            SEQAN_FAIL("Difference does not implemented yet!");
            break;
        default:
            SEQAN_FAIL("Cannot reach here!");
    }

    if (options.verbosity >= 2)
        std::cerr << "Adding " << length(pairs) << " for BED " << bedRecord.name << "\n";

    for (unsigned i = 0; i < length(pairs); ++i)
    {
        std::stringstream ss;
        ss << bedRecord.name << "_" << i;
        appendValue(names, ss.str());
    }

    seqan::RoiRecord record;
    for (unsigned i = 0; i < length(pairs); ++i)
    {
        clear(record);

        record.ref = bedRecord.ref;
        record.beginPos = beginPos + pairs[i].i1;
        record.endPos = beginPos + pairs[i].i2;
        record.len = record.endPos - record.beginPos;
        record.name = names[i];
        record.strand = bedRecord.strand;
        record.countMax = 0;
        resize(record.count, pairs[i].i2 - pairs[i].i1, 0);
        for (int k = 0, j = pairs[i].i1; j != pairs[i].i2; ++j, ++k)
        {
            record.countMax = std::max(record.countMax, (unsigned)counts[j]);
            record.count[k] = counts[j];
        }

        writeRecord(roiFileOut, record);
    }
}

<commit_msg>[FIX] Use list member function empty instead of global empty function.<commit_after>// ==========================================================================
//                   NGS: Regions of Interest Analysis
// ==========================================================================
// Copyright (c) 2012-2013, Bernd Jagla, Institut Pasteur
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================
// Author: Bernd Jagla <bernd.jagla@pasteur.fr>
// Author: Manuel Holtgrewe <manuel.holtgrewe@fu-berlin.de>
// ==========================================================================

#include "project_interval.h"

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::pushBed()
// ----------------------------------------------------------------------------

void IntersectBed::pushBed(TBedRecord const & bedRecord)
{
    if (options.verbosity >= 2)
    {
        std::cerr << "pushBed()\n"
                  << "  ";
        writeRecord(std::cerr, bedRecord, seqan::Bed());
    }

    // Handle contig transition, we can unconditionally update rId.
    if (bedRecord.ref != ref)
        finishContig();
    ref = bedRecord.ref;

    // Register new BED record.
    bedRecords.push_back(bedRecord);
}

// ----------------------------------------------------------------------------
// Member Function IntersectBed::writeEmptyBed()
// ----------------------------------------------------------------------------

void IntersectBed::writeEmptyBed(seqan::BedRecord<seqan::Bed6> const & bedRecord)
{
    seqan::RoiRecord roiRecord;
    roiRecord.ref = bedRecord.ref;
    roiRecord.beginPos = bedRecord.beginPos;
    roiRecord.endPos = bedRecord.endPos;
    roiRecord.strand = bedRecord.strand;
    roiRecord.name = bedRecord.name;
    roiRecord.len = roiRecord.endPos - roiRecord.beginPos;
    roiRecord.countMax = 0;
    for (int i = 0; i < (int)roiRecord.len; ++i)
        appendValue(roiRecord.count, 0);

    writeRecord(roiFileOut, roiRecord);
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::processFirstBedRecord()
// ----------------------------------------------------------------------------

// Return true iff lhs and rhs overlap (both are BED or ROI records).
template <typename TLeft, typename TRight>
bool overlap(TLeft const & lhs, TRight const & rhs)
{
    return (rhs.beginPos < lhs.endPos) && (lhs.beginPos < rhs.endPos);
}

void IntersectBed::processFirstBedRecord()
{
    if (options.verbosity >= 2)
    {
        std::cerr << "processFirstBedRecord()\n";
        if (!bedRecords.empty())
        {
            std::cerr << "  ";
            writeRecord(std::cerr, bedRecords.front(), seqan::Bed());
        }
    }

    // When computing symmetric difference, we write out the BED record as ROI if there is no overlapping ROI record.
    if (options.mode == IntersectBedOptions::DIFF)
    {
        if (roiRecords.empty() || roiRecords.front().beginPos >= bedRecords.front().endPos)
        {
            writeEmptyBed(bedRecords.front());
            return;
        }
    }

    if (roiRecords.empty())
        return;

    // When in DIFF mode:  Mark all ROI records overlapping with current front BED record as such and stop.
    typedef std::list<TRoiRecord>::/*const_*/iterator TRoiIter;
    if (options.mode == IntersectBedOptions::DIFF)
    {
        for (TRoiIter it = roiRecords.begin(); it != roiRecords.end(); ++it)
            if (overlap(*it, bedRecords.front()))
                back(it->data)[0] = '*';  // Mark as overlapping with BED.
        return;
    }

    // Get range of ROI records overlapping with BED record.
    TRoiIter rangeBegin = roiRecords.begin();
    TRoiIter rangeEnd = rangeBegin;
    for (; rangeEnd != roiRecords.end() && overlap(*rangeEnd, bedRecords.front()); ++rangeEnd)
    {
        if (options.verbosity >= 2)
        {
            std::cerr << "ROI RECORD\t";
            writeRecord(std::cerr, *rangeEnd, seqan::Roi());
        }
        continue;
    }

    // ------------------------------------------------------------------------
    // Create a result ROI from that depending on the configuration.
    // ------------------------------------------------------------------------

    // Compute the smallest begin position and the largest end position of BED and all ROI objects.
    TBedRecord const & bedRecord = bedRecords.front();
    int beginPos = bedRecord.beginPos;
    int endPos = bedRecord.endPos;
    if (options.verbosity >= 2)
        std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n";
    for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)
    {
        if (options.verbosity >= 2)
            std::cerr << "it->beginPos, it->endPos == " << it->beginPos << ", " << it->endPos << "\n";
        beginPos = std::min(it->beginPos, beginPos);
        endPos = std::max(it->endPos, endPos);
        if (options.verbosity >= 2)
            std::cerr << "beginPos, endPos == " << beginPos << ", " << endPos << "\n";
    }

    // Create bitmap marking positions as connected/covered.
    seqan::String<bool> connected;
    resize(connected, endPos - beginPos, false);
    updateConnectivity(connected, beginPos, bedRecord, rangeBegin, rangeEnd);

    // Create array with counts.
    seqan::String<int> counts;
    resize(counts, endPos - beginPos, 0);
    for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)
        for (unsigned j = it->beginPos - beginPos, i = 0; i < length(it->count); ++i, ++j)
            counts[j] += it->count[i];  // TODO(holtgrew): Increment or simply set?

    // Write resulting intervals to output file.
    writeRois(connected, counts, beginPos, bedRecord);
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::cleanRoiRecords()
// ----------------------------------------------------------------------------

void IntersectBed::cleanRoiRecords()
{
    if (options.verbosity >= 2)
    {
        std::cerr << "cleanRoiRecords()\n";
    }

    while (!roiRecords.empty() && (bedRecords.empty() || roiRecords.front().endPos <= bedRecords.front().beginPos))
    {
        // Remove data from front ROI, write it out, remove it.
        if (options.mode == IntersectBedOptions::DIFF && back(roiRecords.front().data)[0] == '.')
        {
            clear(roiRecords.front().data);
            writeRecord(roiFileOut, roiRecords.front());
        }
        roiRecords.pop_front();
    }
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::pushRoi()
// ----------------------------------------------------------------------------

void IntersectBed::pushRoi(TRoiRecord const & roiRecord)
{
    if (options.verbosity >= 2)
    {
        std::cerr << "pushRoi()\n"
                  << "  ";
        writeRecord(std::cerr, roiRecord, seqan::Roi());
    }

    // Handle contig transition, we can unconditionally update ref.
    if (roiRecord.ref != ref)
        finishContig();
    ref = roiRecord.ref;

    // Complete processing all BED records that cannot overlap with roiRecord.  After removing each BED record, remove
    // all ROI records that do not overlap with first BED record any more.
    while (!bedRecords.empty() && bedRecords.front().endPos <= roiRecord.beginPos)
    {
        processFirstBedRecord();
        bedRecords.pop_front();
        cleanRoiRecords();
    }

    // Finally, register ROI records.
    roiRecords.push_back(roiRecord);
    // Mark ROI record as not touched yet.  We do this using the data entry.
    appendValue(roiRecords.back().data, ".");
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::finishContig()
// ----------------------------------------------------------------------------

void IntersectBed::finishContig()
{
    if (options.verbosity >= 2)
        std::cerr << "finishContig()\n";

    while (!bedRecords.empty())
    {
        processFirstBedRecord();
        bedRecords.pop_front();
    }

    cleanRoiRecords();
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::updateConnectivity()
// ----------------------------------------------------------------------------

void IntersectBed::updateConnectivity(seqan::String<bool> & bitmap,
                                      int beginPos,  // position of bitmap[0]
                                      seqan::BedRecord<seqan::Bed6> const & bedRecord,
                                      std::list<TRoiRecord>::const_iterator const & rangeBegin,
                                      std::list<TRoiRecord>::const_iterator const & rangeEnd)
{
    if (options.verbosity >= 2)
        std::cerr << "updateConnectivity()\n";

    typedef std::list<TRoiRecord>::const_iterator TRoiIter;

    switch (options.mode)
    {
        case IntersectBedOptions::PROJECTION:
            // Mark whole BED record range as covered.
            for (int pos = bedRecord.beginPos; pos != bedRecord.endPos; ++pos)
                bitmap[pos - beginPos] = true;
            break;
        case IntersectBedOptions::INTERSECTION:
            // Mark intersection of BED record and ROI records as covered.
            for (TRoiIter it = rangeBegin; it != rangeEnd; ++it)
            {
                for (int pos = it->beginPos; pos != it->endPos; ++pos)
                    if (pos >= bedRecord.beginPos && pos < bedRecord.endPos)
                        bitmap[pos - beginPos] = true;
            }
            break;
        case IntersectBedOptions::UNION:
            // Mark union of BED and ROI intervals as being covered.
            for (unsigned i = 0; i < length(bitmap); ++i)
                bitmap[i] = true;
            break;
        case IntersectBedOptions::DIFF:
        default:
            SEQAN_FAIL("Cannot reach here!");
    }
}

// ----------------------------------------------------------------------------
// Member Functions IntersectBed::writeRois()
// ----------------------------------------------------------------------------

void IntersectBed::writeRois(seqan::String<bool> const & bitmap,
                             seqan::String<int> const & counts,
                             int beginPos,  // position of bitmap[0] and counts[0]
                             seqan::BedRecord<seqan::Bed6> const & bedRecord)
{
    // We will build a string of ranges in bitmap/counts for writing out.  The bitmap is used depending on the
    // combination mode.
    typedef seqan::Pair<int, int> TIntPair;
    seqan::String<TIntPair> pairs;
    // We also generate the names of the new regions.
    seqan::StringSet<seqan::CharString> names;

    switch (options.mode)
    {
        case IntersectBedOptions::PROJECTION:
            // Use BED range only.
            appendValue(pairs, TIntPair(bedRecord.beginPos - beginPos, bedRecord.endPos - beginPos));
            break;
        case IntersectBedOptions::INTERSECTION:
            // Search for 0/1 and 1/0 flanks.
            {
                bool state = bitmap[0];
                int lastFlank = 0;
                for (unsigned i = 1; i < length(bitmap); ++i)
                {
                    if (state)
                    {
                        if (!bitmap[i])  // Found a 1/0 flank.
                        {
                            appendValue(pairs, TIntPair(lastFlank, i));
                            state = false;
                            lastFlank = i;
                        }
                    }
                    else
                    {
                        if (bitmap[i])  // Found a 0/1 flank.
                        {
                            state = true;
                            lastFlank = i;
                        }
                    }
                }
                if (state)
                    appendValue(pairs, TIntPair(lastFlank, length(bitmap)));
            }
            break;
        case IntersectBedOptions::UNION:
            // Use whole range, including overlaps to the left of right.
            appendValue(pairs, TIntPair(0, length(counts)));
            break;
        case IntersectBedOptions::DIFF:
            SEQAN_FAIL("Difference does not implemented yet!");
            break;
        default:
            SEQAN_FAIL("Cannot reach here!");
    }

    if (options.verbosity >= 2)
        std::cerr << "Adding " << length(pairs) << " for BED " << bedRecord.name << "\n";

    for (unsigned i = 0; i < length(pairs); ++i)
    {
        std::stringstream ss;
        ss << bedRecord.name << "_" << i;
        appendValue(names, ss.str());
    }

    seqan::RoiRecord record;
    for (unsigned i = 0; i < length(pairs); ++i)
    {
        clear(record);

        record.ref = bedRecord.ref;
        record.beginPos = beginPos + pairs[i].i1;
        record.endPos = beginPos + pairs[i].i2;
        record.len = record.endPos - record.beginPos;
        record.name = names[i];
        record.strand = bedRecord.strand;
        record.countMax = 0;
        resize(record.count, pairs[i].i2 - pairs[i].i1, 0);
        for (int k = 0, j = pairs[i].i1; j != pairs[i].i2; ++j, ++k)
        {
            record.countMax = std::max(record.countMax, (unsigned)counts[j]);
            record.count[k] = counts[j];
        }

        writeRecord(roiFileOut, record);
    }
}

<|endoftext|>


<commit_before>#include <Poco/Exception.h>
#include <Poco/Data/Statement.h>
#include <Poco/Data/RecordSet.h>
#include <Poco/Data/Row.h>
#include <Poco/Data/RowIterator.h>

#include "di/Injectable.h"
#include "dao/poco/PocoSQLLocationDao.h"
#include "dao/poco/PocoDaoManager.h"
#include "transaction/TransactionManager.h"

using namespace std;
using namespace Poco;
using namespace Poco::Data;
using namespace Poco::Data::Keywords;
using namespace BeeeOn;

BEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLLocationDao)
BEEEON_OBJECT_CASTABLE(LocationDao)
BEEEON_OBJECT_REF("daoManager", &PocoSQLLocationDao::setDaoManager)
BEEEON_OBJECT_REF("transactionManager", &PocoSQLLocationDao::setTransactionManager)
BEEEON_OBJECT_REF("sqlLoader", &PocoSQLLocationDao::setSQLLoader)
BEEEON_OBJECT_HOOK("done", &PocoSQLLocationDao::loadQueries)
BEEEON_OBJECT_END(BeeeOn, PocoSQLLocationDao)

PocoSQLLocationDao::PocoSQLLocationDao()
{
	registerQuery(m_queryCreate);
	registerQuery(m_queryUpdate);
	registerQuery(m_queryRemove);
	registerQuery(m_queryFetchById);
	registerQuery(m_queryFetchByIdAndGatewayId);
	registerQuery(m_queryFetchByGatewayId);
}

void PocoSQLLocationDao::create(Location &location)
{
	location.setId(LocationID::random());
	string id(location.id().toString());
	string name(location.name());
	string gatewayID(location.gateway().id().toString());

	Statement sql = (session() << m_queryCreate(),
		use(id, "id"),
		use(name, "name"),
		use(gatewayID, "gateway_id")
	);

	execute(sql);
}

bool PocoSQLLocationDao::fetch(Location &location)
{
	assureHasId(location);
	string id(location.id().toString());

	Statement sql = (session() << m_queryFetchById(),
		use(id, "id")
	);

	if (execute(sql) == 0)
		return false;

	RecordSet result(sql);
	return parseSingle(result, location);
}

bool PocoSQLLocationDao::fetchFrom(Location &location, const Gateway &gateway)
{
	assureHasId(location);
	assureHasId(gateway);

	string id(location.id().toString());
	string gatewayID(gateway.id().toString());

	Statement sql = (session() << m_queryFetchByIdAndGatewayId(),
		use(id, "id"),
		use(gatewayID, "gateway_id")
	);

	if (execute(sql) == 0)
		return false;

	RecordSet result(sql);
	return parseSingle(result, location);
}

void PocoSQLLocationDao::fetchBy(std::vector<Location> &locations,
		const Gateway &gateway)
{
	assureHasId(gateway);

	string gatewayID(gateway.id().toString());

	Statement sql = (session() << m_queryFetchByGatewayId(),
		use(gatewayID, "gateway_id")
	);

	execute(sql);
	RecordSet result(sql);
	parseMany(result, locations);
}

bool PocoSQLLocationDao::update(Location &location)
{
	assureHasId(location);
	assureHasId(location.gateway());

	string id(location.id().toString());
	string name(location.name());

	Statement sql = (session() << m_queryUpdate(),
		use(name, "name"),
		use(id, "id")
	);

	return execute(sql) > 0;
}

bool PocoSQLLocationDao::remove(const Location &location)
{
	assureHasId(location);
	string id(location.id().toString());

	Statement sql = (session() << m_queryRemove(),
		use(id, "id")
	);

	return execute(sql) > 0;
}

bool PocoSQLLocationDao::parseSingle(RecordSet &result, Location &location,
		const string &prefix)
{
	if (result.begin() == result.end())
		return false;

	return parseSingle(*result.begin(), location, prefix);
}

bool PocoSQLLocationDao::parseSingle(Row &result, Location &location,
		const string &prefix)
{
	if (hasColumn(result, prefix + "id"))
		location.setId(LocationID::parse(result[prefix + "id"]));

	location.setName(result[prefix + "name"]);

	Gateway gateway(GatewayID::parse(result[prefix + "gateway_id"]));
	location.setGateway(gateway);

	markLoaded(location);
	return true;
}

bool PocoSQLLocationDao::parseIfIDNotNull(Row &result, Location &location,
		const string &prefix)
{
	const string id = emptyWhenNull(result[prefix + "id"]);
	if (id.empty())
		return false;

	location.setId(LocationID::parse(id));

	if (hasColumn(result, prefix + "name"))
		location.setName(result[prefix + "name"]);

	markLoaded(location);
	return true;
}
<commit_msg>PocoSQLLocationDao: fix order of arguments to locations.update<commit_after>#include <Poco/Exception.h>
#include <Poco/Data/Statement.h>
#include <Poco/Data/RecordSet.h>
#include <Poco/Data/Row.h>
#include <Poco/Data/RowIterator.h>

#include "di/Injectable.h"
#include "dao/poco/PocoSQLLocationDao.h"
#include "dao/poco/PocoDaoManager.h"
#include "transaction/TransactionManager.h"

using namespace std;
using namespace Poco;
using namespace Poco::Data;
using namespace Poco::Data::Keywords;
using namespace BeeeOn;

BEEEON_OBJECT_BEGIN(BeeeOn, PocoSQLLocationDao)
BEEEON_OBJECT_CASTABLE(LocationDao)
BEEEON_OBJECT_REF("daoManager", &PocoSQLLocationDao::setDaoManager)
BEEEON_OBJECT_REF("transactionManager", &PocoSQLLocationDao::setTransactionManager)
BEEEON_OBJECT_REF("sqlLoader", &PocoSQLLocationDao::setSQLLoader)
BEEEON_OBJECT_HOOK("done", &PocoSQLLocationDao::loadQueries)
BEEEON_OBJECT_END(BeeeOn, PocoSQLLocationDao)

PocoSQLLocationDao::PocoSQLLocationDao()
{
	registerQuery(m_queryCreate);
	registerQuery(m_queryUpdate);
	registerQuery(m_queryRemove);
	registerQuery(m_queryFetchById);
	registerQuery(m_queryFetchByIdAndGatewayId);
	registerQuery(m_queryFetchByGatewayId);
}

void PocoSQLLocationDao::create(Location &location)
{
	location.setId(LocationID::random());
	string id(location.id().toString());
	string name(location.name());
	string gatewayID(location.gateway().id().toString());

	Statement sql = (session() << m_queryCreate(),
		use(id, "id"),
		use(name, "name"),
		use(gatewayID, "gateway_id")
	);

	execute(sql);
}

bool PocoSQLLocationDao::fetch(Location &location)
{
	assureHasId(location);
	string id(location.id().toString());

	Statement sql = (session() << m_queryFetchById(),
		use(id, "id")
	);

	if (execute(sql) == 0)
		return false;

	RecordSet result(sql);
	return parseSingle(result, location);
}

bool PocoSQLLocationDao::fetchFrom(Location &location, const Gateway &gateway)
{
	assureHasId(location);
	assureHasId(gateway);

	string id(location.id().toString());
	string gatewayID(gateway.id().toString());

	Statement sql = (session() << m_queryFetchByIdAndGatewayId(),
		use(id, "id"),
		use(gatewayID, "gateway_id")
	);

	if (execute(sql) == 0)
		return false;

	RecordSet result(sql);
	return parseSingle(result, location);
}

void PocoSQLLocationDao::fetchBy(std::vector<Location> &locations,
		const Gateway &gateway)
{
	assureHasId(gateway);

	string gatewayID(gateway.id().toString());

	Statement sql = (session() << m_queryFetchByGatewayId(),
		use(gatewayID, "gateway_id")
	);

	execute(sql);
	RecordSet result(sql);
	parseMany(result, locations);
}

bool PocoSQLLocationDao::update(Location &location)
{
	assureHasId(location);
	assureHasId(location.gateway());

	string id(location.id().toString());
	string name(location.name());

	Statement sql = (session() << m_queryUpdate(),
		use(id, "id"),
		use(name, "name")
	);

	return execute(sql) > 0;
}

bool PocoSQLLocationDao::remove(const Location &location)
{
	assureHasId(location);
	string id(location.id().toString());

	Statement sql = (session() << m_queryRemove(),
		use(id, "id")
	);

	return execute(sql) > 0;
}

bool PocoSQLLocationDao::parseSingle(RecordSet &result, Location &location,
		const string &prefix)
{
	if (result.begin() == result.end())
		return false;

	return parseSingle(*result.begin(), location, prefix);
}

bool PocoSQLLocationDao::parseSingle(Row &result, Location &location,
		const string &prefix)
{
	if (hasColumn(result, prefix + "id"))
		location.setId(LocationID::parse(result[prefix + "id"]));

	location.setName(result[prefix + "name"]);

	Gateway gateway(GatewayID::parse(result[prefix + "gateway_id"]));
	location.setGateway(gateway);

	markLoaded(location);
	return true;
}

bool PocoSQLLocationDao::parseIfIDNotNull(Row &result, Location &location,
		const string &prefix)
{
	const string id = emptyWhenNull(result[prefix + "id"]);
	if (id.empty())
		return false;

	location.setId(LocationID::parse(id));

	if (hasColumn(result, prefix + "name"))
		location.setName(result[prefix + "name"]);

	markLoaded(location);
	return true;
}
<|endoftext|>


<commit_before>/* Copyright 2007-2015 QReal Research Group
 *
 * 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 "trikKitInterpreterCommon/robotModel/real/parts/shell.h"

#include <qrutils/inFile.h>

using namespace trik::robotModel::real::parts;
using namespace kitBase::robotModel;

Shell::Shell(const DeviceInfo &info, const PortInfo &port
		, utils::robotCommunication::TcpRobotCommunicator &tcpRobotCommunicator)
	: robotModel::parts::TrikShell(info, port)
	, mRobotCommunicator(tcpRobotCommunicator)
{
	connect(&mRobotCommunicator, &utils::robotCommunication::TcpRobotCommunicator::printText
			, this, &Shell::textPrinted);
}

void Shell::say(const QString &text)
{
	const QString pathToCommand = ":/trikQts/templates/say.t";
	const QString directCommand = utils::InFile::readAll(pathToCommand)
			.replace("@@TEXT@@", "\"" + text + "\"") + "script.run();";

	mRobotCommunicator.runDirectCommand(directCommand);
}

void Shell::runCommand(const QString &command)
{
	const QString pathToCommand = ":/trikQts/templates/system.t";
	const QString directCommand = utils::InFile::readAll(pathToCommand)
			.replace("@@COMMAND@@", command) + "script.run();";

	mRobotCommunicator.runDirectCommand(directCommand);
}

void Shell::runCode(const QString &code)
{
	mRobotCommunicator.runDirectCommand(code);
}

void Shell::writeToFile(const QString &filePath, const QString &text)
{
	const QString pathToCommand = ":/trikQts/templates/files/writeFile.t";
	const QString directCommand = utils::InFile::readAll(pathToCommand)
			.replace("@@FILE@@", filePath).replace("@@TEXT@@", "\"" + text + "\"") + "script.run();";

	mRobotCommunicator.runDirectCommand(directCommand);
}

void Shell::removeFile(const QString &filePath)
{
	const QString pathToCommand = ":/trikQts/templates/files/removeFile.t";
	const QString directCommand = utils::InFile::readAll(pathToCommand)
			.replace("@@FILE@@", filePath) + "script.run();";

	mRobotCommunicator.runDirectCommand(directCommand);
}

void Shell::print(const QString &text)
{
	const QString pathToCommand = ":/trikQts/templates/functions/print.t";
	const QString directCommand = utils::InFile::readAll(pathToCommand)
			.replace("@@ARGUMENT@@", "\"" + text + "\"") + ";script.run();";

	mRobotCommunicator.runDirectCommand(directCommand);
}

void Shell::initVideoStreaming(QString qual, QString blackwhite)
{
	const QString shellToExecute = QString("\"/etc/init.d/mjpg-encoder-ov7670 start --jpeg-qual ") + qual +
																	QString(" --white-black ") + blackwhite +
																	QString(" && /etc/init.d/mjpg-streamer-ov7670.sh start\"");
	  runCommand(shellToExecute);
}
<commit_msg>JpgEncoder: unnecessary duplicate file deleted<commit_after><|endoftext|>