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

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

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

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

=========================================================================*/
#include "otbDSFuzzyModelEstimation.h"

#include <iostream>
#include "otbCommandLineArgumentParser.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"

#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataToRandomLineGenerator.h"

#include "otbVectorDataProjectionFilter.h"  //Envelope TO WGS84 (OSM friendly)
#include "otbVectorDataIntoImageProjectionFilter.h" //WGS84 to index

#include "otbVectorDataToRoadDescriptionFilter.h"
#include "otbVectorDataToDSValidatedVectorDataFilter.h"

//TESTING
#include "otbVectorDataFileWriter.h"

namespace otb
{

int DSFuzzyModelEstimation::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("DSFuzzyModelEstimation");
  descriptor->SetDescription("Estimate feature fuzzy model parameters using an image and an VectorData");
  descriptor->AddOption("InputImage", "Support to estimate the models on",
                        "in", 1, true, ApplicationDescriptor::InputImage);
  descriptor->AddOption("InputVectorData", "Ground Truth Vector Data",
                        "vdin", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOption("Hypothesis", "Dempster Shafer study hypothesis",
                        "hyp", 1, false, ApplicationDescriptor::StringList);
  descriptor->AddOption("Criterion", "Dempster Shafer Criterion (by default (Belief+Plausibility)/2 >= 0.5))",
                          "cri", 1, false, ApplicationDescriptor::String);
  descriptor->AddOption("DEMDirectory", "DEM directory",
                          "dem", 1, false, ApplicationDescriptor::DirectoryName);

  //TESTING PURPOSE
  descriptor->AddOption("Output", "OutputVectorData",
                        "out", 1, true, ApplicationDescriptor::FileName);
  return EXIT_SUCCESS;
}

int DSFuzzyModelEstimation::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::VectorData<double>                     VectorDataType;
  typedef VectorDataType::ValuePrecisionType          PrecisionType;
  typedef VectorDataType::PrecisionType               CoordRepType;
  typedef otb::VectorDataFileReader<VectorDataType>   VectorDataReaderType;
  typedef otb::VectorDataToRandomLineGenerator<VectorDataType>
                                                      RandomGeneratorType;

  typedef otb::VectorImage<PrecisionType , 2>         ImageType;
  typedef otb::ImageFileReader<ImageType>             ImageReaderType;

  typedef otb::ImageToEnvelopeVectorDataFilter<ImageType, VectorDataType>
                                                      EnvelopeFilterType;

  typedef otb::VectorDataProjectionFilter<VectorDataType, ImageType>
                                                      VectorDataProjFilter;

  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, ImageType>
                                                      VectorDataReProjFilter;

  typedef otb::VectorDataToRoadDescriptionFilter<VectorDataType, ImageType>
                                                      DescriptionFilterType;

  typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType>
                                                      ValidationFilterType;

  typedef otb::VectorDataFileWriter<VectorDataType>   VectorDataWriterType;

  //Instantiate
  ImageReaderType::Pointer                   imgReader = ImageReaderType::New();
  VectorDataReaderType::Pointer               vdReader = VectorDataReaderType::New();
  EnvelopeFilterType::Pointer           envelopeFilter = EnvelopeFilterType::New();
  RandomGeneratorType::Pointer       vdRandomGenerator = RandomGeneratorType::New();
  VectorDataReProjFilter::Pointer     vdReProjFilterGT = VectorDataReProjFilter::New();
  VectorDataReProjFilter::Pointer     vdReProjFilterRL = VectorDataReProjFilter::New();

  VectorDataWriterType::Pointer               vdWriter = VectorDataWriterType::New();

  //Read the image
  imgReader->SetFileName(parseResult->GetParameterString("InputImage"));
  imgReader->UpdateOutputInformation();

  //Read the vector data
  vdReader->SetFileName(parseResult->GetParameterString("InputVectorData"));
  vdReader->Update();

  //Generate the envelope
  envelopeFilter->SetInput(imgReader->GetOutput()); //->Output in WGS84
  envelopeFilter->Update();

  //Generate Random lines
  vdRandomGenerator->SetInput(envelopeFilter->GetOutput());
  vdRandomGenerator->SetNumberOfOutputLine(vdReader->GetOutput()->Size());
  vdRandomGenerator->SetMinLineSize(4);
  vdRandomGenerator->SetMaxLineSize(20);

  //Reproject into image index coordinates
  vdReProjFilterGT->SetInputImage(imgReader->GetOutput());
  vdReProjFilterGT->SetInputVectorData(vdReader->GetOutput());
  vdReProjFilterGT->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory"));
  vdReProjFilterGT->SetUseOutputSpacingAndOriginFromImage(true);
  vdReProjFilterGT->Update();

  vdReProjFilterRL->SetInputImage(imgReader->GetOutput());
  vdReProjFilterRL->SetInputVectorData(vdRandomGenerator->GetOutput());
  vdReProjFilterRL->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory"));
  vdReProjFilterRL->SetUseOutputSpacingAndOriginFromImage(true);
  vdReProjFilterRL->Update();

  vdWriter->SetInput(vdReProjFilterRL->GetOutput());
  vdWriter->SetFileName(parseResult->GetParameterString("Output"));
  vdWriter->Update();

  return EXIT_SUCCESS;
}

}

<commit_msg>STYLE<commit_after>/*=========================================================================

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

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

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

=========================================================================*/
#include "otbDSFuzzyModelEstimation.h"

#include <iostream>
#include "otbCommandLineArgumentParser.h"

#include "otbVectorImage.h"
#include "otbImageFileReader.h"

#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbImageToEnvelopeVectorDataFilter.h"
#include "otbVectorDataToRandomLineGenerator.h"

#include "otbVectorDataProjectionFilter.h"  //Envelope TO WGS84 (OSM friendly)
#include "otbVectorDataIntoImageProjectionFilter.h" //WGS84 to index

#include "otbVectorDataToRoadDescriptionFilter.h"
#include "otbVectorDataToDSValidatedVectorDataFilter.h"

//TESTING
#include "otbVectorDataFileWriter.h"

namespace otb
{

int DSFuzzyModelEstimation::Describe(ApplicationDescriptor* descriptor)
{
  descriptor->SetName("DSFuzzyModelEstimation");
  descriptor->SetDescription("Estimate feature fuzzy model parameters using an image and an VectorData");
  descriptor->AddOption("InputImage", "Support to estimate the models on",
                        "in", 1, true, ApplicationDescriptor::InputImage);
  descriptor->AddOption("InputVectorData", "Ground Truth Vector Data",
                        "vdin", 1, true, ApplicationDescriptor::FileName);
  descriptor->AddOption("Hypothesis", "Dempster Shafer study hypothesis",
                        "hyp", 1, false, ApplicationDescriptor::StringList);
  descriptor->AddOption("Criterion", "Dempster Shafer Criterion (by default (Belief+Plausibility)/2 >= 0.5))",
                          "cri", 1, false, ApplicationDescriptor::String);
  descriptor->AddOption("DEMDirectory", "DEM directory",
                          "dem", 1, false, ApplicationDescriptor::DirectoryName);

  //TESTING PURPOSE
  descriptor->AddOption("Output", "OutputVectorData",
                        "out", 1, true, ApplicationDescriptor::FileName);
  return EXIT_SUCCESS;
}

int DSFuzzyModelEstimation::Execute(otb::ApplicationOptionsResult* parseResult)
{
  typedef otb::VectorData<double>                     VectorDataType;
  typedef VectorDataType::ValuePrecisionType          PrecisionType;
  typedef VectorDataType::PrecisionType               CoordRepType;
  typedef otb::VectorDataFileReader<VectorDataType>   VectorDataReaderType;
  typedef otb::VectorDataToRandomLineGenerator<VectorDataType>
                                                      RandomGeneratorType;

  typedef otb::VectorImage<PrecisionType , 2>         ImageType;
  typedef otb::ImageFileReader<ImageType>             ImageReaderType;

  typedef otb::ImageToEnvelopeVectorDataFilter<ImageType, VectorDataType>
                                                      EnvelopeFilterType;

  typedef otb::VectorDataProjectionFilter<VectorDataType, ImageType>
                                                      VectorDataProjFilter;

  typedef otb::VectorDataIntoImageProjectionFilter<VectorDataType, ImageType>
                                                      VectorDataReProjFilter;

  typedef otb::VectorDataToRoadDescriptionFilter<VectorDataType, ImageType>
                                                      DescriptionFilterType;

  typedef otb::VectorDataToDSValidatedVectorDataFilter<VectorDataType, PrecisionType>
                                                      ValidationFilterType;

  typedef otb::VectorDataFileWriter<VectorDataType>   VectorDataWriterType;

  //Instantiate
  ImageReaderType::Pointer                   imgReader = ImageReaderType::New();
  VectorDataReaderType::Pointer               vdReader = VectorDataReaderType::New();
  EnvelopeFilterType::Pointer           envelopeFilter = EnvelopeFilterType::New();
  RandomGeneratorType::Pointer       vdRandomGenerator = RandomGeneratorType::New();
  VectorDataReProjFilter::Pointer     vdReProjFilterGT = VectorDataReProjFilter::New();
  VectorDataReProjFilter::Pointer     vdReProjFilterRL = VectorDataReProjFilter::New();

  VectorDataWriterType::Pointer               vdWriter = VectorDataWriterType::New();

  //Read the image
  imgReader->SetFileName(parseResult->GetParameterString("InputImage"));
  imgReader->UpdateOutputInformation();

  //Read the vector data
  vdReader->SetFileName(parseResult->GetParameterString("InputVectorData"));
  vdReader->Update();

  //Generate the envelope
  envelopeFilter->SetInput(imgReader->GetOutput()); //->Output in WGS84
  envelopeFilter->Update();

  //Generate Random lines
  vdRandomGenerator->SetInput(envelopeFilter->GetOutput());
  vdRandomGenerator->SetNumberOfOutputLine(vdReader->GetOutput()->Size());
  vdRandomGenerator->SetMinLineSize(4);
  vdRandomGenerator->SetMaxLineSize(20);

  //Reproject into image index coordinates
  vdReProjFilterGT->SetInputImage(imgReader->GetOutput());
  vdReProjFilterGT->SetInputVectorData(vdReader->GetOutput());
  vdReProjFilterGT->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory"));
  vdReProjFilterGT->SetUseOutputSpacingAndOriginFromImage(true);
  vdReProjFilterGT->Update();

  vdReProjFilterRL->SetInputImage(imgReader->GetOutput());
  vdReProjFilterRL->SetInputVectorData(vdRandomGenerator->GetOutput());
  vdReProjFilterRL->SetDEMDirectory(parseResult->GetParameterString("DEMDirectory"));
  vdReProjFilterRL->SetUseOutputSpacingAndOriginFromImage(true);
  vdReProjFilterRL->Update();

  vdWriter->SetInput(vdReProjFilterRL->GetOutput());
  vdWriter->SetFileName(parseResult->GetParameterString("Output"));
  vdWriter->Update();

  return EXIT_SUCCESS;
}

}

<|endoftext|>


<commit_before>#include "../Outer_Parameters.hxx"
#include "setup_constraints.hxx"

