<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbMultiChannelExtractROI.h"
#include "otbStreamingShrinkImageFilter.h"

namespace otb
{
namespace Wrapper
{

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

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

  itkTypeMacro(Quicklook, otb::Application);

  /** Typedefs */
  typedef float InputPixelType;
  typedef float OutputPixelType;
  typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType >   ExtractROIFilterType;
  typedef ExtractROIFilterType::InputImageType InputImageType;
  typedef ExtractROIFilterType::OutputImageType OutputImageType;
  typedef otb::StreamingShrinkImageFilter
        <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType;

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("Quicklook");
    SetDescription("Generates a subsampled version of an image extract");
    SetDocName("Quick Look");
    SetDocLongDescription("Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\n "
                          "This extract is subsampled using the ratio OR the output image Size.");
    SetDocLimitations(" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\n"
                      "Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",   "Input Image");
    SetParameterDescription( "in", "The image to read" );

    AddParameter(ParameterType_OutputImage, "out",  "Output Image");
    SetParameterDescription( "out" , "The subsampled image" );

    AddParameter(ParameterType_ListView, "cl", "Channel List");
    SetParameterDescription( "cl" , "Selected channels" );
    MandatoryOff("cl");

    AddParameter(ParameterType_Int, "rox",  "ROI Origin X");
    SetParameterDescription( "rox" , "first point of ROI in x-direction" );
    MandatoryOff("rox");

    AddParameter(ParameterType_Int, "roy",  "ROI Origin Y");
    SetParameterDescription( "roy" , "first point of ROI in y-direction" );
    MandatoryOff("roy");

    AddParameter(ParameterType_Int, "rsx",  "ROI Size X");
    SetParameterDescription( "rsx" , "size of ROI in x-direction" );
    MandatoryOff("rsx");

    AddParameter(ParameterType_Int, "rsy",  "ROI Size Y");
    SetParameterDescription( "rsy" , "size of ROI in y-direction" );
    MandatoryOff("rsy");

    AddParameter(ParameterType_Int, "sr",  "Sampling ratio");
    SetParameterDescription( "sr" , "Sampling Ratio, default is 2" );
    SetDefaultParameterInt("sr", 2);
    SetMinimumParameterIntValue("sr", 1);
    MandatoryOff("sr");

    AddParameter(ParameterType_Int, "sx",  "Size X");
    SetParameterDescription( "sx" , "quicklook size in x-direction (used if no sampling ration is given)" );
    MandatoryOff("sx");
    DisableParameter("sx");

    AddParameter(ParameterType_Int, "sy",  "Size Y");
    SetParameterDescription( "sy" , "quicklook size in y-direction (used if no sampling ration is given)" );
    MandatoryOff("sy");
    DisableParameter("sy");

    SetDefaultParameterInt("rox", 0);
    SetDefaultParameterInt("roy", 0);
    SetDefaultParameterInt("rsx", 0);
    SetDefaultParameterInt("rsy", 0);

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "qb_RoadExtract.tif");
    SetDocExampleParameterValue("out", "quicklookImage.tif");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    // Update the sizes only if the user does not defined a size
    if ( HasValue("in") )
      {
      InputImageType::Pointer inImage = GetParameterImage("in");

      InputImageType::RegionType  largestRegion = inImage->GetLargestPossibleRegion();

      // Update the values of the channels to be selected
      unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
      if (nbComponents != GetChoiceKeys("cl").size())
        {
        ClearChoices("cl");
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          std::ostringstream key, item;
          key<<"cl.channel"<<idx+1;
          item<<"Channel"<<idx+1;
          AddChoice(key.str(), item.str());
          }
        }

      if (!HasUserValue("rsx")  && !HasUserValue("rsy") )
        {
        SetParameterInt("rsx",largestRegion.GetSize()[0]);
        SetParameterInt("rsy",largestRegion.GetSize()[1]);
        }

      // Put the limit of the index and the size relative the image
      SetMinimumParameterIntValue("rsx", 0);
      SetMaximumParameterIntValue("rsx", largestRegion.GetSize(0));

      SetMinimumParameterIntValue("rsy", 0);
      SetMaximumParameterIntValue("rsy", largestRegion.GetSize(1));

      SetMinimumParameterIntValue("rox", 0);
      SetMaximumParameterIntValue("rox", largestRegion.GetSize(0)-1);

      SetMinimumParameterIntValue("roy", 0);
      SetMaximumParameterIntValue("roy", largestRegion.GetSize(1)-1);

      // Crop the roi region to be included in the largest possible
      // region
      if(!this->CropRegionOfInterest())
        {
        // Put the index of the ROI to origin and try to crop again
        SetParameterInt("rox",0);
        SetParameterInt("roy",0);
        this->CropRegionOfInterest();
        }
      }

  }

bool CropRegionOfInterest()
  {
    FloatVectorImageType::RegionType region;
    region.SetSize(0,  GetParameterInt("rsx"));
    region.SetSize(1,  GetParameterInt("rsy"));
    region.SetIndex(0, GetParameterInt("rox"));
    region.SetIndex(1, GetParameterInt("roy"));

    if ( HasValue("in") )
      {
        if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
          {
            SetParameterInt( "rsx", region.GetSize(0));
            SetParameterInt( "rsy", region.GetSize(1));
            SetParameterInt( "rox", region.GetIndex(0));
            SetParameterInt( "roy", region.GetIndex(1));
            return true;
          }
      }
    return false;
  }

  void DoExecute() ITK_OVERRIDE
  {
    InputImageType::Pointer inImage = GetParameterImage("in");

    m_ExtractROIFilter = ExtractROIFilterType::New();
    m_ResamplingFilter = ShrinkImageFilterType::New();

    // The image on which the quicklook will be generated
    // Will eventually be the m_ExtractROIFilter output

    if (HasUserValue("rox") || HasUserValue("roy")
        || HasUserValue("rsx") || HasUserValue("rsy")
        || (GetSelectedItems("cl").size() > 0))
      {
      m_ExtractROIFilter->SetInput(inImage);
      m_ExtractROIFilter->SetStartX(GetParameterInt("rox"));
      m_ExtractROIFilter->SetStartY(GetParameterInt("roy"));
      m_ExtractROIFilter->SetSizeX(GetParameterInt("rsx"));
      m_ExtractROIFilter->SetSizeY(GetParameterInt("rsy"));

      if ((GetSelectedItems("cl").size() > 0))
        {
        for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
          {
          m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 );
          }
        }
      else
        {
        unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          m_ExtractROIFilter->SetChannel(idx + 1);
          }
        }
      m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() );
      }
    else
      {
      m_ResamplingFilter->SetInput(inImage);
      }

    unsigned int Ratio = static_cast<unsigned int>(GetParameterInt("sr"));
    unsigned int SamplingRatioX = 1;
    unsigned int SamplingRatioY = 1;

    if ( !HasUserValue("sr") )
      {
      if ( IsParameterEnabled("sx") && IsParameterEnabled("sy") )
        {
        SamplingRatioX =  GetParameterInt("rsx") / GetParameterInt("sx");
        SamplingRatioY =  GetParameterInt("rsy") / GetParameterInt("sy");
        if (SamplingRatioX > Ratio) Ratio = SamplingRatioX;
        if (SamplingRatioY > Ratio) Ratio = SamplingRatioY;
        }
      else
        {
        if ( IsParameterEnabled("sx") )
          {
          Ratio =  GetParameterInt("rsx") / GetParameterInt("sx");
          }
        if ( IsParameterEnabled("sy") )
          {
          Ratio =  GetParameterInt("rsy") / GetParameterInt("sy");
          }
        }
      }

    if ( Ratio < 1)
      {
      otbAppLogFATAL( << "Error in SizeX and/or SizeY : ratio must be greater than 1.");
      return;
      }
    otbAppLogINFO( << "Ratio used: "<<Ratio << ".");

    m_ResamplingFilter->SetShrinkFactor( Ratio );
    m_ResamplingFilter->Update();

    SetParameterOutputImage("out", m_ResamplingFilter->GetOutput());
  }

  ExtractROIFilterType::Pointer m_ExtractROIFilter;
  ShrinkImageFilterType::Pointer m_ResamplingFilter;

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::Quicklook)
<commit_msg>BUG: only modify parameters if different<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbMultiChannelExtractROI.h"
#include "otbStreamingShrinkImageFilter.h"

