text:
/*

Copyright (c) 2015, Project OSRM, Dennis Luxen, others
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.

*/

#include "../typedefs.h"
#include "../algorithms/tiny_components.hpp"
#include "../data_structures/dynamic_graph.hpp"
#include "../Util/graph_loader.hpp"
#include "../Util/make_unique.hpp"
#include "../Util/osrm_exception.hpp"
#include "../Util/simple_logger.hpp"
#include "../Util/FingerPrint.h"

#include <boost/filesystem.hpp>

#if defined(__APPLE__) || defined (_WIN32)
#include <gdal.h>
#include <ogrsf_frmts.h>
#else
#include <gdal/gdal.h>
#include <gdal/ogrsf_frmts.h>
#endif

#include <osrm/Coordinate.h>

#include <fstream>
#include <memory>
#include <string>
#include <vector>

std::vector<QueryNode> coordinate_list;
std::vector<TurnRestriction> restriction_list;
std::vector<NodeID> bollard_node_list;
std::vector<NodeID> traffic_lights_list;

struct TarjanEdgeData
{
    TarjanEdgeData() : distance(INVALID_EDGE_WEIGHT), name_id(INVALID_NAMEID) {}
    TarjanEdgeData(int distance, unsigned name_id) : distance(distance), name_id(name_id) {}
    int distance;
    unsigned name_id;
};

using TarjanDynamicGraph = DynamicGraph<TarjanEdgeData>;
using TarjanEdge = TarjanDynamicGraph::InputEdge;

void DeleteFileIfExists(const std::string &file_name)
{
    if (boost::filesystem::exists(file_name))
    {
        boost::filesystem::remove(file_name);
    }
}

int main(int argc, char *argv[])
{
    LogPolicy::GetInstance().Unmute();
    try
    {
        // enable logging
        if (argc < 3)
        {
            SimpleLogger().Write(logWARNING) << "usage:\n" << argv[0]
                                             << " <osrm> <osrm.restrictions>";
            return -1;
        }

        SimpleLogger().Write() << "Using restrictions from file: " << argv[2];
        std::ifstream restriction_ifstream(argv[2], std::ios::binary);
        const FingerPrint fingerprint_orig;
        FingerPrint fingerprint_loaded;
        restriction_ifstream.read((char *)&fingerprint_loaded, sizeof(FingerPrint));

        // check fingerprint and warn if necessary
        if (!fingerprint_loaded.TestGraphUtil(fingerprint_orig))
        {
            SimpleLogger().Write(logWARNING) << argv[2] << " was prepared with a different build. "
                                                           "Reprocess to get rid of this warning.";
        }

        if (!restriction_ifstream.good())
        {
            throw osrm::exception("Could not access <osrm-restrictions> files");
        }
        uint32_t usable_restrictions = 0;
        restriction_ifstream.read((char *)&usable_restrictions, sizeof(uint32_t));
        restriction_list.resize(usable_restrictions);

        // load restrictions
        if (usable_restrictions > 0)
        {
            restriction_ifstream.read((char *)&(restriction_list[0]),
                                      usable_restrictions * sizeof(TurnRestriction));
        }
        restriction_ifstream.close();

        std::ifstream input_stream(argv[1], std::ifstream::in | std::ifstream::binary);
        if (!input_stream.is_open())
        {
            throw osrm::exception("Cannot open osrm file");
        }

        // load graph data
        std::vector<ImportEdge> edge_list;
        const NodeID number_of_nodes = readBinaryOSRMGraphFromStream(input_stream,
                                                                     edge_list,
                                                                     bollard_node_list,
                                                                     traffic_lights_list,
                                                                     &coordinate_list,
                                                                     restriction_list);
        input_stream.close();

        BOOST_ASSERT_MSG(restriction_list.size() == usable_restrictions,
                         "size of restriction_list changed");

        SimpleLogger().Write() << restriction_list.size() << " restrictions, "
                               << bollard_node_list.size() << " bollard nodes, "
                               << traffic_lights_list.size() << " traffic lights";

        traffic_lights_list.clear();
        traffic_lights_list.shrink_to_fit();

        // Building an node-based graph
        DeallocatingVector<TarjanEdge> graph_edge_list;
        for (const NodeBasedEdge &input_edge : edge_list)
        {
            if (input_edge.source == input_edge.target)
            {
                continue;
            }

            if (input_edge.forward)
            {
                graph_edge_list.emplace_back(input_edge.source,
                                       input_edge.target,
                                       (std::max)((int)input_edge.weight, 1),
                                       input_edge.name_id);
            }
            if (input_edge.backward)
            {
                graph_edge_list.emplace_back(input_edge.target,
                                       input_edge.source,
                                       (std::max)((int)input_edge.weight, 1),
                                       input_edge.name_id);
            }
        }
        edge_list.clear();
        edge_list.shrink_to_fit();
        BOOST_ASSERT_MSG(0 == edge_list.size() && 0 == edge_list.capacity(),
                         "input edge vector not properly deallocated");

        tbb::parallel_sort(graph_edge_list.begin(), graph_edge_list.end());
        auto graph = std::make_shared<TarjanDynamicGraph>(number_of_nodes, graph_edge_list);
        edge_list.clear();
        edge_list.shrink_to_fit();

        SimpleLogger().Write() << "Starting SCC graph traversal";

        RestrictionMap restriction_map(restriction_list);
        auto tarjan = osrm::make_unique<TarjanSCC<TarjanDynamicGraph>>(graph,
                                                                       restriction_map,
                                                                       bollard_node_list);
        tarjan->run();
        SimpleLogger().Write() << "identified: " << tarjan->get_number_of_components()
                           << " many components";
        SimpleLogger().Write() << "identified " << tarjan->get_size_one_count() << " SCCs of size 1";

        // output
        TIMER_START(SCC_RUN_SETUP);

        // remove files from previous run if exist
        DeleteFileIfExists("component.dbf");
        DeleteFileIfExists("component.shx");
        DeleteFileIfExists("component.shp");

        Percent p(graph->GetNumberOfNodes());

        OGRRegisterAll();

        const char *pszDriverName = "ESRI Shapefile";
        OGRSFDriver *poDriver =
            OGRSFDriverRegistrar::GetRegistrar()->GetDriverByName(pszDriverName);
        if (nullptr == poDriver)
        {
            throw osrm::exception("ESRI Shapefile driver not available");
        }
        OGRDataSource *poDS = poDriver->CreateDataSource("component.shp", nullptr);

        if (nullptr == poDS)
        {
            throw osrm::exception("Creation of output file failed");
        }

        OGRSpatialReference *poSRS = new OGRSpatialReference();
        poSRS->importFromEPSG(4326);

        OGRLayer *poLayer = poDS->CreateLayer("component", poSRS, wkbLineString, nullptr);

        if (nullptr == poLayer)
        {
            throw osrm::exception("Layer creation failed.");
        }
        TIMER_STOP(SCC_RUN_SETUP);
        SimpleLogger().Write() << "shapefile setup took " << TIMER_MSEC(SCC_RUN_SETUP)/1000. << "s";

        uint64_t total_network_distance = 0;
        p.reinit(graph->GetNumberOfNodes());
        TIMER_START(SCC_OUTPUT);
        for (const NodeID source : osrm::irange(0u, graph->GetNumberOfNodes()))
        {
            p.printIncrement();
            for (const auto current_edge : graph->GetAdjacentEdgeRange(source))
            {
                const TarjanDynamicGraph::NodeIterator target = graph->GetTarget(current_edge);

                if (source < target || graph->EndEdges(target) == graph->FindEdge(target, source))
                {
                    total_network_distance +=
                        100 * FixedPointCoordinate::ApproximateEuclideanDistance(
                                  coordinate_list[source].lat,
                                  coordinate_list[source].lon,
                                  coordinate_list[target].lat,
                                  coordinate_list[target].lon);

                    BOOST_ASSERT(current_edge != SPECIAL_EDGEID);
                    BOOST_ASSERT(source != SPECIAL_NODEID);
                    BOOST_ASSERT(target != SPECIAL_NODEID);

                    const unsigned size_of_containing_component =
                        std::min(tarjan->get_component_size(source),
                                 tarjan->get_component_size(target));

                    // edges that end on bollard nodes may actually be in two distinct components
                    if (size_of_containing_component < 1000)
                    {
                        OGRLineString lineString;
                        lineString.addPoint(coordinate_list[source].lon / COORDINATE_PRECISION,
                                            coordinate_list[source].lat / COORDINATE_PRECISION);
                        lineString.addPoint(coordinate_list[target].lon / COORDINATE_PRECISION,
                                            coordinate_list[target].lat / COORDINATE_PRECISION);

                        OGRFeature *poFeature = OGRFeature::CreateFeature(poLayer->GetLayerDefn());

                        poFeature->SetGeometry(&lineString);
                        if (OGRERR_NONE != poLayer->CreateFeature(poFeature))
                        {
                            throw osrm::exception("Failed to create feature in shapefile.");
                        }
                        OGRFeature::DestroyFeature(poFeature);
                    }
                }
            }
        }
        OGRSpatialReference::DestroySpatialReference(poSRS);
        OGRDataSource::DestroyDataSource(poDS);
        TIMER_STOP(SCC_OUTPUT);
        SimpleLogger().Write() << "generating output took: " << TIMER_MSEC(SCC_OUTPUT)/1000. << "s";

        SimpleLogger().Write() << "total network distance: "
                               << (uint64_t)total_network_distance / 100 / 1000. << " km";

        SimpleLogger().Write() << "finished component analysis";
    }
    catch (const std::exception &e)
    {
        SimpleLogger().Write(logWARNING) << "[exception] " << e.what();
    }
    return 0;
}

max_stars_repo_name: cypox/devacus-backend

max_issues_repo_name: cypox/devacus-backend

max_forks_repo_name: VRPTools/pkg-osrm-backend


text:
// header guard
#ifndef STATEMACHINE_HPP
#define STATEMACHINE_HPP

// ref: https://boost-ext.github.io/sml/index.html
// https://boost-ext.github.io/sml/examples.html, hello world
#include <iostream>
#include <iomanip>
#include <string>
#include <thread>
#include <chrono>
#include <cassert>
#include <vector>
#include <boost/sml.hpp>
#include <boost/mpl/placeholders.hpp>

#include "Rp4bPwm.h"
#include "CommonDef.h"
#include "Util.h"
#include "PrintUtils.h"

using namespace std;
namespace sml = boost::sml;

const int Backward = 0;
const int Forward = 1;
const int On = 1;
const int Off = 0;