#include "../../ostream_set.hxx"
#include "../../ostream_map.hxx"
#include "../../ostream_vector.hxx"
#include "../../set_stream_precision.hxx"

namespace
{}

void compute_y_transform(
  const std::vector<std::vector<std::vector<std::vector<Function>>>>
    &function_blocks,
  const std::vector<std::set<El::BigFloat>> &points,
  const std::vector<El::BigFloat> &objectives,
  const std::vector<El::BigFloat> &normalization,
  const Outer_Parameters &parameters, const size_t &max_index,
  const El::Grid &global_grid,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
  El::BigFloat &primal_c_scale);

boost::optional<int64_t> load_checkpoint(
  const boost::filesystem::path &checkpoint_directory,
  boost::optional<int64_t> &backup_generation, int64_t &current_generation,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
  El::Matrix<El::BigFloat> &y, std::vector<std::set<El::BigFloat>> &points,
  El::BigFloat &threshold, El::BigFloat &primal_c_scale);

void copy_matrix(const El::Matrix<El::BigFloat> &source,
                 El::DistMatrix<El::BigFloat> &destination);
void copy_matrix(const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &source,
                 El::Matrix<El::BigFloat> &destination);

void fill_weights(const El::Matrix<El::BigFloat> &y, const size_t &max_index,
                  const std::vector<El::BigFloat> &normalization,
                  std::vector<El::BigFloat> &weights);

void find_new_points(
  const size_t &num_blocks, const size_t &rank, const size_t &num_procs,
  const El::BigFloat &infinity,
  const std::vector<std::vector<std::vector<std::vector<Function>>>>
    &function_blocks,
  const std::vector<El::BigFloat> &weights,
  const std::vector<std::set<El::BigFloat>> &points,
  std::vector<std::vector<El::BigFloat>> &new_points, bool &has_new_points);

void save_checkpoint(
  const boost::filesystem::path &checkpoint_directory,
  const Verbosity &verbosity,
  const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,
  const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
  const El::Matrix<El::BigFloat> &y,
  const std::vector<std::set<El::BigFloat>> &points,
  const El::BigFloat &infinity, const El::BigFloat &threshold,
  const El::BigFloat &primal_c_scale,
  boost::optional<int64_t> &backup_generation, int64_t &current_generation);

std::vector<El::BigFloat> compute_optimal(
  const std::vector<std::vector<std::vector<std::vector<Function>>>>
    &function_blocks,
  const std::vector<std::vector<El::BigFloat>> &initial_points,
  const std::vector<El::BigFloat> &objectives,
  const std::vector<El::BigFloat> &normalization,
  const Outer_Parameters &parameters_in)
{
  if(initial_points.size() != function_blocks.size())
    {
      throw std::runtime_error(
        "Size are different: Positive_Matrix_With_Prefactor: "
        + std::to_string(function_blocks.size())
        + ", initial points: " + std::to_string(initial_points.size()));
    }
  Outer_Parameters parameters(parameters_in);

  const size_t rank(El::mpi::Rank()), num_procs(El::mpi::Size()),
    num_weights(normalization.size());

  const size_t num_blocks(initial_points.size());
  std::vector<El::BigFloat> weights(num_weights, 0);
  std::vector<std::set<El::BigFloat>> points(num_blocks);
  std::vector<std::vector<El::BigFloat>> new_points(num_blocks);

  // GMP does not have a special infinity value, so we use max double.
  const El::BigFloat infinity(std::numeric_limits<double>::max());
  // Use the input points and add inifinty
  for(size_t block(0); block < num_blocks; ++block)
    {
      for(auto &point : initial_points.at(block))
        {
          points.at(block).emplace(point);
        }
      points.at(block).emplace(infinity);
    }

  // TODO: This is duplicated from sdp2input/write_output/write_output.cxx
  size_t max_index(0);
  El::BigFloat max_normalization(0);
  for(size_t index(0); index != normalization.size(); ++index)
    {
      const El::BigFloat element(Abs(normalization[index]));
      if(element > max_normalization)
        {
          max_normalization = element;
          max_index = index;
        }
    }

  const El::Grid global_grid;
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_to_y_star(global_grid),
    dual_objective_b_star(global_grid);
  El::BigFloat primal_c_scale;

  parameters.solver.duality_gap_threshold = 1.1;
  El::Matrix<El::BigFloat> yp_saved(yp_to_y_star.Height(), 1);
  El::Zero(yp_saved);

  int64_t current_generation(0);
  boost::optional<int64_t> backup_generation;
  load_checkpoint(parameters.solver.checkpoint_in, backup_generation,
                  current_generation, yp_to_y_star, dual_objective_b_star,
                  yp_saved, points, parameters.solver.duality_gap_threshold,
                  primal_c_scale);
  if(backup_generation)
    {
      El::Matrix<El::BigFloat> y(yp_saved.Height(), 1);

      El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),
               yp_to_y_star.LockedMatrix(), yp_saved, El::BigFloat(0.0), y);

      if(El::mpi::Rank() == 0 && parameters.verbosity >= Verbosity::regular)
        {
          std::cout << "Loaded checkpoint " << backup_generation << "\n";
        }
      fill_weights(y, max_index, normalization, weights);
    }
  else
    {
      compute_y_transform(function_blocks, points, objectives, normalization,
                          parameters, max_index, global_grid, yp_to_y_star,
                          dual_objective_b_star, primal_c_scale);
    }

  while(parameters.solver.duality_gap_threshold
        > parameters_in.solver.duality_gap_threshold)
    {
      std::map<size_t, size_t> new_to_old;
      size_t num_constraints(0), old_index(0);
      std::vector<size_t> matrix_dimensions;
      for(size_t block(0); block != num_blocks; ++block)
        {
          for(size_t offset(0); offset != points.at(block).size(); ++offset)
            {
              new_to_old.emplace(num_constraints + offset, old_index + offset);
            }
          old_index += points.at(block).size();
          for(auto &point : new_points.at(block))
            {
              points.at(block).emplace(point);
            }
          num_constraints += points.at(block).size();
          matrix_dimensions.insert(matrix_dimensions.end(),
                                   points.at(block).size(),
                                   function_blocks[block].size());
          if(rank == 0 && parameters.verbosity >= Verbosity::debug)
            {
              std::cout << "points: " << block << " " << points.at(block)
                        << "\n";
            }
        }
      if(rank == 0 && parameters.verbosity >= Verbosity::regular)
        {
          std::cout << "num_constraints: " << num_constraints << "\n";
        }

      std::vector<std::vector<El::BigFloat>> primal_objective_c;
      primal_objective_c.reserve(num_constraints);
      std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
      free_var_matrix.reserve(num_constraints);

      setup_constraints(max_index, num_blocks, infinity, function_blocks,
                        normalization, points, primal_objective_c,
                        free_var_matrix);

      const El::BigFloat objective_const(objectives.at(max_index)
                                         / normalization.at(max_index));

      Block_Info block_info(matrix_dimensions, parameters.verbosity);

      El::Grid grid(block_info.mpi_comm.value);

      SDP sdp(objective_const, primal_objective_c, free_var_matrix,
              yp_to_y_star, dual_objective_b_star, primal_c_scale, block_info,
              grid);

      SDP_Solver solver(parameters.solver, parameters.verbosity,
                        parameters.require_initial_checkpoint, block_info,
                        grid, sdp.dual_objective_b.Height());

      for(auto &y_block : solver.y.blocks)
        {
          copy_matrix(yp_saved, y_block);
        }

      boost::property_tree::ptree parameter_properties(
        to_property_tree(parameters));
      bool has_new_points(false);
      while(!has_new_points
            && parameters.solver.duality_gap_threshold
                 > parameters_in.solver.duality_gap_threshold)
        {
          if(rank == 0 && parameters.verbosity >= Verbosity::regular)
            {
              std::cout << "Threshold: "
                        << parameters.solver.duality_gap_threshold << "\n";
            }

          Timers timers(parameters.verbosity >= Verbosity::debug);
          SDP_Solver_Terminate_Reason reason
            = solver.run(parameters.solver, parameters.verbosity,
                         parameter_properties, block_info, sdp, grid, timers);

          if(rank == 0 && parameters.verbosity >= Verbosity::regular)
            {
              set_stream_precision(std::cout);
              std::cout << "-----" << reason << "-----\n"
                        << '\n'
                        << "primalObjective = " << solver.primal_objective
                        << '\n'
                        << "dualObjective   = " << solver.dual_objective
                        << '\n'
                        << "dualityGap      = " << solver.duality_gap << '\n'
                        << "primalError     = " << solver.primal_error()
                        << '\n'
                        << "dualError       = " << solver.dual_error << '\n'
                        << '\n';
            }

          if(reason == SDP_Solver_Terminate_Reason::MaxComplementarityExceeded
             || reason == SDP_Solver_Terminate_Reason::MaxIterationsExceeded
             || reason == SDP_Solver_Terminate_Reason::MaxRuntimeExceeded)
            {
              std::stringstream ss;
              ss << "Can not find solution: " << reason;
              throw std::runtime_error(ss.str());
            }

          El::Matrix<El::BigFloat> y(dual_objective_b_star.Height(), 1);
          El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(
            solver.y.blocks.at(0));

          El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),
                   yp_to_y_star.LockedMatrix(), yp_star.LockedMatrix(),
                   El::BigFloat(0.0), y);

          fill_weights(y, max_index, normalization, weights);
          if(rank == 0 && parameters.verbosity >= Verbosity::regular)
            {
              set_stream_precision(std::cout);
              std::cout << "weight: " << weights << "\n";

              El::BigFloat optimal(0);
              for(size_t index(0); index < objectives.size(); ++index)
                {
                  optimal += objectives[index] * weights[index];
                }
              std::cout << "optimal: " << optimal << "\n";
            }
          find_new_points(num_blocks, rank, num_procs, infinity,
                          function_blocks, weights, points, new_points,
                          has_new_points);
          if(!has_new_points)
            {
              parameters.solver.duality_gap_threshold
                /= parameters.duality_gap_reduction;
            }
        }
      El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(
        solver.y.blocks.front());
      copy_matrix(yp_star, yp_saved);
      save_checkpoint(parameters.solver.checkpoint_out, parameters.verbosity,
                      yp_to_y_star, dual_objective_b_star, yp_saved, points,
                      infinity, parameters.solver.duality_gap_threshold,
                      primal_c_scale, backup_generation, current_generation);
    }
  return weights;
}
<commit_msg>Make things more quiet by default<commit_after>#include "../Outer_Parameters.hxx"
#include "setup_constraints.hxx"

#include "../../ostream_set.hxx"
#include "../../ostream_map.hxx"
#include "../../ostream_vector.hxx"
#include "../../set_stream_precision.hxx"

namespace
{}

void compute_y_transform(
  const std::vector<std::vector<std::vector<std::vector<Function>>>>
    &function_blocks,
  const std::vector<std::set<El::BigFloat>> &points,
  const std::vector<El::BigFloat> &objectives,
  const std::vector<El::BigFloat> &normalization,
  const Outer_Parameters &parameters, const size_t &max_index,
  const El::Grid &global_grid,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
  El::BigFloat &primal_c_scale);