namespace otb
{
namespace Wrapper
{

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

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

  itkTypeMacro(Quicklook, otb::Application);

  /** Typedefs */
  typedef float InputPixelType;
  typedef float OutputPixelType;
  typedef otb::MultiChannelExtractROI< InputPixelType, OutputPixelType >   ExtractROIFilterType;
  typedef ExtractROIFilterType::InputImageType InputImageType;
  typedef ExtractROIFilterType::OutputImageType OutputImageType;
  typedef otb::StreamingShrinkImageFilter
        <ExtractROIFilterType::OutputImageType, ExtractROIFilterType::OutputImageType> ShrinkImageFilterType;

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("Quicklook");
    SetDescription("Generates a subsampled version of an image extract");
    SetDocName("Quick Look");
    SetDocLongDescription("Generates a subsampled version of an extract of an image defined by ROIStart and ROISize.\n "
                          "This extract is subsampled using the ratio OR the output image Size.");
    SetDocLimitations(" This application does not provide yet the optimal way to decode coarser level of resolution from JPEG2000 images (like in Monteverdi).\n"
                      "Trying to subsampled huge JPEG200 image with the application will lead to poor performances for now.");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",   "Input Image");
    SetParameterDescription( "in", "The image to read" );

    AddParameter(ParameterType_OutputImage, "out",  "Output Image");
    SetParameterDescription( "out" , "The subsampled image" );

    AddParameter(ParameterType_ListView, "cl", "Channel List");
    SetParameterDescription( "cl" , "Selected channels" );
    MandatoryOff("cl");

    AddParameter(ParameterType_Int, "rox",  "ROI Origin X");
    SetParameterDescription( "rox" , "first point of ROI in x-direction" );
    MandatoryOff("rox");

    AddParameter(ParameterType_Int, "roy",  "ROI Origin Y");
    SetParameterDescription( "roy" , "first point of ROI in y-direction" );
    MandatoryOff("roy");

    AddParameter(ParameterType_Int, "rsx",  "ROI Size X");
    SetParameterDescription( "rsx" , "size of ROI in x-direction" );
    MandatoryOff("rsx");

    AddParameter(ParameterType_Int, "rsy",  "ROI Size Y");
    SetParameterDescription( "rsy" , "size of ROI in y-direction" );
    MandatoryOff("rsy");

    AddParameter(ParameterType_Int, "sr",  "Sampling ratio");
    SetParameterDescription( "sr" , "Sampling Ratio, default is 2" );
    SetDefaultParameterInt("sr", 2);
    SetMinimumParameterIntValue("sr", 1);
    MandatoryOff("sr");

    AddParameter(ParameterType_Int, "sx",  "Size X");
    SetParameterDescription( "sx" , "quicklook size in x-direction (used if no sampling ration is given)" );
    MandatoryOff("sx");
    DisableParameter("sx");

    AddParameter(ParameterType_Int, "sy",  "Size Y");
    SetParameterDescription( "sy" , "quicklook size in y-direction (used if no sampling ration is given)" );
    MandatoryOff("sy");
    DisableParameter("sy");

    SetDefaultParameterInt("rox", 0);
    SetDefaultParameterInt("roy", 0);
    SetDefaultParameterInt("rsx", 0);
    SetDefaultParameterInt("rsy", 0);

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "qb_RoadExtract.tif");
    SetDocExampleParameterValue("out", "quicklookImage.tif");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    // Update the sizes only if the user does not defined a size
    if ( HasValue("in") )
      {
      InputImageType::Pointer inImage = GetParameterImage("in");

      InputImageType::RegionType  largestRegion = inImage->GetLargestPossibleRegion();

      // Update the values of the channels to be selected
      unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
      if (nbComponents != GetChoiceKeys("cl").size())
        {
        ClearChoices("cl");
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          std::ostringstream key, item;
          key<<"cl.channel"<<idx+1;
          item<<"Channel"<<idx+1;
          AddChoice(key.str(), item.str());
          }
        }

      if (!HasUserValue("rsx")  && !HasUserValue("rsy") )
        {
        SetParameterInt("rsx",largestRegion.GetSize()[0]);
        SetParameterInt("rsy",largestRegion.GetSize()[1]);
        }

      // Put the limit of the index and the size relative the image
      SetMinimumParameterIntValue("rsx", 0);
      SetMaximumParameterIntValue("rsx", largestRegion.GetSize(0));

      SetMinimumParameterIntValue("rsy", 0);
      SetMaximumParameterIntValue("rsy", largestRegion.GetSize(1));

      SetMinimumParameterIntValue("rox", 0);
      SetMaximumParameterIntValue("rox", largestRegion.GetSize(0)-1);

      SetMinimumParameterIntValue("roy", 0);
      SetMaximumParameterIntValue("roy", largestRegion.GetSize(1)-1);

      // Crop the roi region to be included in the largest possible
      // region
      if(!this->CropRegionOfInterest())
        {
        // Put the index of the ROI to origin and try to crop again
        SetParameterInt("rox",0);
        SetParameterInt("roy",0);
        this->CropRegionOfInterest();
        }
      }

  }

bool CropRegionOfInterest()
  {
    FloatVectorImageType::RegionType region;
    region.SetSize(0,  GetParameterInt("rsx"));
    region.SetSize(1,  GetParameterInt("rsy"));
    region.SetIndex(0, GetParameterInt("rox"));
    region.SetIndex(1, GetParameterInt("roy"));
    FloatVectorImageType::RegionType region0 = region;

    if ( HasValue("in") )
      {
        if (region.Crop(GetParameterImage("in")->GetLargestPossibleRegion()))
          {
            if (region0.GetSize(0) != region.GetSize(0))
              SetParameterInt( "rsx", region.GetSize(0));
            if (region0.GetSize(1) != region.GetSize(1))
              SetParameterInt( "rsy", region.GetSize(1));
            if (region0.GetIndex(0) != region.GetIndex(0))
              SetParameterInt( "rox", region.GetIndex(0));
            if (region0.GetIndex(1) != region.GetIndex(1))
              SetParameterInt( "roy", region.GetIndex(1));
            return true;
          }
      }
    return false;
  }

  void DoExecute() ITK_OVERRIDE
  {
    InputImageType::Pointer inImage = GetParameterImage("in");

    m_ExtractROIFilter = ExtractROIFilterType::New();
    m_ResamplingFilter = ShrinkImageFilterType::New();

    // The image on which the quicklook will be generated
    // Will eventually be the m_ExtractROIFilter output

    if (HasUserValue("rox") || HasUserValue("roy")
        || HasUserValue("rsx") || HasUserValue("rsy")
        || (GetSelectedItems("cl").size() > 0))
      {
      m_ExtractROIFilter->SetInput(inImage);
      m_ExtractROIFilter->SetStartX(GetParameterInt("rox"));
      m_ExtractROIFilter->SetStartY(GetParameterInt("roy"));
      m_ExtractROIFilter->SetSizeX(GetParameterInt("rsx"));
      m_ExtractROIFilter->SetSizeY(GetParameterInt("rsy"));

      if ((GetSelectedItems("cl").size() > 0))
        {
        for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
          {
          m_ExtractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1 );
          }
        }
      else
        {
        unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
        for (unsigned int idx = 0; idx < nbComponents; ++idx)
          {
          m_ExtractROIFilter->SetChannel(idx + 1);
          }
        }
      m_ResamplingFilter->SetInput( m_ExtractROIFilter->GetOutput() );
      }
    else
      {
      m_ResamplingFilter->SetInput(inImage);
      }

    unsigned int Ratio = static_cast<unsigned int>(GetParameterInt("sr"));
    unsigned int SamplingRatioX = 1;
    unsigned int SamplingRatioY = 1;

    if ( !HasUserValue("sr") )
      {
      if ( IsParameterEnabled("sx") && IsParameterEnabled("sy") )
        {
        SamplingRatioX =  GetParameterInt("rsx") / GetParameterInt("sx");
        SamplingRatioY =  GetParameterInt("rsy") / GetParameterInt("sy");
        if (SamplingRatioX > Ratio) Ratio = SamplingRatioX;
        if (SamplingRatioY > Ratio) Ratio = SamplingRatioY;
        }
      else
        {
        if ( IsParameterEnabled("sx") )
          {
          Ratio =  GetParameterInt("rsx") / GetParameterInt("sx");
          }
        if ( IsParameterEnabled("sy") )
          {
          Ratio =  GetParameterInt("rsy") / GetParameterInt("sy");
          }
        }
      }

    if ( Ratio < 1)
      {
      otbAppLogFATAL( << "Error in SizeX and/or SizeY : ratio must be greater than 1.");
      return;
      }
    otbAppLogINFO( << "Ratio used: "<<Ratio << ".");

    m_ResamplingFilter->SetShrinkFactor( Ratio );
    m_ResamplingFilter->Update();

    SetParameterOutputImage("out", m_ResamplingFilter->GetOutput());
  }

  ExtractROIFilterType::Pointer m_ExtractROIFilter;
  ShrinkImageFilterType::Pointer m_ResamplingFilter;

};

}
}

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


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linenoise/linenoise.h"
#include "raptor.h"
#include "routing/raptor_api.h"
#include "type/data.h"
#include "utils/timer.h"
#include "type/response.pb.h"
#include "routing_cli_utils.h"
#include "ptreferential/ptreferential_api.h"
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "type/pb_converter.h"