// anonymous namespace
namespace {

// events
struct eInit {};
struct eOnTime {};

// for this implementation, states are just empty classes
class Idle1;
class HomingSlowRetract;
class HomingRetract;
class HomingExtend;
class MovingToOpen;
class Open;
class MovingToClose;
class Closed;
class Failed;
class ObstructionDetected;
class ObstructionPause;
class PauseDone;

// transition table
// example: src_state +event<>[guard] / action = dst_state,
// transition from src_state to dst_state on event with guard and action
class sm_chicken_coop {
   using self = sm_chicken_coop;
public:

   explicit sm_chicken_coop(IoValues &ioValues, AppConfig &ac, Rp4bPwm &pwm, NoBlockTimer &nbTimer, float &light) :
      _ioValues(ioValues), _ac(ac), _pwm(pwm), _nbTimer(nbTimer), _light(light) {
         _readyFlag = false;
   } // end ctor

   auto operator()()  {
      using namespace sml;

      // guards
      auto Retracted = [this] () -> bool {
         return (_ioValues["retracted"] == 0);
      }; // end Retracted

      auto Extended = [this] () -> bool {
         return (_ioValues["extended"] == 0);
      }; // end Extended

      auto Obstructed = [this] () -> bool {
         return (_ioValues["obstructed"] == 0);
      }; // end Obstructed

      auto TimerDone = [this] () -> bool {
         return (_nbTimer.IsDone());
      }; // end TimerDone

      auto IsMorning = [this] () -> bool {
         return (_light <= 600);
      }; // end IsMorning

      auto IsNight = [this] () -> bool {
         return (_light >= 800);
      }; // end IsNight

      auto ReturnTrue = [] () -> bool {
         return true;
      }; // end ReturnTrue

      return make_transition_table (

         // start homing
         *state<Idle1> + event<eInit> / [&] {ReadyFlag(false);} = state<HomingSlowRetract>,
         state<HomingSlowRetract> + sml::on_entry<_> / [&] {MotorDirection(Backward); MotorSpeed(_ac.homingPwmHz); MotorEnable(true); StartTimer(34000);},
         state<HomingSlowRetract> + sml::on_exit<_> / [&] {MotorEnable(false);},
         state<HomingSlowRetract> + event<eOnTime>[Retracted] / [&] {PrintLn("HomingExtend"); KillTimer();} = state<HomingExtend>,
         state<HomingSlowRetract> + event<eOnTime>[TimerDone] / [] {PrintLn("Failed1");} = state<Failed>,

         state<HomingExtend> + sml::on_entry<_> / [&] {MotorDirection(Forward); MotorSpeed(_ac.slowPwmHz); MotorEnable(true); StartTimer(2000);},
         state<HomingExtend> + sml::on_exit<_> / [&] {MotorEnable(false);},
         state<HomingExtend> + event<eOnTime>[TimerDone] / [&] {PrintLn("HomingRetract"); KillTimer();} = state<HomingRetract>,

         state<HomingRetract> + sml::on_entry<_> / [&] {MotorDirection(Backward); MotorSpeed(_ac.slowPwmHz); MotorEnable(true); StartTimer(5000);},
         state<HomingRetract> + sml::on_exit<_> / [&] {MotorEnable(false); ReadyFlag(true);},
         state<HomingRetract> + event<eOnTime>[Retracted] / [&] {PrintLn("Closed"); KillTimer();} = state<Closed>,
         state<HomingRetract> + event<eOnTime>[TimerDone] / [] {PrintLn("Failed2");} = state<Failed>,
         // end homing

         state<Closed> + sml::on_entry<_> / [&] {MotorEnable(false);},
         state<Closed> + event<eOnTime>[IsMorning] / [] {PrintLn("MovingToOpen");} = state<MovingToOpen>,

         state<MovingToOpen> + sml::on_entry<_> / [&] {MotorDirection(Forward); MotorSpeed(_ac.fastPwmHz); MotorEnable(true); StartTimer(7000);},
         state<MovingToOpen> + event<eOnTime>[Extended] / [&] {PrintLn("Open"); KillTimer();} = state<Open>,
         state<MovingToOpen> + event<eOnTime>[TimerDone] / [] {PrintLn("Failed3");} = state<Failed>,

         state<Open> + sml::on_entry<_> / [&] {MotorEnable(false);},
         state<Open> + event<eOnTime>[IsNight] / [&] {PrintLn("MovingToClose"); KillTimer();} = state<MovingToClose>,
         state<Open> + event<eOnTime>[TimerDone] / [] {PrintLn("Failed4");} = state<Failed>,

         state<MovingToClose> + sml::on_entry<_> / [&] {MotorDirection(Backward); MotorSpeed(_ac.slowPwmHz); MotorEnable(true); StartTimer(17000);},
         state<MovingToClose> + event<eOnTime>[Retracted] / [&] {PrintLn("Closed"); KillTimer();} = state<Closed>,
         state<MovingToClose> + event<eOnTime>[TimerDone] / [] {PrintLn("Failed5");} = state<Failed>,

         // obstruction
         state<MovingToClose> + event<eOnTime>[Obstructed] / [&] {PrintLn("ObstructionDetected"); KillTimer();} = state<ObstructionDetected>,
         state<ObstructionDetected> + event<eOnTime>[ReturnTrue] / [] {PrintLn("ObstructionPause"); } = state<ObstructionPause>,
         state<ObstructionPause> + sml::on_entry<_> / [&] {MotorEnable(false); StartTimer(3000);},
         state<ObstructionPause> + event<eOnTime>[TimerDone] / [&] {PrintLn("PauseDone"); KillTimer();} = state<PauseDone>,

         state<PauseDone> + event<eOnTime>[Obstructed] / [] {PrintLn("MovingToOpen");} = state<MovingToOpen>,
         state<PauseDone> + event<eOnTime>[!Obstructed] / [] {PrintLn("MovingToClose");} = state<MovingToClose>

      );

   } // end operator()

private:

   IoValues &_ioValues;
   AppConfig &_ac;
   Rp4bPwm &_pwm;
   NoBlockTimer &_nbTimer;
   float &_light;
   bool _readyFlag;

   // actions
   void ReadyFlag(bool state) {
      _readyFlag = state;
   } // end ReadyFlag

   void MotorDirection(int dir) {
      _ioValues["direction"] = (dir ? 1 : 0);
      PrintLn((boost::format{ "%1%, from  %2%" } % _ioValues["direction"] % dir).str());
   } // end MotorDirection

   void MotorSpeed(int hz) {
      _pwm.SetFrequenceHz(hz);
   } // end MotorSpeed

   void MotorEnable(bool state) {
      _pwm.Enable(state);
      _ioValues["enable"] = (state ? 1 : 0);
   }  // end MotorEnable

   void KillTimer() {
      _nbTimer.Cancel();
   } // end KillTimer

   void StartTimer (unsigned tm) {
      _nbTimer.SetupTimer(tm);
      _nbTimer.StartTimer();
   } // end StartTimer

   void SetMovingLed(bool state) {
      _ioValues["door_cycling"] = (state ? 1 : 0);
   } // end SetMovingLed

}; // end struct

} // end anonymous namespace

#endif // end header guard

ext: hpp


text:
#ifndef __postfix_t_hpp__
#define __postfix_t_hpp__

#include <deque>
#include <iosfwd>
#include <unordered_map>
#include <sstream>
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/math/constants/constants.hpp>
#include "debug.hpp"
#include "num_t.hpp"
#include "stream_saver_t.hpp"
#include "display_types_t.hpp"
#include "make_property.hpp"
#include "hex_printer_t.hpp"
#include "bin_printer_t.hpp"
#include "oct_printer_t.hpp"
#include "commaifier_t.hpp"
#include "constants.hpp"

/**
 * A postfix calculation engine.
 */
struct postfix_t
{
   postfix_t()
      :enabled_(true)
      ,display_type_(display_types_t::dec)
   {
   }

   /**
    * Remove everything from the results stack.
    */
   void clear()
   {
      numbers_.clear();
   }

   /**
    * Give the engine something to do.
    */
   void push(const std::string& op)
   {
      try
      {
         std::string op_copy = op;
         boost::algorithm::to_lower(op_copy);
         auto handler = handlers_.find(op_copy);
         if (handler != handlers_.end())
         {
            handler->second(*this);
            return;
         }

         op_copy = remove_commas(op_copy);
         if (check_matches_and_strip_hexadecimal(op_copy))
         {
            push_hexadecimal(op_copy);
         }
         else if (check_matches_and_strip_octal(op_copy))
         {
            push_octal(op_copy);
         }
         else if (check_matches_and_strip_binary(op_copy))
         {
            push_binary(op_copy);
         }
         else
         {
            push_decimal(op_copy);
         }
      }
      catch (std::exception& e)
      {
         ooo(eee)
            << "failed to push: "
            << e.what();
      }
   }

   // Overloads for type safety.
   void push(const num_t& number) { numbers_.push_back(number); }
   void push(double number) { numbers_.push_back(number); }
   void push(int number) { numbers_.push_back(number); }
   void push(unsigned int number) { numbers_.push_back(number); }
   void push(short number) { numbers_.push_back(number); }
   void push(unsigned short number) { numbers_.push_back(number); }

   void push(char op)
   {
      std::string converted(1, op);
      this->push(converted);
   }

   void push(unsigned char op)
   {
      std::string converted(1, op);
      this->push(converted);
   }

   /**
    * @return the top of the stack without removing it.
    */
   num_t top() const
   {
      ensure(numbers_.size() > 0);
      return numbers_.back();
   }

   /**
    * @return the top of the stack and remove it.
    */
   num_t pop()
   {
      num_t result = top();
      numbers_.pop_back();
      return result;
   }

   /**
    * @return true when we can apply a binary operation.
    */
   bool can_bop() const
   {
      return numbers_.size() >= 2;
   }

   /**
    * @return true when we can apply a unary operation.
    */
   bool can_uop() const
   {
      return numbers_.size() >= 1;
   }

   /**
    * @return the stack rendered into a readable form.
    */
   std::string str() const
   {
      std::stringstream ss;
      ss << *this;
      std::string result(ss.str());
      return result;
   }

private:
   friend std::ostream& operator<<(std::ostream& o, const postfix_t& p);

   make_property(bool, enabled);
   make_property(display_types_t, display_type);

   // This is not an std::stack because stacks can't iterate
   // and I want to be able to iterate in order to print.
   std::deque<num_t> numbers_;

   /**
    * Let num_t handle the parsing.
    */
   void push_decimal(const std::string& d)
   {
      try
      {
         num_t bignum(d);
         numbers_.push_back(bignum);
      }
      catch (std::runtime_error&)
      {
         throw "failed push";
      }
   }