boost::optional<int64_t> load_checkpoint(
  const boost::filesystem::path &checkpoint_directory,
  boost::optional<int64_t> &backup_generation, int64_t &current_generation,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
  El::Matrix<El::BigFloat> &y, std::vector<std::set<El::BigFloat>> &points,
  El::BigFloat &threshold, El::BigFloat &primal_c_scale);

void copy_matrix(const El::Matrix<El::BigFloat> &source,
                 El::DistMatrix<El::BigFloat> &destination);
void copy_matrix(const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &source,
                 El::Matrix<El::BigFloat> &destination);

void fill_weights(const El::Matrix<El::BigFloat> &y, const size_t &max_index,
                  const std::vector<El::BigFloat> &normalization,
                  std::vector<El::BigFloat> &weights);

void find_new_points(
  const size_t &num_blocks, const size_t &rank, const size_t &num_procs,
  const El::BigFloat &infinity,
  const std::vector<std::vector<std::vector<std::vector<Function>>>>
    &function_blocks,
  const std::vector<El::BigFloat> &weights,
  const std::vector<std::set<El::BigFloat>> &points,
  std::vector<std::vector<El::BigFloat>> &new_points, bool &has_new_points);

void save_checkpoint(
  const boost::filesystem::path &checkpoint_directory,
  const Verbosity &verbosity,
  const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &yp_to_y_star,
  const El::DistMatrix<El::BigFloat, El::STAR, El::STAR> &dual_objective_b_star,
  const El::Matrix<El::BigFloat> &y,
  const std::vector<std::set<El::BigFloat>> &points,
  const El::BigFloat &infinity, const El::BigFloat &threshold,
  const El::BigFloat &primal_c_scale,
  boost::optional<int64_t> &backup_generation, int64_t &current_generation);

std::vector<El::BigFloat> compute_optimal(
  const std::vector<std::vector<std::vector<std::vector<Function>>>>
    &function_blocks,
  const std::vector<std::vector<El::BigFloat>> &initial_points,
  const std::vector<El::BigFloat> &objectives,
  const std::vector<El::BigFloat> &normalization,
  const Outer_Parameters &parameters_in)
{
  if(initial_points.size() != function_blocks.size())
    {
      throw std::runtime_error(
        "Size are different: Positive_Matrix_With_Prefactor: "
        + std::to_string(function_blocks.size())
        + ", initial points: " + std::to_string(initial_points.size()));
    }
  Outer_Parameters parameters(parameters_in);
  if(parameters.verbosity != Verbosity::debug)
    {
      parameters.verbosity = Verbosity::none;
    }

  const size_t rank(El::mpi::Rank()), num_procs(El::mpi::Size()),
    num_weights(normalization.size());

  const size_t num_blocks(initial_points.size());
  std::vector<El::BigFloat> weights(num_weights, 0);
  std::vector<std::set<El::BigFloat>> points(num_blocks);
  std::vector<std::vector<El::BigFloat>> new_points(num_blocks);

  // GMP does not have a special infinity value, so we use max double.
  const El::BigFloat infinity(std::numeric_limits<double>::max());
  // Use the input points and add inifinty
  for(size_t block(0); block < num_blocks; ++block)
    {
      for(auto &point : initial_points.at(block))
        {
          points.at(block).emplace(point);
        }
      points.at(block).emplace(infinity);
    }

  // TODO: This is duplicated from sdp2input/write_output/write_output.cxx
  size_t max_index(0);
  El::BigFloat max_normalization(0);
  for(size_t index(0); index != normalization.size(); ++index)
    {
      const El::BigFloat element(Abs(normalization[index]));
      if(element > max_normalization)
        {
          max_normalization = element;
          max_index = index;
        }
    }

  const El::Grid global_grid;
  El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_to_y_star(global_grid),
    dual_objective_b_star(global_grid);
  El::BigFloat primal_c_scale;

  parameters.solver.duality_gap_threshold = 1.1;
  El::Matrix<El::BigFloat> yp_saved(yp_to_y_star.Height(), 1);
  El::Zero(yp_saved);

  int64_t current_generation(0);
  boost::optional<int64_t> backup_generation;
  load_checkpoint(parameters.solver.checkpoint_in, backup_generation,
                  current_generation, yp_to_y_star, dual_objective_b_star,
                  yp_saved, points, parameters.solver.duality_gap_threshold,
                  primal_c_scale);
  if(backup_generation)
    {
      El::Matrix<El::BigFloat> y(yp_saved.Height(), 1);

      El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),
               yp_to_y_star.LockedMatrix(), yp_saved, El::BigFloat(0.0), y);

      if(El::mpi::Rank() == 0 && parameters_in.verbosity >= Verbosity::regular)
        {
          std::cout << "Loaded checkpoint " << backup_generation << "\n";
        }
      fill_weights(y, max_index, normalization, weights);
    }
  else
    {
      compute_y_transform(function_blocks, points, objectives, normalization,
                          parameters, max_index, global_grid, yp_to_y_star,
                          dual_objective_b_star, primal_c_scale);
    }

  while(parameters.solver.duality_gap_threshold
        > parameters_in.solver.duality_gap_threshold)
    {
      std::map<size_t, size_t> new_to_old;
      size_t num_constraints(0), old_index(0);
      std::vector<size_t> matrix_dimensions;
      for(size_t block(0); block != num_blocks; ++block)
        {
          for(size_t offset(0); offset != points.at(block).size(); ++offset)
            {
              new_to_old.emplace(num_constraints + offset, old_index + offset);
            }
          old_index += points.at(block).size();
          for(auto &point : new_points.at(block))
            {
              points.at(block).emplace(point);
            }
          num_constraints += points.at(block).size();
          matrix_dimensions.insert(matrix_dimensions.end(),
                                   points.at(block).size(),
                                   function_blocks[block].size());
          if(rank == 0 && parameters_in.verbosity >= Verbosity::debug)
            {
              std::cout << "points: " << block << " " << points.at(block)
                        << "\n";
            }
        }
      if(rank == 0 && parameters_in.verbosity >= Verbosity::regular)
        {
          std::cout << "num_constraints: " << num_constraints << "\n";
        }

      std::vector<std::vector<El::BigFloat>> primal_objective_c;
      primal_objective_c.reserve(num_constraints);
      std::vector<El::Matrix<El::BigFloat>> free_var_matrix;
      free_var_matrix.reserve(num_constraints);

      setup_constraints(max_index, num_blocks, infinity, function_blocks,
                        normalization, points, primal_objective_c,
                        free_var_matrix);

      const El::BigFloat objective_const(objectives.at(max_index)
                                         / normalization.at(max_index));

      Block_Info block_info(matrix_dimensions, parameters.verbosity);

      El::Grid grid(block_info.mpi_comm.value);

      SDP sdp(objective_const, primal_objective_c, free_var_matrix,
              yp_to_y_star, dual_objective_b_star, primal_c_scale, block_info,
              grid);

      SDP_Solver solver(parameters.solver, parameters.verbosity,
                        parameters.require_initial_checkpoint, block_info,
                        grid, sdp.dual_objective_b.Height());

      for(auto &y_block : solver.y.blocks)
        {
          copy_matrix(yp_saved, y_block);
        }

      boost::property_tree::ptree parameter_properties(
        to_property_tree(parameters));
      bool has_new_points(false);
      while(!has_new_points
            && parameters.solver.duality_gap_threshold
                 > parameters_in.solver.duality_gap_threshold)
        {
          if(rank == 0 && parameters_in.verbosity >= Verbosity::regular)
            {
              std::cout << "Threshold: "
                        << parameters.solver.duality_gap_threshold << "\n";
            }

          Timers timers(parameters.verbosity >= Verbosity::debug);
          SDP_Solver_Terminate_Reason reason
            = solver.run(parameters.solver, parameters.verbosity,
                         parameter_properties, block_info, sdp, grid, timers);

          if(rank == 0 && parameters_in.verbosity >= Verbosity::regular)
            {
              set_stream_precision(std::cout);
              std::cout << "-----" << reason << "-----\n"
                        << '\n'
                        << "primalObjective = " << solver.primal_objective
                        << '\n'
                        << "dualObjective   = " << solver.dual_objective
                        << '\n'
                        << "dualityGap      = " << solver.duality_gap << '\n'
                        << "primalError     = " << solver.primal_error()
                        << '\n'
                        << "dualError       = " << solver.dual_error << '\n'
                        << '\n';
            }

          if(reason == SDP_Solver_Terminate_Reason::MaxComplementarityExceeded
             || reason == SDP_Solver_Terminate_Reason::MaxIterationsExceeded
             || reason == SDP_Solver_Terminate_Reason::MaxRuntimeExceeded)
            {
              std::stringstream ss;
              ss << "Can not find solution: " << reason;
              throw std::runtime_error(ss.str());
            }

          El::Matrix<El::BigFloat> y(dual_objective_b_star.Height(), 1);
          El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(
            solver.y.blocks.at(0));

          El::Gemv(El::Orientation::NORMAL, El::BigFloat(1.0),
                   yp_to_y_star.LockedMatrix(), yp_star.LockedMatrix(),
                   El::BigFloat(0.0), y);

          fill_weights(y, max_index, normalization, weights);
          if(rank == 0 && parameters_in.verbosity >= Verbosity::regular)
            {
              set_stream_precision(std::cout);
              std::cout << "weight: " << weights << "\n";

              El::BigFloat optimal(0);
              for(size_t index(0); index < objectives.size(); ++index)
                {
                  optimal += objectives[index] * weights[index];
                }
              std::cout << "optimal: " << optimal << "\n";
            }
          find_new_points(num_blocks, rank, num_procs, infinity,
                          function_blocks, weights, points, new_points,
                          has_new_points);
          if(!has_new_points)
            {
              parameters.solver.duality_gap_threshold
                /= parameters.duality_gap_reduction;
            }
        }
      El::DistMatrix<El::BigFloat, El::STAR, El::STAR> yp_star(
        solver.y.blocks.front());
      copy_matrix(yp_star, yp_saved);
      save_checkpoint(parameters.solver.checkpoint_out,
                      parameters_in.verbosity, yp_to_y_star,
                      dual_objective_b_star, yp_saved, points, infinity,
                      parameters.solver.duality_gap_threshold, primal_c_scale,
                      backup_generation, current_generation);
    }
  return weights;
}
<|endoftext|>


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

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

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

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

#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"

#include <memory>

#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "tensorflow/lite/core/shims/cc/shims_test_util.h"
#include "tensorflow/lite/kernels/builtin_op_kernels.h"
#include "tensorflow/lite/mutable_op_resolver.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/port/status_matchers.h"
#include "tensorflow_lite_support/cc/task/core/task_api_factory.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/core/tflite_engine.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h"