namespace nr = navitia::routing;
namespace nt = navitia::type;
namespace bt = boost::posix_time;
namespace po = boost::program_options ;
namespace pb = pbnavitia;

void completion(const char *buf, linenoiseCompletions *lc) {
    if (buf[0] == 'j' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"journey");
    }
    if (buf[0] == 'p' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"ptref");
    }
}

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "A filename is needed" << std::endl;
        return 1;
    }
    std::string start, target, date;
    nt::Data data;
    data.load(std::string(argv[1]));
    navitia::cli::compute_options compute_opt;
    po::variables_map vm;
    char *line;

    nr::RAPTOR raptor(data);
    /* Parse options, with --multiline we enable multi line editing. */
    linenoiseSetCompletionCallback(completion);
    linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
    while((line = linenoise("hello> ")) != NULL) {
        linenoiseHistoryAdd(line);
        linenoiseHistorySave("history.txt");
        std::string str_line(line);
        auto splitted_line = po::split_unix(str_line);
        if (splitted_line.empty()) {
            continue;
        }
        if (splitted_line[0] == "journey") {
            po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), vm);
            po::notify(vm);
            compute_opt.compute(vm, raptor);
        } else if (splitted_line[0] == "ptref") {
            if (splitted_line.size() < 2) {
                std::cerr << "an ID is needed" << std::endl;
            }
            const std::string id = splitted_line[1];
            #define SHOW_ID_CLI(type_name, collection_name) \
            auto collection_name##_map = data.pt_data->collection_name##_map;\
            if ( collection_name##_map.find(id) != collection_name##_map.end()) {\
                pbnavitia::type_name p;\
                navitia::fill_pb_object(collection_name##_map.at(id), data, &p);\
                std::cout << p.DebugString() << std::endl;}
            ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)
        }
    }
    return 0;
}
<commit_msg>Cli: add comment<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linenoise/linenoise.h"
#include "raptor.h"
#include "routing/raptor_api.h"
#include "type/data.h"
#include "utils/timer.h"
#include "type/response.pb.h"
#include "routing_cli_utils.h"
#include "ptreferential/ptreferential_api.h"
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include "type/pb_converter.h"

namespace nr = navitia::routing;
namespace nt = navitia::type;
namespace bt = boost::posix_time;
namespace po = boost::program_options ;
namespace pb = pbnavitia;

void completion(const char *buf, linenoiseCompletions *lc) {
    if (buf[0] == 'j' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"journey");
    }
    if (buf[0] == 'p' || buf[0] == '\0') {
        linenoiseAddCompletion(lc,"ptref");
    }
}
/* This program takes a path to a nav.lz4 navitia's file
 * It will be loaded at the begginning of the program
 */
int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "A filename is needed" << std::endl;
        return 1;
    }
    std::string start, target, date;
    nt::Data data;
    data.load(std::string(argv[1]));
    navitia::cli::compute_options compute_opt;
    po::variables_map vm;
    char *line;

    nr::RAPTOR raptor(data);
    /* Parse options, with --multiline we enable multi line editing. */
    linenoiseSetCompletionCallback(completion);
    linenoiseHistoryLoad("history.txt"); /* Load the history at startup */
    while((line = linenoise("hello> ")) != NULL) {
        linenoiseHistoryAdd(line);
        linenoiseHistorySave("history.txt");
        std::string str_line(line);
        auto splitted_line = po::split_unix(str_line);
        if (splitted_line.empty()) {
            continue;
        }
        if (splitted_line[0] == "journey") {
            po::store(po::command_line_parser(splitted_line).options(compute_opt.desc).run(), vm);
            po::notify(vm);
            compute_opt.compute(vm, raptor);
        } else if (splitted_line[0] == "ptref") {
            if (splitted_line.size() < 2) {
                std::cerr << "an ID is needed" << std::endl;
            }
            const std::string id = splitted_line[1];
            #define SHOW_ID_CLI(type_name, collection_name) \
            auto collection_name##_map = data.pt_data->collection_name##_map;\
            if ( collection_name##_map.find(id) != collection_name##_map.end()) {\
                pbnavitia::type_name p;\
                navitia::fill_pb_object(collection_name##_map.at(id), data, &p);\
                std::cout << p.DebugString() << std::endl;}
            ITERATE_NAVITIA_PT_TYPES(SHOW_ID_CLI)
        }
    }
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>coverity#1130457 Uncaught exception<commit_after><|endoftext|>


<commit_before>// [WriteFile Name=ExportTiles, Category=Layers]
// [Legal]
// Copyright 2016 Esri.

// 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.
// [Legal]

#include "ExportTiles.h"

#include <QUrl>

#include "Map.h"
#include "MapQuickView.h"
#include "Basemap.h"
#include "ExportTiles.h"
#include "ArcGISTiledLayer.h"
#include "ExportTileCacheTask.h"
#include "Envelope.h"
#include "GeometryEngine.h"
#include "SpatialReference.h"
#include "TileCache.h"

using namespace Esri::ArcGISRuntime;

ExportTiles::ExportTiles(QQuickItem* parent) :
    QQuickItem(parent),
    m_map(nullptr),
    m_mapView(nullptr),
    m_serviceUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"),
    m_exportTileCacheTask(nullptr)
{
}

ExportTiles::~ExportTiles()
{
}

void ExportTiles::componentComplete()
{
    QQuickItem::componentComplete();

    // find QML MapView component
    m_mapView = findChild<MapQuickView*>("mapView");

    // create a tiled basemap
    ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(m_serviceUrl);
    Basemap* basemap = new Basemap(tiledLayer, this);

    // create a new map instance
    m_map = new Map(basemap, this);

    // set an initial viewpoint
    Envelope env(12362601, 936021, 10187678, 2567213, SpatialReference(3857));
    Viewpoint viewpoint(env);
    m_map->setInitialViewpoint(viewpoint);

    // set map on the map view
    m_mapView->setMap(m_map);

    // create the task from the tiled layer's map service info once it is loaded
    connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer](Error)
    {
        m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->mapServiceInfo(), this);
    });
}