   std::string remove_commas(const std::string& s)
   {
      std::string result = s;
      result.erase
      (
         std::remove(result.begin(), result.end(), ','), result.end()
      );
      return result;
   }

   /**
    * Attempt to interpret a nondecimal number.
    * @param[in] the nondecimal number with prefix removed.
    * @param[in] digits the mapping of digit to value for
    * all values in the base. Alphabetical characters should
    * be lowercase.
    */
   void push_nondecimal
   (
      const std::string& n,
      const std::unordered_map<char, num_t>& digits
   )
   {
      std::vector<std::string> components;
      boost::split(components, n, boost::is_any_of("."), boost::token_compress_on);
      num_t result = 0;
      num_t multiplier = 1;
      num_t base_multiplier = digits.size();
      num_t divider = base_multiplier;
      switch (components.size())
      {
         case 2:
            {
               std::string::const_iterator i =
                  components[1].cbegin();
               std::string::const_iterator end =
                  components[1].cend();
               for (;i < end; ++i)
               {
                  auto p = digits.find(*i);
                  if (p == digits.end())
                  {
                     throw "push_nondecimal invalid digit";
                  }
                  result += p->second / divider;
                  divider *= base_multiplier;
               }
            }
            // intentional fallthrough
         case 1:
            {
               std::string::const_iterator i =
                  components[0].cend() - 1;
               std::string::const_iterator begin =
                  components[0].cbegin();
               for (; begin <= i; --i)
               {
                  auto p = digits.find(*i);
                  if (p == digits.end())
                  {
                     throw "push_nondecimal invalid digit";
                  }
                  result += multiplier * p->second;
                  multiplier *= base_multiplier;
               }
            }
            break;
         case 0:
            throw "push_nondecimal no components";
         default:
            throw "push_nondecimal too many components";
      }
      numbers_.push_back(result);
   }

   std::unordered_map<char, num_t> hex_digits =
   {
      {'0', 0}, {'1', 1}, {'2', 2}, {'3', 3},
      {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7},
      {'8', 8}, {'9', 9}, {'a', 10}, {'b', 11},
      {'c', 12}, {'d', 13}, {'e', 14}, {'f', 15},
   };
   /**
    * @param[in] a hexidecimal number string
    */
   void push_hexadecimal(const std::string& x)
   {
      push_nondecimal(x, hex_digits);
   }

   std::unordered_map<char, num_t> oct_digits =
   {
      {'0', 0}, {'1', 1}, {'2', 2}, {'3', 3},
      {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7},
   };
   /**
    * @param[in] an octal number string
    */
   void push_octal(const std::string& o)
   {
      push_nondecimal(o, oct_digits);
   }

   std::unordered_map<char, num_t> bin_digits =
   {
      {'0', 0}, {'1', 1},
   };
   /**
    * @param[in] a binary number string
    */
   void push_binary(const std::string& b)
   {
      push_nondecimal(b, bin_digits);
   }

   /**
    * Check a string to see if it begins with any of the
    * candidate prefixes and remove it. The first matched
    * prefix ends the operation.
    * @param[in] candidate_prefixes the set of prefixes
    * @param[in] s the string to check
    * @return true if one of the prefixes matched and was
    * removed.
    */
   bool check_matches_and_strip_prefix
   (
      const std::vector<std::string>& candidate_prefixes,
      std::string& s
   )
   {
      bool result = false;
      for (auto prefix : candidate_prefixes)
      {
         result = result || boost::starts_with(s, prefix);
         if (result)
         {
            s.erase(0, prefix.size());
            break;
         }
      }
      return result;
   }

   std::vector<std::string> hex_prefixes =
   {
      "x", "h", "0x", "0h"
   };
   /**
    * Checks to see if a number is marked with a hexadecimal
    * prefix and removes it.
    * @param[in] x the potential hexadecimal number
    * @return true if x was hexadecimal
    */
   bool check_matches_and_strip_hexadecimal(std::string& x)
   {
      bool result = check_matches_and_strip_prefix(hex_prefixes, x);
      return result;
   }

   std::vector<std::string> octal_prefixes =
   {
      "o", "0o"
   };
   /**
    * Checks to see if a number is marked with a octal
    * prefix and removes it.
    * @param[in] x the potential octal number
    * @return true if x was octal
    */
   bool check_matches_and_strip_octal(std::string& o)
   {
      bool result = check_matches_and_strip_prefix(octal_prefixes, o);
      return result;
   }

   std::vector<std::string> binary_prefixes =
   {
      "b", "0b"
   };
   /**
    * Checks to see if a number is marked with a binary
    * prefix and removes it.
    * @param[in] x the potential binary number
    * @return true if x was binary
    */
   bool check_matches_and_strip_binary(std::string& b)
   {
      bool result = check_matches_and_strip_prefix(binary_prefixes, b);
      return result;
   }
   /**
    * The operators.
    */
   std::unordered_map
   <
      std::string,
      std::function<void(postfix_t&)>
   > handlers_ =
   {
      {
         "+",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = lhs + rhs;
            p.push(result);
         }
      },
      {
         "-",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = lhs - rhs;
            p.push(result);
         }
      },
      {
         "*",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = lhs * rhs;
            p.push(result);
         }
      },
      {
         "/",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = lhs / rhs;
            p.push(result);
         }
      },
      {
         "%",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = fmod(lhs, rhs);
            p.push(result);
         }
      },
      {
         "<<",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t orig_rhs = rhs;
            num_t lhs = p.pop();
            num_t orig_lhs = lhs;
            num_t result = lhs;
            while (p.enabled() && rhs > 0)
            {
               result *= 2;
               --rhs;
            }
            if (p.enabled())
            {
               p.push(result);
            }
            else
            {
               p.push(orig_lhs);
               p.push(orig_rhs);
            }
         }
      },
      {
         ">>",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t orig_rhs = rhs;
            num_t lhs = p.pop();
            num_t orig_lhs = lhs;
            num_t result = lhs;
            while (p.enabled() && rhs > 0)
            {
               result /= 2;
               --rhs;
            }
            if (p.enabled())
            {
               p.push(result);
            }
            else
            {
               p.push(orig_lhs);
               p.push(orig_rhs);
            }
         }
      },
      {
         "^",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = pow(lhs, rhs);
            p.push(result);
         }
      },
      {
         "!",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t orig_rhs = rhs;
            num_t result = 1;
            if (rhs == 0)
            {
               p.push(result);
               return;
            }
            while
            (
               p.enabled()
               &&
               rhs > 1
               && boost::math::isfinite(result)
            )
            {
               result *= rhs;
               --rhs;
            }
            if (p.enabled())
            {
               p.push(result);
            }
            else
            {
               p.push(orig_rhs);
            }
         }
      },
      {
         "++",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs + 1;
            p.push(result);
         }
      },
      {
         "--",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs - 1;
            p.push(result);
         }
      },
      {
         "abs",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = fabs(rhs);
            p.push(result);
         }
      },
      {
         "acos",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = acos(rhs);
            p.push(result);
         }
      },
      {
         "asin",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = asin(rhs);
            p.push(result);
         }
      },
      {
         "atan",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = atan(rhs);
            p.push(result);
         }
      },
      {
         "atan2",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            num_t result = atan2(lhs, rhs);
            p.push(result);
         }
      },
      {
         "avg",
         [](postfix_t& p)
         {
            num_t result = 0;
            num_t count = 0;
            while (p.can_uop())
            {
               ++count;
               result += p.pop();
            }
            result /= count;
            p.push(result);
         }
      },
      {
         "bin",
         [](postfix_t& p)
         {
            p.display_type(display_types_t::bin);
         }
      },
      {
         "c",
         [](postfix_t& p)
         {
           p.push(299792458);
         }
      },
      {
         "ceil",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = ceil(rhs);
            p.push(result);
         }
      },
      {
         "cf",
         [](postfix_t& p)
         {
           ensure(p.can_uop());
           num_t rhs = p.pop();
           num_t result = (rhs * 9 / 5) + 32;
           p.push(result);
         }
      },
      {
         "clear",
         [](postfix_t& p)
         {
            p.clear();
         }
      },
      {
         "clr",
         [](postfix_t& p)
         {
            p.clear();
         }
      },
      {
         "cos",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = cos(rhs);
            p.push(result);
         }
      },
      {
         "cosh",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = cosh(rhs);
            p.push(result);
         }
      },
      {
         "dec",
         [](postfix_t& p)
         {
            p.display_type(display_types_t::dec);
         }
      },
      {
         "com",
         [](postfix_t& p)
         {
            p.display_type(display_types_t::com);
         }
      },
      {
         "e",
         [](postfix_t& p)
         {
            p.push(exp(num_t(1)));
         }
      },
      {
         "exp",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = exp(rhs);
            p.push(result);
         }
      },
      {
         "eng",
         [](postfix_t& p)
         {
            p.display_type(display_types_t::eng);
         }
      },
      {
         "fc",
         [](postfix_t& p)
         {
           ensure(p.can_uop());
           num_t rhs = p.pop();
           num_t result = (rhs - 32) * 5 / 9;
           p.push(result);
         }
      },
      {
         "floor",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = floor(rhs);
            p.push(result);
         }
      },
      {
         "fpj",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs * joules_in_one_foot_pound;
            p.push(result);
         }
      },
      {
         "frac",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs - trunc(rhs);
            p.push(result);
         }
      },
      {
         "frexp",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            int exp = 0;
            num_t rhs = p.pop();
            num_t result = frexp(rhs, &exp);
            p.push(result);
            p.push(exp);
         }
      },
      {
         "ftm",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs / feet_in_one_meter;
            p.push(result);
         }
      },
      {
         "gl",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs * liters_in_one_gallon;
            p.push(result);
         }
      },
      {
         "hex",
         [](postfix_t& p)
         {
            p.display_type(display_types_t::hex);
         }
      },
      {
         "hpw",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs * watts_in_one_horsepower;
            p.push(result);
         }
      },
      {
         "jfp",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs / joules_in_one_foot_pound;
            p.push(result);
         }
      },
      {
         "kgp",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs / pounds_in_one_kilogram;
            p.push(result);
         }
      },
      {
         "lg",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.top();
            num_t result = rhs / liters_in_one_gallon;
            p.push(result);
         }
      },
      {
         "log",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = log10(rhs);
            p.push(result);
         }
      },
      {
         "ln",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = log(rhs);
            p.push(result);
         }
      },
      {
         "mft",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs * feet_in_one_meter;
            p.push(result);
         }
      },
      {
         "neg",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = -rhs;
            p.push(result);
         }
      },
      {
         "oct",
         [](postfix_t& p)
         {
            p.display_type(display_types_t::oct);
         }
      },
      {
         "pkg",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs * pounds_in_one_kilogram;
            p.push(result);
         }
      },
      {
         "pi",
         [](postfix_t& p)
         {
            p.push(boost::math::constants::pi<num_t>());
         }
      },
      {
         "pop",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            p.pop();
         }
      },
      {
         "prod",
         [](postfix_t& p)
         {
            num_t result = 1;
            while (p.can_uop())
            {
               result *= p.pop();
            }
            p.push(result);
         }
      },
      {
         "round",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = round(rhs);
            p.push(result);
         }
      },
      {
         "sin",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = sin(rhs);
            p.push(result);
         }
      },
      {
         "sinh",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = sinh(rhs);
            p.push(result);
         }
      },
      {
         "sqrt",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = sqrt(rhs);
            p.push(result);
         }
      },
      {
         "stddev",
         [](postfix_t& p)
         {
            num_t sum = 0;
            num_t count = 0;
            std::vector<num_t> copies;
            while (p.can_uop())
            {
               num_t x = p.pop();
               sum += x;
               ++count;
               copies.push_back(x);
            }
            num_t avg = sum / count;
            num_t sum_of_square_diffs = 0;
            for (auto n : copies)
            {
               num_t diff = n - avg;
               diff *= diff;
               sum_of_square_diffs += diff;
            }
            num_t result = sum_of_square_diffs / (count - 1);
            p.push(result);
         }
      },
      {
         "sum",
         [](postfix_t& p)
         {
            num_t result = 0;
            while (p.can_uop())
            {
               result += p.pop();
            }
            p.push(result);
         }
      },
      {
         "swap",
         [](postfix_t& p)
         {
            ensure(p.can_bop());
            num_t rhs = p.pop();
            num_t lhs = p.pop();
            p.push(rhs);
            p.push(lhs);
         }
      },
      {
         "tan",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = tan(rhs);
            p.push(result);
         }
      },
      {
         "tanh",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = tanh(rhs);
            p.push(result);
         }
      },
      {
         "trunc",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = trunc(rhs);
            p.push(result);
         }
      },
      {
         "whp",
         [](postfix_t& p)
         {
            ensure(p.can_uop());
            num_t rhs = p.pop();
            num_t result = rhs / watts_in_one_horsepower;
            p.push(result);
         }
      },
   };
};