namespace tflite {
namespace task {
namespace vision {
namespace {

using ::testing::HasSubstr;
using ::testing::Optional;
using ::testing::ElementsAreArray;
using ::tflite::support::kTfLiteSupportPayload;
using ::tflite::support::StatusOr;
using ::tflite::support::TfLiteSupportStatus;
using ::tflite::task::JoinPath;
using ::tflite::task::core::PopulateTensor;
using ::tflite::task::core::TaskAPIFactory;
using ::tflite::task::core::TfLiteEngine;

constexpr char kTestDataDirectory[] =
    "tensorflow_lite_support/cc/test/testdata/task/vision/";

constexpr std::string kModelPath =
    "tensorflow_lite_support/cc/test/testdata/task/vision/dilated_conv.tflite";

StatusOr<ImageData> LoadImage(std::string image_name) {
  return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
                                      kTestDataDirectory, image_name));
}

class DynamicInputTest : public tflite_shims::testing::Test {
    public:
        void SetUp()
        {
            engine = absl::make_unique<TfLiteEngine>();
            engine->BuildModelFromFile(kModelPath);
            engine->InitInterpreter();

            ASSERT_OK_AND_ASSIGN(preprocessor， processor::ImagePreprocessor::Create(
                engine.get(), {0}));
        }
    private:
        std::unique_ptr<ImagePreprocessor> preprocessor;
        std::unique_ptr<TfLiteEngine> engine;
};

// See if input tensor dims signature for height and width is -1
// because it is so in the model.
TEST_F(DynamicInputTest, InputHeightAndWidthMutable)
{
    const TfLiteIntArray* input_dims_signature =
        preprocessor->Tensor()->dims_signature;
    EXPECT_EQ(input_dims_signature->data[1], -1);
    EXPECT_EQ(input_dims_signature->data[2], -1);
}

// See if output tensor has been re-dimmed as per the input
// tensor.
TEST_F(DynamicInputTest, OutputHeightAndWidthMutable)
{
    SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg"));
    std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer(
        image.pixel_data, FrameBuffer::Dimension{image.width, image.height});

    preprocessor->Preprocess(image_frame_buffer);
    const TFLiteIntArray* output_dims = engine->GetOutputs()[0]->dims;

    const size_t input_height = Tensor()->dims->data[1];
    const size_t input_width = Tensor()->dims->data[2];
    const size_t output_height = output_dims->data[1];
    const size_t output_width = output_dims->data[2];

    EXPECT_EQ(input_height, output_height);
    EXPECT_EQ(input_width, output_width);
}
}  // namespace
}  // namespace vision
}  // namespace task
}  // namespace tflite
<commit_msg>clang-format it.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.

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

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

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

#include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h"

#include <memory>

#include "absl/flags/flag.h"
#include "absl/status/status.h"
#include "absl/strings/cord.h"
#include "tensorflow/lite/core/shims/cc/shims_test_util.h"
#include "tensorflow/lite/kernels/builtin_op_kernels.h"
#include "tensorflow/lite/mutable_op_resolver.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/port/status_matchers.h"
#include "tensorflow_lite_support/cc/task/core/task_api_factory.h"
#include "tensorflow_lite_support/cc/task/core/task_utils.h"
#include "tensorflow_lite_support/cc/task/core/tflite_engine.h"
#include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h"

namespace tflite {
namespace task {
namespace vision {
namespace {

using ::testing::ElementsAreArray;
using ::testing::HasSubstr;
using ::testing::Optional;
using ::tflite::support::kTfLiteSupportPayload;
using ::tflite::support::StatusOr;
using ::tflite::support::TfLiteSupportStatus;
using ::tflite::task::JoinPath;
using ::tflite::task::core::PopulateTensor;
using ::tflite::task::core::TaskAPIFactory;
using ::tflite::task::core::TfLiteEngine;

constexpr char kTestDataDirectory[] =
    "tensorflow_lite_support/cc/test/testdata/task/vision/";

constexpr std::string kModelPath =
    "tensorflow_lite_support/cc/test/testdata/task/vision/dilated_conv.tflite";

StatusOr<ImageData> LoadImage(std::string image_name) {
  return DecodeImageFromFile(
      JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name));
}

class DynamicInputTest : public tflite_shims::testing::Test {
 public:
  void SetUp() {
    engine = absl::make_unique<TfLiteEngine>();
    engine->BuildModelFromFile(kModelPath);
    engine->InitInterpreter();

    ASSERT_OK_AND_ASSIGN(
        preprocessor， processor::ImagePreprocessor::Create(engine.get(), {0}));
  }

 private:
  std::unique_ptr<ImagePreprocessor> preprocessor;
  std::unique_ptr<TfLiteEngine> engine;
};

// See if input tensor dims signature for height and width is -1
// because it is so in the model.
TEST_F(DynamicInputTest, InputHeightAndWidthMutable) {
  const TfLiteIntArray* input_dims_signature =
      preprocessor->Tensor()->dims_signature;
  EXPECT_EQ(input_dims_signature->data[1], -1);
  EXPECT_EQ(input_dims_signature->data[2], -1);
}

// See if output tensor has been re-dimmed as per the input
// tensor.
TEST_F(DynamicInputTest, OutputHeightAndWidthMutable) {
  SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg"));
  std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer(
      image.pixel_data, FrameBuffer::Dimension{image.width, image.height});

  preprocessor->Preprocess(image_frame_buffer);
  const TFLiteIntArray* output_dims = engine->GetOutputs()[0]->dims;

  const size_t input_height = Tensor()->dims->data[1];
  const size_t input_width = Tensor()->dims->data[2];
  const size_t output_height = output_dims->data[1];
  const size_t output_width = output_dims->data[2];

  EXPECT_EQ(input_height, output_height);
  EXPECT_EQ(input_width, output_width);
}
}  // namespace
}  // namespace vision
}  // namespace task
}  // namespace tflite
<|endoftext|>


<commit_before>
#include <stdio.h>
#include <string>
#include "statesaver.h"

using namespace std;

StateSaver::StateSaver(QMTopology& qmtop, string &filein, string & fileout){
    Open(qmtop, filein, fileout);
}

void StateSaver::Open(QMTopology &qmtop, string &filein, string & fileout) {
    _qmtop = &qmtop;
    _out.open(fileout.c_str(),ios::binary|ios::out);
    _in.open(filein.c_str(), ios::in | ios::binary);
    _mode = 'b';
}

StateSaver::StateSaver(QMTopology& qmtop, string & file, const char & mode){
    Open(qmtop, file, mode);
}

void StateSaver::Open(QMTopology &qmtop, string &file, const char & mode) {
    _qmtop = &qmtop;
    _mode = mode;
    if (mode == 'w') {_out.open( file.c_str(),ios::binary|ios::out);}
    else if (mode == 'r') {_in.open(file.c_str(), ios::in | ios::binary);}
    else {
        throw runtime_error(string("Open mode not available" ) + mode );
    }
}

//void StateSaver::Open(string file)

void StateSaver::Save() {

    streampos start = _out.tellp();
    _startpos.push_back(start);
    Write_TimeStep();
    Write_PBCs();
    Write_Molecules();
    Write_QMBeads();
    Write_QMNeighbourlist();
    //Write NBL
    //_out.close();
    //_out = datafile(datafile.c_str(), ios::binary|ios::out);
}

void StateSaver::Close(){
    if (_mode == 'w' || _mode == 'b'){
        vector <streampos>::iterator itb=_startpos.begin();
        for ( ;itb !=_startpos.end(); ++itb){
            write<streampos>(*itb);
        }
        write<int>(_startpos.size());
        _out.close();
    }
    if (_mode == 'r' || _mode == 'b'){
        _in.close();
    }
}

void StateSaver::Load() {
    _qmtop->Cleanup();
    _qmtop->nblist().Cleanup();
    _qmtop->CreateResidue("dummy");

    Read_TimeStep();
    Read_PBCs();
    Read_Molecules();
    Read_QMBeads();
    Read_QMNeighbourlist();
}

void StateSaver::Write_TimeStep(){
    write<double>(_qmtop->getTime());
    write<int>(_qmtop->getStep());
}

void StateSaver::Write_PBCs(){
    write<matrix>(_qmtop->getBox());
}

void StateSaver::Write_Molecules() {
    assert(_out.is_open());

    write<unsigned long>(_qmtop->MoleculeCount());
    for (MoleculeContainer::iterator iter = _qmtop->Molecules().begin();
            iter != _qmtop->Molecules().end() ; ++iter) {
         Molecule *mol=*iter;
    write<int>(mol->getId());
    write<string>(mol->getName());
    //write<int>(mol->BeadCount());
        }
    }

void StateSaver::Write_QMBeads() {
    assert(_out.is_open());

    write<unsigned long>(_qmtop->BeadCount());
    for (BeadContainer::iterator iter = _qmtop->Beads().begin();
            iter != _qmtop->Beads().end(); ++iter) {
        QMBead *bi = dynamic_cast<QMBead*> (*iter);

        write<byte_t > (bi->getSymmetry());
        write<string > (bi->getName());
        write<string > (bi->getType()->getName());
        write<int>(bi->getResnr());
        write<double>(bi->getM());
        write<double>(bi->getQ());

        write<string > (bi->GetCrgUnit()->getName());
        write<double > (bi->GetCrgUnit()->getEnergy());
        write<unsigned short>(bi->getiPos());
        write<vec > (bi->getPos());
        write<vec > (bi->getU());
        write<vec > (bi->getV());
        write<int>(bi->getMolecule()->getId());

    }
}

void StateSaver::Write_QMNeighbourlist() {
    assert(_out.is_open());

    QMNBList &nblist = _qmtop->nblist();

    write<int>(nblist.size());//?
    //cout <<"There are so many pairs in nblist: " <<(int)nblist.size()<<"\n";
    for(QMNBList::iterator iter = nblist.begin();
        iter!=nblist.end();++iter) {
        QMPair *pair = *iter;
        CrgUnit *crg1 = (*iter)->first;
        CrgUnit *crg2 = (*iter)->second;

        write<unsigned int>(crg1->getId());
        write<unsigned int>(crg2->getId());
        write<string > (crg1->getName());
        write<string > (crg2->getName());
        write<int>(pair->Js().size());
        vector<double>::iterator itj=pair->Js().begin();
        for (;itj!= pair->Js().end(); itj++){
            write<double>(*itj);
        }
        write<double>(pair->rate12());
        write<double>(pair->rate21());
        write<vec>(pair->r());
    }
    //
    //write<unsigned long>(_qmtop->BeadCount());
}

void StateSaver::Read_TimeStep(){
    assert(_in.is_open());

    _qmtop->setTime(read<double>());
    _qmtop->setStep(read<int>());
}

void StateSaver::Read_PBCs(){
    assert(_in.is_open());

    _qmtop->setBox(read<matrix>());
}

void StateSaver::Read_Molecules(){
    assert(_in.is_open());

    unsigned long nr_mols = read<unsigned long>();
    //cout << "Total number of mols is " << nr_mols << "\n";
    for (unsigned long i = 0; i < nr_mols; i++) {
        int molid=read<int>();
    //cout << "This molecule has id "<<molid<<"\n";
        string mol_name=read<string>();
    //cout << "This molecules has name "<<mol_name<<"\n";
    Molecule *mol = _qmtop->CreateMolecule(mol_name);
    }

}