void ExportTiles::exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2, QString dataPath)
{
    // create an envelope from the QML rectangle corners
    auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);
    auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);
    auto extent = Envelope(corner1, corner2);
    auto tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator());

    // connect to sync task doneLoading signal
    connect(m_exportTileCacheTask, &ExportTileCacheTask::defaultExportTileCacheParametersCompleted, [this, &dataPath](QUuid, ExportTileCacheParameters parameters)
    {
        m_parameters = parameters;

        // execute the task and obtain the job
        auto exportJob = m_exportTileCacheTask->exportTileCache(m_parameters, dataPath);

        // check if there is a valid job
        if (exportJob)
        {
            // connect to the job's status changed signal
            connect(exportJob, &ExportTileCacheJob::jobStatusChanged, [this, exportJob]()
            {
                // connect to the job's status changed signal to know once it is done
                switch (exportJob->jobStatus()) {
                case JobStatus::Failed:
                    emit updateStatus("Export failed");
                    emit hideWindow(5000, false);
                    break;
                case JobStatus::NotStarted:
                    emit updateStatus("Job not started");
                    break;
                case JobStatus::Paused:
                    emit updateStatus("Job paused");
                    break;
                case JobStatus::Started:
                    emit updateStatus("In progress...");
                    break;
                case JobStatus::Succeeded:
                    emit updateStatus("Adding TPK...");
                    emit hideWindow(1500, true);
                    displayOutputTileCache(exportJob->result());
                    break;
                default:
                    break;
                }
            });

            // start the export job
            exportJob->start();
        }
        else
        {
            emit updateStatus("Export failed");
            emit hideWindow(5000, false);
        }
    });
    // generate parameters
    m_exportTileCacheTask->createDefaultExportTileCacheParameters(tileCacheExtent, m_mapView->mapScale(), m_exportTileCacheTask->mapServiceInfo().maxScale());

}

// display the tile cache once the task is complete
void ExportTiles::displayOutputTileCache(TileCache* tileCache)
{
    // create a new tiled layer from the output tile cache
    auto tiledLayer = new ArcGISTiledLayer(tileCache, this);

    // add the new layer to a basemap
    auto basemap = new Basemap(tiledLayer, this);

    // set the new basemap on the map
    m_map->setBasemap(basemap);

    // zoom to the new layer and hide window once loaded
    connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer]()
    {
        if (tiledLayer->loadStatus() == LoadStatus::Loaded)
        {
            m_mapView->setViewpointScale(m_mapView->mapScale() * 0.5);
        }
    });
}
<commit_msg>Fix ExportTiles connection to take by val<commit_after>// [WriteFile Name=ExportTiles, Category=Layers]
// [Legal]
// Copyright 2016 Esri.

// 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.
// [Legal]

#include "ExportTiles.h"

#include <QUrl>

#include "Map.h"
#include "MapQuickView.h"
#include "Basemap.h"
#include "ExportTiles.h"
#include "ArcGISTiledLayer.h"
#include "ExportTileCacheTask.h"
#include "Envelope.h"
#include "GeometryEngine.h"
#include "SpatialReference.h"
#include "TileCache.h"

using namespace Esri::ArcGISRuntime;

ExportTiles::ExportTiles(QQuickItem* parent) :
    QQuickItem(parent),
    m_map(nullptr),
    m_mapView(nullptr),
    m_serviceUrl("http://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer"),
    m_exportTileCacheTask(nullptr)
{
}

ExportTiles::~ExportTiles()
{
}

void ExportTiles::componentComplete()
{
    QQuickItem::componentComplete();

    // find QML MapView component
    m_mapView = findChild<MapQuickView*>("mapView");

    // create a tiled basemap
    ArcGISTiledLayer* tiledLayer = new ArcGISTiledLayer(m_serviceUrl);
    Basemap* basemap = new Basemap(tiledLayer, this);

    // create a new map instance
    m_map = new Map(basemap, this);

    // set an initial viewpoint
    Envelope env(12362601, 936021, 10187678, 2567213, SpatialReference(3857));
    Viewpoint viewpoint(env);
    m_map->setInitialViewpoint(viewpoint);

    // set map on the map view
    m_mapView->setMap(m_map);

    // create the task from the tiled layer's map service info once it is loaded
    connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer](Error)
    {
        m_exportTileCacheTask = new ExportTileCacheTask(tiledLayer->mapServiceInfo(), this);
    });
}

void ExportTiles::exportTileCacheFromCorners(double xCorner1, double yCorner1, double xCorner2, double yCorner2, QString dataPath)
{
    // create an envelope from the QML rectangle corners
    auto corner1 = m_mapView->screenToLocation(xCorner1, yCorner1);
    auto corner2 = m_mapView->screenToLocation(xCorner2, yCorner2);
    auto extent = Envelope(corner1, corner2);
    auto tileCacheExtent = GeometryEngine::project(extent, SpatialReference::webMercator());

    // connect to sync task doneLoading signal
    connect(m_exportTileCacheTask, &ExportTileCacheTask::defaultExportTileCacheParametersCompleted, [this, dataPath](QUuid, ExportTileCacheParameters parameters)
    {
        m_parameters = parameters;

        // execute the task and obtain the job
        auto exportJob = m_exportTileCacheTask->exportTileCache(m_parameters, dataPath);

        // check if there is a valid job
        if (exportJob)
        {
            // connect to the job's status changed signal
            connect(exportJob, &ExportTileCacheJob::jobStatusChanged, [this, exportJob]()
            {
                // connect to the job's status changed signal to know once it is done
                switch (exportJob->jobStatus()) {
                case JobStatus::Failed:
                    emit updateStatus("Export failed");
                    emit hideWindow(5000, false);
                    break;
                case JobStatus::NotStarted:
                    emit updateStatus("Job not started");
                    break;
                case JobStatus::Paused:
                    emit updateStatus("Job paused");
                    break;
                case JobStatus::Started:
                    emit updateStatus("In progress...");
                    break;
                case JobStatus::Succeeded:
                    emit updateStatus("Adding TPK...");
                    emit hideWindow(1500, true);
                    displayOutputTileCache(exportJob->result());
                    break;
                default:
                    break;
                }
            });

            // start the export job
            exportJob->start();
        }
        else
        {
            emit updateStatus("Export failed");
            emit hideWindow(5000, false);
        }
    });
    // generate parameters
    m_exportTileCacheTask->createDefaultExportTileCacheParameters(tileCacheExtent, m_mapView->mapScale(), m_exportTileCacheTask->mapServiceInfo().maxScale());

}

// display the tile cache once the task is complete
void ExportTiles::displayOutputTileCache(TileCache* tileCache)
{
    // create a new tiled layer from the output tile cache
    auto tiledLayer = new ArcGISTiledLayer(tileCache, this);

    // add the new layer to a basemap
    auto basemap = new Basemap(tiledLayer, this);

    // set the new basemap on the map
    m_map->setBasemap(basemap);

    // zoom to the new layer and hide window once loaded
    connect(tiledLayer, &ArcGISTiledLayer::doneLoading, [this, tiledLayer]()
    {
        if (tiledLayer->loadStatus() == LoadStatus::Loaded)
        {
            m_mapView->setViewpointScale(m_mapView->mapScale() * 0.5);
        }
    });
}
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH
#define DUNE_STUFF_FUNCTION_INTERFACE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>
#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/function.hh>

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>