/**
 * Ostream support for postfix_t.
 */
inline std::ostream& operator<<(std::ostream& o, const postfix_t& p)
{
   static hex_printer_t hex_printer;
   static oct_printer_t oct_printer;
   static bin_printer_t bin_printer;
   stream_saver_t saver(o);

   const std::size_t count = p.numbers_.size();
   std::size_t i = 0;
   for (num_t num : p.numbers_)
   {
      switch (p.display_type())
      {
         case display_types_t::hex:
            o << hex_printer.convert(num);
            break;
         case display_types_t::oct:
            o << oct_printer.convert(num);
            break;
         case display_types_t::bin:
            o << bin_printer.convert(num);
            break;
         case display_types_t::eng:
            o << num;
            break;
         case display_types_t::com:
            o << commaifier_t(num.str()).str();
            break;
         case display_types_t::dec:
         default:
            o << num.str();
            break;
      }
      if (i < count - 1) o << "   ";
      ++i;
   }

   return o;
}

#endif

max_stars_repo_name: kensmith/mancalc

max_issues_repo_name: kensmith/mancalc

max_forks_repo_name: kensmith/mancalc


text:
#ifndef DICOMFILE_HPP
#define DICOMFILE_HPP

#include <iostream>
#include <memory>

#include <boost/filesystem.hpp>

#include "data/dataset/datasets.hpp"
#include "data/dataset/transfer_processor.hpp"
#include "util/channel_sev_logger.hpp"

namespace dicom
{

namespace filesystem
{

/**
 * @brief The dicomfile class encapsulates a dicom dataset / iod for writing to
 *        and reading from a stream in the format as specified by DICOM standard
 *        part 10 chapter 7.
 */
class dicomfile
{
   private:
      dicom::data::dataset::iod& dataset_;
      dicom::data::dataset::iod filemetaheader;

      std::array<unsigned char, 128> preamble;
      std::array<unsigned char, 4> prefix;

      dicom::data::dictionary::dictionaries& dict;
      std::unique_ptr<dicom::data::dataset::transfer_processor> metaheader_proc;
      std::unique_ptr<dicom::data::dataset::transfer_processor> transfer_proc;

      util::log::channel_sev_logger logger;

      /**
       * @brief create_filemetaheader creates the meta file header (0002 group)
       *        using information from the dicom dataset to be written.
       */
      void create_filemetaheader();

   public:
      /**
       * @brief dicomfile , ctor
       * @param dataset dataset which shall be written to a stream in binary or
       *        deserialized into incase of reading from a strem
       * @param dict dictionary to be used, applies to little endian vr
       */
      dicomfile(dicom::data::dataset::iod& dataset,
                dicom::data::dictionary::dictionaries& dict);

      /**
       * @brief write_dataset writes the iod to the given stream in binary
       * @param os stream to write into
       * @return stream written to
       */
      std::ostream& write_dataset(std::ostream& os);

      /**
       * @brief read_dataset reads from the given stream in binary
       * @param is stream to read from
       * @return stream read from
       */
      std::istream& read_dataset(std::istream& is);

      /**
       * @brief set_transfer_syntax explicitly sets the transfer syntax used to
       *        read or write the dataset (excluding the file meta header)
       * @param transfer_syntax UID of the requested transfer syntax
       */
      void set_transfer_syntax(std::string transfer_syntax);

      /**
       * @brief dataset is used to access the dataset, for example to access
       *        dataset read from stream
       * @return dataset encapsulated in this instance
       */
      dicom::data::dataset::iod& dataset();
};

std::ostream& operator<<(std::ostream& os, dicomfile& dicom);

std::istream& operator>>(std::istream& is, dicomfile& dicom);

}

}

#endif // DICOMFILE_HPP

max_stars_repo_name: mariusherzog/dicom

max_issues_repo_name: mariusherzog/dicom

max_forks_repo_name: mariusherzog/dicom


text:
/**
 * $Id$
 *
 * Copyright (C)
 * 2014 - $Date$
 *     Martin Wolf <boostnumpy@martin-wolf.org>
 *
 * \file    boost/numpy/dstream/wiring/models/scalars_to_vector_of_scalar_callable.hpp
 * \version $Revision$
 * \date    $Date$
 * \author  Martin Wolf <boostnumpy@martin-wolf.org>
 *
 * \brief This file defines the scalars_to_vector_of_scalar_callable template
 *        for wiring a function or class member function that takes
 *        scalar input values and returns a std::vector of a scalar type to a
 *        mapping that has only scalar inputs and has either one 1D array with N
 *        elements, or N scalar arrays as output.
 *
 *        This file is distributed under the Boost Software License,
 *        Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
 *        http://www.boost.org/LICENSE_1_0.txt).
 */
#if !BOOST_PP_IS_ITERATING

#ifndef BOOST_NUMPY_DSTREAM_WIRING_MODEL_SCALARS_TO_VECTOR_OF_SCALAR_CALLABLE_HPP_INCLUDED
#define BOOST_NUMPY_DSTREAM_WIRING_MODEL_SCALARS_TO_VECTOR_OF_SCALAR_CALLABLE_HPP_INCLUDED

#include <vector>

#include <boost/preprocessor/iteration/iterate.hpp>
#include <boost/preprocessor/iteration/local.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>

#include <boost/mpl/and.hpp>
#include <boost/mpl/at.hpp>
#include <boost/mpl/bitor.hpp>
#include <boost/mpl/long.hpp>
#include <boost/mpl/or.hpp>

#include <boost/utility/enable_if.hpp>

#include <boost/numpy/limits.hpp>
#include <boost/numpy/mpl/types_from_fctptr_signature.hpp>
#include <boost/numpy/dstream/mapping/detail/definition.hpp>
#include <boost/numpy/dstream/wiring.hpp>
#include <boost/numpy/dstream/wiring/default_wiring_model_selector_fwd.hpp>

namespace boost {
namespace numpy {
namespace dstream {
namespace wiring {
namespace model {

namespace detail {

template <class MappingDefinition, class FTypes>
struct scalars_to_vector_of_scalar_callable_api
{
    template <unsigned Idx>
    struct out_arr_value_type
    {
        typedef typename FTypes::return_type::value_type
                type;
    };

    template <unsigned Idx>
    struct in_arr_value_type
    {
        typedef typename boost::mpl::at< typename FTypes::in_type_vector, boost::mpl::long_<Idx> >::type
                type;
    };

    template <unsigned Idx>
    struct out_arr_iter_operand_flags
    {
        typedef boost::mpl::bitor_<
                      typename numpy::detail::iter_operand::flags::WRITEONLY
                    , typename numpy::detail::iter_operand::flags::NBO
                    , typename numpy::detail::iter_operand::flags::ALIGNED
                >
                type;
    };

    template <unsigned Idx>
    struct in_arr_iter_operand_flags
    {
        typedef typename numpy::detail::iter_operand::flags::READONLY
                type;
    };

    template <class LoopService>
    struct iter_flags
    {
        typedef typename numpy::detail::iter::flags::DONT_NEGATE_STRIDES
                type;
    };

    BOOST_STATIC_CONSTANT(order_t, order = numpy::KEEPORDER);

    BOOST_STATIC_CONSTANT(casting_t, casting = numpy::SAME_KIND_CASTING);

    BOOST_STATIC_CONSTANT(intptr_t, buffersize = 0);
};

template <unsigned out_arity, unsigned in_arity>
struct scalars_to_vector_of_scalar_callable_arity;

#define BOOST_PP_ITERATION_PARAMS_1                                            \
    (3, (1, BOOST_NUMPY_LIMIT_OUTPUT_ARITY, <boost/numpy/dstream/wiring/models/scalars_to_vector_of_scalar_callable.hpp>))
#include BOOST_PP_ITERATE()

template <bool is_single_output, class MappingDefinition>
struct n_out_values;

template <class MappingDefinition>
struct n_out_values<true, MappingDefinition>
{
    typedef boost::mpl::integral_c<unsigned, MappingDefinition::out::core_shape_t0::dim0>
            type;
};

template <class MappingDefinition>
struct n_out_values<false, MappingDefinition>
{
    typedef boost::mpl::integral_c<unsigned, MappingDefinition::out::arity>
            type;
};

template <class MappingDefinition, class FTypes>
struct scalars_to_vector_of_scalar_callable_impl_select
{
    typedef typename dstream::mapping::detail::out_mapping<typename MappingDefinition::out>::template arity_is_equal_to<1>::type
            is_single_output_t;