void StateSaver::Read_QMBeads() {
    assert(_in.is_open());

    unsigned long nr_qmbeads = read<unsigned long>();
    //cout << "Total number of QMBeads is " << nr_qmbeads << "\n";
    for (unsigned long i = 0; i < nr_qmbeads; i++) {

        byte_t symmetry =       read<byte_t> ();
        string bead_name =      read<string> ();
        string type_name =      read<string> ();
        int resnr =             read<int>();
        double M =              read<double>();
        double Q =              read<double>();

        string crg_unit_name =  read<string> ();
        double energy = read<double>();

        unsigned short ipos =   read<unsigned short>();
        vec Pos =               read<vec> ();
        vec U =                 read<vec> ();
        vec V =                 read<vec> ();
        int molid =             read<int>();

        BeadType *type = _qmtop->GetOrCreateBeadType(type_name);

        /*cout << "Bead Symmetry " << (int)symmetry << "\n";
        cout << "Bead Name " << bead_name << "\n";
        cout << "Bead Type " << type_name << "\n";
        cout << "Residue Number " << resnr << "\n";
        cout << "Bead Mass " << M << "\n";
        cout << "Bead Charge " << Q << "\n";
        cout << "Molid  " << molid << "\n";*/

        QMBead *bead = dynamic_cast<QMBead*>(_qmtop->CreateBead(symmetry, bead_name, type, resnr, M, Q));
        _qmtop->getMolecule(molid)->AddBead(bead, bead_name);

        CrgUnit * acrg = _qmtop->GetCrgUnitByName(crg_unit_name);
        if(acrg == NULL)
            acrg = _qmtop->CreateCrgUnit(crg_unit_name, type_name, molid);
        acrg->setEnergy(energy);

        bead->setCrg(acrg);
        bead->setiPos(ipos);
        bead->setPos(Pos);
        bead->setU(U);
        bead->setV(V);
        bead->UpdateCrg();

        /*cout << "The charge unit is called " << crg_unit_name << "\n";
        cout << "This charge unit has energy " << energy <<"\n";
        cout << "This bead is at int position " << ipos << "\n";
        cout << "This bead hast position  " << U << "\n";
        cout << "This bead has U " << U << "\n";
        cout << "This bead has V " << V << "\n";*/
    }
}

void StateSaver::Read_QMNeighbourlist() {
    assert(_in.is_open());

    int nr_pairs = read<int>();
    //cout << "Total number of QMPairs is " << nr_pairs << "\n";
    for (int i = 0; i < nr_pairs; i++) {

        unsigned int id1=read<unsigned int>();
        unsigned int id2=read<unsigned int>();
        string crg_unit_name1 =  read<string> ();
        string crg_unit_name2 =  read<string> ();
        //cout << "This pair has charge unit ids " << id1 << " and " <<id2 <<"\n";

        CrgUnit *crg1=_qmtop->GetCrgUnitByName(crg_unit_name1);
        CrgUnit *crg2=_qmtop->GetCrgUnitByName(crg_unit_name2);
        //cout << "This pair has names " << crg_unit_name1 << " and " <<crg_unit_name2 <<"\n";

        QMPair *pair=new QMPair(crg1,crg2, _qmtop);
        _qmtop->nblist().AddPair(pair);
        int sizeJs=read<int>();
        vector <double> Js;
        for (int s=0;s<sizeJs;s++){
            double J=read<double>();
            Js.push_back(J);
            //cout << "This pair has J " << J <<"\n";
        }
        pair->setJs(Js);

        double rate12=read<double>();
        double rate21=read<double>();
        pair->setRate12(rate12);
        pair->setRate21(rate21);
        //cout << "This pair has rates " << rate12 << " and " << rate21 <<"\n";

        pair->setR(read<vec>());
        //cout << "This pair has connecting vector r_ij = " << pair->r() << endl;
    }
}

bool StateSaver::Seek(const int& pos){

    _in.seekg (- sizeof(int), ios::end); // put in at the end;
    int n = read<int>();
    if (pos> n){
        return false;
    }
    _in.seekg (- sizeof(int) - (n-pos) * sizeof(streampos) , ios::end); // put in at the end;
    streampos newpos = read<streampos>();
    _in.seekg(newpos, ios::beg);
    return true;
}<commit_msg>update error message<commit_after>
#include <stdio.h>
#include <string>
#include "statesaver.h"

using namespace std;

StateSaver::StateSaver(QMTopology& qmtop, string &filein, string & fileout){
    Open(qmtop, filein, fileout);
}

void StateSaver::Open(QMTopology &qmtop, string &filein, string & fileout) {
    _qmtop = &qmtop;
    _out.open(fileout.c_str(),ios::binary|ios::out);
    _in.open(filein.c_str(), ios::in | ios::binary);
    _mode = 'b';
}

StateSaver::StateSaver(QMTopology& qmtop, string & file, const char & mode){
    Open(qmtop, file, mode);
}

void StateSaver::Open(QMTopology &qmtop, string &file, const char & mode) {
    _qmtop = &qmtop;
    _mode = mode;
    if (mode == 'w') {_out.open( file.c_str(),ios::binary|ios::out);}
    else if (mode == 'r') {_in.open(file.c_str(), ios::in | ios::binary);}
    else {
        throw runtime_error(string("Open mode not available: " ) + mode );
    }
}

//void StateSaver::Open(string file)

void StateSaver::Save() {

    streampos start = _out.tellp();
    _startpos.push_back(start);
    Write_TimeStep();
    Write_PBCs();
    Write_Molecules();
    Write_QMBeads();
    Write_QMNeighbourlist();
    //Write NBL
    //_out.close();
    //_out = datafile(datafile.c_str(), ios::binary|ios::out);
}

void StateSaver::Close(){
    if (_mode == 'w' || _mode == 'b'){
        vector <streampos>::iterator itb=_startpos.begin();
        for ( ;itb !=_startpos.end(); ++itb){
            write<streampos>(*itb);
        }
        write<int>(_startpos.size());
        _out.close();
    }
    if (_mode == 'r' || _mode == 'b'){
        _in.close();
    }
}

void StateSaver::Load() {
    _qmtop->Cleanup();
    _qmtop->nblist().Cleanup();
    _qmtop->CreateResidue("dummy");

    Read_TimeStep();
    Read_PBCs();
    Read_Molecules();
    Read_QMBeads();
    Read_QMNeighbourlist();
}

void StateSaver::Write_TimeStep(){
    write<double>(_qmtop->getTime());
    write<int>(_qmtop->getStep());
}

void StateSaver::Write_PBCs(){
    write<matrix>(_qmtop->getBox());
}

void StateSaver::Write_Molecules() {
    assert(_out.is_open());

    write<unsigned long>(_qmtop->MoleculeCount());
    for (MoleculeContainer::iterator iter = _qmtop->Molecules().begin();
            iter != _qmtop->Molecules().end() ; ++iter) {
         Molecule *mol=*iter;
    write<int>(mol->getId());
    write<string>(mol->getName());
    //write<int>(mol->BeadCount());
        }
    }

void StateSaver::Write_QMBeads() {
    assert(_out.is_open());

    write<unsigned long>(_qmtop->BeadCount());
    for (BeadContainer::iterator iter = _qmtop->Beads().begin();
            iter != _qmtop->Beads().end(); ++iter) {
        QMBead *bi = dynamic_cast<QMBead*> (*iter);

        write<byte_t > (bi->getSymmetry());
        write<string > (bi->getName());
        write<string > (bi->getType()->getName());
        write<int>(bi->getResnr());
        write<double>(bi->getM());
        write<double>(bi->getQ());

        write<string > (bi->GetCrgUnit()->getName());
        write<double > (bi->GetCrgUnit()->getEnergy());
        write<unsigned short>(bi->getiPos());
        write<vec > (bi->getPos());
        write<vec > (bi->getU());
        write<vec > (bi->getV());
        write<int>(bi->getMolecule()->getId());

    }
}

void StateSaver::Write_QMNeighbourlist() {
    assert(_out.is_open());

    QMNBList &nblist = _qmtop->nblist();

    write<int>(nblist.size());//?
    //cout <<"There are so many pairs in nblist: " <<(int)nblist.size()<<"\n";
    for(QMNBList::iterator iter = nblist.begin();
        iter!=nblist.end();++iter) {
        QMPair *pair = *iter;
        CrgUnit *crg1 = (*iter)->first;
        CrgUnit *crg2 = (*iter)->second;

        write<unsigned int>(crg1->getId());
        write<unsigned int>(crg2->getId());
        write<string > (crg1->getName());
        write<string > (crg2->getName());
        write<int>(pair->Js().size());
        vector<double>::iterator itj=pair->Js().begin();
        for (;itj!= pair->Js().end(); itj++){
            write<double>(*itj);
        }
        write<double>(pair->rate12());
        write<double>(pair->rate21());
        write<vec>(pair->r());
    }
    //
    //write<unsigned long>(_qmtop->BeadCount());
}

void StateSaver::Read_TimeStep(){
    assert(_in.is_open());

    _qmtop->setTime(read<double>());
    _qmtop->setStep(read<int>());
}

void StateSaver::Read_PBCs(){
    assert(_in.is_open());

    _qmtop->setBox(read<matrix>());
}

void StateSaver::Read_Molecules(){
    assert(_in.is_open());

    unsigned long nr_mols = read<unsigned long>();
    //cout << "Total number of mols is " << nr_mols << "\n";
    for (unsigned long i = 0; i < nr_mols; i++) {
        int molid=read<int>();
    //cout << "This molecule has id "<<molid<<"\n";
        string mol_name=read<string>();
    //cout << "This molecules has name "<<mol_name<<"\n";
    Molecule *mol = _qmtop->CreateMolecule(mol_name);
    }

}

void StateSaver::Read_QMBeads() {
    assert(_in.is_open());

    unsigned long nr_qmbeads = read<unsigned long>();
    //cout << "Total number of QMBeads is " << nr_qmbeads << "\n";
    for (unsigned long i = 0; i < nr_qmbeads; i++) {

        byte_t symmetry =       read<byte_t> ();
        string bead_name =      read<string> ();
        string type_name =      read<string> ();
        int resnr =             read<int>();
        double M =              read<double>();
        double Q =              read<double>();

        string crg_unit_name =  read<string> ();
        double energy = read<double>();

        unsigned short ipos =   read<unsigned short>();
        vec Pos =               read<vec> ();
        vec U =                 read<vec> ();
        vec V =                 read<vec> ();
        int molid =             read<int>();

        BeadType *type = _qmtop->GetOrCreateBeadType(type_name);

        /*cout << "Bead Symmetry " << (int)symmetry << "\n";
        cout << "Bead Name " << bead_name << "\n";
        cout << "Bead Type " << type_name << "\n";
        cout << "Residue Number " << resnr << "\n";
        cout << "Bead Mass " << M << "\n";
        cout << "Bead Charge " << Q << "\n";
        cout << "Molid  " << molid << "\n";*/

        QMBead *bead = dynamic_cast<QMBead*>(_qmtop->CreateBead(symmetry, bead_name, type, resnr, M, Q));
        _qmtop->getMolecule(molid)->AddBead(bead, bead_name);

        CrgUnit * acrg = _qmtop->GetCrgUnitByName(crg_unit_name);
        if(acrg == NULL)
            acrg = _qmtop->CreateCrgUnit(crg_unit_name, type_name, molid);
        acrg->setEnergy(energy);

        bead->setCrg(acrg);
        bead->setiPos(ipos);
        bead->setPos(Pos);
        bead->setU(U);
        bead->setV(V);
        bead->UpdateCrg();

        /*cout << "The charge unit is called " << crg_unit_name << "\n";
        cout << "This charge unit has energy " << energy <<"\n";
        cout << "This bead is at int position " << ipos << "\n";
        cout << "This bead hast position  " << U << "\n";
        cout << "This bead has U " << U << "\n";
        cout << "This bead has V " << V << "\n";*/
    }
}