namespace Dune {
namespace Stuff {
namespace Function {

//! forward
template< class RangeFieldImp >
class Coefficient;

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Interface
{
public:
  typedef Interface<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;

  typedef DomainFieldImp                                  DomainFieldType;
  static const int                                        dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;

  typedef RangeFieldImp                                 RangeFieldType;
  static const int                                      dimRange = rangeDim;
  typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;

  typedef Common::Parameter::FieldType  ParamFieldType;
  static const int                      maxParamDim = Common::Parameter::maxDim;
  typedef Common::Parameter::Type       ParamType;

  typedef ThisType                      ComponentType;
  typedef Coefficient< RangeFieldType > CoefficientType;

  static const std::string id()
  {
    return "function";
  }

  /** \defgroup type ´´Theis method has to be implemented for parametric functions and determines,
   *                   which evaluate() is callable.''
   */
  /* @{ */
  virtual bool parametric() const
  {
    return false;
  }
  /* @} */

  /** \defgroup info ´´These methods should be implemented in order to identify the function.'' */
  /* @{ */
  virtual std::string name() const
  {
    return id();
  }

  virtual int order() const
  {
    return -1;
  }
  /* @} */

  /** \defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == false!");
  }
  /* @} */

  /** \defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, const ParamType& /*_mu*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual size_t paramSize() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual bool separable() const
  {
    return false;
  }
  /* @} */

  /** \defgroup separable ´´These methods have to be implemented, if separable() == true.'' */
  /* @{ */
  virtual size_t numComponents() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }

  virtual size_t numCoefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }
  /* @} */

  /** \defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' */
  /* @{ */
  virtual RangeType evaluate(const DomainType& _x) const
  {
    assert(!parametric());
    RangeType ret;
    evaluate(_x, ret);
    return ret;
  }

//  virtual RangeType evaluate(const DomainType& x, const ParamType& mu) const
//  {
//    RangeType ret;
//    evaluate(x, mu, ret);
//    return ret;
//  }

//  virtual void evaluate(const ParamType& x, const ParamType& mu, RangeType& ret) const
//  {
//    // process input
//    assert(x.size() == dimDomain);
//    DomainType x_fvector;
//    for (int i = 0; i < dimDomain; ++i)
//      x_fvector[i] = x(i);
//    // evaluate
//    evaluate(x_fvector, mu, ret);
//  }

//  virtual void evaluate(const DomainType& x, const ParamType& mu, ParamType& ret) const
//  {
//    // evaluate
//    RangeType ret_fvector;
//    evaluate(x, mu, ret_fvector);
//    // process output
//    assert(ret.size() == dimRange);
//    for (int i = 0; i < dimRange; ++i)
//      ret(i) = ret_fvector[i];
//  }

//  virtual void evaluate(const ParamType& x, const ParamType& mu, ParamType& ret) const
//  {
//    // process input
//    assert(x.size() == dimDomain);
//    DomainType x_fvector;
//    for (int i = 0; i < dimDomain; ++i)
//      x_fvector[i] = x(i);
//    // evaluate
//    RangeType ret_fvector;
//    evaluate(x_fvector, mu, ret_fvector);
//    // process output
//    assert(ret.size() == dimRange);
//    for (int i = 0; i < dimRange; ++i)
//      ret(i) = ret_fvector[i];
//  }

//  virtual ParamType evaluate(const ParamType& x, const ParamType& mu) const
//  {
//    ParamType ret;
//    evaluate(x, mu, ret);
//    return ret;
//  }

//  void report(std::ostream& out = std::cout, std::string prefix = "") const
//  {
//    out << prefix << "parameter explanation:" << std::endl;
//    assert(paramExplanation().size() == paramSize());
//    assert(paramRange().size() == 2);
//    assert(paramRange()[0].size() == paramSize());
//    assert(paramRange()[1].size() == paramSize());
//    for (unsigned int pp = 0; pp < paramSize(); ++pp)
//      out << prefix << "  " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl;
//  }
/* @} */
}; // class Interface

} // namespace Function
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_INTERFACE_HH
<commit_msg>[function.interface] paramSize() returns 0 in the nonparametric case<commit_after>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH
#define DUNE_STUFF_FUNCTION_INTERFACE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>
#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/function.hh>

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>

namespace Dune {
namespace Stuff {
namespace Function {

//! forward
template< class RangeFieldImp >
class Coefficient;

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Interface
{
public:
  typedef Interface<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;

  typedef DomainFieldImp                                  DomainFieldType;
  static const int                                        dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;

  typedef RangeFieldImp                                 RangeFieldType;
  static const int                                      dimRange = rangeDim;
  typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;

  typedef Common::Parameter::FieldType  ParamFieldType;
  static const int                      maxParamDim = Common::Parameter::maxDim;
  typedef Common::Parameter::Type       ParamType;

  typedef ThisType                      ComponentType;
  typedef Coefficient< RangeFieldType > CoefficientType;

  static const std::string id()
  {
    return "function";
  }

  /** \defgroup type ´´Theis method has to be implemented for parametric functions and determines,
   *                   which evaluate() is callable.''
   */
  /* @{ */
  virtual bool parametric() const
  {
    return false;
  }
  /* @} */

  /** \defgroup info ´´These methods should be implemented in order to identify the function.'' */
  /* @{ */
  virtual std::string name() const
  {
    return id();
  }

  virtual int order() const
  {
    return -1;
  }
  /* @} */

  /** \defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == false!");
  }
  /* @} */

  /** \defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, const ParamType& /*_mu*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual bool separable() const
  {
    return false;
  }
  /* @} */

  /** \defgroup separable ´´These methods have to be implemented, if separable() == true.'' */
  /* @{ */
  virtual size_t numComponents() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }

  virtual size_t numCoefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if separable() == true!");
  }
  /* @} */

  /** \defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' */
  /* @{ */
  virtual RangeType evaluate(const DomainType& _x) const
  {
    assert(!parametric());
    RangeType ret;
    evaluate(_x, ret);
    return ret;
  }

//  virtual RangeType evaluate(const DomainType& x, const ParamType& mu) const
//  {
//    RangeType ret;
//    evaluate(x, mu, ret);
//    return ret;
//  }

//  virtual void evaluate(const ParamType& x, const ParamType& mu, RangeType& ret) const
//  {
//    // process input
//    assert(x.size() == dimDomain);
//    DomainType x_fvector;
//    for (int i = 0; i < dimDomain; ++i)
//      x_fvector[i] = x(i);
//    // evaluate
//    evaluate(x_fvector, mu, ret);
//  }

//  virtual void evaluate(const DomainType& x, const ParamType& mu, ParamType& ret) const
//  {
//    // evaluate
//    RangeType ret_fvector;
//    evaluate(x, mu, ret_fvector);
//    // process output
//    assert(ret.size() == dimRange);
//    for (int i = 0; i < dimRange; ++i)
//      ret(i) = ret_fvector[i];
//  }

//  virtual void evaluate(const ParamType& x, const ParamType& mu, ParamType& ret) const
//  {
//    // process input
//    assert(x.size() == dimDomain);
//    DomainType x_fvector;
//    for (int i = 0; i < dimDomain; ++i)
//      x_fvector[i] = x(i);
//    // evaluate
//    RangeType ret_fvector;
//    evaluate(x_fvector, mu, ret_fvector);
//    // process output
//    assert(ret.size() == dimRange);
//    for (int i = 0; i < dimRange; ++i)
//      ret(i) = ret_fvector[i];
//  }

//  virtual ParamType evaluate(const ParamType& x, const ParamType& mu) const
//  {
//    ParamType ret;
//    evaluate(x, mu, ret);
//    return ret;
//  }

//  void report(std::ostream& out = std::cout, std::string prefix = "") const
//  {
//    out << prefix << "parameter explanation:" << std::endl;
//    assert(paramExplanation().size() == paramSize());
//    assert(paramRange().size() == 2);
//    assert(paramRange()[0].size() == paramSize());
//    assert(paramRange()[1].size() == paramSize());
//    for (unsigned int pp = 0; pp < paramSize(); ++pp)
//      out << prefix << "  " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl;
//  }
/* @} */
}; // class Interface

} // namespace Function
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTION_INTERFACE_HH
<|endoftext|>