    typedef typename n_out_values<is_single_output_t::value, MappingDefinition>::type
            n_out_values_t;

    typedef typename scalars_to_vector_of_scalar_callable_arity<n_out_values_t::value, MappingDefinition::in::arity>::template impl<
                  is_single_output_t::value
                , MappingDefinition
                , FTypes
                >::type
            type;
};

}// namespace detail

struct scalars_to_vector_of_scalar_callable
  : wiring_model_selector_type
{
    template <
         class MappingDefinition
       , class FTypes
    >
    struct select
    {
        typedef typename detail::scalars_to_vector_of_scalar_callable_impl_select<MappingDefinition, FTypes>::type
                type;
    };
};

}// namespace model

template <class MappingDefinition, class FTypes>
struct default_wiring_model_selector<
      MappingDefinition
    , FTypes
    , typename enable_if<
          typename boost::mpl::and_<
              typename dstream::mapping::detail::in_mapping<typename MappingDefinition::in>::all_arrays_are_scalars::type
            , typename numpy::mpl::all_fct_args_are_scalars<FTypes>::type
            , typename numpy::mpl::fct_return_is_std_vector_of_scalar<FTypes>::type
            , typename boost::mpl::or_<
                  typename boost::mpl::and_<
                      typename dstream::mapping::detail::out_mapping<typename MappingDefinition::out>::template arity_is_equal_to<1>::type
                    , typename dstream::mapping::detail::out_mapping<typename MappingDefinition::out>::template array<0>::is_1d::type
                  >::type
                , typename boost::mpl::and_<
                      typename dstream::mapping::detail::out_mapping<typename MappingDefinition::out>::template arity_is_greater<1>::type
                    , typename dstream::mapping::detail::out_mapping<typename MappingDefinition::out>::all_arrays_are_scalars::type
                  >::type
              >::type
          >::type
      >::type
>
{
    typedef model::scalars_to_vector_of_scalar_callable
            type;
};

}// namespace wiring
}// namespace dstream
}// namespace numpy
}// namespace boost

#endif // BOOST_NUMPY_DSTREAM_WIRING_MODEL_SCALARS_TO_VECTOR_OF_SCALAR_CALLABLE_HPP_INCLUDED
// EOF
//==============================================================================
#else

#if BOOST_PP_ITERATION_DEPTH() == 1

// Loop over the InArity.
#define BOOST_PP_ITERATION_PARAMS_2 \
    (3, (1, BOOST_NUMPY_LIMIT_INPUT_ARITY, <boost/numpy/dstream/wiring/models/scalars_to_vector_of_scalar_callable.hpp>))
#include BOOST_PP_ITERATE()

#else
#if BOOST_PP_ITERATION_DEPTH() == 2

#define OUT_ARITY BOOST_PP_RELATIVE_ITERATION(1)
#define IN_ARITY BOOST_PP_ITERATION()

#define BOOST_NUMPY_DSTREAM_WIRING_MODEL__in_arr_value(z, n, data) \
    BOOST_PP_COMMA_IF(n) typename FTypes:: BOOST_PP_CAT(arg_type,n)(BOOST_PP_CAT(in_arr_value,n))

template <>
struct scalars_to_vector_of_scalar_callable_arity<OUT_ARITY, IN_ARITY>
{
    BOOST_STATIC_CONSTANT(unsigned, out_arity = OUT_ARITY);
    BOOST_STATIC_CONSTANT(unsigned, in_arity = IN_ARITY);

    template <
          bool is_single_output
        , class MappingDefinition
        , class FTypes
    >
    struct impl;

    //--------------------------------------------------------------------------
    // Partial specialization for single output, where the output is a 1d
    // array.
    template <
          class MappingDefinition
        , class FTypes
    >
    struct impl<true, MappingDefinition, FTypes>
    {
        typedef impl<true, MappingDefinition, FTypes>
                type;

        typedef scalars_to_vector_of_scalar_callable_api<MappingDefinition, FTypes>
                api;

        typedef typename api::template out_arr_value_type<0>::type
                out_arr_value_t;
        #define BOOST_NUMPY_DEF(z, n, data) \
            typedef typename api::template in_arr_value_type<n>::type \
                    BOOST_PP_CAT(in_arr_value_t,n);
        BOOST_PP_REPEAT(IN_ARITY, BOOST_NUMPY_DEF, ~)
        #undef BOOST_NUMPY_DEF

        template <class ClassT, class FCaller>
        static
        void
        iterate(
              ClassT & self
            , FCaller const & f_caller
            , numpy::detail::iter & iter
            , std::vector< std::vector<intptr_t> > const & out_core_shapes
            , std::vector< std::vector<intptr_t> > const & in_core_shapes
            , bool & error_flag
        )
        {
            do {
                intptr_t const out_op_value_stride = iter.get_item_size(0);
                intptr_t size = iter.get_inner_loop_size();
                while(size--)
                {
                    // Construct references to the output array values.
                    #define BOOST_NUMPY_DEF(z, n, data) \
                        out_arr_value_t & BOOST_PP_CAT(out_arr_value,n) =\
                            *reinterpret_cast<out_arr_value_t *>(iter.get_data(0) + n * out_op_value_stride);
                    BOOST_PP_REPEAT(OUT_ARITY, BOOST_NUMPY_DEF, ~)
                    #undef BOOST_NUMPY_DEF

                    // Construct references to the input array values.
                    #define BOOST_NUMPY_DEF(z, n, data) \
                        BOOST_PP_CAT(in_arr_value_t,n) & BOOST_PP_CAT(in_arr_value,n) =\
                            *reinterpret_cast<BOOST_PP_CAT(in_arr_value_t,n) *>(iter.get_data(MappingDefinition::out::arity + n));
                    BOOST_PP_REPEAT(IN_ARITY, BOOST_NUMPY_DEF, ~)
                    #undef BOOST_NUMPY_DEF

                    // Call the to-be-exposed function and implicitly convert
                    // between types, in case function types differ from array
                    // value types.
                    typename FTypes::return_type ret = f_caller.call(
                          self
                        , BOOST_PP_REPEAT(IN_ARITY, BOOST_NUMPY_DSTREAM_WIRING_MODEL__in_arr_value, ~)
                    );

                    if(ret.size() != OUT_ARITY)
                    {
                        std::cerr << "Function returned std::vector of wrong "
                                  << "size! Must be " << OUT_ARITY << ", but "
                                  << "was " << ret.size() << "!"
                                  << std::endl;
                        error_flag = true;
                        return;
                    }

                    // Set the return values to the output array.
                    #define BOOST_NUMPY_DEF(z, n, data) \
                        BOOST_PP_CAT(out_arr_value,n) = out_arr_value_t(ret[n]);
                    BOOST_PP_REPEAT(OUT_ARITY, BOOST_NUMPY_DEF, ~)
                    #undef BOOST_NUMPY_DEF

                    iter.add_inner_loop_strides_to_data_ptrs();
                }
            } while(iter.next());
        }
    };

    // Specialization for multiple scalar output arrays.
    template <
          class MappingDefinition
        , class FTypes
    >
    struct impl<false, MappingDefinition, FTypes>
    {
        typedef impl<false, MappingDefinition, FTypes>
                type;

        typedef scalars_to_vector_of_scalar_callable_api<MappingDefinition, FTypes>
                api;

        #define BOOST_NUMPY_DEF(z, n, data) \
            typedef typename api::template out_arr_value_type<n>::type \
                    BOOST_PP_CAT(out_arr_value_t,n);
        BOOST_PP_REPEAT(OUT_ARITY, BOOST_NUMPY_DEF, ~)
        #undef BOOST_NUMPY_DEF

        #define BOOST_NUMPY_DEF(z, n, data) \
            typedef typename api::template in_arr_value_type<n>::type \
                    BOOST_PP_CAT(in_arr_value_t,n);
        BOOST_PP_REPEAT(IN_ARITY, BOOST_NUMPY_DEF, ~)
        #undef BOOST_NUMPY_DEF

        template <class ClassT, class FCaller>
        static
        void
        iterate(
              ClassT & self
            , FCaller const & f_caller
            , numpy::detail::iter & iter
            , std::vector< std::vector<intptr_t> > const & out_core_shapes
            , std::vector< std::vector<intptr_t> > const & in_core_shapes
            , bool & error_flag
        )
        {
            do {
                intptr_t size = iter.get_inner_loop_size();
                while(size--)
                {
                    // Construct references to the output array values.
                    #define BOOST_NUMPY_DEF(z, n, data) \
                        BOOST_PP_CAT(out_arr_value_t,n) & BOOST_PP_CAT(out_arr_value,n) =\
                            *reinterpret_cast<BOOST_PP_CAT(out_arr_value_t,n) *>(iter.get_data(n));
                    BOOST_PP_REPEAT(OUT_ARITY, BOOST_NUMPY_DEF, ~)
                    #undef BOOST_NUMPY_DEF

                    // Construct references to the input array values.
                    #define BOOST_NUMPY_DEF(z, n, data) \
                        BOOST_PP_CAT(in_arr_value_t,n) & BOOST_PP_CAT(in_arr_value,n) =\
                            *reinterpret_cast<BOOST_PP_CAT(in_arr_value_t,n) *>(iter.get_data(MappingDefinition::out::arity + n));
                    BOOST_PP_REPEAT(IN_ARITY, BOOST_NUMPY_DEF, ~)
                    #undef BOOST_NUMPY_DEF

                    // Call the to-be-exposed function and implicitly convert
                    // between types, in case function types differ from array
                    // value types.
                    typename FTypes::return_type ret = f_caller.call(
                          self
                        , BOOST_PP_REPEAT(IN_ARITY, BOOST_NUMPY_DSTREAM_WIRING_MODEL__in_arr_value, ~)
                    );

                    if(ret.size() != OUT_ARITY)
                    {
                        std::cerr << "Function returned std::vector of wrong "
                                  << "size! Must be " << OUT_ARITY << ", but "
                                  << "was " << ret.size() << "!"
                                  << std::endl;
                        error_flag = true;
                        return;
                    }

                    // Set the return values to the output array.
                    #define BOOST_NUMPY_DEF(z, n, data) \
                        BOOST_PP_CAT(out_arr_value,n) = BOOST_PP_CAT(out_arr_value_t,n)(ret[n]);
                    BOOST_PP_REPEAT(OUT_ARITY, BOOST_NUMPY_DEF, ~)
                    #undef BOOST_NUMPY_DEF

                    iter.add_inner_loop_strides_to_data_ptrs();
                }
            } while(iter.next());
        }
    };
};