void StateSaver::Read_QMNeighbourlist() {
    assert(_in.is_open());

    int nr_pairs = read<int>();
    //cout << "Total number of QMPairs is " << nr_pairs << "\n";
    for (int i = 0; i < nr_pairs; i++) {

        unsigned int id1=read<unsigned int>();
        unsigned int id2=read<unsigned int>();
        string crg_unit_name1 =  read<string> ();
        string crg_unit_name2 =  read<string> ();
        //cout << "This pair has charge unit ids " << id1 << " and " <<id2 <<"\n";

        CrgUnit *crg1=_qmtop->GetCrgUnitByName(crg_unit_name1);
        CrgUnit *crg2=_qmtop->GetCrgUnitByName(crg_unit_name2);
        //cout << "This pair has names " << crg_unit_name1 << " and " <<crg_unit_name2 <<"\n";

        QMPair *pair=new QMPair(crg1,crg2, _qmtop);
        _qmtop->nblist().AddPair(pair);
        int sizeJs=read<int>();
        vector <double> Js;
        for (int s=0;s<sizeJs;s++){
            double J=read<double>();
            Js.push_back(J);
            //cout << "This pair has J " << J <<"\n";
        }
        pair->setJs(Js);

        double rate12=read<double>();
        double rate21=read<double>();
        pair->setRate12(rate12);
        pair->setRate21(rate21);
        //cout << "This pair has rates " << rate12 << " and " << rate21 <<"\n";

        pair->setR(read<vec>());
        //cout << "This pair has connecting vector r_ij = " << pair->r() << endl;
    }
}

bool StateSaver::Seek(const int& pos){

    _in.seekg (- sizeof(int), ios::end); // put in at the end;
    int n = read<int>();
    if (pos> n){
        return false;
    }
    _in.seekg (- sizeof(int) - (n-pos) * sizeof(streampos) , ios::end); // put in at the end;
    streampos newpos = read<streampos>();
    _in.seekg(newpos, ios::beg);
    return true;
}<|endoftext|>


<commit_before>/** \copyright
 * Copyright (c) 2012, Stuart W Baker
 * 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.
 *
 * 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
 *
 * \file HwInit.cxx
 * This file represents the hardware initialization for the TI Tiva MCU.
 *
 * @author Stuart W. Baker
 * @date 5 January 2013
 */

#include <cstdint>
#include <new>

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "inc/hw_gpio.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "TivaDev.hxx"
#include "TivaDCC.hxx"
#include "TivaGPIO.hxx"

#include "dcc_control.hxx"
#include "hardware.hxx"
#include "DccHardware.hxx"

struct Debug {
  // High between start_cutout and end_cutout from the TivaRailcom driver.
  typedef DummyPin RailcomDriverCutout;
  // Flips every time an uart byte is received error.
  typedef DummyPin RailcomError;
  // Flips every time an 'E0' byte is received in the railcom driver.
  typedef DummyPin RailcomE0;

    typedef DummyPin RailcomDataReceived;
    typedef DummyPin RailcomAnyData;
    typedef DummyPin RailcomPackets;
};
#include "TivaRailcom.hxx"

/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";

/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";

/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";

/** USB Device CDC serial driver instance */
static TivaCdc cdc0("/dev/serUSB0", INT_RESOLVE(INT_USB0_, 0));

/** UART 0 serial driver instance */
static TivaUart uart2("/dev/ser0", UART2_BASE, INT_RESOLVE(INT_UART2_, 0));

/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));

// Bit storing whether our dcc output is enabled or not.
static bool g_dcc_on = false;

TivaRailcomDriver<RailcomDefs> railcom_driver("/dev/railcom");
TivaDCC<DccHwDefs> dcc_hw("/dev/mainline", &railcom_driver);

extern "C" {
/** Timer interrupt for DCC packet handling.
 */
void timer0a_interrupt_handler(void)
{
  dcc_hw.interrupt_handler();
}

void timer1a_interrupt_handler(void)
{
  dcc_hw.os_interrupt_handler();
}

void uart6_interrupt_handler(void)
{
  railcom_driver.os_interrupt_handler();
}

void uart2_interrupt_handler(void)
{
  uart2.interrupt_handler();
}

void hw_set_to_safe(void)
{
    dcc_hw.disable_output();
}

/** Blink LED */
uint32_t blinker_pattern = 0;
static uint32_t rest_pattern = 0;

void resetblink(uint32_t pattern)
{
    blinker_pattern = pattern;
    /* make a timer event trigger immediately */
}

void setblink(uint32_t pattern)
{
    resetblink(pattern);
}

void timer5a_interrupt_handler(void)
{
    //
    // Clear the timer interrupt.
    //
    MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
    // Set output LED.
    io::BlinkerLed::set(rest_pattern & 1);
    // Shift and maybe reset pattern.
    rest_pattern >>= 1;
    if (!rest_pattern)
        rest_pattern = blinker_pattern;
}

void diewith(uint32_t pattern)
{
    hw_set_to_safe();
    vPortClearInterruptMask(0x20);
    asm("cpsie i\n");

    resetblink(pattern);
    while (1)
        ;
}

/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). */
void set_gpio_led(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0xff);
    MAP_GPIOPinTypeGPIOOutput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD);
    MAP_GPIOPinWrite(port, pin, 0xff);
}

/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_low(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0);
    MAP_GPIOPinTypeGPIOOutput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
    MAP_GPIOPinWrite(port, pin, 0);
}

/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_high(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0xff);
    MAP_GPIOPinTypeGPIOOutput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
    MAP_GPIOPinWrite(port, pin, 0xff);
}

/** Configures a gpio pin for input with external pullup. */
void set_gpio_extinput(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0);
    MAP_GPIOPinTypeGPIOInput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
}

/** Configures a gpio pin for input with internal pullup. */
void set_gpio_puinput(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0);
    MAP_GPIOPinTypeGPIOInput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
}

void enable_dcc() {
    g_dcc_on = true;
    io::TrackOnLed::set(true);
    dcc_hw.enable_output();
}

void disable_dcc() {
    dcc_hw.disable_output();
    g_dcc_on = false;
    io::TrackOnLed::set(false);
}

bool query_dcc() {
  return g_dcc_on;
}

/** Initialize the processor hardware.
 */
void hw_preinit(void)
{
    /* Globally disables interrupts until the FreeRTOS scheduler is up. */
    asm("cpsid i\n");

    /* First we take care of the important pins that control the power
     * transistors */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOQ);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);

    // Q2/Q3 are wired together with A2-A3 on the timer output pins. Let's turn
    // them into high-impedance mode and turn off pullups.
    MAP_GPIOPinTypeGPIOInput(GPIO_PORTQ_BASE, GPIO_PIN_2 | GPIO_PIN_3);
    // Disables any pullup/down.
    MAP_GPIOPadConfigSet(GPIO_PORTQ_BASE, GPIO_PIN_2 | GPIO_PIN_3,
                         GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);

    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOP);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    dcc_hw.hw_init();
    disable_dcc();

    // A4 controls the accessory bus, active high.
    set_gpio_drive_low(GPIO_PORTA_BASE, GPIO_PIN_4);

    /* Setup the system clock. */
    MAP_SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_USE_PLL |
                           SYSCTL_OSC_MAIN | SYSCTL_CFG_VCO_480,
                           120000000);

    // USB pins initialization.
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOQ);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);

    HWREG(GPIO_PORTD_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
    HWREG(GPIO_PORTD_BASE + GPIO_O_CR) = 0xff;
    MAP_GPIOPinConfigure(GPIO_PD6_USB0EPEN);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);
    MAP_GPIOPinTypeUSBDigital(GPIO_PORTD_BASE, GPIO_PIN_6);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    MAP_GPIOPinTypeGPIOInput(GPIO_PORTQ_BASE, GPIO_PIN_4);
    MAP_IntPrioritySet(INT_USB0, 0xff); // USB interrupt low priority

    /* blinker LED pin initialization */
    io::BlinkerLed::hw_init();

    /* Blinker timer initialization. */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
    MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
    MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, configCPU_CLOCK_HZ / 8);
    MAP_TimerControlStall(TIMER5_BASE, TIMER_A, true);
    MAP_IntEnable(INT_TIMER5A);

    /* This interrupt should hit even during kernel operations. */
    MAP_IntPrioritySet(INT_TIMER5A, 0);
    MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
    MAP_TimerEnable(TIMER5_BASE, TIMER_A);

    /* UART0 pin initialization */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    MAP_GPIOPinConfigure(GPIO_PD4_U2RX);
    MAP_GPIOPinConfigure(GPIO_PD5_U2TX);
    MAP_GPIOPinTypeUART(GPIO_PORTD_BASE, GPIO_PIN_4 | GPIO_PIN_5);

    /* CAN pin initialization */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    MAP_GPIOPinConfigure(GPIO_PA0_CAN0RX);
    MAP_GPIOPinConfigure(GPIO_PA1_CAN0TX);
    MAP_GPIOPinTypeCAN(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    /* USB0 pin initialization */
    //MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);
    //MAP_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    /* USB interrupt priority */

    /* Boosterpack LEDs */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOQ);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOP);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
    LED_RED_Pin::hw_init();
    LED_YELLOW_Pin::hw_init();
    LED_BLUE_Pin::hw_init();
#ifdef HW_V1
    set_gpio_extinput(LED_GREEN_Pin::GPIO_BASE, LED_GREEN_Pin::GPIO_PIN);
#elif defined(HW_V2)
    LED_GREEN_Pin::hw_init();
#else
#error define version with HWVER=HW_V1 or HWVER=HW_V2
#endif
    // onboard LEDs.
    LED_B1_Pin::hw_init(); LED_B1_Pin::set(true);
    LED_B2_Pin::hw_init(); LED_B2_Pin::set(true);
    LED_B3_Pin::hw_init(); LED_B3_Pin::set(true);
    LED_B4_Pin::hw_init(); LED_B4_Pin::set(true);

    // Switches
    USR_SW1_Pin::hw_init();
    USR_SW2_Pin::hw_init();

    /* Timer hardware for DCC signal generation */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);

    /* Temporary enable Irq for blinking. */
    asm("cpsie i\n");

    io::TrackOnLed::set(true);

    blinker_pattern = 0x80002;
    uint32_t counter = (configCPU_CLOCK_HZ / 3);
    while (!USR_SW1_Pin::get() || counter) {
      if (counter) --counter;
    }

    /* Globally disables interrupts until the FreeRTOS scheduler is up. */
    asm("cpsid i\n");

    LED_B1_Pin::set(false);
    LED_B2_Pin::set(false);
    LED_B3_Pin::set(false);
    LED_B4_Pin::set(false);

}

}  // extern C
<commit_msg>adds acc_enable pin as tivagpio.<commit_after>/** \copyright
 * Copyright (c) 2012, Stuart W Baker
 * 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.
 *
 * 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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.
 *
 * \file HwInit.cxx
 * This file represents the hardware initialization for the TI Tiva MCU.
 *
 * @author Stuart W. Baker
 * @date 5 January 2013
 */