<commit_before>/* Copyright 2017 Christian */

#include <sstream>
#include "ros/ros.h"
#include "std_msgs/String.h"

/**
 * This tutorial demonstrates simple sending of messages over the ROS system.
 */
int main(int argc, char **argv) {
  /**
   * The ros::init() function needs to see argc and argv so that it can perform
   * any ROS arguments and name remapping that were provided at the command line.
   * For programmatic remappings you can use a different version of init() which takes
   * remappings directly, but for most command-line programs, passing argc and argv is
   * the easiest way to do it.  The third argument to init() is the name of the node.
   *
   * You must call one of the versions of ros::init() before using any other
   * part of the ROS system.
   */
  ros::init(argc, argv, "talker");

  /**
   * NodeHandle is the main access point to communications with the ROS system.
   * The first NodeHandle constructed will fully initialize this node, and the last
   * NodeHandle destructed will close down the node.
   */
  ros::NodeHandle n;

  /**
   * The advertise() function is how you tell ROS that you want to
   * publish on a given topic name. This invokes a call to the ROS
   * master node, which keeps a registry of who is publishing and who
   * is subscribing. After this advertise() call is made, the master
   * node will notify anyone who is trying to subscribe to this topic name,
   * and they will in turn negotiate a peer-to-peer connection with this
   * node.  advertise() returns a Publisher object which allows you to
   * publish messages on that topic through a call to publish().  Once
   * all copies of the returned Publisher object are destroyed, the topic
   * will be automatically unadvertised.
   *
   * The second parameter to advertise() is the size of the message queue
   * used for publishing messages.  If messages are published more quickly
   * than we can send them, the number here specifies how many messages to
   * buffer up before throwing some away.
   */
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

  ros::Rate loop_rate(10);

  /**
   * A count of how many messages we have sent. This is used to create
   * a unique string for each message.
   */
  int year = 2017;
  while (ros::ok()) {
    /**
     * This is a message object. You stuff it with data, and then publish it.
     */
    std_msgs::String msg;

    std::stringstream ss;
    ss << "Welcome Class ENPM808X of " << year;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());

    /**
     * The publish() function is how you send messages. The parameter
     * is the message object. The type of this object must agree with the type
     * given as a template parameter to the advertise<>() call, as was done
     * in the constructor above.
     */
    chatter_pub.publish(msg);

    ros::spinOnce();

    loop_rate.sleep();
    ++year;
  }

  return 0;
}
<commit_msg>Modifying Talker node to broadcast a tf frame<commit_after>/* Copyright 2017 Christian */
#include <tf/transform_broadcaster.h>
#include <sstream>
#include "ros/ros.h"
#include "std_msgs/String.h"

/**
 * This tutorial has been modified to broadcast tf frames over the ROS system.
 */
int main(int argc, char **argv) {
  /**
   * The ros::init() function needs to see argc and argv so that it can perform
   * any ROS arguments and name remapping that were provided at the command line.
   * For programmatic remappings you can use a different version of init() which takes
   * remappings directly, but for most command-line programs, passing argc and argv is
   * the easiest way to do it.  The third argument to init() is the name of the node.
   *
   * You must call one of the versions of ros::init() before using any other
   * part of the ROS system.
   */
  ros::init(argc, argv, "talker");

  /**
   * NodeHandle is the main access point to communications with the ROS system.
   * The first NodeHandle constructed will fully initialize this node, and the last
   * NodeHandle destructed will close down the node.
   */
  ros::NodeHandle n;

  /**
   * The advertise() function is how you tell ROS that you want to
   * publish on a given topic name. This invokes a call to the ROS
   * master node, which keeps a registry of who is publishing and who
   * is subscribing. After this advertise() call is made, the master
   * node will notify anyone who is trying to subscribe to this topic name,
   * and they will in turn negotiate a peer-to-peer connection with this
   * node.  advertise() returns a Publisher object which allows you to
   * publish messages on that topic through a call to publish().  Once
   * all copies of the returned Publisher object are destroyed, the topic
   * will be automatically unadvertised.
   *
   * The second parameter to advertise() is the size of the message queue
   * used for publishing messages.  If messages are published more quickly
   * than we can send them, the number here specifies how many messages to
   * buffer up before throwing some away.
   */
  ros::Publisher chatter_pub = n.advertise<std_msgs::String>("chatter", 1000);

  /**
   * loop_rate is an object that defines that frequency in Hz at which the while loop
   * will work
   */
  ros::Rate loop_rate(10);

  /**
   * tfBroadcaster is an object that will be used to broadcast the trasnform
   */
  tf::TransformBroadcaster tfBroadcaster;

  /**
   * A count of how many messages we have sent. This is used to create
   * a unique string for each message.
   */
  int year = 2017;

  while (ros::ok()) {
    /**
     * This is a message object. You stuff it with data, and then publish it.
     */
    std_msgs::String msg;

    std::stringstream ss;
    ss << "Welcome Class ENPM808X of " << year;
    msg.data = ss.str();

    ROS_INFO("%s", msg.data.c_str());

    /**
     * The publish() function is how you send messages. The parameter
     * is the message object. The type of this object must agree with the type
     * given as a template parameter to the advertise<>() call, as was done
     * in the constructor above.
     */
    chatter_pub.publish(msg);

    /**
     * The transform object will contain the rotation and translation parameters
     */
    tf::Transform transform;

    /**
     * Setting the world frame reference in the transform vector x = 0.2 ,y = 0, z = 0.3
     */
    transform.setOrigin(tf::Vector3(0.2, 0.0, 0.3));

    /**
     * Quaternion object used to define rotation
     */
    tf::Quaternion tfQuatrn;

    /**
     * Setting rotation to be only in the z plane (180 turn around Z axis)
     */
    tfQuatrn.setRPY(0, 0, 1);

    /**
     * Embedding translation and rotation data into transform object
     */
    transform.setRotation(tfQuatrn);

    /**
     * Broadcasting the transform using 4 parameters:
     * transform contains translation and rotation matrix
     * Time::now() contains the time stamp of the system
     * world parent frame name
     * talk child fram name
     */
    tfBroadcaster.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", "talk"));

    ros::spinOnce();

    loop_rate.sleep();
  }

  return 0;
}
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH

#include <memory>

#include <dune/stuff/common/configuration.hh>

#include "interfaces.hh"

namespace Dune {
namespace Stuff {
namespace Functions {
namespace internal {

template< class K, int dim >
struct UnitMatrix
{
  typedef FieldMatrix< K, dim, dim > type;

  static type value()
  {
    type ret(0);
    for (size_t dd = 0; dd < dim; ++dd)
      ret[dd][dd] = 1;
    return ret;
  }
}; // struct UnitMatrix

template< class K >
struct UnitMatrix< K, 1 >
{
  typedef FieldVector< K, 1 > type;