#undef BOOST_NUMPY_DSTREAM_WIRING_MODEL__in_arr_value

#undef IN_ARITY
#undef OUT_ARITY

#endif // BOOST_PP_ITERATION_DEPTH == 2
#endif // BOOST_PP_ITERATION_DEPTH == 1

#endif // BOOST_PP_IS_ITERATING

max_stars_repo_name: IceCube-SPNO/BoostNumpy

max_issues_repo_name: IceCube-SPNO/BoostNumpy

max_forks_repo_name: IceCube-SPNO/BoostNumpy


text:
#pragma once

#include <cstddef>
#include <cstdint>
#include <cstring>

#include <boost/endian/conversion.hpp>
#include <boost/functional/hash.hpp>

namespace unet {

#define UNET_PACK __attribute__((packed))

#define UNET_ASSERT_SIZE(type, size) \
  static_assert(sizeof(type) == size, "Type has an unexpected size!")

#define UNET_STD_HASH_AS_MEM_HASH(type)           \
  namespace std {                                 \
  template <>                                     \
  struct hash<type> {                             \
    std::size_t operator()(const type& x) const { \
      unet::Memhash<type> h;                      \
      return h(x);                                \
    }                                             \
  };                                              \
  }

// Performs a host to network byte order conversion on x.
//
// Return x in network byte order
template <typename T>
T hostToNet(T x) {
  return boost::endian::endian_reverse(x);
}

// Performs a network to host byte order conversion on x.
//
// Return x in host byte order.
template <typename T>
T netToHost(T x) {
  return hostToNet(x);
}

// A std::memcmp based == operator for types which declare a MemcmpTag.
template <typename T, typename = typename T::MemcmpTag>
bool operator==(const T& lhs, const T& rhs) {
  return std::memcmp(&lhs, &rhs, sizeof(T)) == 0;
}

// A std::memcmp based != operator for types which declare a MemcmpTag.
template <typename T, typename = typename T::MemcmpTag>
bool operator!=(const T& lhs, const T& rhs) {
  return !(lhs == rhs);
}

// A hash based on the the memory layout of T.
template <typename T>
struct Memhash {
  std::size_t operator()(const T& x) const {
    auto p = reinterpret_cast<const std::uint8_t*>(&x);
    return boost::hash_range(p, p + sizeof(T));
  }
};

}  // namespace unet

max_stars_repo_name: andreimaximov/unet

max_issues_repo_name: andreimaximov/unet