#include <cstdint>
#include <new>

#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "inc/hw_ints.h"
#include "inc/hw_gpio.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "os/OS.hxx"
#include "TivaDev.hxx"
#include "TivaDCC.hxx"
#include "TivaGPIO.hxx"

#include "dcc_control.hxx"
#include "hardware.hxx"
#include "DccHardware.hxx"

struct Debug {
  // High between start_cutout and end_cutout from the TivaRailcom driver.
  typedef DummyPin RailcomDriverCutout;
  // Flips every time an uart byte is received error.
  typedef DummyPin RailcomError;
  // Flips every time an 'E0' byte is received in the railcom driver.
  typedef DummyPin RailcomE0;

    typedef DummyPin RailcomDataReceived;
    typedef DummyPin RailcomAnyData;
    typedef DummyPin RailcomPackets;
};
#include "TivaRailcom.hxx"

/** override stdin */
const char *STDIN_DEVICE = "/dev/ser0";

/** override stdout */
const char *STDOUT_DEVICE = "/dev/ser0";

/** override stderr */
const char *STDERR_DEVICE = "/dev/ser0";

/** USB Device CDC serial driver instance */
static TivaCdc cdc0("/dev/serUSB0", INT_RESOLVE(INT_USB0_, 0));

/** UART 0 serial driver instance */
static TivaUart uart2("/dev/ser0", UART2_BASE, INT_RESOLVE(INT_UART2_, 0));

/** CAN 0 CAN driver instance */
static TivaCan can0("/dev/can0", CAN0_BASE, INT_RESOLVE(INT_CAN0_, 0));

// Bit storing whether our dcc output is enabled or not.
static bool g_dcc_on = false;

TivaRailcomDriver<RailcomDefs> railcom_driver("/dev/railcom");
TivaDCC<DccHwDefs> dcc_hw("/dev/mainline", &railcom_driver);

extern "C" {
/** Timer interrupt for DCC packet handling.
 */
void timer0a_interrupt_handler(void)
{
  dcc_hw.interrupt_handler();
}

void timer1a_interrupt_handler(void)
{
  dcc_hw.os_interrupt_handler();
}

void uart6_interrupt_handler(void)
{
  railcom_driver.os_interrupt_handler();
}

void uart2_interrupt_handler(void)
{
  uart2.interrupt_handler();
}

void hw_set_to_safe(void)
{
    dcc_hw.disable_output();
    AccHwDefs::ACC_ENABLE_Pin::hw_set_to_safe();
}

/** Blink LED */
uint32_t blinker_pattern = 0;
static uint32_t rest_pattern = 0;

void resetblink(uint32_t pattern)
{
    blinker_pattern = pattern;
    /* make a timer event trigger immediately */
}

void setblink(uint32_t pattern)
{
    resetblink(pattern);
}

void timer5a_interrupt_handler(void)
{
    //
    // Clear the timer interrupt.
    //
    MAP_TimerIntClear(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
    // Set output LED.
    io::BlinkerLed::set(rest_pattern & 1);
    // Shift and maybe reset pattern.
    rest_pattern >>= 1;
    if (!rest_pattern)
        rest_pattern = blinker_pattern;
}

void diewith(uint32_t pattern)
{
    hw_set_to_safe();
    vPortClearInterruptMask(0x20);
    asm("cpsie i\n");

    resetblink(pattern);
    while (1)
        ;
}

/** Configures a GPIO pin to directly drive a LED (with 8mA output drive). */
void set_gpio_led(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0xff);
    MAP_GPIOPinTypeGPIOOutput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_8MA_SC, GPIO_PIN_TYPE_STD);
    MAP_GPIOPinWrite(port, pin, 0xff);
}

/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_low(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0);
    MAP_GPIOPinTypeGPIOOutput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
    MAP_GPIOPinWrite(port, pin, 0);
}

/** Configures a GPIO pin to directly drive a LED (with 2mA output drive). */
void set_gpio_drive_high(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0xff);
    MAP_GPIOPinTypeGPIOOutput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
    MAP_GPIOPinWrite(port, pin, 0xff);
}

/** Configures a gpio pin for input with external pullup. */
void set_gpio_extinput(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0);
    MAP_GPIOPinTypeGPIOInput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);
}

/** Configures a gpio pin for input with internal pullup. */
void set_gpio_puinput(uint32_t port, uint32_t pin) {
    MAP_GPIOPinWrite(port, pin, 0);
    MAP_GPIOPinTypeGPIOInput(port, pin);
    MAP_GPIOPadConfigSet(port, pin, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU);
}

void enable_dcc() {
    g_dcc_on = true;
    io::TrackOnLed::set(true);
    dcc_hw.enable_output();
}

void disable_dcc() {
    dcc_hw.disable_output();
    g_dcc_on = false;
    io::TrackOnLed::set(false);
}

bool query_dcc() {
  return g_dcc_on;
}

/** Initialize the processor hardware.
 */
void hw_preinit(void)
{
    /* Globally disables interrupts until the FreeRTOS scheduler is up. */
    asm("cpsid i\n");

    /* First we take care of the important pins that control the power
     * transistors */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOQ);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);

    // Q2/Q3 are wired together with A2-A3 on the timer output pins. Let's turn
    // them into high-impedance mode and turn off pullups.
    MAP_GPIOPinTypeGPIOInput(GPIO_PORTQ_BASE, GPIO_PIN_2 | GPIO_PIN_3);
    // Disables any pullup/down.
    MAP_GPIOPadConfigSet(GPIO_PORTQ_BASE, GPIO_PIN_2 | GPIO_PIN_3,
                         GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD);

    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOP);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    dcc_hw.hw_init();
    disable_dcc();

    // controls the accessory bus.
    AccHwDefs::ACC_ENABLE_Pin::hw_set_to_safe();

    /* Setup the system clock. */
    MAP_SysCtlClockFreqSet(SYSCTL_XTAL_25MHZ | SYSCTL_USE_PLL |
                           SYSCTL_OSC_MAIN | SYSCTL_CFG_VCO_480,
                           120000000);

    // USB pins initialization.
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOQ);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);

    HWREG(GPIO_PORTD_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY;
    HWREG(GPIO_PORTD_BASE + GPIO_O_CR) = 0xff;
    MAP_GPIOPinConfigure(GPIO_PD6_USB0EPEN);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);
    MAP_GPIOPinTypeUSBDigital(GPIO_PORTD_BASE, GPIO_PIN_6);
    MAP_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    MAP_GPIOPinTypeGPIOInput(GPIO_PORTQ_BASE, GPIO_PIN_4);
    MAP_IntPrioritySet(INT_USB0, 0xff); // USB interrupt low priority

    /* blinker LED pin initialization */
    io::BlinkerLed::hw_init();

    /* Blinker timer initialization. */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER5);
    MAP_TimerConfigure(TIMER5_BASE, TIMER_CFG_PERIODIC);
    MAP_TimerLoadSet(TIMER5_BASE, TIMER_A, configCPU_CLOCK_HZ / 8);
    MAP_TimerControlStall(TIMER5_BASE, TIMER_A, true);
    MAP_IntEnable(INT_TIMER5A);

    /* This interrupt should hit even during kernel operations. */
    MAP_IntPrioritySet(INT_TIMER5A, 0);
    MAP_TimerIntEnable(TIMER5_BASE, TIMER_TIMA_TIMEOUT);
    MAP_TimerEnable(TIMER5_BASE, TIMER_A);

    /* UART0 pin initialization */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOD);
    MAP_GPIOPinConfigure(GPIO_PD4_U2RX);
    MAP_GPIOPinConfigure(GPIO_PD5_U2TX);
    MAP_GPIOPinTypeUART(GPIO_PORTD_BASE, GPIO_PIN_4 | GPIO_PIN_5);

    /* CAN pin initialization */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    MAP_GPIOPinConfigure(GPIO_PA0_CAN0RX);
    MAP_GPIOPinConfigure(GPIO_PA1_CAN0TX);
    MAP_GPIOPinTypeCAN(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    /* USB0 pin initialization */
    //MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOL);
    //MAP_GPIOPinTypeUSBAnalog(GPIO_PORTL_BASE, GPIO_PIN_6 | GPIO_PIN_7);
    /* USB interrupt priority */

    /* Boosterpack LEDs */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOQ);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPION);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOP);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);
    LED_RED_Pin::hw_init();
    LED_YELLOW_Pin::hw_init();
    LED_BLUE_Pin::hw_init();
#ifdef HW_V1
    set_gpio_extinput(LED_GREEN_Pin::GPIO_BASE, LED_GREEN_Pin::GPIO_PIN);
#elif defined(HW_V2)
    LED_GREEN_Pin::hw_init();
#else
#error define version with HWVER=HW_V1 or HWVER=HW_V2
#endif
    // onboard LEDs.
    LED_B1_Pin::hw_init(); LED_B1_Pin::set(true);
    LED_B2_Pin::hw_init(); LED_B2_Pin::set(true);
    LED_B3_Pin::hw_init(); LED_B3_Pin::set(true);
    LED_B4_Pin::hw_init(); LED_B4_Pin::set(true);

    // Switches
    USR_SW1_Pin::hw_init();
    USR_SW2_Pin::hw_init();

    /* Timer hardware for DCC signal generation */
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER1);
    MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);

    /* Temporary enable Irq for blinking. */
    asm("cpsie i\n");

    io::TrackOnLed::set(true);

    blinker_pattern = 0x80002;
    uint32_t counter = (configCPU_CLOCK_HZ / 3);
    while (!USR_SW1_Pin::get() || counter) {
      if (counter) --counter;
    }

    /* Globally disables interrupts until the FreeRTOS scheduler is up. */
    asm("cpsid i\n");

    LED_B1_Pin::set(false);
    LED_B2_Pin::set(false);
    LED_B3_Pin::set(false);
    LED_B4_Pin::set(false);

}

}  // extern C
<|endoftext|>


<commit_before>
// take a signal, fft it, and inverse everything.

#include "aquila/global.h"
#include "aquila/source/generator/SineGenerator.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include <algorithm>
#include <functional>
#include <memory>