  static type value()
  {
    return type(1);
  }
}; // struct UnitMatrix

template< class K, int dim >
typename UnitMatrix< K, dim >::type unit_matrix()
{
  return UnitMatrix< K, dim >::value();
}

} // namespace internal

template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 >
class Constant
  : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols>
{
  typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
      BaseType;
  typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >  ThisType;

  template< class R, size_t r, size_t rC >
  struct Get{ static std::string value_str()
  {
    std::string str = "[";
    for (size_t rr = 0; rr < r; ++rr) {
      if (rr > 0)
        str += "; ";
      for (size_t cc = 0; cc < rC; ++cc) {
        if (cc > 0)
          str += " ";
        if (cc == rr)
          str += "1";
        else
          str += "0";
      }
    }
    str += "]";
    return str;
  } };

  template< class R, int rC >
  struct Get< R, 1, rC >{ static std::string value_str()
  {
    std::string str = "[";
    for (size_t cc = 0; cc < rC; ++cc) {
      if (cc > 0)
        str += " ";
      str += "1";
    }
    str += "]";
    return str;
  } };

  template< class R, int r >
  struct Get< R, r, 1 >{ static std::string value_str()
  {
      return Get< R, 1, r >::value_str();
  } };

  template< class R >
  struct Get< R, 1, 1 >{ static std::string value_str()
  {
    return "1";
  } };

public:
  typedef typename BaseType::DomainType        DomainType;
  typedef typename BaseType::RangeType         RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  using typename BaseType::LocalfunctionType;

  static const bool available = true;

  static std::string static_id()
  {
    return BaseType::static_id() + ".constant";
  }

  static Common::Configuration default_config(const std::string sub_name = "")
  {
    Common::Configuration config;
    config["value"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str();
    config["name"] = static_id();
    if (sub_name.empty())
      return config;
    else {
      Common::Configuration tmp;
      tmp.add(config, sub_name);
      return tmp;
    }
  } // ... default_config(...)

  static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(),
                                            const std::string sub_name = static_id())
  {
    // get correct config
    const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
    const Common::Configuration default_cfg = default_config();
    return Common::make_unique< ThisType >(
          cfg.get("value",  default_cfg.get< RangeType >("value")),
          cfg.get("name",   default_cfg.get< std::string >("name")));
  } // ... create(...)

  explicit Constant(const RangeType& constant, const std::string name_in = static_id())
    : constant_(constant)
    , name_(name_in)
  {}

  explicit Constant(const RangeFieldImp& constant, const std::string name_in = static_id())
    : constant_(constant)
    , name_(name_in)
  {}

  Constant(const ThisType& other) = default;

  virtual std::string type() const override final
  {
    return BaseType::static_id() + ".constant";
  }

  virtual size_t order() const override final
  {
    return 0;
  }

  virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const override final
  {
    ret = constant_;
  }

  virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const override final
  {
    ret *= 0.0;
  }

  virtual std::string name() const override final
  {
    return name_;
  }

private:
  const RangeType constant_;
  const std::string name_;
};

} // namespace Functions
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH
<commit_msg>[functions.constant] fixed int/size_t template arguments<commit_after>// This file is part of the dune-stuff project:
//   https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber

#ifndef DUNE_STUFF_FUNCTIONS_CONSTANT_HH
#define DUNE_STUFF_FUNCTIONS_CONSTANT_HH

#include <memory>

#include <dune/stuff/common/configuration.hh>

#include "interfaces.hh"

namespace Dune {
namespace Stuff {
namespace Functions {
namespace internal {

template< class K, int dim >
struct UnitMatrix
{
  typedef FieldMatrix< K, dim, dim > type;

  static type value()
  {
    type ret(0);
    for (size_t dd = 0; dd < dim; ++dd)
      ret[dd][dd] = 1;
    return ret;
  }
}; // struct UnitMatrix

template< class K >
struct UnitMatrix< K, 1 >
{
  typedef FieldVector< K, 1 > type;

  static type value()
  {
    return type(1);
  }
}; // struct UnitMatrix

template< class K, int dim >
typename UnitMatrix< K, dim >::type unit_matrix()
{
  return UnitMatrix< K, dim >::value();
}

} // namespace internal

template< class EntityImp, class DomainFieldImp, size_t domainDim, class RangeFieldImp, size_t rangeDim, size_t rangeDimCols = 1 >
class Constant
  : public GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols>
{
  typedef GlobalFunctionInterface< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >
      BaseType;
  typedef Constant < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, rangeDim, rangeDimCols >  ThisType;

  template< class R, size_t r, size_t rC >
  struct Get{ static std::string value_str()
  {
    std::string str = "[";
    for (size_t rr = 0; rr < r; ++rr) {
      if (rr > 0)
        str += "; ";
      for (size_t cc = 0; cc < rC; ++cc) {
        if (cc > 0)
          str += " ";
        if (cc == rr)
          str += "1";
        else
          str += "0";
      }
    }
    str += "]";
    return str;
  } };

  template< class R, size_t rC >
  struct Get< R, 1, rC >{ static std::string value_str()
  {
    std::string str = "[";
    for (size_t cc = 0; cc < rC; ++cc) {
      if (cc > 0)
        str += " ";
      str += "1";
    }
    str += "]";
    return str;
  } };

  template< class R, size_t r >
  struct Get< R, r, 1 >{ static std::string value_str()
  {
      return Get< R, 1, r >::value_str();
  } };

  template< class R >
  struct Get< R, 1, 1 >{ static std::string value_str()
  {
    return "1";
  } };

public:
  typedef typename BaseType::DomainType        DomainType;
  typedef typename BaseType::RangeType         RangeType;
  typedef typename BaseType::JacobianRangeType JacobianRangeType;

  using typename BaseType::LocalfunctionType;

  static const bool available = true;

  static std::string static_id()
  {
    return BaseType::static_id() + ".constant";
  }

  static Common::Configuration default_config(const std::string sub_name = "")
  {
    Common::Configuration config;
    config["value"] = Get< RangeFieldImp, rangeDim, rangeDimCols >::value_str();
    config["name"] = static_id();
    config.report();
    if (sub_name.empty())
      return config;
    else {
      Common::Configuration tmp;
      tmp.add(config, sub_name);
      return tmp;
    }
  } // ... default_config(...)

  static std::unique_ptr< ThisType > create(const Common::Configuration config = default_config(),
                                            const std::string sub_name = static_id())
  {
    // get correct config
    const Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
    const Common::Configuration default_cfg = default_config();
    return Common::make_unique< ThisType >(
          cfg.get("value", default_cfg.get< RangeType >("value")),
          cfg.get("name",  default_cfg.get< std::string >("name")));
  } // ... create(...)

  explicit Constant(const RangeType& constant, const std::string name_in = static_id())
    : constant_(constant)
    , name_(name_in)
  {}

  explicit Constant(const RangeFieldImp& constant, const std::string name_in = static_id())
    : constant_(constant)
    , name_(name_in)
  {}

  Constant(const ThisType& other) = default;

  virtual std::string type() const override final
  {
    return BaseType::static_id() + ".constant";
  }

  virtual size_t order() const override final
  {
    return 0;
  }

  virtual void evaluate(const DomainType& /*x*/, RangeType& ret) const override final
  {
    ret = constant_;
  }

  virtual void jacobian(const DomainType& /*x*/, JacobianRangeType& ret) const override final
  {
    ret *= 0.0;
  }

  virtual std::string name() const override final
  {
    return name_;
  }

private:
  const RangeType constant_;
  const std::string name_;
};

} // namespace Functions
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_FUNCTIONS_CONSTANT_HH
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH
#define DUNE_STUFF_LA_CONTAINER_EIGEN_HH

#ifdef HAVE_EIGEN

#include <Eigen/Core>
#include <Eigen/Sparse>

#include "pattern.hh"

namespace Dune {
namespace Stuff {
namespace LA {
namespace Container {
namespace Eigen {

template< class ElementImp = double >
class SparseMatrix
  : ::Eigen::SparseMatrix< ElementImp, ::Eigen::RowMajor >
{
public:
  typedef ElementImp ElementType;

  typedef ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType;

  typedef SparseMatrix< ElementType > ThisType;

  typedef typename BaseType::Index size_type;

  SparseMatrix(const size_type _rows, const size_type _cols)
    : BaseType(_rows, _cols)
  {}

  SparseMatrix(const size_type _rows, const size_type _cols,
               const Dune::Stuff::LA::Container::Pattern::Default& _pattern)
    : BaseType(_rows, _cols)
  {
    assert(size_type(_pattern.rows()) == _rows && "Given pattern too short!");
    typedef Dune::Stuff::LA::Container::Pattern::Default PatternType;
    typedef PatternType::ColumnsType ColumnsType;
    for (size_type row = 0; row < size_type(_pattern.rows()); ++row) {
      BaseType::startVec(row);
      const ColumnsType& columns = _pattern.columns(row);
      for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) {
        const size_type column = *columnIt;
        BaseType::insertBackByOuterInner(row, column);
      }
      // create diagonal entry (insertBackByOuterInner() can not handle empty rows)
      if (columns.size() == 0)
        BaseType::insertBackByOuterInner(row, row);
    }
    BaseType::finalize();
    BaseType::makeCompressed();
    BaseType::setZero();
  } // SparseMatrix(...)