max_forks_repo_name: andreimaximov/unet


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2015-2018 Regents of the University of California.
 *
 * Based on work by Martin Ba (http://stackoverflow.com/a/26718189)
 *
 * This file is distributed under the Boost Software License, Version 1.0.
 * (See http://www.boost.org/LICENSE_1_0.txt)
 */

#ifndef NDN_TESTS_UNIT_BOOST_MULTI_LOG_FORMATTER_HPP
#define NDN_TESTS_UNIT_BOOST_MULTI_LOG_FORMATTER_HPP

#include <boost/version.hpp>

#if BOOST_VERSION >= 105900
#include <boost/test/unit_test_parameters.hpp>
#else
#include <boost/test/detail/unit_test_parameters.hpp>
#endif // BOOST_VERSION >= 105900

#include <boost/test/unit_test_log_formatter.hpp>
#include <boost/test/output/compiler_log_formatter.hpp>
#include <boost/test/output/xml_log_formatter.hpp>

namespace boost {
namespace unit_test {
namespace output {

/**
 * @brief Log formatter for Boost.Test that outputs the logging to multiple formatters
 *
 * The log formatter is designed to output to one or multiple formatters at the same time.  For
 * example, one HRF formatter can output to the standard output, while XML formatter output to
 * the file.
 *
 * Usage:
 *
 *     // Call in init_unit_test_suite: (this will override the --log_format parameter)
 *     auto formatter = new boost::unit_test::output::multi_log_formatter; // same as already configured logger
 *
 *     // Prepare and add additional logger(s)
 *     formatter.add(std::make_shared<boost::unit_test::output::xml_log_formatter>(),
 *                   std::make_shared<std::ofstream>("out.xml"));
 *
 *      boost::unit_test::unit_test_log.set_formatter(formatter);
 *
 * @note Calling `boost::unit_test::unit_test_log.set_stream(...)` will change the stream for
 *       the original logger.
 */
class multi_log_formatter : public unit_test_log_formatter
{
public:
  /**
   * @brief Create instance of the logger, based on the configured logger instance
   */
  multi_log_formatter()
  {
    auto format =
#if BOOST_VERSION > 105900
      runtime_config::get<output_format>(runtime_config::LOG_FORMAT);
#else
      runtime_config::log_format();
#endif // BOOST_VERSION > 105900

    switch (format) {
      default:
#if BOOST_VERSION >= 105900
      case OF_CLF:
#else
      case CLF:
#endif // BOOST_VERSION >= 105900
        m_loggers.push_back({std::make_shared<compiler_log_formatter>(), nullptr});
        break;
#if BOOST_VERSION >= 105900
      case OF_XML:
#else
      case XML:
#endif // BOOST_VERSION >= 105900
        m_loggers.push_back({std::make_shared<xml_log_formatter>(), nullptr});
        break;
    }
  }

  void
  add(std::shared_ptr<unit_test_log_formatter> formatter, std::shared_ptr<std::ostream> os)
  {
    m_loggers.push_back({formatter, os});
  }

  // Formatter interface
  void
  log_start(std::ostream& os, counter_t test_cases_amount)
  {
    for (auto& l : m_loggers)
      l.logger->log_start(l.os == nullptr ? os : *l.os, test_cases_amount);
  }

  void
  log_finish(std::ostream& os)
  {
    for (auto& l : m_loggers)
      l.logger->log_finish(l.os == nullptr ? os : *l.os);
  }

  void
  log_build_info(std::ostream& os)
  {
    for (auto& l : m_loggers)
      l.logger->log_build_info(l.os == nullptr ? os : *l.os);
  }

  void
  test_unit_start(std::ostream& os, const test_unit& tu)
  {
    for (auto& l : m_loggers)
      l.logger->test_unit_start(l.os == nullptr ? os : *l.os, tu);
  }

  void
  test_unit_finish(std::ostream& os, const test_unit& tu, unsigned long elapsed)
  {
    for (auto& l : m_loggers)
      l.logger->test_unit_finish(l.os == nullptr ? os : *l.os, tu, elapsed);
  }

  void
  test_unit_skipped(std::ostream& os, const test_unit& tu)
  {
    for (auto& l : m_loggers)
      l.logger->test_unit_skipped(l.os == nullptr ? os : *l.os, tu);
  }

#if BOOST_VERSION >= 105900
  void
  log_exception_start(std::ostream& os, const log_checkpoint_data& lcd, const execution_exception& ex)
  {
    for (auto& l : m_loggers)
      l.logger->log_exception_start(l.os == nullptr ? os : *l.os, lcd, ex);
  }

  void
  log_exception_finish(std::ostream& os)
  {
    for (auto& l : m_loggers)
      l.logger->log_exception_finish(l.os == nullptr ? os : *l.os);
  }
#else
  void
  log_exception(std::ostream& os, const log_checkpoint_data& lcd, const execution_exception& ex)
  {
    for (auto& l : m_loggers)
      l.logger->log_exception(l.os == nullptr ? os : *l.os, lcd, ex);
  }
#endif // BOOST_VERSION >= 105900

  void
  log_entry_start(std::ostream& os, const log_entry_data& entry_data, log_entry_types let)
  {
    for (auto& l : m_loggers)
      l.logger->log_entry_start(l.os == nullptr ? os : *l.os, entry_data, let);
  }

  void
  log_entry_value(std::ostream& os, const_string value)
  {
    for (auto& l : m_loggers)
      l.logger->log_entry_value(l.os == nullptr ? os : *l.os, value);
  }

  void
  log_entry_finish(std::ostream& os)
  {
    for (auto& l : m_loggers)
      l.logger->log_entry_finish(l.os == nullptr ? os : *l.os);
  }

#if BOOST_VERSION >= 105900
  void
  entry_context_start(std::ostream& os, log_level level)
  {
    for (auto& l : m_loggers)
      l.logger->entry_context_start(l.os == nullptr ? os : *l.os, level);
  }

  void
  log_entry_context(std::ostream& os, const_string value)
  {
    for (auto& l : m_loggers)
      l.logger->log_entry_context(l.os == nullptr ? os : *l.os, value);
  }

  void
  entry_context_finish(std::ostream& os)
  {
    for (auto& l : m_loggers)
      l.logger->entry_context_finish(l.os == nullptr ? os : *l.os);
  }
#endif // BOOST_VERSION >= 105900

private:
  struct LoggerInfo
  {
    std::shared_ptr<unit_test_log_formatter> logger;
    std::shared_ptr<std::ostream> os;
  };
  std::vector<LoggerInfo> m_loggers;
};

} // namespace output
} // namespace unit_test
} // namespace boost

#endif // NDN_TESTS_UNIT_BOOST_MULTI_LOG_FORMATTER_HPP


text:
#include "gtfs/fare.hpp"
#include "gtfs/constructor.hpp"

#include <boost/assert.hpp>

namespace nepomuk
{
namespace gtfs
{

bool checkFareAttributeCSVHeader(std::map<std::string, std::size_t> const &header)
{
    return header.count("fare_id") && header.count("price") && header.count("currency_type") &&
           header.count("payment_method") && header.count("transfers");
}

FareAttribute makeFareAttribute(std::map<std::string, std::size_t> const &header,
                                std::vector<std::string> &values)
{
    const auto to_payment = [](std::string value) {
        return value == "0" ? PaymentType::PAYABLE_ON_BOARD : PaymentType::PRIOR_TO_BORDING;
    };

    const auto to_transfer = [](std::string value) {
        if (value == "0")
            return TransferPolicy::FORBIDDEN;
        else if (value == "1")
            return TransferPolicy::SINGLE;
        else if (value == "2")
            return TransferPolicy::DOUBLE;
        else
        {
            BOOST_ASSERT(value.empty());
            return TransferPolicy::UNLIMITED;
        }
    };

    return {
        construct<FareID>("fare_id", stringToID<FareID>, header, values),
        construct<std::uint64_t>("price", toInt, header, values),
        construct<std::string>("currency_code", forward, header, values),
        construct<PaymentType>("payment_method", to_payment, header, values),
        construct<TransferPolicy>("transfers", to_transfer, header, values),
        construct_as_optional<std::uint64_t, false>("transfer_duration", toInt, header, values)};
}

bool checkFareRuleCSVHeader(std::map<std::string, std::size_t> const &header)
{
    return header.count("fare_id");
}

FareRule makeFareRule(std::map<std::string, std::size_t> const &header,
                      std::vector<std::string> &values)
{
    return {
        construct<FareID>("fare_id", stringToID<FareID>, header, values),
        construct_as_optional<RouteID, false>("route_id", stringToID<RouteID>, header, values),
        construct_as_optional<ZoneID, false>("origin_id", stringToID<ZoneID>, header, values),
        construct_as_optional<ZoneID, false>("destination_id", stringToID<ZoneID>, header, values),
        construct_as_optional<ZoneID, false>("contains_id", stringToID<ZoneID>, header, values)};
}

} // namespace gtfs
} // namespace nepomuk

ext: cpp

max_stars_repo_name: mapbox/nepomuk

max_issues_repo_name: mapbox/nepomuk

max_forks_repo_name: mapbox/nepomuk


text:
/*=========================================================================
* GPU accelerated motion compensation for MRI
*
* Copyright (c) 2016 Bernhard Kainz, Amir Alansary, Maria Kuklisova-Murgasova,
* Kevin Keraudren, Markus Steinberger
* (b.kainz@imperial.ac.uk)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
=========================================================================*/
#include <iostream>
#include <boost/program_options.hpp>
#include <irtkPatchBasedReconstruction.h>

#include <irtkResampling.h>

namespace po = boost::program_options;

#define OFF 0
#define ON 1

//current test
//-i 14_3T_nody_001.nii.gz 21_3T_nody_001.nii.gz -o testPSFRecon1.nii -m mask_10_3T_brain_smooth_dilated.nii.gz --thickness 2.5 2.5
//-i 14_3T_nody_001.nii.gz 21_3T_nody_001.nii.gz -o testPSFRecon1.nii -m mask_10_3T_brain_smooth_dilated.nii.gz --debug
//-i 14_3T_nody_001.nii.gz 21_3T_nody_001.nii.gz -o testPSFRecon1.nii -m mask_10_3T_brain_smooth_dilated.nii.gz --iterations 1 --sr_iterations 1 --debug
//-i 14_3T_nody_001.nii.gz 21_3T_nody_001.nii.gz 10_3T_nody_001.nii.gz 23_3T_nody_001.nii.gz -o testPSFRecon1.nii -m mask_10_3T_brain_smooth_dilated.nii.gz --iterations 1 --sr_iterations 1 --debug
//-i 14_3T_nody_001_d_2.nii.gz 14_3T_nody_001_d_2.nii.gz -o testPSFRecon1.nii -m mask_10_3T_brain_smooth_dilated_d_2.nii.gz --iterations 1 --sr_iterations 1 --resolution 1 --debug
//-o 201507091115_PHILIPS484E467_2801_WIPchest_recon.nii.gz -i 201507091115_PHILIPS484E467_2801_WIPchest_tse_ms_oblSENSE.nii.gz 201507091115_PHILIPS484E467_901_WIPchest_tse_ms_sagSENSE.nii.gz 201507091115_PHILIPS484E467_1001_WIPchest_tse_ms_corSENSE.nii.gz 201507091115_PHILIPS484E467_1101_WIPchest_tse_ms_traSENSE.nii.gz 201507091115_PHILIPS484E467_1401_WIPchest_tse_ms_oblSENSE.nii.gz 201507091115_PHILIPS484E467_1601_WIPchest_tse_ms_oblSENSE.nii.gz 201507091115_PHILIPS484E467_2701_WIPchest_tse_ms_oblSENSE.nii.gz 201507091115_PHILIPS484E467_2901_WIPchest_tse_ms_oblSENSE.nii.gz 201507091115_PHILIPS484E467_3301_WIPchest_tse_ms_oblSENSE.nii.gz 201507091115_PHILIPS484E467_3801_WIPchest_tse_ms_oblSENSE.nii.gz -m 201507091115_PHILIPS484E467_901_WIPchest_tse_ms_sagSENSE_mask.nii.gz --resolution 0.4 --sr_iterations 9  --iterations 9
//D:\zwi\201507091115_PHILIPS484E467_aortaTest\test\chest\withObl
//TODO problem with custom thickness in registration
//-o iFIND2_201507031509_PHILIPS484E467_1103_DelRecT2_brain_recon.nii.gz -i iFIND2_201507031509_PHILIPS484E467_1103_DelRecT2_brain_sag.nii.gz iFIND2_201507031509_PHILIPS484E467_1303_DelRecT2_brain_tra.nii.gz iFIND2_201507031509_PHILIPS484E467_1403_DelRecT2_brain_cor.nii.gz -m iFIND2_201507031509_PHILIPS484E467_1103_DelRecT2_brain_sag_mask.nii.gz --resolution 0.6 --sr_iterations 5 --iterations 7 -p 4 4 4
//-i /home/bk14/cudarecon/data/14_3T_nody_001.nii.gz /home/bk14/cudarecon/data/21_3T_nody_001.nii.gz -o testPSFRecon1.nii -m /home/bk14/cudarecon/data/mask_10_3T_brain_smooth_dilated.nii.gz --iterations 1 --sr_iterations 1 --debug

//TODO add option to do registration (CPU) with ful slices (no patch splitting) -- will unify tools

int main(int argc, char** argv)
{

    //TODO IRTK data I/O implementation and parameters
    //TODO boost I/O
    //TODO GUI
    int cuda_device = 0;

    vector<string> inputStacks;
    vector<string> inputTransformations;
    string outputName;
    string maskName;
    string evaluationGtName;
    vector<string> evaluationMaskNames;
    int nStacks;
    vector<irtkGenericImage<float> > stacks;
    vector<irtkRigidTransformation> stack_transformations;

    //TODO for anatomical improvements, recompute patches per iteration and make patches getting larger per iteration
    vector<float> thickness;
    irtkGenericImage<char> mask;
    // vector < irtkGenericImage<char> > evaluationMask;
    std::vector<unsigned int> patchSize;
    std::vector<unsigned int> patchStride;
    unsigned int spxSize;
    unsigned int spxExtend;

    vector<int> devicesToUse; //TODO multi GPU currently only first in list
    vector<int> packages;
    string existingReconstructionTargetName;

    // general default configurations
    float output_resolution = 0.75;
    bool _debug 			= false;
    bool _patch_extraction	= false;
    int sr_iterations 		= 7;
    int iterations 			= 7;
    int _dilateMask       	= 0;
    bool useFullSlices 		= false;
    bool _noMatchIntensities= false;
    bool _superpixel        = false;
    bool _hierarchical      = false;
    bool _resample          = false;
    bool _evaluateBaseline  = false;

    // patch-based default configurations
    patchSize.resize(2);
    patchStride.resize(2);
    patchSize[0] 			= 32;
    patchSize[1] 			= 32;
    patchStride[0] 			= 16;
    patchStride[1] 			= 16;

    // superpixel default configurations
    spxSize 				= 16;
    spxExtend 				= 50; // 50% percent

    try
    {
        po::options_description desc("Options");
        desc.add_options()
            ("help,h", "Print usage messages")
            ("output,o", po::value<string>(&outputName)->required(), "Name for the reconstructed volume. Nifti or Analyze format.")
            ("mask,m", po::value<string>(&maskName), "Binary mask to define the region od interest. Nifti or Analyze format.")
            ("input,i", po::value<vector<string> >(&inputStacks)->multitoken(), "[stack_1] .. [stack_N]  The input stacks. Nifti or Analyze format.")
            ("existingReconTarget,e", po::value<string>(&existingReconstructionTargetName), "Set an existing reconstruction as target image.")
            ("patchSize", po::value< vector<unsigned int> >(&patchSize)->multitoken(), "defines the size of the 2D patches for patchBased reconstruction")
            ("patchStride", po::value< vector<unsigned int> >(&patchStride)->multitoken(), "defines the stride of the 2D patches for patchBased reconstruction")
            ("resolution", po::value< float >(&output_resolution)->default_value(0.75), "Isotropic output resolution of the volume. [Default: 0.75mm]")
            ("transformation,t", po::value< vector<string> >(&inputTransformations)->multitoken(), "The transformations of the input stack to template in \'dof\' format used in IRTK. Only rough alignment with correct orienation and some overlap is needed. Use \'id\' for an identity transformation for at least one stack. The first stack with \'id\' transformation  will be resampled as template.")
            ("noMatchIntensities", po::bool_switch(&_noMatchIntensities)->default_value(false), "Skip match intensities between the input stacks")
            ("superpixel,s", po::bool_switch(&_superpixel)->default_value(false), "Turn on superpixel-based reconstruction. [Default: false]")
            ("spxSize", po::value< unsigned int >(&spxSize)->multitoken(), "defines the initial size (<=64) of the 2D superpixels for the superpixel-based reconstruction. [Default: 16]")
            ("spxExtend", po::value< unsigned int >(&spxExtend)->multitoken(), "defines a ratio [0-100]%% from a superpixel size for dilation or overlapping. [Default: 50%%]")
            ("hierarchical", po::bool_switch(&_hierarchical)->default_value(false), "Turn on hierarchical-based reconstruction. [Default: false]")
            ("debug", po::bool_switch(&_debug)->default_value(false), "Write debug images.")
            ("resample", po::bool_switch(&_resample)->default_value(false), "Resample input stacks before reconstruction [Note: consumes larger memory].")
            ("useFullSlices", po::bool_switch(&useFullSlices)->default_value(false), "Use full slices instead of patches.")
            ("dilateMask", po::value< int >(&_dilateMask)->default_value(0), "Dilate reconstruction mask n-iterations.")
            ("iterations", po::value< int >(&iterations)->default_value(7), "number of registration iterations.")
            ("sr_iterations", po::value< int >(&sr_iterations)->default_value(7), "number of Super-resolution iterations.")
            ("packages,p", po::value< vector<int> >(&packages)->multitoken(), "Give number of packages used during acquisition for each stack. The stacks will be split into packages during registration iteration 1 and then into odd and even slices within each package during registration iteration 2. The method will then continue with slice to  volume approach. [Default: slice to volume registration only]")
            ("devices,d", po::value< vector<int> >(&devicesToUse)->multitoken(), "Select the CP > 3.0 GPUs on which the reconstruction should be executed. Default: all devices > CP 3.0")
            ("thickness", po::value< vector<float> >(&thickness)->multitoken(), "[th_1] .. [th_N] Give patch thickness.[Default: twice voxel size in z direction] -- TODO")
            ;

        if (EVALUATE){
            desc.add_options()
                ("evaluateGt", po::value<string>(&evaluationGtName)->multitoken(), "Ground truth filename for reconstruction evaluation.")
                ("evaluation,v", po::value<vector<string> >(&evaluationMaskNames)->multitoken(), "Binary mask to define the region of interest for evaluation. Nifti or Analyze format.")
                ("evaluateBaseline", po::bool_switch(&_evaluateBaseline)->default_value(false), "Evaluate baseline - measure the evaluation metrics between the first and last stack before the reconstruction.")
                ("patchExtraction", po::bool_switch(&_patch_extraction)->default_value(false), "Evaluate patch extraction only.")
                ;
            }
        po::variables_map vm;
        try
        {
            po::store(po::parse_command_line(argc, argv, desc), vm); // can throw

            if (vm.count("help"))
            {
                std::cout << "Application to perform reconstruction of volumetric MRI from thick patches." << std::endl
                          << desc << std::endl;
                return EXIT_SUCCESS;
            }

            po::notify(vm);
        }
        catch (po::error& e)
        {
            std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return EXIT_FAILURE;
        }
    }
    catch (std::exception& e)
    {
        std::cerr << "Unhandled exception while parsing arguments:  "
                  << e.what() << ", application will now exit" << std::endl;
        return EXIT_FAILURE;
    }
    string testn = outputName;

    if (devicesToUse.size() == 0)
        devicesToUse.push_back(0);

    //TODO multi GPU
    cudaSetDevice(devicesToUse[0]);
    cuda_device = devicesToUse[0]; //select one device (should be fixed to use multi-GPU)

    cout << "Reconstructed volume name ... " << outputName << endl;
    nStacks = inputStacks.size();
    cout << "Number of stacks ... " << nStacks << endl;

    bool setThickness = false;
    if (thickness.empty())
        setThickness = true;

    vector<int> packagesN;
    vector<float> thicknessN;

    for (int i = 0; i < nStacks; i++)
    {
        irtkGenericImage<float> stack;
        stack.Read(inputStacks[i].c_str());

#if 0
        //TODO test for registration improvement
        // resamples to recon space -- deactivate for faster recon but less accurate registration
        irtkImageAttributes attr = stack.GetImageAttributes();
        //TODO customized slice thickness
        irtkResamplingWithPadding<float> resampling(output_resolution, output_resolution, attr._dz, -1);
        resampling.SetInput(&stack);
        resampling.SetOutput(&stack);
        resampling.Run();
        //test end
#endif
        double dx, dy, dz;
        stack.GetPixelSize(&dx, &dy, &dz);
        if (setThickness)
        {
            thickness.push_back(dz);
        }
        else
        {
            thickness[i] = thickness[i] / 2.0; //given that it is called thickness and to maintain same scheme as earlier versions
        }

        //stack.PutPixelSize(dx, dy, thickness[i]);

        cout << "Reading stack ... " << inputStacks[i] << " thickness " << thickness[i] << " * 2 " << endl;

        //separate 4D volumes
        if (stack.GetT() > 1)
        {
            irtkImageAttributes attr = stack.GetImageAttributes();
            attr._t = 1;
            for (int t = 0; t < stack.GetT(); t++)
            {
                cout << "Splitting stack ... " << inputStacks[i] << endl;
                irtkGenericImage<float> stackn(attr);
                memcpy(stackn.GetPointerToVoxels(), stack.GetPointerToVoxels() + t*stack.GetX()*stack.GetY()*stack.GetZ(),
                       stack.GetX()*stack.GetY()*stack.GetZ() * sizeof(float));
                stacks.push_back(stackn);

                thicknessN.push_back(thickness[i]);
                if (!packages.empty())
                    packagesN.push_back(packages[i]);
            }
        }
        else
        {
            stacks.push_back(stack);
            if (!thickness.empty())
                thicknessN.push_back(thickness[i]);
            if (!packages.empty())
                packagesN.push_back(packages[i]);

            else
            {
                printf("using standard package size\n");
            }
        }
    }

    thickness = thicknessN;
    if (!packages.empty())
        packages = packagesN;

    nStacks = stacks.size();

    /*for (int i = 0; i < stacks.size(); i++)
        {
        char buffer[255];
        sprintf(buffer, "test%i.nii", i);
        stacks[i].Write(buffer);
        }
        std::cin.get();*/

    printf("useFullSlices %s \n", useFullSlices ? "true" : "false");

    if (_hierarchical)
    {
        if ( _superpixel && !useFullSlices ) {
            cout << "hierarchical-superpixel-based ON" << endl;
	        patchSize[0] 	= spxSize;
	        patchSize[1] 	= spxSize;
	        patchStride[0] 	= spxExtend;
            patchStride[1] 	= spxExtend;
        }else{
            if (useFullSlices) {
                printf("SVR ON - useFullSlices \n");
                _hierarchical   = false;
            }else{
                cout << "hierarchical-patch-based ON" << endl;

            }
        }
    }else{
        if ( _superpixel && !useFullSlices ) {
            cout << "superpixel-based ON" << endl;
            patchSize[0] 	= spxSize;
	        patchSize[1] 	= spxSize;
	        patchStride[0] 	= spxExtend;
            patchStride[1] 	= spxExtend;
        }else{
            if (useFullSlices) {
                printf("SVR ON - useFullSlices \n");
            }else{
                cout << "patch-based ON" << endl;
            }
        }
    }

    cout << "cuda_dev = " << cuda_device << endl;

    // TODO: intenral implementation
    if (!_hierarchical)
    {
        irtkPatchBasedReconstruction<float> reconstruction(cuda_device, output_resolution, make_uint2(patchSize[0], patchSize[1]), make_uint2(patchStride[0], patchStride[1]),
        iterations, sr_iterations, _dilateMask, _resample, _noMatchIntensities, _superpixel, _hierarchical, _debug, _patch_extraction);

        reconstruction.setImageStacks(stacks, thicknessN, inputTransformations, packagesN);
        reconstruction.setUseFullSlices(useFullSlices);

        if (packagesN.size() == nStacks)
        {
            reconstruction.setPackageDenominators(packagesN);
            printf("setting package denominators...\n");
        }

        if (!maskName.empty())
        {
            mask.Read((char*)(maskName.c_str()));
            reconstruction.setMask(mask);
        }

        reconstruction.setEvaluationBaseline(_evaluateBaseline);

        if (!evaluationMaskNames.empty())
        {
            // read organ masks for evaluating the reconstruction quality at these regions
            reconstruction.setEvaluationMaskName(evaluationMaskNames);
        }

        if (!evaluationGtName.empty())
        {
            // read organ masks for evaluating the reconstruction quality at these regions
            reconstruction.setEvaluationGtName(evaluationGtName);
        }

        if (!existingReconstructionTargetName.empty())
        {
            irtkGenericImage<float>* existingReconstructionTarget = new irtkGenericImage<float>();
            existingReconstructionTarget->Read(existingReconstructionTargetName.c_str());
            reconstruction.setExistingReconstructionTarget(existingReconstructionTarget);
        }

        reconstruction.run();

   		if (_patch_extraction) return 0; // evaluate patch extraction only

        reconstruction.getReconstruction()->Write(outputName.c_str());

    }else{
        // hierarchical-based

        for (int iter = 0; iter <= (iterations); iter++)
        {

            printf("Hierarchical level - %i  -------------------------------- \n", iter);

            int recon_iter = 1;
            if (_patch_extraction) recon_iter = iterations;

            irtkPatchBasedReconstruction<float> reconstruction_h(cuda_device, output_resolution, make_uint2(patchSize[0], patchSize[1]), make_uint2(patchStride[0], patchStride[1]), recon_iter, sr_iterations, _dilateMask, _resample, _noMatchIntensities, _superpixel, _hierarchical, _debug, _patch_extraction);
            reconstruction_h.setImageStacks(stacks, thicknessN, inputTransformations, packagesN);
            reconstruction_h.setUseFullSlices(useFullSlices);

            if (packagesN.size() == nStacks)
            {
                reconstruction_h.setPackageDenominators(packagesN);
                printf("setting package denominators...\n");
            }

            if (!maskName.empty())
            {
                mask.Read((char*)(maskName.c_str()));
                reconstruction_h.setMask(mask);
            }

            if (!evaluationMaskNames.empty()) { reconstruction_h.setEvaluationMaskName(evaluationMaskNames); } // read organ masks for evaluating the reconstruction quality at these regions
            if (!evaluationGtName.empty()) { reconstruction_h.setEvaluationGtName(evaluationGtName); } // read organ masks for evaluating the reconstruction quality at these regions

            if (iter==0)
            {
                if (!existingReconstructionTargetName.empty())
                {
                	reconstruction_h.setEvaluationBaseline(_evaluateBaseline);
                    irtkGenericImage<float>* existingReconstructionTarget = new irtkGenericImage<float>();
                    existingReconstructionTarget->Read(existingReconstructionTargetName.c_str());
                    reconstruction_h.setExistingReconstructionTarget(existingReconstructionTarget);
                }
            }else{

                // update existing reconstruction target
                char newReconstructionTargetName[256];

                if ( !_superpixel) {
                	sprintf(newReconstructionTargetName, "reconimage1_%i_%i.nii.gz", patchSize[0]+4,patchStride[0]+2);
            	} else {
            		sprintf(newReconstructionTargetName, "reconimage1_%i_%i.nii.gz", patchSize[0]+4,patchStride[0]);
            	}

                printf("Existing Reconstruction Target Name %s \n", newReconstructionTargetName);
                irtkGenericImage<float>* existingReconstructionTarget = new irtkGenericImage<float>();
                existingReconstructionTarget->Read(newReconstructionTargetName);
                reconstruction_h.setExistingReconstructionTarget(existingReconstructionTarget);
            }

            reconstruction_h.run();
            reconstruction_h.setEvaluationBaseline(false);

			if (_patch_extraction) return 0;

            if (iter<iterations)
            {
                printf("Reconstruction is done! ... increase patch size and repeat \n");
                // increase patch size
                patchSize[0]   -= 4; patchSize[1]   -= 4;
                if ( !_superpixel) { patchStride[0] -= 2; patchStride[1] -= 2; }
            }else{
                printf("Final reconstruction is done! ... save output image and exit \n");
                reconstruction_h.getReconstruction()->Write(outputName.c_str());
            }

            // reconstruction_h.release();

        }
    }

    return EXIT_SUCCESS;

}

max_stars_repo_name: gordon-n-stevenson/fetalReconstruction

max_stars_repo_licenses: Zlib Unlicense Intel MIT

max_issues_repo_name: gordon-n-stevenson/fetalReconstruction

max_issues_repo_licenses: Zlib Unlicense Intel MIT

max_forks_repo_name: gordon-n-stevenson/fetalReconstruction

max_forks_repo_licenses: Zlib Unlicense Intel MIT