int main()
{

	const std::size_t SIZE = 64;
	const Aquila::FrequencyType f_lp = 500;
	const Aquila::FrequencyType sampleFreq = 2000;
	const Aquila::FrequencyType f1 = 56, f2 = 30, f3 = 75, f4 = 900;

	Aquila::SineGenerator sineGenerator1(sampleFreq);
	sineGenerator1.setAmplitude(32).setFrequency(f1).generate(SIZE);
	Aquila::SineGenerator sineGenerator2(sampleFreq);
	sineGenerator2.setAmplitude(8).setFrequency(f4).setPhase(0.75).generate(SIZE);
	Aquila::SineGenerator sineGenerator3(sampleFreq);
	sineGenerator3.setAmplitude)(20).setFrequency(f3).setPhase(2.1).generate(SIZE);
	Aquila::SineGenerator sineGenerator4(sampleFreq);
	sineGenerator4.setAmplitude(60).setFrequency(f2).setPhase(0.4).generate(SIZE);

	auto sum = sineGenerator4 + sineGenerator3 + sineGenerator2 + sineGenerator1;
	auto other_sum = sineGenerator4 + sineGenerator3 + sineGenerator2 + sineGenerator1;

	Aquila::TextPlot plt("Signal waveform before filtration");
	plt.plot(sum);

	// just get this much working.

	// where does fft Get its freq values from???

	auto fft = Aquila::FftFactory::getFft(SIZE);
	Aquila::SpectrumType spectrum = fft->fft(sum.toArray());
	plt.setTitle("Signal spectrum before filtration");
	plt.splotSpectrum(spectrum);

	Aquila::SpectrumType inverse(SIZE);
	for (std::size_t i = 0; i < SIZE; ++i) {
		inverse[i] = -1;
	}

	plt.setTitle("inverse Spectrum");
	plt.plotSpectrum(inverse);

	std::transform(
		std::begin(spectrum),
		std::end(spectrum),
		std::begin(inverse),
		std::begin(spectrum),
		[] (Aquila::ComplexType x, Aquila::ComplexType y) {return x * y}
	);
	plt.setTitle("Flipped Signal");
	plt.plotSpectrum(spectrum);

	// back to time-domain
	double flip_sig[SIZE];
	fft->ifft(spectrum, flip_sig);
	plt.setTitle("Signal after flipping");
	plt.plot(flip_sig, SIZE);

	// sum norm and flipped versions; 0? Does it add frequency spectra?
	auto final = flip_sig + other_sum;
	plt.setTitle("Cancelled noise?");
	plt.plot(final);

}<commit_msg>noise-cancel concept test<commit_after>
// take a signal, fft it, and inverse everything.

#include "aquila/global.h"
#include "aquila/source/generator/SineGenerator.h"
#include "aquila/transform/FftFactory.h"
#include "aquila/tools/TextPlot.h"
#include <algorithm>
#include <functional>
#include <memory>

int main()
{

	const std::size_t SIZE = 64;
	const Aquila::FrequencyType f_lp = 500;
	const Aquila::FrequencyType sampleFreq = 2000;
	const Aquila::FrequencyType f1 = 56, f2 = 30, f3 = 75, f4 = 900;

	Aquila::SineGenerator sineGenerator1(sampleFreq);
	sineGenerator1.setAmplitude(32).setFrequency(f1).generate(SIZE);
	Aquila::SineGenerator sineGenerator2(sampleFreq);
	sineGenerator2.setAmplitude(8).setFrequency(f4).setPhase(0.75).generate(SIZE);
	Aquila::SineGenerator sineGenerator3(sampleFreq);
	sineGenerator3.setAmplitude)(20).setFrequency(f3).setPhase(2.1).generate(SIZE);
	Aquila::SineGenerator sineGenerator4(sampleFreq);
	sineGenerator4.setAmplitude(60).setFrequency(f2).setPhase(0.4).generate(SIZE);

	auto sum = sineGenerator4 + sineGenerator3 + sineGenerator2 + sineGenerator1;
	auto other_sum = sineGenerator4 + sineGenerator3 + sineGenerator2 + sineGenerator1;

	Aquila::TextPlot plt("Signal waveform before filtration");
	plt.plot(sum);

	// just get this much working.

	// where does fft Get its freq values from???
	// oh: "sum.toArray()."

	auto fft = Aquila::FftFactory::getFft(SIZE);
	Aquila::SpectrumType spectrum = fft->fft(sum.toArray());
	plt.setTitle("Signal spectrum before filtration");
	plt.splotSpectrum(spectrum);

	Aquila::SpectrumType inverse(SIZE);
	for (std::size_t i = 0; i < SIZE; ++i) {
		inverse[i] = -1;
	}

	plt.setTitle("inverse Spectrum");
	plt.plotSpectrum(inverse);

	std::transform(
		std::begin(spectrum),
		std::end(spectrum), // is this really the most efficient
		std::begin(inverse),// way of multiplying a spectrum by -1?
		std::begin(spectrum),// most likely not.
		[] (Aquila::ComplexType x, Aquila::ComplexType y) {return x * y}
	);
	plt.setTitle("Flipped Signal");
	plt.plotSpectrum(spectrum);

	// back to time-domain
	double flip_sig[SIZE];
	fft->ifft(spectrum, flip_sig);
	plt.setTitle("Signal after flipping");
	plt.plot(flip_sig, SIZE);

	// sum norm and flipped versions; 0? Does it add frequency spectra?
	auto final = flip_sig + other_sum;
	plt.setTitle("Cancelled noise?");
	plt.plot(final);

}<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include "enrichment_tests.h"

#include <cmath>

#include "composition.h"
#include "context.h"
#include "cyc_limits.h"
#include "recorder.h"
#include "error.h"
#include "material.h"
#include "timer.h"

using cyclus::CompMap;
using cyclus::Composition;
using cyclus::Material;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetUp() {
  feed_ = 0.0072;
  product_ = 0.05;
  tails_ = 0.002;

  assay_u_ = product_;
  mass_u_ = 10;

  cyclus::Timer ti;
  cyclus::Recorder rec;
  cyclus::Context ctx(&ti, &rec);

  CompMap v;
  v[922350000] = assay_u_;
  v[922380000] = 1 - assay_u_;
  Composition::Ptr comp = Composition::CreateFromAtom(v);
  mat_ = Material::CreateUntracked(mass_u_, comp);

  SetEnrichmentParameters();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::TearDown() {}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetEnrichmentParameters() {
  double feed_val = (1 - 2 * feed_) * std::log(1 / feed_ - 1);
  double tails_val = (1 - 2 * tails_) * std::log(1 / tails_ - 1);
  double product_val = (1 - 2 * product_) * std::log(1 / product_ - 1);

  feed_qty_ = mass_u_ * (product_ - tails_) / (feed_ - tails_);
  tails_qty_ = mass_u_ * (product_ - feed_) / (feed_ - tails_);
  swu_ = mass_u_ * product_val + tails_qty_ * tails_val - feed_qty_ * feed_val;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, assays) {
  cyclus::enrichment::Assays a(feed_, product_, tails_);
  EXPECT_DOUBLE_EQ(feed_, a.Feed());
  EXPECT_DOUBLE_EQ(product_, a.Product());
  EXPECT_DOUBLE_EQ(tails_, a.Tails());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, valuefunction) {
  EXPECT_THROW(cyclus::enrichment::ValueFunc(0 - cyclus::eps()),
               cyclus::ValueError);
  EXPECT_THROW(cyclus::enrichment::ValueFunc(1), cyclus::ValueError);

  double step = 0.001;
  double test_value = 0;
  while (test_value < 1) {
    double expected = (1 - 2 * test_value) * std::log(1 / test_value - 1);
    EXPECT_DOUBLE_EQ(expected, cyclus::enrichment::ValueFunc(test_value));
    test_value += step;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, material) {
  EXPECT_DOUBLE_EQ(assay_u_, cyclus::enrichment::UraniumAssay(mat_));
  EXPECT_DOUBLE_EQ(mass_u_, cyclus::enrichment::UraniumQty(mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, enrichmentcalcs) {
  cyclus::enrichment::Assays assays(feed_, cyclus::enrichment::UraniumAssay(mat_),
                                    tails_);
  double product_qty = cyclus::enrichment::UraniumQty(mat_);
  EXPECT_DOUBLE_EQ(feed_qty_, FeedQty(product_qty, assays));
  EXPECT_DOUBLE_EQ(tails_qty_, TailsQty(product_qty, assays));
  EXPECT_DOUBLE_EQ(swu_, SwuRequired(product_qty, assays));
}
<commit_msg>updated enrichment tests for 32 bit, fixes #776<commit_after>#include <gtest/gtest.h>

#include "enrichment_tests.h"

#include <cmath>

#include "composition.h"
#include "context.h"
#include "cyc_limits.h"
#include "recorder.h"
#include "error.h"
#include "material.h"
#include "timer.h"

using cyclus::CompMap;
using cyclus::Composition;
using cyclus::Material;

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetUp() {
  feed_ = 0.0072;
  product_ = 0.05;
  tails_ = 0.002;

  assay_u_ = product_;
  mass_u_ = 10;

  cyclus::Timer ti;
  cyclus::Recorder rec;
  cyclus::Context ctx(&ti, &rec);

  CompMap v;
  v[922350000] = assay_u_;
  v[922380000] = 1 - assay_u_;
  Composition::Ptr comp = Composition::CreateFromAtom(v);
  mat_ = Material::CreateUntracked(mass_u_, comp);

  SetEnrichmentParameters();
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::TearDown() {}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void EnrichmentTests::SetEnrichmentParameters() {
  double feed_val = (1 - 2 * feed_) * std::log(1 / feed_ - 1);
  double tails_val = (1 - 2 * tails_) * std::log(1 / tails_ - 1);
  double product_val = (1 - 2 * product_) * std::log(1 / product_ - 1);

  feed_qty_ = mass_u_ * (product_ - tails_) / (feed_ - tails_);
  tails_qty_ = mass_u_ * (product_ - feed_) / (feed_ - tails_);
  swu_ = mass_u_ * product_val + tails_qty_ * tails_val - feed_qty_ * feed_val;
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, assays) {
  cyclus::enrichment::Assays a(feed_, product_, tails_);
  EXPECT_DOUBLE_EQ(feed_, a.Feed());
  EXPECT_DOUBLE_EQ(product_, a.Product());
  EXPECT_DOUBLE_EQ(tails_, a.Tails());
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, valuefunction) {
  EXPECT_THROW(cyclus::enrichment::ValueFunc(0 - cyclus::eps()),
               cyclus::ValueError);
  EXPECT_THROW(cyclus::enrichment::ValueFunc(1), cyclus::ValueError);

  double step = 0.001;
  double test_value = 0;
  while (test_value < 1) {
    double expected = (1 - 2 * test_value) * std::log(1 / test_value - 1);
    EXPECT_DOUBLE_EQ(expected, cyclus::enrichment::ValueFunc(test_value));
    test_value += step;
  }
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, material) {
  EXPECT_DOUBLE_EQ(assay_u_, cyclus::enrichment::UraniumAssay(mat_));
  EXPECT_DOUBLE_EQ(mass_u_, cyclus::enrichment::UraniumQty(mat_));
}

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(EnrichmentTests, enrichmentcalcs) {
  cyclus::enrichment::Assays assays(feed_, cyclus::enrichment::UraniumAssay(mat_),
                                    tails_);
  double product_qty = cyclus::enrichment::UraniumQty(mat_);
  EXPECT_DOUBLE_EQ(feed_qty_, FeedQty(product_qty, assays));
  EXPECT_DOUBLE_EQ(tails_qty_, TailsQty(product_qty, assays));
  EXPECT_NEAR(swu_, SwuRequired(product_qty, assays), 1e-8);
}
<|endoftext|>