  SparseMatrix(const size_type _rows, const size_type _cols, const size_type _nonZerosPerRow)
    : BaseType(_rows, _cols)
  {
    BaseType::reserve(_nonZerosPerRow);
    BaseType::setZero();
  }

  void reserve(const size_type _nonZerosPerRow)
  {
    BaseType::reserve(_nonZerosPerRow);
    BaseType::setZero();
  }

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::coeff(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class SparseMatrix

template< class ElementImp = double >
class DenseMatrix
  : ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, ::Eigen::Dynamic >
{
public:
  typedef ElementImp ElementType;

  typedef ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType;

  typedef DenseMatrix< ElementType > ThisType;

  typedef typename BaseType::Index size_type;

  DenseMatrix(const size_type _rows, const size_type _cols)
    : BaseType(_rows, _cols)
  {
    BaseType::setZero();
  }

  DenseMatrix(const size_type _rows, const size_type _cols,
              const Dune::Stuff::LA::Container::Pattern::Default&)
    : BaseType(_rows, _cols)
  {
    BaseType::setZero();
  } // SparseMatrix(...)

  DenseMatrix(const size_type _rows, const size_type _cols, const size_type)
    : BaseType(_rows, _cols)
  {
    BaseType::setZero();
  }

  void reserve(const size_type)
  {
    BaseType::setZero();
  }

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::operator()(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class DenseMatrix

template< class ElementImp = double>
class DenseVector
  : public ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, 1 >
{
public:
  typedef ElementImp ElementType;

  typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType;

  typedef typename BaseType::Index size_type;

  DenseVector(const size_type _size)
    : BaseType(_size)
  {
    BaseType::setZero();
  }

  size_type size() const
  {
    return BaseType::size();
  }

  void add(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) += val;
  }

  void set(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) = val;
  }

  const ElementType get(const size_type i) const
  {
    return BaseType::operator()(i);
  }

  const ElementType& operator[](const size_type i) const
  {
    return BaseType::coeff(i);
  }

  ElementType& operator[](const size_type i)
  {
    return BaseType::coeffRef(i);
  }
}; // class DenseVector

} // namespace Container
} // namespace Eigen
} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // HAVE_EIGEN

#endif // DUNE_STUFF_LA_CONTAINER_EIGEN_HH
<commit_msg>[la.container.eigen] fixed eigen guard<commit_after>#ifndef DUNE_STUFF_LA_CONTAINER_EIGEN_HH
#define DUNE_STUFF_LA_CONTAINER_EIGEN_HH

#if HAVE_EIGEN

#include <Eigen/Core>
#include <Eigen/Sparse>

#include "pattern.hh"

namespace Dune {
namespace Stuff {
namespace LA {
namespace Container {
namespace Eigen {

template< class ElementImp = double >
class SparseMatrix
  : ::Eigen::SparseMatrix< ElementImp, ::Eigen::RowMajor >
{
public:
  typedef ElementImp ElementType;

  typedef ::Eigen::SparseMatrix< ElementType, ::Eigen::RowMajor > BaseType;

  typedef SparseMatrix< ElementType > ThisType;

  typedef typename BaseType::Index size_type;

  SparseMatrix(const size_type _rows, const size_type _cols)
    : BaseType(_rows, _cols)
  {}

  SparseMatrix(const size_type _rows, const size_type _cols,
               const Dune::Stuff::LA::Container::Pattern::Default& _pattern)
    : BaseType(_rows, _cols)
  {
    assert(size_type(_pattern.rows()) == _rows && "Given pattern too short!");
    typedef Dune::Stuff::LA::Container::Pattern::Default PatternType;
    typedef PatternType::ColumnsType ColumnsType;
    for (size_type row = 0; row < size_type(_pattern.rows()); ++row) {
      BaseType::startVec(row);
      const ColumnsType& columns = _pattern.columns(row);
      for (typename ColumnsType::const_iterator columnIt = columns.begin(); columnIt != columns.end(); ++columnIt) {
        const size_type column = *columnIt;
        BaseType::insertBackByOuterInner(row, column);
      }
      // create diagonal entry (insertBackByOuterInner() can not handle empty rows)
      if (columns.size() == 0)
        BaseType::insertBackByOuterInner(row, row);
    }
    BaseType::finalize();
    BaseType::makeCompressed();
    BaseType::setZero();
  } // SparseMatrix(...)

  SparseMatrix(const size_type _rows, const size_type _cols, const size_type _nonZerosPerRow)
    : BaseType(_rows, _cols)
  {
    BaseType::reserve(_nonZerosPerRow);
    BaseType::setZero();
  }

  void reserve(const size_type _nonZerosPerRow)
  {
    BaseType::reserve(_nonZerosPerRow);
    BaseType::setZero();
  }

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::coeffRef(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::coeff(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class SparseMatrix

template< class ElementImp = double >
class DenseMatrix
  : ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, ::Eigen::Dynamic >
{
public:
  typedef ElementImp ElementType;

  typedef ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, ::Eigen::Dynamic > BaseType;

  typedef DenseMatrix< ElementType > ThisType;

  typedef typename BaseType::Index size_type;

  DenseMatrix(const size_type _rows, const size_type _cols)
    : BaseType(_rows, _cols)
  {
    BaseType::setZero();
  }

  DenseMatrix(const size_type _rows, const size_type _cols,
              const Dune::Stuff::LA::Container::Pattern::Default&)
    : BaseType(_rows, _cols)
  {
    BaseType::setZero();
  } // SparseMatrix(...)

  DenseMatrix(const size_type _rows, const size_type _cols, const size_type)
    : BaseType(_rows, _cols)
  {
    BaseType::setZero();
  }

  void reserve(const size_type)
  {
    BaseType::setZero();
  }

  size_type rows() const
  {
    return BaseType::rows();
  }

  size_type cols() const
  {
    return BaseType::cols();
  }

  void add(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) += val;
  }

  void set(const size_type i, const size_type j, const ElementType& val)
  {
    BaseType::operator()(i, j) = val;
  }

  const ElementType get(const size_type i, const size_type j) const
  {
    return BaseType::operator()(i, j);
  }

  BaseType& base()
  {
    return *this;
  }

  const BaseType& base() const
  {
    return *this;
  }
}; // class DenseMatrix

template< class ElementImp = double>
class DenseVector
  : public ::Eigen::Matrix< ElementImp, ::Eigen::Dynamic, 1 >
{
public:
  typedef ElementImp ElementType;

  typedef typename ::Eigen::Matrix< ElementType, ::Eigen::Dynamic, 1 > BaseType;

  typedef typename BaseType::Index size_type;

  DenseVector(const size_type _size)
    : BaseType(_size)
  {
    BaseType::setZero();
  }

  size_type size() const
  {
    return BaseType::size();
  }

  void add(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) += val;
  }

  void set(const size_type i, const ElementType& val)
  {
    BaseType::operator()(i) = val;
  }

  const ElementType get(const size_type i) const
  {
    return BaseType::operator()(i);
  }

  const ElementType& operator[](const size_type i) const
  {
    return BaseType::coeff(i);
  }

  ElementType& operator[](const size_type i)
  {
    return BaseType::coeffRef(i);
  }
}; // class DenseVector

} // namespace Container
} // namespace Eigen
} // namespace LA
} // namespace Stuff
} // namespace Dune

#endif // HAVE_EIGEN

#endif // DUNE_STUFF_LA_CONTAINER_EIGEN_HH
<|endoftext|>