<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

constexpr const std::size_t width = 220;        //Should not be changed
constexpr const std::size_t height = 40;        //Should not be changed

constexpr const std::size_t patch_width = 40;   //Should not be changed
constexpr const std::size_t patch_height = 40;  //Should not be changed

constexpr const std::size_t epochs = 25;
constexpr const std::size_t patch_stride = 20;

constexpr const std::size_t NF1 = 17;
constexpr const std::size_t K1 = 30;
constexpr const std::size_t C1 = 2;
constexpr const std::size_t B1 = 25;
constexpr const dll::unit_type HT1 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::NONE;

constexpr const std::size_t NF2 = 5;
constexpr const std::size_t K2 = 30;
constexpr const std::size_t C2 = 2;
constexpr const std::size_t B2 = 25;
constexpr const dll::unit_type HT2 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::NONE;

const auto rate_0 = [](double& value){ value = 1.0 * value; };
const auto rate_1 = [](double& value){ value = 1.0 * value; };

const auto wd_l1_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l1_1 = [](double& value){ value = 1.0 * value; };

const auto wd_l2_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l2_1 = [](double& value){ value = 1.0 * value; };

const auto pbias_0 = [](double& value){ value = 1.0 * value; };
const auto pbias_1 = [](double& value){ value = 1.0 * value; };

const auto pbias_lambda_0 = [](double& value){ value = 1.0 * value; };
const auto pbias_lambda_1 = [](double& value){ value = 1.0 * value; };

} // end of namespace third

#endif
<commit_msg>Slight changes<commit_after>//This file will be put in 160.98.22.23
//=======================================================================
// Copyright Baptiste Wicht 2015.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

constexpr const std::size_t width = 220;        //Should not be changed
constexpr const std::size_t height = 40;        //Should not be changed

constexpr const std::size_t patch_width = 40;   //Should not be changed
constexpr const std::size_t patch_height = 40;  //Should not be changed

constexpr const std::size_t epochs = 25;
constexpr const std::size_t patch_stride = 20;

constexpr const std::size_t NF1 = 17;
constexpr const std::size_t K1 = 40;
constexpr const std::size_t C1 = 2;
constexpr const std::size_t B1 = 25;
constexpr const dll::unit_type HT1 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::NONE;

constexpr const std::size_t NF2 = 5;
constexpr const std::size_t K2 = 40;
constexpr const std::size_t C2 = 2;
constexpr const std::size_t B2 = 25;
constexpr const dll::unit_type HT2 = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2 = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::NONE;

const auto rate_0 = [](double& value){ value = 1.0 * value; };
const auto rate_1 = [](double& value){ value = 1.0 * value; };

const auto wd_l1_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l1_1 = [](double& value){ value = 1.0 * value; };

const auto wd_l2_0 = [](double& value){ value = 1.0 * value; };
const auto wd_l2_1 = [](double& value){ value = 1.0 * value; };

const auto pbias_0 = [](double& value){ value = 2.0 * value; };
const auto pbias_1 = [](double& value){ value = 2.0 * value; };

const auto pbias_lambda_0 = [](double& value){ value = 1.0 * value; };
const auto pbias_lambda_1 = [](double& value){ value = 1.0 * value; };

} // end of namespace third

#endif
<|endoftext|>


<commit_before>// Simple keogram composition program using OpenCV
// Copyright 2018 Jarno Paananen <jarno.paananen@gmail.com>
// Based on a script by Thomas Jacquin
// Rotation added by Agustin Nunez @agnunez
// SPDX-License-Identifier: MIT

#include <getopt.h>
#include <glob.h>
#include <stdio.h>
#include <sys/stat.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>

#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"

//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
int loglevel = 0;

void usage_and_exit(int x) {
  std::cout
      << "Usage:\tkeogram -d <imagedir> -e <ext> -o <outputfile> [<other_args>]"
      << std::endl;
  if (x)
    std::cout
        << KRED
        << "Source directory, image extension, and output file are required"
        << std::endl;

  std::cout << KNRM << std::endl;
  std::cout << "Arguments:" << std::endl;
  std::cout << "-d | --directory <str> : directory from which to load images "
               "(required)"
            << std::endl;
  std::cout << "-e | --extension <str> : image extension to process (required)"
            << std::endl;
  std::cout << "-o | --output-file <str> : name of output file (required)"
            << std::endl;
  std::cout << "-r | --rotate <float> : number of degrees to rotate image, "
               "counterclockwise (0)"
            << std::endl;
  std::cout << "-s | --image-size <int>x<int> : only process images of a given "
               "size, eg. 1280x960"
            << std::endl;
  std::cout << "-h | --help : display this help message" << std::endl;
  std::cout << "-v | --verbose : Increase logging verbosity" << std::endl;
  std::cout << "-n | --no-label : Disable hour labels" << std::endl;
  std::cout
      << "-C | --font-color <str> : label font color, in HTML format (0000ff)"
      << std::endl;
  std::cout << "-L | --font-line <int> : font line thickness (3)" << std::endl;
  std::cout << "-N | --font-name <str> : font name (simplex)" << std::endl;
  std::cout << "-S | --font-side <float> : font size (2.0)" << std::endl;
  std::cout << "-T | --font-type <int> : font line type (1)" << std::endl;

  std::cout << KNRM << std::endl;
  std::cout
      << "Font name is one of these OpenCV font names:\n\tSimplex, Plain, "
         "Duplex, Complex, Triplex, ComplexSmall, ScriptSimplex, ScriptComplex"
      << std::endl;
  std::cout << "Font Type is an OpenCV line type: 0=antialias, 1=8-connected, "
               "2=4-connected"
            << std::endl;
  std::cout << KNRM << std::endl;
  std::cout << "    ex: keogram --directory ../images/current/ --extension jpg "
               "--output-file keogram.jpg --font-size 2"
            << std::endl;
  std::cout << "    ex: keogram -d . -e png -o /home/pi/allsky/keogram.jpg -n"
            << KNRM << std::endl;
  exit(x);
}

int get_font_by_name(char* s) {
  // case insensitively check the user-specified font, and use something
  // sensible in case of erroneous input
  if (strcasecmp(s, "plain") == 0)
    return cv::FONT_HERSHEY_PLAIN;
  if (strcasecmp(s, "duplex") == 0)
    return cv::FONT_HERSHEY_DUPLEX;
  if (strcasecmp(s, "complex") == 0)
    return cv::FONT_HERSHEY_COMPLEX;
  if (strcasecmp(s, "complexsmall") == 0)
    return cv::FONT_HERSHEY_COMPLEX_SMALL;
  if (strcasecmp(s, "triplex") == 0)
    return cv::FONT_HERSHEY_TRIPLEX;
  if (strcasecmp(s, "scriptsimplex") == 0)
    return cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
  if (strcasecmp(s, "scriptcomplex") == 0)
    return cv::FONT_HERSHEY_SCRIPT_COMPLEX;
  if (strcasecmp(s, "simplex"))  // yes, this is intentional
    std::cout << KRED << "Unknown font '" << s << "', using SIMPLEX " << KNRM
              << std::endl;
  return cv::FONT_HERSHEY_SIMPLEX;
}

int main(int argc, char* argv[]) {
  int c;
  bool labelsEnabled = true, parse_filename = false;
  int fontFace = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
  double fontScale = 2;
  int fontType = cv::LINE_8;
  int thickness = 3;
  unsigned char fontColor[3] = {255, 0, 0};
  double angle = 0;
  std::string directory, extension, outputfile;
  int width = 0, height = 0;

  while (1) {  // getopt loop
    int option_index = 0;
    static struct option long_options[] = {
        {"directory", required_argument, 0, 'd'},
        {"image-size", required_argument, 0, 's'},
        {"extension", required_argument, 0, 'e'},
        {"output", required_argument, 0, 'o'},
        {"font-color", required_argument, 0, 'C'},
        {"font-line", required_argument, 0, 'L'},
        {"font-name", required_argument, 0, 'N'},
        {"font-size", required_argument, 0, 'S'},
        {"font-type", required_argument, 0, 'T'},
        {"rotate", required_argument, 0, 'r'},
        {"parse-filename", no_argument, 0, 'p'},
        {"no-label", no_argument, 0, 'n'},
        {"verbose", no_argument, 0, 'v'},
        {"help", no_argument, 0, 'h'},
        {0, 0, 0, 0}};

    c = getopt_long(argc, argv, "d:e:o:r:s:C:L:N:S:T:npvh", long_options,
                    &option_index);
    if (c == -1)
      break;
    switch (c) {  // option switch
      int tmp;
      case 'h':
        usage_and_exit(0);
        // NOTREACHED
      case 'd':
        directory = optarg;
        break;
      case 'e':
        extension = optarg;
        break;
      case 'o':
        outputfile = optarg;
        break;
      case 'p':
        parse_filename = true;
        break;
      case 'n':
        labelsEnabled = false;
        break;
      case 'r':
        angle = atof(optarg);
        break;
      case 's':
        sscanf(optarg, "%dx%d", &width, &height);
        // 122.8Mpx should be enough for anybody.
        if (height < 0 || height > 9600 || width < 0 || width > 12800)
          height = width = 0;
        break;
      case 'v':
        loglevel++;
        break;
      case 'C':
        if (strchr(optarg, ' ')) {
          int r, g, b;
          sscanf(optarg, "%d %d %d", &b, &g, &r);
          fontColor[0] = b & 0xff;
          fontColor[1] = g & 0xff;
          fontColor[2] = r & 0xff;
          break;
        }
        if (optarg[0] == '#')  // skip '#' if input is like '#coffee'
          optarg++;
        sscanf(optarg, "%06x", &tmp);
        fontColor[0] = tmp & 0xff;
        fontColor[1] = (tmp >> 8) & 0xff;
        fontColor[2] = (tmp >> 16) & 0xff;
        break;
      case 'L':
        thickness = atoi(optarg);
        break;
      case 'N':
        fontFace = get_font_by_name(optarg);
        break;
      case 'S':
        fontScale = atof(optarg);
        break;
      case 'T':
        tmp = atoi(optarg);
        if (tmp == 2)
          fontType = cv::LINE_4;
        else if (tmp == 0)
          fontType = cv::LINE_AA;
        else
          fontType = cv::LINE_8;
        break;
      default:
        break;
    }  // option switch
  }    // getopt loop

  if (directory.empty() || extension.empty() || outputfile.empty())
    usage_and_exit(3);

  glob_t files;
  std::string wildcard = directory + "/*." + extension;
  glob(wildcard.c_str(), 0, NULL, &files);
  if (files.gl_pathc == 0) {
    globfree(&files);
    std::cout << "No images found, exiting." << std::endl;
    return 0;
  }

  cv::Mat accumulated;

  int prevHour = -1;
  int nchan = 0;

  for (size_t f = 0; f < files.gl_pathc; f++) {
    cv::Mat imagesrc = cv::imread(files.gl_pathv[f], cv::IMREAD_UNCHANGED);
    if (!imagesrc.data) {
      std::cout << "Error reading file " << basename(files.gl_pathv[f])
                << std::endl;
      continue;
    }

    if (loglevel)
      std::cout << "[" << f + 1 << "/" << files.gl_pathc << "] "
                << basename(files.gl_pathv[f]) << std::endl;

    if (height && width &&
        (imagesrc.cols != width || imagesrc.rows != height)) {
      fprintf(stderr, "%s size %dx%d != %dx%d\n", files.gl_pathv[f],
              imagesrc.cols, imagesrc.cols, width, height);
      continue;
    }
    if (nchan == 0)
      nchan = imagesrc.channels();

    if (imagesrc.channels() != nchan)
      continue;

    cv::Point2f center((imagesrc.cols - 1) / 2.0, (imagesrc.rows - 1) / 2.0);
    cv::Mat rot = cv::getRotationMatrix2D(center, angle, 1.0);
    cv::Rect2f bbox =
        cv::RotatedRect(cv::Point2f(), imagesrc.size(), angle).boundingRect2f();
    rot.at<double>(0, 2) += bbox.width / 2.0 - imagesrc.cols / 2.0;
    rot.at<double>(1, 2) += bbox.height / 2.0 - imagesrc.rows / 2.0;
    cv::Mat imagedst;
    cv::warpAffine(imagesrc, imagedst, rot, bbox.size());
    if (accumulated.empty()) {
      accumulated.create(imagedst.rows, files.gl_pathc, imagesrc.type());
    }

    // Copy middle column to destination
    imagedst.col(imagedst.cols / 2).copyTo(accumulated.col(f));

    if (labelsEnabled) {
      struct tm ft;  // the time of the file, by any means necessary
      if (parse_filename) {
        // engage your safety squints!
        char* s;
        s = strrchr(files.gl_pathv[f], '-');
        s++;
        sscanf(s, "%04d%02d%02d%02d%02d%02d.%*s", &ft.tm_year, &ft.tm_mon,
               &ft.tm_mday, &ft.tm_hour, &ft.tm_min, &ft.tm_sec);
      } else {
        // sometimes you can believe the file time on disk
        struct stat s;
        stat(files.gl_pathv[f], &s);
        struct tm* t = localtime(&s.st_mtime);
        ft.tm_hour = t->tm_hour;
      }

      if (ft.tm_hour != prevHour) {
        if (prevHour != -1) {
          // Draw a dashed line and label for hour
          cv::LineIterator it(accumulated, cv::Point(f, 0),
                              cv::Point(f, accumulated.rows));
          for (int i = 0; i < it.count; i++, ++it) {
            // 4 pixel dashed line
            if (i & 4) {
              uchar* p = *it;
              for (int c = 0; c < it.elemSize; c++) {
                *p = ~(*p);
                p++;
              }
            }
          }

          // Draw text label to the left of the dash
          char hour[3];
          snprintf(hour, 3, "%02d", ft.tm_hour);
          std::string text(hour);
          int baseline = 0;
          cv::Size textSize =
              cv::getTextSize(text, fontFace, fontScale, thickness, &baseline);

          if (f - textSize.width >= 0) {
            cv::putText(accumulated, text,
                        cv::Point(f - textSize.width,
                                  accumulated.rows - textSize.height),
                        fontFace, fontScale,
                        cv::Scalar(fontColor[0], fontColor[1], fontColor[2]),
                        thickness, fontType);
          }
        }
        prevHour = ft.tm_hour;
      }
    }
  }
  globfree(&files);

  std::vector<int> compression_params;
  compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
  compression_params.push_back(9);
  compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
  compression_params.push_back(95);

  cv::imwrite(outputfile, accumulated, compression_params);
}
<commit_msg>refactor argument parsing and config storage<commit_after>// Simple keogram composition program using OpenCV
// Copyright 2018 Jarno Paananen <jarno.paananen@gmail.com>
// Based on a script by Thomas Jacquin
// Rotation added by Agustin Nunez @agnunez
// SPDX-License-Identifier: MIT

#include <getopt.h>
#include <glob.h>
#include <stdio.h>
#include <sys/stat.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>

#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/opencv.hpp>

#define KNRM "\x1B[0m"
#define KRED "\x1B[31m"
#define KGRN "\x1B[32m"
#define KYEL "\x1B[33m"
#define KBLU "\x1B[34m"
#define KMAG "\x1B[35m"
#define KCYN "\x1B[36m"
#define KWHT "\x1B[37m"

struct config_t {
  std::string img_src_dir, img_src_ext, dst_keogram;
  bool labels_enabled, keogram_enabled, parse_filename, junk;
  int img_width;
  int img_height;
  int fontFace;
  int fontType;
  int lineWidth;
  int verbose;
  uint8_t a, r, g, b;
  double fontScale;
  double rotation_angle;
  double brightness_limit;
} config;

void parse_args(int, char**, struct config_t*);
void usage_and_exit(int);
int get_font_by_name(char*);

//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------

void parse_args(int argc, char** argv, struct config_t* cf) {
  int c;

  cf->labels_enabled = true;
  cf->parse_filename = false;
  cf->fontFace = cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
  cf->fontScale = 2;
  cf->fontType = cv::LINE_8;
  cf->lineWidth = 3;
  cf->a = cf->r = cf->g = 0;
  cf->b = 0xff;
  cf->rotation_angle = 0;
  cf->verbose = cf->img_width = cf->img_height = 0;

  while (1) {  // getopt loop
    int option_index = 0;
    static struct option long_options[] = {
        {"directory", required_argument, 0, 'd'},
        {"image-size", required_argument, 0, 's'},
        {"extension", required_argument, 0, 'e'},
        {"output", required_argument, 0, 'o'},
        {"font-color", required_argument, 0, 'C'},
        {"font-line", required_argument, 0, 'L'},
        {"font-name", required_argument, 0, 'N'},
        {"font-size", required_argument, 0, 'S'},
        {"font-type", required_argument, 0, 'T'},
        {"rotate", required_argument, 0, 'r'},
        {"parse-filename", no_argument, 0, 'p'},
        {"no-label", no_argument, 0, 'n'},
        {"verbose", no_argument, 0, 'v'},
        {"help", no_argument, 0, 'h'},
        {0, 0, 0, 0}};

    c = getopt_long(argc, argv, "d:e:o:r:s:C:L:N:S:T:npvh", long_options,
                    &option_index);
    if (c == -1)
      break;
    switch (c) {  // option switch
      case 'h':
        usage_and_exit(0);
        // NOTREACHED
      case 'd':
        cf->img_src_dir = optarg;
        break;
      case 'e':
        cf->img_src_ext = optarg;
        break;
      case 'o':
        cf->dst_keogram = optarg;
        break;
      case 'p':
        cf->parse_filename = true;
        break;
      case 'n':
        cf->labels_enabled = false;
        break;
      case 'r':
        cf->rotation_angle = atof(optarg);
        break;
      case 's':
        int height, width;
        sscanf(optarg, "%dx%d", &width, &height);
        // 122.8Mpx should be enough for anybody.
        if (height < 0 || height > 9600 || width < 0 || width > 12800)
          height = width = 0;
        cf->img_height = height;
        cf->img_width = width;
        break;
      case 'v':
        cf->verbose++;
        break;
      case 'C':
        int tmp;
        if (strchr(optarg, ' ')) {
          int r, g, b;
          sscanf(optarg, "%d %d %d", &b, &g, &r);
          cf->b = b & 0xff;
          cf->g = g & 0xff;
          cf->r = r & 0xff;
          break;
        }
        if (optarg[0] == '#')  // skip '#' if input is like '#coffee'
          optarg++;
        sscanf(optarg, "%06x", &tmp);
        cf->b = tmp & 0xff;
        cf->g = (tmp >> 8) & 0xff;
        cf->r = (tmp >> 16) & 0xff;
        break;
      case 'L':
        cf->lineWidth = atoi(optarg);
        break;
      case 'N':
        cf->fontFace = get_font_by_name(optarg);
        break;
      case 'S':
        cf->fontScale = atof(optarg);
        break;
      case 'T':
        tmp = atoi(optarg);
        if (tmp == 2)
          cf->fontType = cv::LINE_4;
        else if (tmp == 0)
          cf->fontType = cv::LINE_AA;
        else
          cf->fontType = cv::LINE_8;
        break;
      default:
        break;
    }  // option switch
  }    // getopt loop
}

void usage_and_exit(int x) {
  std::cout
      << "Usage:\tkeogram -d <imagedir> -e <ext> -o <outputfile> [<other_args>]"
      << std::endl;
  if (x)
    std::cout
        << KRED
        << "Source directory, image extension, and output file are required"
        << std::endl;

  std::cout << KNRM << std::endl;
  std::cout << "Arguments:" << std::endl;
  std::cout << "-d | --directory <str> : directory from which to load images "
               "(required)"
            << std::endl;
  std::cout << "-e | --extension <str> : image extension to process (required)"
            << std::endl;
  std::cout << "-o | --output-file <str> : name of output file (required)"
            << std::endl;
  std::cout << "-r | --rotate <float> : number of degrees to rotate image, "
               "counterclockwise (0)"
            << std::endl;
  std::cout << "-s | --image-size <int>x<int> : only process images of a given "
               "size, eg. 1280x960"
            << std::endl;
  std::cout << "-h | --help : display this help message" << std::endl;
  std::cout << "-v | --verbose : Increase logging verbosity" << std::endl;
  std::cout << "-n | --no-label : Disable hour labels" << std::endl;
  std::cout
      << "-C | --font-color <str> : label font color, in HTML format (0000ff)"
      << std::endl;
  std::cout << "-L | --font-line <int> : font line thickness (3)" << std::endl;
  std::cout << "-N | --font-name <str> : font name (simplex)" << std::endl;
  std::cout << "-S | --font-side <float> : font size (2.0)" << std::endl;
  std::cout << "-T | --font-type <int> : font line type (1)" << std::endl;

  std::cout << KNRM << std::endl;
  std::cout
      << "Font name is one of these OpenCV font names:\n\tSimplex, Plain, "
         "Duplex, Complex, Triplex, ComplexSmall, ScriptSimplex, ScriptComplex"
      << std::endl;
  std::cout << "Font Type is an OpenCV line type: 0=antialias, 1=8-connected, "
               "2=4-connected"
            << std::endl;
  std::cout << KNRM << std::endl;
  std::cout << "    ex: keogram --directory ../images/current/ --extension jpg "
               "--output-file keogram.jpg --font-size 2"
            << std::endl;
  std::cout << "    ex: keogram -d . -e png -o /home/pi/allsky/keogram.jpg -n"
            << KNRM << std::endl;
  exit(x);
}

int get_font_by_name(char* s) {
  // case insensitively check the user-specified font, and use something
  // sensible in case of erroneous input
  if (strcasecmp(s, "plain") == 0)
    return cv::FONT_HERSHEY_PLAIN;
  if (strcasecmp(s, "duplex") == 0)
    return cv::FONT_HERSHEY_DUPLEX;
  if (strcasecmp(s, "complex") == 0)
    return cv::FONT_HERSHEY_COMPLEX;
  if (strcasecmp(s, "complexsmall") == 0)
    return cv::FONT_HERSHEY_COMPLEX_SMALL;
  if (strcasecmp(s, "triplex") == 0)
    return cv::FONT_HERSHEY_TRIPLEX;
  if (strcasecmp(s, "scriptsimplex") == 0)
    return cv::FONT_HERSHEY_SCRIPT_SIMPLEX;
  if (strcasecmp(s, "scriptcomplex") == 0)
    return cv::FONT_HERSHEY_SCRIPT_COMPLEX;
  if (strcasecmp(s, "simplex"))  // yes, this is intentional
    std::cout << KRED << "Unknown font '" << s << "', using SIMPLEX " << KNRM
              << std::endl;
  return cv::FONT_HERSHEY_SIMPLEX;
}

int main(int argc, char* argv[]) {
  struct config_t config;

  parse_args(argc, argv, &config);

  if (config.img_src_dir.empty() || config.img_src_ext.empty() ||
      config.dst_keogram.empty())
    usage_and_exit(3);

  glob_t files;
  std::string wildcard = config.img_src_dir + "/*." + config.img_src_ext;
  glob(wildcard.c_str(), 0, NULL, &files);
  if (files.gl_pathc == 0) {
    globfree(&files);
    std::cout << "No images found, exiting." << std::endl;
    return 0;
  }

  cv::Mat accumulated;

  int prevHour = -1;
  int nchan = 0;

  for (size_t f = 0; f < files.gl_pathc; f++) {
    cv::Mat imagesrc = cv::imread(files.gl_pathv[f], cv::IMREAD_UNCHANGED);
    if (!imagesrc.data) {
      std::cout << "Error reading file " << basename(files.gl_pathv[f])
                << std::endl;
      continue;
    }

    if (config.verbose)
      std::cout << "[" << f + 1 << "/" << files.gl_pathc << "] "
                << basename(files.gl_pathv[f]) << std::endl;

    if (config.img_height && config.img_width &&
        (imagesrc.cols != config.img_width ||
         imagesrc.rows != config.img_height)) {
      fprintf(stderr, "%s size %dx%d != %dx%d\n", files.gl_pathv[f],
              imagesrc.cols, imagesrc.cols, config.img_width,
              config.img_height);
      continue;
    }
    if (nchan == 0)
      nchan = imagesrc.channels();

    if (imagesrc.channels() != nchan)
      continue;

    cv::Point2f center((imagesrc.cols - 1) / 2.0, (imagesrc.rows - 1) / 2.0);
    cv::Mat rot = cv::getRotationMatrix2D(center, config.rotation_angle, 1.0);
    cv::Rect2f bbox =
        cv::RotatedRect(cv::Point2f(), imagesrc.size(), config.rotation_angle)
            .boundingRect2f();
    rot.at<double>(0, 2) += bbox.width / 2.0 - imagesrc.cols / 2.0;
    rot.at<double>(1, 2) += bbox.height / 2.0 - imagesrc.rows / 2.0;
    cv::Mat imagedst;
    cv::warpAffine(imagesrc, imagedst, rot, bbox.size());
    if (accumulated.empty()) {
      accumulated.create(imagedst.rows, files.gl_pathc, imagesrc.type());
    }

    // Copy middle column to destination
    imagedst.col(imagedst.cols / 2).copyTo(accumulated.col(f));

    if (config.labels_enabled) {
      struct tm ft;  // the time of the file, by any means necessary
      if (config.parse_filename) {
        // engage your safety squints!
        char* s;
        s = strrchr(files.gl_pathv[f], '-');
        s++;
        sscanf(s, "%04d%02d%02d%02d%02d%02d.%*s", &ft.tm_year, &ft.tm_mon,
               &ft.tm_mday, &ft.tm_hour, &ft.tm_min, &ft.tm_sec);
      } else {
        // sometimes you can believe the file time on disk
        struct stat s;
        stat(files.gl_pathv[f], &s);
        struct tm* t = localtime(&s.st_mtime);
        ft.tm_hour = t->tm_hour;
      }

      if (ft.tm_hour != prevHour) {
        if (prevHour != -1) {
          // Draw a dashed line and label for hour
          cv::LineIterator it(accumulated, cv::Point(f, 0),
                              cv::Point(f, accumulated.rows));
          for (int i = 0; i < it.count; i++, ++it) {
            // 4 pixel dashed line
            if (i & 4) {
              uchar* p = *it;
              for (int c = 0; c < it.elemSize; c++) {
                *p = ~(*p);
                p++;
              }
            }
          }

          // Draw text label to the left of the dash
          char hour[3];
          snprintf(hour, 3, "%02d", ft.tm_hour);
          std::string text(hour);
          int baseline = 0;
          cv::Size textSize =
              cv::getTextSize(text, config.fontFace, config.fontScale,
                              config.lineWidth, &baseline);

          if (f - textSize.width >= 0) {
            cv::putText(accumulated, text,
                        cv::Point(f - textSize.width,
                                  accumulated.rows - textSize.height),
                        config.fontFace, config.fontScale,
                        cv::Scalar(config.b, config.g, config.r),
                        config.lineWidth, config.fontType);
          }
        }
        prevHour = ft.tm_hour;
      }
    }
  }
  globfree(&files);

  std::vector<int> compression_params;
  compression_params.push_back(cv::IMWRITE_PNG_COMPRESSION);
  compression_params.push_back(9);
  compression_params.push_back(cv::IMWRITE_JPEG_QUALITY);
  compression_params.push_back(95);

  cv::imwrite(config.dst_keogram, accumulated, compression_params);
}
<|endoftext|>


<commit_before>#ifndef memory_hh_INCLUDED
#define memory_hh_INCLUDED

#include <cstddef>
#include <new>
#include <utility>

#include "assert.hh"
#include "meta.hh"

namespace Kakoune
{

enum class MemoryDomain
{
    Undefined,
    String,
    SharedString,
    BufferContent,
    BufferMeta,
    Options,
    Highlight,
    Regions,
    Display,
    Mapping,
    Commands,
    Hooks,
    Aliases,
    EnvVars,
    Faces,
    Values,
    Registers,
    Client,
    WordDB,
    Selections,
    History,
    Remote,
    Events,
    Completion,
    Regex,
    Count
};

inline const char* domain_name(MemoryDomain domain)
{
    switch (domain)
    {
        case MemoryDomain::Undefined: return "Undefined";
        case MemoryDomain::String: return "String";
        case MemoryDomain::SharedString: return "SharedString";
        case MemoryDomain::BufferContent: return "BufferContent";
        case MemoryDomain::BufferMeta: return "BufferMeta";
        case MemoryDomain::Options: return "Options";
        case MemoryDomain::Highlight: return "Highlight";
        case MemoryDomain::Regions: return "Regions";
        case MemoryDomain::Display: return "Display";
        case MemoryDomain::Mapping: return "Mapping";
        case MemoryDomain::Commands: return "Commands";
        case MemoryDomain::Hooks: return "Hooks";
        case MemoryDomain::WordDB: return "WordDB";
        case MemoryDomain::Aliases: return "Aliases";
        case MemoryDomain::EnvVars: return "EnvVars";
        case MemoryDomain::Faces: return "Faces";
        case MemoryDomain::Values: return "Values";
        case MemoryDomain::Registers: return "Registers";
        case MemoryDomain::Client: return "Client";
        case MemoryDomain::Selections: return "Selections";
        case MemoryDomain::History: return "History";
        case MemoryDomain::Remote: return "Remote";
        case MemoryDomain::Events: return "Events";
        case MemoryDomain::Completion: return "Completion";
        case MemoryDomain::Regex: return "Regex";
        case MemoryDomain::Count: break;
    }
    kak_assert(false);
    return "";
}

struct MemoryStats
{
    size_t allocated_bytes;
    size_t allocation_count;
    size_t total_allocation_count;
};

extern MemoryStats memory_stats[(size_t)MemoryDomain::Count];

inline void on_alloc(MemoryDomain domain, size_t size)
{
    auto& stats = memory_stats[(int)domain];
    stats.allocated_bytes += size;
    ++stats.allocation_count;
    ++stats.total_allocation_count;
}

inline void on_dealloc(MemoryDomain domain, size_t size)
{
    auto& stats = memory_stats[(int)domain];
    kak_assert(stats.allocated_bytes >= size);
    stats.allocated_bytes -= size;
    --stats.allocation_count;
}

template<typename T, MemoryDomain domain>
struct Allocator
{
    using value_type = T;

    Allocator() = default;
    template<typename U>
    Allocator(const Allocator<U, domain>&) {}

    template<typename U>
    struct rebind { using other = Allocator<U, domain>; };

    T* allocate(size_t n)
    {
        size_t size = sizeof(T) * n;
        on_alloc(domain, size);
        return reinterpret_cast<T*>(::operator new(size));
    }

    void deallocate(T* ptr, size_t n)
    {
        size_t size = sizeof(T) * n;
        on_dealloc(domain, size);
        ::operator delete(ptr);
    }
};

template<typename T1, MemoryDomain d1, typename T2, MemoryDomain d2>
constexpr bool operator==(const Allocator<T1, d1>&, const Allocator<T2, d2>&)
{
    return d1 == d2;
}

template<typename T1, MemoryDomain d1, typename T2, MemoryDomain d2>
constexpr bool operator!=(const Allocator<T1, d1>&, const Allocator<T2, d2>&)
{
    return d1 != d2;
}

constexpr MemoryDomain memory_domain(Meta::AnyType) { return MemoryDomain::Undefined; }

template<typename T>
constexpr decltype(T::Domain) memory_domain(Meta::Type<T>) { return T::Domain; }

template<MemoryDomain d>
struct UseMemoryDomain
{
    static constexpr MemoryDomain Domain = d;
    static void* operator new(size_t size)
    {
        on_alloc(Domain, size);
        return ::operator new(size);
    }

    static void* operator new[](size_t size)
    {
        on_alloc(Domain, size);
        return ::operator new[](size);
    }

    static void* operator new(size_t size, void* ptr)
    {
        return ::operator new(size, ptr);
    }

    static void operator delete(void* ptr, size_t size)
    {
        on_dealloc(Domain, size);
        ::operator delete(ptr);
    }

    static void operator delete[](void* ptr, size_t size)
    {
        on_dealloc(Domain, size);
        ::operator delete[](ptr);
    }
};

}

#endif // memory_hh_INCLUDED
<commit_msg>always inline custom operator new/delete to avoid spurious warnings<commit_after>#ifndef memory_hh_INCLUDED
#define memory_hh_INCLUDED

#include <cstddef>
#include <new>
#include <utility>

#include "assert.hh"
#include "meta.hh"

namespace Kakoune
{

enum class MemoryDomain
{
    Undefined,
    String,
    SharedString,
    BufferContent,
    BufferMeta,
    Options,
    Highlight,
    Regions,
    Display,
    Mapping,
    Commands,
    Hooks,
    Aliases,
    EnvVars,
    Faces,
    Values,
    Registers,
    Client,
    WordDB,
    Selections,
    History,
    Remote,
    Events,
    Completion,
    Regex,
    Count
};

inline const char* domain_name(MemoryDomain domain)
{
    switch (domain)
    {
        case MemoryDomain::Undefined: return "Undefined";
        case MemoryDomain::String: return "String";
        case MemoryDomain::SharedString: return "SharedString";
        case MemoryDomain::BufferContent: return "BufferContent";
        case MemoryDomain::BufferMeta: return "BufferMeta";
        case MemoryDomain::Options: return "Options";
        case MemoryDomain::Highlight: return "Highlight";
        case MemoryDomain::Regions: return "Regions";
        case MemoryDomain::Display: return "Display";
        case MemoryDomain::Mapping: return "Mapping";
        case MemoryDomain::Commands: return "Commands";
        case MemoryDomain::Hooks: return "Hooks";
        case MemoryDomain::WordDB: return "WordDB";
        case MemoryDomain::Aliases: return "Aliases";
        case MemoryDomain::EnvVars: return "EnvVars";
        case MemoryDomain::Faces: return "Faces";
        case MemoryDomain::Values: return "Values";
        case MemoryDomain::Registers: return "Registers";
        case MemoryDomain::Client: return "Client";
        case MemoryDomain::Selections: return "Selections";
        case MemoryDomain::History: return "History";
        case MemoryDomain::Remote: return "Remote";
        case MemoryDomain::Events: return "Events";
        case MemoryDomain::Completion: return "Completion";
        case MemoryDomain::Regex: return "Regex";
        case MemoryDomain::Count: break;
    }
    kak_assert(false);
    return "";
}

struct MemoryStats
{
    size_t allocated_bytes;
    size_t allocation_count;
    size_t total_allocation_count;
};

extern MemoryStats memory_stats[(size_t)MemoryDomain::Count];

inline void on_alloc(MemoryDomain domain, size_t size)
{
    auto& stats = memory_stats[(int)domain];
    stats.allocated_bytes += size;
    ++stats.allocation_count;
    ++stats.total_allocation_count;
}

inline void on_dealloc(MemoryDomain domain, size_t size)
{
    auto& stats = memory_stats[(int)domain];
    kak_assert(stats.allocated_bytes >= size);
    stats.allocated_bytes -= size;
    --stats.allocation_count;
}

template<typename T, MemoryDomain domain>
struct Allocator
{
    using value_type = T;

    Allocator() = default;
    template<typename U>
    Allocator(const Allocator<U, domain>&) {}

    template<typename U>
    struct rebind { using other = Allocator<U, domain>; };

    T* allocate(size_t n)
    {
        size_t size = sizeof(T) * n;
        on_alloc(domain, size);
        return reinterpret_cast<T*>(::operator new(size));
    }

    void deallocate(T* ptr, size_t n)
    {
        size_t size = sizeof(T) * n;
        on_dealloc(domain, size);
        ::operator delete(ptr);
    }
};

template<typename T1, MemoryDomain d1, typename T2, MemoryDomain d2>
constexpr bool operator==(const Allocator<T1, d1>&, const Allocator<T2, d2>&)
{
    return d1 == d2;
}

template<typename T1, MemoryDomain d1, typename T2, MemoryDomain d2>
constexpr bool operator!=(const Allocator<T1, d1>&, const Allocator<T2, d2>&)
{
    return d1 != d2;
}

constexpr MemoryDomain memory_domain(Meta::AnyType) { return MemoryDomain::Undefined; }

template<typename T>
constexpr decltype(T::Domain) memory_domain(Meta::Type<T>) { return T::Domain; }

template<MemoryDomain d>
struct UseMemoryDomain
{
    static constexpr MemoryDomain Domain = d;

    [[gnu::always_inline]]
    static void* operator new(size_t size)
    {
        on_alloc(Domain, size);
        return ::operator new(size);
    }

    [[gnu::always_inline]]
    static void* operator new[](size_t size)
    {
        on_alloc(Domain, size);
        return ::operator new[](size);
    }

    [[gnu::always_inline]]
    static void* operator new(size_t size, void* ptr)
    {
        return ::operator new(size, ptr);
    }

    [[gnu::always_inline]]
    static void operator delete(void* ptr, size_t size)
    {
        on_dealloc(Domain, size);
        ::operator delete(ptr);
    }

    [[gnu::always_inline]]
    static void operator delete[](void* ptr, size_t size)
    {
        on_dealloc(Domain, size);
        ::operator delete[](ptr);
    }
};

}

#endif // memory_hh_INCLUDED
<|endoftext|>


<commit_before>// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

//#define THIRD_RBM_1       //One layer of RBM
//#define THIRD_RBM_2       //Two layers of RBM
//#define THIRD_RBM_3       //Three layers of RBM

//#define THIRD_CRBM_PMP_1    //One layer of CRBM with Probabilistic Max Pooling (C1)
#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3    //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)

//#define THIRD_CRBM_MP_1  //One layers of CRBM with Max Pooling after each layer (C1)
//#define THIRD_CRBM_MP_2  //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3  //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)

constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width  = 20;

constexpr const std::size_t epochs       = 50;
constexpr const std::size_t train_stride = 2;
constexpr const std::size_t test_stride  = 2;

constexpr const std::size_t NF1          = 9;
constexpr const std::size_t K1           = 8;
constexpr const std::size_t C1           = 2;
constexpr const std::size_t B1           = 32;
constexpr const dll::unit_type HT1       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;

constexpr const std::size_t NF2          = 3;
constexpr const std::size_t K2           = 8;
constexpr const std::size_t C2           = 2;
constexpr const std::size_t B2           = 32;
constexpr const dll::unit_type HT2       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;

constexpr const std::size_t NF3          = 3;
constexpr const std::size_t K3           = 48;
constexpr const std::size_t C3           = 2;
constexpr const std::size_t B3           = 25;
constexpr const dll::unit_type HT3       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;

const auto rate_0 = [](weight& value) { value = 0.1 * value; };
const auto rate_1 = [](weight& value) { value = 0.1 * value; };
const auto rate_2 = [](weight& value) { value = 1.0 * value; };

const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };

const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };

const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };

const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };

const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };

const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 1.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };

} // end of namespace third

#endif
<commit_msg>Larger batch size<commit_after>// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#ifndef WORD_SPOTTER_CONFIG_THIRD_HPP
#define WORD_SPOTTER_CONFIG_THIRD_HPP

namespace third {

//#define THIRD_RBM_1       //One layer of RBM
//#define THIRD_RBM_2       //Two layers of RBM
//#define THIRD_RBM_3       //Three layers of RBM

//#define THIRD_CRBM_PMP_1    //One layer of CRBM with Probabilistic Max Pooling (C1)
#define THIRD_CRBM_PMP_2 //Two layers of CRBM with Probabilistic Max Pooling (C1/C2)
//#define THIRD_CRBM_PMP_3    //Three layers of CRBM with Probabilistic Max Pooling (C1/C2/C3)

//#define THIRD_CRBM_MP_1  //One layers of CRBM with Max Pooling after each layer (C1)
//#define THIRD_CRBM_MP_2  //Two layers of CRBM with Max Pooling after each layer (C1/C2)
//#define THIRD_CRBM_MP_3  //Three layers of CRBM with Max Pooling after each layer (C1/C2/C3)

constexpr const std::size_t patch_height = 40; //Should not be changed
constexpr const std::size_t patch_width  = 20;

constexpr const std::size_t epochs       = 50;
constexpr const std::size_t train_stride = 2;
constexpr const std::size_t test_stride  = 2;

constexpr const std::size_t NF1          = 9;
constexpr const std::size_t K1           = 8;
constexpr const std::size_t C1           = 2;
constexpr const std::size_t B1           = 64;
constexpr const dll::unit_type HT1       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT1      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM1 = dll::sparsity_method::LEE;

constexpr const std::size_t NF2          = 3;
constexpr const std::size_t K2           = 8;
constexpr const std::size_t C2           = 2;
constexpr const std::size_t B2           = 64;
constexpr const dll::unit_type HT2       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT2      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM2 = dll::sparsity_method::LEE;

constexpr const std::size_t NF3          = 3;
constexpr const std::size_t K3           = 48;
constexpr const std::size_t C3           = 2;
constexpr const std::size_t B3           = 64;
constexpr const dll::unit_type HT3       = dll::unit_type::BINARY;
constexpr const dll::decay_type DT3      = dll::decay_type::L2;
constexpr const dll::sparsity_method SM3 = dll::sparsity_method::NONE;

const auto rate_0 = [](weight& value) { value = 0.1 * value; };
const auto rate_1 = [](weight& value) { value = 0.1 * value; };
const auto rate_2 = [](weight& value) { value = 1.0 * value; };

const auto momentum_0 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_1 = [](weight& ini, weight& fin) { ini = 0.9; fin = 0.9; };
const auto momentum_2 = [](weight& ini, weight& fin) { ini = 1.0 * ini; fin = 1.0 * fin; };

const auto wd_l1_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l1_2 = [](weight& value) { value = 1.0 * value; };

const auto wd_l2_0 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_1 = [](weight& value) { value = 1.0 * value; };
const auto wd_l2_2 = [](weight& value) { value = 1.0 * value; };

const auto pbias_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_2 = [](weight& value) { value = 1.0 * value; };

const auto pbias_lambda_0 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_1 = [](weight& value) { value = 1.0 * value; };
const auto pbias_lambda_2 = [](weight& value) { value = 1.0 * value; };

const auto sparsity_target_0 = [](weight& value) { value = 10.0 * value; };
const auto sparsity_target_1 = [](weight& value) { value = 1.0 * value; };
const auto sparsity_target_2 = [](weight& value) { value = 1.0 * value; };

} // end of namespace third

#endif
<|endoftext|>


<commit_before>// Copyright 2013, Rolf Meyer
// See LICENCE for more information

#include <node.h>
#include <v8.h>
#include <node_buffer.h>
#include <vector>
#include <iostream>
#include <cstring>

#include "reader.h"

using namespace v8;
using namespace node;

/**
 * plugin global secure card context
 **/
#ifndef USE_LIBNFC
static pcsc_context *context;
#else
static nfc_context *context;
#endif
static std::vector<reader_data *> readers_data;

/**
 * Get Names of the Readers connected to the computer
 * @param hContext The SCard Context used to search
 * @return An Array of Strings with reader names
 **/
Handle<Value> getReader(const Arguments& args) {
#ifndef USE_LIBNFC
  LONG res;
  char *reader_names;
#else
  size_t numDevices;
  const size_t MAX_READERS = 16;
  nfc_connstring reader_names[MAX_READERS];
#endif
  char *reader_iter = NULL;
  int   reader_count = 0;

  HandleScope scope;
  Persistent<Object> readers;

  if(args.Length() > 0){
    ThrowException(Exception::TypeError(String::New("This function does not take any arguments")));
    return scope.Close(Undefined());
  }

  // Allocate buffer. We assume autoallocate is not present (on Mac OS X anyway)
  readers = Persistent<Object>::New(Object::New());
#ifndef USE_LIBNFC
  res = pcsc_list_devices(context, &reader_names);
  if(res != SCARD_S_SUCCESS || reader_names[0] == '\0') {
    //delete [] reader_names;
    ThrowException(Exception::Error(String::New("Unable to list readers")));
    return scope.Close(Undefined());
  }
#else
  numDevices = nfc_list_devices(context, reader_names, MAX_READERS);
  if(numDevices == 0) {
    return scope.Close(readers);
  }
    // open any device
#endif

  // Clean before use
  for(std::vector<reader_data *>::iterator iter;iter!=readers_data.end();iter++) {
    reader_data *data = *iter;
#ifndef USE_LIBNFC
    delete [] data->state.szReader;
#endif
    delete data;
  }
  readers_data.clear();

  // Get number of readers from null separated string
#ifndef USE_LIBNFC
  reader_iter = reader_names;
  while(*reader_iter != '\0') {
    readers_data.push_back(new reader_data(reader_iter, context));
#else
  reader_iter = reader_names[0];
  char *names_end = reader_names[0] + (MAX_READERS * sizeof(nfc_connstring));
  while(reader_iter <= names_end) {
    // see if we can claim it
    nfc_device *dev = NULL;
    dev = nfc_open(context, reader_iter);
    if (dev == NULL) {
      // XXX: failed to open connstring
      reader_iter += sizeof(nfc_connstring);
      continue;
    }
    std::cout << "Found device: " << nfc_device_get_name(dev) << std::endl;
    nfc_close(dev);
    readers_data.push_back(new reader_data(reader_iter, dev));
#endif
    // Node Object:
    Local<External> data = Local<External>::New(External::New(readers_data.back()));
    Local<Object> reader = Local<Object>::New(Object::New());
    reader->Set(String::NewSymbol("name"), String::New(reader_iter));
    reader->Set(String::NewSymbol("listen"), FunctionTemplate::New(ReaderListen)->GetFunction());
    reader->Set(String::NewSymbol("setLed"), FunctionTemplate::New(ReaderSetLed)->GetFunction());
    reader->Set(String::NewSymbol("release"), FunctionTemplate::New(ReaderRelease)->GetFunction());
    reader->SetHiddenValue(String::NewSymbol("data"), data);
    readers->Set(String::NewSymbol(reader_iter), reader);
#ifndef USE_LIBNFC
    reader_iter += strlen(reader_iter)+1;
    reader_count++;
#else
    reader_iter += sizeof(nfc_connstring);
#endif
  }
  //delete [] reader_names;

  return scope.Close(readers);
}

/**
 * Node.js initialization function
 * @param exports The Commonjs module exports object
 **/
void init(Handle<Object> exports) {
#ifndef USE_LIBNFC
  pcsc_init(&context);
#else
  nfc_init(&context);
#endif
  if(!context) {
    ThrowException(Exception::Error(String::New("Cannot establish context")));
    return;
  }

  exports->Set(String::NewSymbol("getReader"),
      FunctionTemplate::New(getReader)->GetFunction());
	// AtExit(&PCSC::close);
}

NODE_MODULE(node_mifare, init)
<commit_msg>do not call open in our code<commit_after>// Copyright 2013, Rolf Meyer
// See LICENCE for more information

#include <node.h>
#include <v8.h>
#include <node_buffer.h>
#include <vector>
#include <iostream>
#include <cstring>

#include "reader.h"

using namespace v8;
using namespace node;

/**
 * plugin global secure card context
 **/
#ifndef USE_LIBNFC
static pcsc_context *context;
#else
static nfc_context *context;
#endif
static std::vector<reader_data *> readers_data;

/**
 * Get Names of the Readers connected to the computer
 * @param hContext The SCard Context used to search
 * @return An Array of Strings with reader names
 **/
Handle<Value> getReader(const Arguments& args) {
#ifndef USE_LIBNFC
  LONG res;
  char *reader_names;
#else
  size_t numDevices;
  const size_t MAX_READERS = 16;
  nfc_connstring reader_names[MAX_READERS];
#endif
  char *reader_iter = NULL;
  int   reader_count = 0;

  HandleScope scope;
  Persistent<Object> readers;

  if(args.Length() > 0){
    ThrowException(Exception::TypeError(String::New("This function does not take any arguments")));
    return scope.Close(Undefined());
  }

  // Allocate buffer. We assume autoallocate is not present (on Mac OS X anyway)
  readers = Persistent<Object>::New(Object::New());
#ifndef USE_LIBNFC
  res = pcsc_list_devices(context, &reader_names);
  if(res != SCARD_S_SUCCESS || reader_names[0] == '\0') {
    //delete [] reader_names;
    ThrowException(Exception::Error(String::New("Unable to list readers")));
    return scope.Close(Undefined());
  }
#else
  numDevices = nfc_list_devices(context, reader_names, MAX_READERS);
  if(numDevices == 0) {
    return scope.Close(readers);
  }
    // open any device
#endif

  // Clean before use
  for(std::vector<reader_data *>::iterator iter;iter!=readers_data.end();iter++) {
    reader_data *data = *iter;
#ifndef USE_LIBNFC
    delete [] data->state.szReader;
#endif
    delete data;
  }
  readers_data.clear();

  // Get number of readers from null separated string
#ifndef USE_LIBNFC
  reader_iter = reader_names;
  while(*reader_iter != '\0') {
    readers_data.push_back(new reader_data(reader_iter, context));
#else
  reader_iter = reader_names[0];
  char *names_end = reader_names[0] + (MAX_READERS * sizeof(nfc_connstring));
  while(reader_iter <= names_end) {
    // see if we can claim it
    nfc_device *dev = NULL;
/*
    dev = nfc_open(context, reader_iter);
    if (dev == NULL) {
      // XXX: failed to open connstring
      reader_iter += sizeof(nfc_connstring);
      continue;
    }
    std::cout << "Found device: " << nfc_device_get_name(dev) << std::endl;
    nfc_close(dev);
*/
    readers_data.push_back(new reader_data(reader_iter, dev));
#endif
    // Node Object:
    Local<External> data = Local<External>::New(External::New(readers_data.back()));
    Local<Object> reader = Local<Object>::New(Object::New());
    reader->Set(String::NewSymbol("name"), String::New(reader_iter));
    reader->Set(String::NewSymbol("listen"), FunctionTemplate::New(ReaderListen)->GetFunction());
    reader->Set(String::NewSymbol("setLed"), FunctionTemplate::New(ReaderSetLed)->GetFunction());
    reader->Set(String::NewSymbol("release"), FunctionTemplate::New(ReaderRelease)->GetFunction());
    reader->SetHiddenValue(String::NewSymbol("data"), data);
    readers->Set(String::NewSymbol(reader_iter), reader);
#ifndef USE_LIBNFC
    reader_iter += strlen(reader_iter)+1;
    reader_count++;
#else
    reader_iter += sizeof(nfc_connstring);
#endif
  }
  //delete [] reader_names;

  return scope.Close(readers);
}

/**
 * Node.js initialization function
 * @param exports The Commonjs module exports object
 **/
void init(Handle<Object> exports) {
#ifndef USE_LIBNFC
  pcsc_init(&context);
#else
  nfc_init(&context);
#endif
  if(!context) {
    ThrowException(Exception::Error(String::New("Cannot establish context")));
    return;
  }

  exports->Set(String::NewSymbol("getReader"),
      FunctionTemplate::New(getReader)->GetFunction());
	// AtExit(&PCSC::close);
}

NODE_MODULE(node_mifare, init)
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_TIMER_EVENT_HXX
#define BENG_PROXY_TIMER_EVENT_HXX

#include "Event.hxx"
#include "util/BindMethod.hxx"

/**
 * Invoke an event callback after a certain amount of time.
 */
class TimerEvent {
    Event event;

    BoundMethod<void()> callback;

public:
    TimerEvent(EventLoop &loop, BoundMethod<void()> _callback)
        :event(loop, -1, 0, Callback, this), callback(_callback) {}

    bool IsPending() const {
        return event.IsTimerPending();
    }

    void Add(const struct timeval &tv) {
        event.Add(tv);
    }

    void Cancel() {
        event.Delete();
    }

private:
    static void Callback(gcc_unused evutil_socket_t fd,
                         gcc_unused short events,
                         void *ctx) {
        auto &event = *(TimerEvent *)ctx;
        event.callback();
    }
};

#endif
<commit_msg>event/TimerEvent: make callback const<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_TIMER_EVENT_HXX
#define BENG_PROXY_TIMER_EVENT_HXX

#include "Event.hxx"
#include "util/BindMethod.hxx"

/**
 * Invoke an event callback after a certain amount of time.
 */
class TimerEvent {
    Event event;

    const BoundMethod<void()> callback;

public:
    TimerEvent(EventLoop &loop, BoundMethod<void()> _callback)
        :event(loop, -1, 0, Callback, this), callback(_callback) {}

    bool IsPending() const {
        return event.IsTimerPending();
    }

    void Add(const struct timeval &tv) {
        event.Add(tv);
    }

    void Cancel() {
        event.Delete();
    }

private:
    static void Callback(gcc_unused evutil_socket_t fd,
                         gcc_unused short events,
                         void *ctx) {
        auto &event = *(TimerEvent *)ctx;
        event.callback();
    }
};

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/util/util.hpp>

#include <nix/file/DataArrayFS.hpp>
#include <nix/hdf5/DataSetHDF5.hpp> // FIXME
#include <nix/file/DimensionFS.hpp>

using namespace std;
using namespace nix::base;
using namespace boost::filesystem;

namespace nix {
namespace file {

DataArrayFS::DataArrayFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const string &loc)
    : EntityWithSourcesFS(file, block, loc),
      dimensions(loc + path::preferred_separator + "dimensions", file->fileMode()) {
}

DataArrayFS::DataArrayFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,
                         const string &id, const string &type, const string &name)
    : DataArrayFS(file, block, loc, id, type, name, util::getTime()) {
}

DataArrayFS::DataArrayFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,
                             const string &id, const string &type, const string &name, time_t time)
    : EntityWithSourcesFS(file, block, loc, id, type, name, time),
      dimensions(loc + path::preferred_separator  + name + path::preferred_separator + "dimensions", file->fileMode()) {
}

//--------------------------------------------------
// Element getters and setters
//--------------------------------------------------

boost::optional<std::string> DataArrayFS::label() const {
    boost::optional<std::string> ret;
    string value;
    if (hasAttr("label")) {
        getAttr("label", value);
        ret = value;
    }
    return ret;
}

void DataArrayFS::label(const string &label) {
    if (label.empty()) {
        throw EmptyString("label");
    }
    else {
        setAttr("label", label);
        forceUpdatedAt();
    }
}

void DataArrayFS::label(const none_t t) {
    if (hasAttr("label")) {
        removeAttr("label");
    }
    forceUpdatedAt();
}

boost::optional<std::string> DataArrayFS::unit() const {
    boost::optional<std::string> ret;
    string value;
    if (hasAttr("unit")) {
        getAttr("unit", value);
        ret = value;
    }
    return ret;
}

void DataArrayFS::unit(const string &unit) {
    if (unit.empty()) { // TODO maybe switch to unsetting
        throw EmptyString("unit");
    }
    else {
        setAttr("unit", unit);
        forceUpdatedAt();
    }
}

void DataArrayFS::unit(const none_t t) {
    if (hasAttr("unit")) {
        removeAttr("unit");
    }
    forceUpdatedAt();
}

// TODO use defaults
boost::optional<double> DataArrayFS::expansionOrigin() const {
    boost::optional<double> ret;
    double expansion_origin;
    if (hasAttr("expansion_origin")) {
        getAttr("expansion_origin", expansion_origin);
        ret = expansion_origin;
    }
    return ret;
}

void DataArrayFS::expansionOrigin(double expansion_origin) {
    setAttr("expansion_origin", expansion_origin);
    forceUpdatedAt();
}

void DataArrayFS::expansionOrigin(const none_t t) {
    if (hasAttr("expansion_origin")) {
        removeAttr("expansion_origin");
    }
    forceUpdatedAt();
}

// TODO use defaults
vector<double> DataArrayFS::polynomCoefficients() const {
    vector<double> polynom_coefficients;
    if (hasAttr("polynom_coefficients")) {
        getAttr("polynom_coefficients", polynom_coefficients);
    }
    return polynom_coefficients;
}

void DataArrayFS::polynomCoefficients(const vector<double> &coefficients) {
    setAttr("polynom_coefficients", coefficients);
    forceUpdatedAt();
}

void DataArrayFS::polynomCoefficients(const none_t t) {
    if (hasAttr("polynom_coefficients")) {
        removeAttr("polynom_coefficients");
    }
    forceUpdatedAt();
}

//--------------------------------------------------
// Methods concerning dimensions
//--------------------------------------------------

size_t DataArrayFS::dimensionCount() const {
    return dimensions.subdirCount();
}

shared_ptr<IDimension> DataArrayFS::getDimension(size_t index) const {
    shared_ptr<IDimension> dim;
    path p = dimensions.sub_dir_by_index(index);
    if (!p.empty()) {
        dim = openDimensionFS(p.string(), index, fileMode());
    }
    return dim;
}

std::shared_ptr<base::ISetDimension> DataArrayFS::createSetDimension(size_t index) {
    SetDimensionFS dim(dimensions.location(), index, fileMode());
    return make_shared<SetDimensionFS>(dim);
}

std::shared_ptr<base::IRangeDimension> DataArrayFS::createRangeDimension(size_t index, const std::vector<double> &ticks) {
    RangeDimensionFS dim(dimensions.location(), index, ticks, fileMode());
    return make_shared<RangeDimensionFS>(dim);
}

std::shared_ptr<base::IRangeDimension> DataArrayFS::createAliasRangeDimension() {
    RangeDimensionFS dim(dimensions.location(), 1, *this, fileMode());
    return make_shared<RangeDimensionFS>(dim);
}

std::shared_ptr<base::ISampledDimension> DataArrayFS::createSampledDimension(size_t index, double sampling_interval) {
    SampledDimensionFS dim(dimensions.location(), index, sampling_interval, fileMode());
    return make_shared<SampledDimensionFS>(dim);
}

/*
Group DataArrayFS::createDimensionGroup(size_t index) {
    boost::optional<Group> g = dimension_group(true);

    size_t dim_max = dimensionCount() + 1;
    if (index > dim_max || index <= 0)
        throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max));

    string str_id = util::numToStr(index);
    if (g->hasGroup(str_id)) {
        g->removeGroup(str_id);
    }

    return g->openGroup(str_id, true);
}
*/

bool DataArrayFS::deleteDimension(size_t index) {
    bool deleted = false;
    size_t dim_count = dimensionCount();
    string str_id = util::numToStr(index);
    if (dimensions.hasObject(str_id)) {
            deleted = dimensions.removeObjectByNameOrAttribute("entity_id", str_id);
        }
        if (deleted && index < dim_count) {
            for (size_t old_id = index + 1; old_id <= dim_count; old_id++) {
                string str_old_id = util::numToStr(old_id);
                string str_new_id = util::numToStr(old_id - 1);
                dimensions.renameSubdir(str_old_id, str_new_id);
            }
        }
    return deleted;
}

//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------

DataArrayFS::~DataArrayFS() {
}

void DataArrayFS::createData(DataType dtype, const NDSize &size) {
    /*
    if (group().hasData("data")) {
        throw new std::runtime_error("DataArray alread exists"); //TODO: FIXME, better exception
    }

    group().createData("data", dtype, size); //FIXME: check if this 2-step creation is needed
    DataSet ds = group().openData("data");
    */ //FIXME
}

bool DataArrayFS::hasData() const {
    return hasObject("data");
}

void DataArrayFS::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) {
    /*
    DataSet ds;

    if (!group().hasData("data")) {
        //FIXME: this case should actually never be possible, replace with exception?
        ds = group().createData("data", dtype, count);
    } else {
        ds = group().openData("data");
    }

    if (offset.size()) {
        Selection fileSel = ds.createSelection();
        fileSel.select(count, offset);
        Selection memSel(DataSpace::create(count, false));

        ds.write(dtype, data, fileSel, memSel);
    } else {
        ds.write(dtype, count, data);
    }
    */ // FIXME
}

void DataArrayFS::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const {
    if (!hasObject("data")) {
        return;
    }
    /*
    DataSet ds = group().openData("data");

    if (offset.size()) {
        Selection fileSel = ds.createSelection();
        // if count.size() == 0, i.e. we want to read a scalar,
        // we have to supply something that fileSel can make sense of
        fileSel.select(count ? count : NDSize(offset.size(), 1), offset);
        Selection memSel(DataSpace::create(count, false));

        ds.read(dtype, data, fileSel, memSel);
    } else {
        ds.read(dtype, count, data);
    }
    */
}

NDSize DataArrayFS::dataExtent(void) const {
    if (!hasObject("data")) {
        return NDSize{};
    }
    // FIXME
    return NDSize{};
}

void DataArrayFS::dataExtent(const NDSize &extent) {
    if (!hasObject("data")) {
        throw runtime_error("Data field not found in DataArray!");
    }
    // FIXME
    // DataSet ds = group().openData("data");
    // ds.setExtent(extent);
}

DataType DataArrayFS::dataType(void) const {
    if (!hasObject("data")) {
        return DataType::Nothing;
    }
    // FIXME
    return DataType::Nothing;
}

} // ns nix::file
} // ns nix<commit_msg>[file_backend/DataArray] change dimByIndex to use the name or index attrib<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.

#include <nix/util/util.hpp>

#include <nix/file/DataArrayFS.hpp>
#include <nix/hdf5/DataSetHDF5.hpp> // FIXME
#include <nix/file/DimensionFS.hpp>

using namespace std;
using namespace nix::base;
using namespace boost::filesystem;

namespace nix {
namespace file {

DataArrayFS::DataArrayFS(const std::shared_ptr<base::IFile> &file, const std::shared_ptr<base::IBlock> &block, const string &loc)
    : EntityWithSourcesFS(file, block, loc),
      dimensions(loc + path::preferred_separator + "dimensions", file->fileMode()) {
}

DataArrayFS::DataArrayFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,
                         const string &id, const string &type, const string &name)
    : DataArrayFS(file, block, loc, id, type, name, util::getTime()) {
}

DataArrayFS::DataArrayFS(const shared_ptr<IFile> &file, const shared_ptr<IBlock> &block, const string &loc,
                             const string &id, const string &type, const string &name, time_t time)
    : EntityWithSourcesFS(file, block, loc, id, type, name, time),
      dimensions(loc + path::preferred_separator  + name + path::preferred_separator + "dimensions", file->fileMode()) {
}

//--------------------------------------------------
// Element getters and setters
//--------------------------------------------------

boost::optional<std::string> DataArrayFS::label() const {
    boost::optional<std::string> ret;
    string value;
    if (hasAttr("label")) {
        getAttr("label", value);
        ret = value;
    }
    return ret;
}

void DataArrayFS::label(const string &label) {
    if (label.empty()) {
        throw EmptyString("label");
    }
    else {
        setAttr("label", label);
        forceUpdatedAt();
    }
}

void DataArrayFS::label(const none_t t) {
    if (hasAttr("label")) {
        removeAttr("label");
    }
    forceUpdatedAt();
}

boost::optional<std::string> DataArrayFS::unit() const {
    boost::optional<std::string> ret;
    string value;
    if (hasAttr("unit")) {
        getAttr("unit", value);
        ret = value;
    }
    return ret;
}

void DataArrayFS::unit(const string &unit) {
    if (unit.empty()) { // TODO maybe switch to unsetting
        throw EmptyString("unit");
    }
    else {
        setAttr("unit", unit);
        forceUpdatedAt();
    }
}

void DataArrayFS::unit(const none_t t) {
    if (hasAttr("unit")) {
        removeAttr("unit");
    }
    forceUpdatedAt();
}

// TODO use defaults
boost::optional<double> DataArrayFS::expansionOrigin() const {
    boost::optional<double> ret;
    double expansion_origin;
    if (hasAttr("expansion_origin")) {
        getAttr("expansion_origin", expansion_origin);
        ret = expansion_origin;
    }
    return ret;
}

void DataArrayFS::expansionOrigin(double expansion_origin) {
    setAttr("expansion_origin", expansion_origin);
    forceUpdatedAt();
}

void DataArrayFS::expansionOrigin(const none_t t) {
    if (hasAttr("expansion_origin")) {
        removeAttr("expansion_origin");
    }
    forceUpdatedAt();
}

// TODO use defaults
vector<double> DataArrayFS::polynomCoefficients() const {
    vector<double> polynom_coefficients;
    if (hasAttr("polynom_coefficients")) {
        getAttr("polynom_coefficients", polynom_coefficients);
    }
    return polynom_coefficients;
}

void DataArrayFS::polynomCoefficients(const vector<double> &coefficients) {
    setAttr("polynom_coefficients", coefficients);
    forceUpdatedAt();
}

void DataArrayFS::polynomCoefficients(const none_t t) {
    if (hasAttr("polynom_coefficients")) {
        removeAttr("polynom_coefficients");
    }
    forceUpdatedAt();
}

//--------------------------------------------------
// Methods concerning dimensions
//--------------------------------------------------

size_t DataArrayFS::dimensionCount() const {
    return dimensions.subdirCount();
}

shared_ptr<IDimension> DataArrayFS::getDimension(size_t index) const {
    shared_ptr<IDimension> dim;
    boost::optional<path> p = dimensions.findByNameOrAttribute("index", util::numToStr(index));
    if (p) {
        dim = openDimensionFS(p->string(), index, fileMode());
    }
    return dim;
}

std::shared_ptr<base::ISetDimension> DataArrayFS::createSetDimension(size_t index) {
    SetDimensionFS dim(dimensions.location(), index, fileMode());
    return make_shared<SetDimensionFS>(dim);
}

std::shared_ptr<base::IRangeDimension> DataArrayFS::createRangeDimension(size_t index, const std::vector<double> &ticks) {
    RangeDimensionFS dim(dimensions.location(), index, ticks, fileMode());
    return make_shared<RangeDimensionFS>(dim);
}

std::shared_ptr<base::IRangeDimension> DataArrayFS::createAliasRangeDimension() {
    RangeDimensionFS dim(dimensions.location(), 1, *this, fileMode());
    return make_shared<RangeDimensionFS>(dim);
}

std::shared_ptr<base::ISampledDimension> DataArrayFS::createSampledDimension(size_t index, double sampling_interval) {
    SampledDimensionFS dim(dimensions.location(), index, sampling_interval, fileMode());
    return make_shared<SampledDimensionFS>(dim);
}

/*
Group DataArrayFS::createDimensionGroup(size_t index) {
    boost::optional<Group> g = dimension_group(true);

    size_t dim_max = dimensionCount() + 1;
    if (index > dim_max || index <= 0)
        throw new runtime_error("Invalid dimension index: has to be 0 < index <= " + util::numToStr(dim_max));

    string str_id = util::numToStr(index);
    if (g->hasGroup(str_id)) {
        g->removeGroup(str_id);
    }

    return g->openGroup(str_id, true);
}
*/

bool DataArrayFS::deleteDimension(size_t index) {
    bool deleted = false;
    size_t dim_count = dimensionCount();
    string str_id = util::numToStr(index);
    if (dimensions.hasObject(str_id)) {
            deleted = dimensions.removeObjectByNameOrAttribute("entity_id", str_id);
        }
        if (deleted && index < dim_count) {
            for (size_t old_id = index + 1; old_id <= dim_count; old_id++) {
                string str_old_id = util::numToStr(old_id);
                string str_new_id = util::numToStr(old_id - 1);
                dimensions.renameSubdir(str_old_id, str_new_id);
            }
        }
    return deleted;
}

//--------------------------------------------------
// Other methods and functions
//--------------------------------------------------

DataArrayFS::~DataArrayFS() {
}

void DataArrayFS::createData(DataType dtype, const NDSize &size) {
    /*
    if (group().hasData("data")) {
        throw new std::runtime_error("DataArray alread exists"); //TODO: FIXME, better exception
    }

    group().createData("data", dtype, size); //FIXME: check if this 2-step creation is needed
    DataSet ds = group().openData("data");
    */ //FIXME
}

bool DataArrayFS::hasData() const {
    return hasObject("data");
}

void DataArrayFS::write(DataType dtype, const void *data, const NDSize &count, const NDSize &offset) {
    /*
    DataSet ds;

    if (!group().hasData("data")) {
        //FIXME: this case should actually never be possible, replace with exception?
        ds = group().createData("data", dtype, count);
    } else {
        ds = group().openData("data");
    }

    if (offset.size()) {
        Selection fileSel = ds.createSelection();
        fileSel.select(count, offset);
        Selection memSel(DataSpace::create(count, false));

        ds.write(dtype, data, fileSel, memSel);
    } else {
        ds.write(dtype, count, data);
    }
    */ // FIXME
}

void DataArrayFS::read(DataType dtype, void *data, const NDSize &count, const NDSize &offset) const {
    if (!hasObject("data")) {
        return;
    }
    /*
    DataSet ds = group().openData("data");

    if (offset.size()) {
        Selection fileSel = ds.createSelection();
        // if count.size() == 0, i.e. we want to read a scalar,
        // we have to supply something that fileSel can make sense of
        fileSel.select(count ? count : NDSize(offset.size(), 1), offset);
        Selection memSel(DataSpace::create(count, false));

        ds.read(dtype, data, fileSel, memSel);
    } else {
        ds.read(dtype, count, data);
    }
    */
}

NDSize DataArrayFS::dataExtent(void) const {
    if (!hasObject("data")) {
        return NDSize{};
    }
    // FIXME
    return NDSize{};
}

void DataArrayFS::dataExtent(const NDSize &extent) {
    if (!hasObject("data")) {
        throw runtime_error("Data field not found in DataArray!");
    }
    // FIXME
    // DataSet ds = group().openData("data");
    // ds.setExtent(extent);
}

DataType DataArrayFS::dataType(void) const {
    if (!hasObject("data")) {
        return DataType::Nothing;
    }
    // FIXME
    return DataType::Nothing;
}

} // ns nix::file
} // ns nix<|endoftext|>


<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2016 INRIA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
/*! \file

  Basic class to handle with dynamical system integrators over a time step.
*/

#ifndef ONESTEPINTEGRATOR_H
#define ONESTEPINTEGRATOR_H

#include "SiconosConst.hpp"
#include "SimulationTypeDef.hpp"
#include "DynamicalSystemsSet.hpp"
#include "OneStepIntegratorTypes.hpp"
#include "SimulationGraphs.hpp"

// work around gccxml bug that does not accept an argument ot the deprecated attribute
#ifndef __GCCXML__

#ifdef __GNUC__
#define DEPRECATED_OSI_API(func) func __attribute__ ((deprecated ("This constructor of function is deprecrated and will be removed in the next major Siconos release! Use the insertDynamicalSystem method in NonSmoothDynamicalSystem !")))
#elif defined(_MSC_VER)
#define DEPRECATED_OSI_API(func) __declspec(deprecated("This constructor will be removed in the next major Siconos release and does not work with MSVC 2013 ! Use the insertDynamicalSystem method in NonSmoothDynamicalSystem !")) func
#else
#define DEPRECATED_OSI_API(func) func
#endif

#else
#define DEPRECATED_OSI_API(func) func
#endif

/**  Generic class to manage DynamicalSystem(s) time-integration
 *
 *  \author SICONOS Development Team - copyright INRIA
 *  \version 3.0.0.
 *  \date (Creation) Apr 26, 2004
 *
 * !!! This is a virtual class, interface for some specific integrators !!!
 *
 * At the time, available integrators are:
 *

 *
 EulerMoreauOSI

 *
 MoreauJeanOSI

 *
 MoreauJeanCombinedProjectionOSI

 *
 MoreauJeanDirectProjectionOSI

 *
 D1MinusLinearOSI

 *
 D1MinusLinearOSIHalfExplicitAccelerationLevelOSI

 *
 D1MinusLinearOSIHalfExplicitVelocityLevelOSI

 *
 SchatzmanPaoliOSI

 *
 LsodarOSI

 *
 Hem5OSI

 *
 NewMarkAlphaOSI

 *
 ZeroOrderHoldOSI

 *

 *
 */
class OneStepIntegrator :public std11::enable_shared_from_this<OneStepIntegrator>
{

public :
  /** List of indices used to save tmp work matrices and vectors (last one is the size of the present list) */
  enum OSI_DSWorkVectorId {local_buffer, residu_free, free, free_tdg,
                           qtmp, acce_memory, acce_like, work_vector_of_vector_size};

  enum OSI_DSWorkMatrixId {dense_output_coefficients, work_vector_of_matrix_size};

protected:
/** serialization hooks
 */
  ACCEPT_SERIALIZATION(OneStepIntegrator);

/** type/name of the Integrator */
  OSI::TYPES _integratorType;

/** a graph of dynamical systems to integrate
 * For the moment, we point to the graph of dynamical systems in
 * in the topology. We use the properties "osi" to check if the dynamical
 * system is integrated by this osi. It has to be improved by using a subgraph
 * to avoid the use of checkOSI
 */
  SP::DynamicalSystemsGraph _dynamicalSystemsGraph;

  /** size of the memory for the integrator */
  unsigned int _sizeMem;

  /** steps of the integrator
   */
  unsigned int _steps;

  /** _levelMinForOutput is the minimum level for the output
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMinForOutput;

  /** _levelMaxForOutput is the maximunm level for the output
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMaxForOutput;

  /** _levelMinForInput is the minimum level for the input
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMinForInput;

  /** _levelMaxForInput is the maximum level for the input
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMaxForInput;

/** A link to the simulation that owns this OSI */
  SP::Simulation _simulation;

/** basic constructor with Id
 *  \param type integrator type/name
 */
  OneStepIntegrator(const OSI::TYPES& type);

/** default constructor
 */
  OneStepIntegrator() {};

  /** struct to add terms in the integration. Useful for Control */
  SP::ExtraAdditionalTerms _extraAdditionalTerms;

private:

/** copy constructor, private, no copy nor pass-by value allowed */
  OneStepIntegrator(const OneStepIntegrator&);

/** assignment (private => forbidden)
 * \param  OSI
 * \return OneStepIntegrator&
 */
  OneStepIntegrator& operator=(const OneStepIntegrator& OSI);

public:

/** destructor
 */
  virtual ~OneStepIntegrator() {};

// --- GETTERS/SETTERS ---

  /** get the type of the OneStepIntegrator
   *  \return std::string : the type of the OneStepIntegrator
   */
  inline OSI::TYPES getType() const
  {
    return _integratorType;
  }

  /** set the type of the OneStepIntegrator
   *  \param newType std::string : the type of the OneStepIntegrator
   */
  inline void setType(const OSI::TYPES& newType)
  {
    _integratorType = newType;
  };

  /** Check if the dynamical system bundle in the node of the
   * _dynamicalSystemGraph is interagted or not by this osi.
   * \param dsi the iterator on the node of the graph
   */
  inline bool checkOSI(DynamicalSystemsGraph::VIterator dsi)
  {
    return  (_dynamicalSystemsGraph->properties(*dsi).osi.get()) == this;
  };

  /** Check if the dynamical system bundle in the node of the
   * _dynamicalSystemGraph is interagted or not by this osi.
   * \param dsgv the descriptor on the node of the graph
   */
  inline bool checkOSI(DynamicalSystemsGraph::VDescriptor dsgv)
  {
    return  (_dynamicalSystemsGraph->properties(dsgv).osi.get()) == this;
  };

  /** get the set of DynamicalSystem associated with the Integrator
   *  \return a SP::DynamicalSystemsGraph
   */
  inline SP::DynamicalSystemsGraph dynamicalSystemsGraph() const
  {
    return _dynamicalSystemsGraph;
  };

  /** get _sizeMem value
   *  \return an unsigned int
   */
  inline unsigned int getSizeMem() const
  {
    return _sizeMem;
  };

  /** set _sizeMem
   *  \param newValue an unsigned int
   */
  inline void setSizeMem(unsigned int newValue)
  {
    _sizeMem = newValue;
  };

  /** get the Simulation that owns the OneStepIntegrator
   *  \return a pointer to Simulation
   */
  inline SP::Simulation simulation() const
  {
    return _simulation;
  }

  /** set the Simulation of the OneStepIntegrator
   *  \param newS a pointer to Simulation
   */
  inline void setSimulationPtr(SP::Simulation newS)
  {
    _simulation = newS;
  }

  // --- OTHERS ... ---

  /** initialise the integrator
   * \param m a Model
   */
  virtual void initialize(Model& m ) = 0;

  /** initialization of the work vectors and matrices (properties) related to
   *  one dynamical system on the graph and needed by the osi
   * \param m the Model
   * \param t time of initialization
   * \param ds the dynamical system
   */
  virtual void initializeDynamicalSystem(Model& m, double t, SP::DynamicalSystem ds) =0 ;

  /** initialization of the work vectors and matrices (properties) related to
   *  one interaction on the graph and needed by the osi
   * \param t0 time of initialization
   * \param inter the interaction
   * \param interProp the properties on the graph
   * \param DSG the dynamical systems graph
   */
  virtual void initializeInteraction(double t0, Interaction &inter,
			     InteractionProperties& interProp,
			     DynamicalSystemsGraph & DSG) =0 ;

  /** get the number of index sets required for the simulation
   * \return unsigned int
   */
  virtual unsigned int numberOfIndexSets() const=0;

  virtual unsigned int levelMinForOutput()
  {
    return _levelMinForOutput;
  }
  virtual unsigned int levelMaxForOutput()
  {
    return _levelMaxForOutput;
  }
  virtual unsigned int levelMinForInput()
  {
    return _levelMinForInput;
  }
  virtual unsigned int levelMaxForInput()
  {
    return _levelMaxForInput;
  }

  /** compute the initial state of the Newton loop.
   */
  virtual void computeInitialNewtonState();

  /** return the maximum of all norms for the discretized residus of DS
   *  \return a double
   */
  virtual double computeResidu();

  /** integrates the Dynamical System linked to this integrator, without taking constraints
   * into account.
   */
  virtual void computeFreeState();

  /** integrates the Interaction linked to this integrator, without taking non-smooth effects into account
   * \param vertex_inter of the interaction graph
   * \param osnsp pointer to OneStepNSProblem
   */
  virtual void computeFreeOutput(InteractionsGraph::VDescriptor& vertex_inter, OneStepNSProblem* osnsp);

  /** integrate the system, between tinit and tend (->iout=true), with possible stop at tout (->iout=false)
   *  \param tinit initial time
   *  \param tend end time
   *  \param tout real end time
   *  \param idid flag used in EventDriven schemes
   */
  virtual void integrate(double& tinit, double& tend, double& tout, int& idid) = 0;

  /** set to zero all the r vectors of the DynamicalSystems of the present OSI
   */
  void resetNonSmoothPart();

  /** set to zero all the r vectors of the DynamicalSystems of the present OSI for a given level
   * \param level
   */
  void resetNonSmoothPart(unsigned int level);

  /** update the state of the DynamicalSystem attached to this Integrator
   *  \param level level of interest for the dynamics
   * level is set to 0 by default since in all time-stepping schemes we update all the state
   * whatever the value of level
   */
  virtual void updateState(const unsigned int level = 0) = 0;

  /** update the output of the Interaction attached to this Integrator
   */
  void updateOutput(double time);

  /** update the input of the Interaction attached to this Integrator
   */
  void updateInput(double time);

  /** update the output of the Interaction attached to this Integrator
   *  \param level level of interest for the dynamics
   */
  void updateOutput(double time, unsigned int level);

  /** update the input of the Interaction attached to this Integrator
   *  \param level level of interest for the dynamics
   */
  void updateInput(double time, unsigned int level);

  /** print the data to the screen
   */
  virtual void display() = 0;

  /**
   */
  virtual void prepareNewtonIteration(double time) = 0;

  /** Apply the rule to one Interaction to known if is it should be included
   * in the IndexSet of level i
   * \param inter
   * \param i
   * \return bool
   */
  virtual bool addInteractionInIndexSet(SP::Interaction inter, unsigned int i)
  {
    RuntimeException::selfThrow("OneStepIntegrator::addInteractionInIndexSet - Should be called at this level");
    return 0;
  }
  ;

  /** Apply the rule to one Interaction to know if is it should be removed
   * from the IndexSet of level i
   * \param inter
   * \param i
   * \return bool
   */
  virtual bool removeInteractionInIndexSet(SP::Interaction inter, unsigned int i)
  {
    RuntimeException::selfThrow("OneStepIntegrator::removeInteractionInIndexSet - Should not be called at this level");
    return 0;
  };

  /** get the ExtraAdditionalTerms.
   * \return the ExtraAdditionalTerms
   */
  inline SP::ExtraAdditionalTerms extraAdditionalTerms()
  {
    return _extraAdditionalTerms;
  }

  /** set the ExtraAdditionalTerms to add smooth terms for the integration process.
   * Useful when a control loop is added to a DynamicalSystem.
   * \param eat the ExtraAdditionalTerms to use
   */
  inline void setExtraAdditionalTerms(SP::ExtraAdditionalTerms eat)
  {
    _extraAdditionalTerms = eat;
  }

  /** visitors hook
   */
  VIRTUAL_ACCEPT_VISITORS(OneStepIntegrator);

};

#endif // ONESTEPINTEGRATOR_H
<commit_msg>[kernel] Fix swig abstracting OSI classes<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2016 INRIA.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/
/*! \file

  Basic class to handle with dynamical system integrators over a time step.
*/

#ifndef ONESTEPINTEGRATOR_H
#define ONESTEPINTEGRATOR_H

#include "SiconosConst.hpp"
#include "SimulationTypeDef.hpp"
#include "DynamicalSystemsSet.hpp"
#include "OneStepIntegratorTypes.hpp"
#include "SimulationGraphs.hpp"

// work around gccxml bug that does not accept an argument ot the deprecated attribute
#ifndef __GCCXML__

#ifdef __GNUC__
#define DEPRECATED_OSI_API(func) func __attribute__ ((deprecated ("This constructor of function is deprecrated and will be removed in the next major Siconos release! Use the insertDynamicalSystem method in NonSmoothDynamicalSystem !")))
#elif defined(_MSC_VER)
#define DEPRECATED_OSI_API(func) __declspec(deprecated("This constructor will be removed in the next major Siconos release and does not work with MSVC 2013 ! Use the insertDynamicalSystem method in NonSmoothDynamicalSystem !")) func
#else
#define DEPRECATED_OSI_API(func) func
#endif

#else
#define DEPRECATED_OSI_API(func) func
#endif

/**  Generic class to manage DynamicalSystem(s) time-integration
 *
 *  \author SICONOS Development Team - copyright INRIA
 *  \version 3.0.0.
 *  \date (Creation) Apr 26, 2004
 *
 * !!! This is a virtual class, interface for some specific integrators !!!
 *
 * At the time, available integrators are:
 *

 *
 EulerMoreauOSI

 *
 MoreauJeanOSI

 *
 MoreauJeanCombinedProjectionOSI

 *
 MoreauJeanDirectProjectionOSI

 *
 D1MinusLinearOSI

 *
 D1MinusLinearOSIHalfExplicitAccelerationLevelOSI

 *
 D1MinusLinearOSIHalfExplicitVelocityLevelOSI

 *
 SchatzmanPaoliOSI

 *
 LsodarOSI

 *
 Hem5OSI

 *
 NewMarkAlphaOSI

 *
 ZeroOrderHoldOSI

 *

 *
 */
class OneStepIntegrator :public std11::enable_shared_from_this<OneStepIntegrator>
{

public :
  /** List of indices used to save tmp work matrices and vectors (last one is the size of the present list) */
  enum OSI_DSWorkVectorId {local_buffer, residu_free, free, free_tdg,
                           qtmp, acce_memory, acce_like, work_vector_of_vector_size};

  enum OSI_DSWorkMatrixId {dense_output_coefficients, work_vector_of_matrix_size};

protected:
/** serialization hooks
 */
  ACCEPT_SERIALIZATION(OneStepIntegrator);

/** type/name of the Integrator */
  OSI::TYPES _integratorType;

/** a graph of dynamical systems to integrate
 * For the moment, we point to the graph of dynamical systems in
 * in the topology. We use the properties "osi" to check if the dynamical
 * system is integrated by this osi. It has to be improved by using a subgraph
 * to avoid the use of checkOSI
 */
  SP::DynamicalSystemsGraph _dynamicalSystemsGraph;

  /** size of the memory for the integrator */
  unsigned int _sizeMem;

  /** steps of the integrator
   */
  unsigned int _steps;

  /** _levelMinForOutput is the minimum level for the output
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMinForOutput;

  /** _levelMaxForOutput is the maximunm level for the output
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMaxForOutput;

  /** _levelMinForInput is the minimum level for the input
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMinForInput;

  /** _levelMaxForInput is the maximum level for the input
   * needed by the OneStepIntegrator
   */
  unsigned int _levelMaxForInput;

/** A link to the simulation that owns this OSI */
  SP::Simulation _simulation;

/** basic constructor with Id
 *  \param type integrator type/name
 */
  OneStepIntegrator(const OSI::TYPES& type);

/** default constructor
 */
  OneStepIntegrator() {};

  /** struct to add terms in the integration. Useful for Control */
  SP::ExtraAdditionalTerms _extraAdditionalTerms;

private:

/** copy constructor, private, no copy nor pass-by value allowed */
  OneStepIntegrator(const OneStepIntegrator&);

/** assignment (private => forbidden)
 * \param  OSI
 * \return OneStepIntegrator&
 */
  OneStepIntegrator& operator=(const OneStepIntegrator& OSI);

public:

/** destructor
 */
  virtual ~OneStepIntegrator() {};

// --- GETTERS/SETTERS ---

  /** get the type of the OneStepIntegrator
   *  \return std::string : the type of the OneStepIntegrator
   */
  inline OSI::TYPES getType() const
  {
    return _integratorType;
  }

  /** set the type of the OneStepIntegrator
   *  \param newType std::string : the type of the OneStepIntegrator
   */
  inline void setType(const OSI::TYPES& newType)
  {
    _integratorType = newType;
  };

  /** Check if the dynamical system bundle in the node of the
   * _dynamicalSystemGraph is interagted or not by this osi.
   * \param dsi the iterator on the node of the graph
   */
  inline bool checkOSI(DynamicalSystemsGraph::VIterator dsi)
  {
    return  (_dynamicalSystemsGraph->properties(*dsi).osi.get()) == this;
  };

  /** Check if the dynamical system bundle in the node of the
   * _dynamicalSystemGraph is interagted or not by this osi.
   * \param dsgv the descriptor on the node of the graph
   */
  inline bool checkOSI(DynamicalSystemsGraph::VDescriptor dsgv)
  {
    return  (_dynamicalSystemsGraph->properties(dsgv).osi.get()) == this;
  };

  /** get the set of DynamicalSystem associated with the Integrator
   *  \return a SP::DynamicalSystemsGraph
   */
  inline SP::DynamicalSystemsGraph dynamicalSystemsGraph() const
  {
    return _dynamicalSystemsGraph;
  };

  /** get _sizeMem value
   *  \return an unsigned int
   */
  inline unsigned int getSizeMem() const
  {
    return _sizeMem;
  };

  /** set _sizeMem
   *  \param newValue an unsigned int
   */
  inline void setSizeMem(unsigned int newValue)
  {
    _sizeMem = newValue;
  };

  /** get the Simulation that owns the OneStepIntegrator
   *  \return a pointer to Simulation
   */
  inline SP::Simulation simulation() const
  {
    return _simulation;
  }

  /** set the Simulation of the OneStepIntegrator
   *  \param newS a pointer to Simulation
   */
  inline void setSimulationPtr(SP::Simulation newS)
  {
    _simulation = newS;
  }

  // --- OTHERS ... ---

  /** initialise the integrator
   * \param m a Model
   */
  virtual void initialize(Model& m ) = 0;

  /** initialization of the work vectors and matrices (properties) related to
   *  one dynamical system on the graph and needed by the osi
   * \param m the Model
   * \param t time of initialization
   * \param ds the dynamical system
   */
  virtual void initializeDynamicalSystem(Model& m, double t, SP::DynamicalSystem ds) =0 ;

  /** initialization of the work vectors and matrices (properties) related to
   *  one interaction on the graph and needed by the osi
   * \param t0 time of initialization
   * \param inter the interaction
   * \param interProp the properties on the graph
   * \param DSG the dynamical systems graph
   */
  virtual void initializeInteraction(double t0, Interaction &inter,
			     InteractionProperties& interProp,
			     DynamicalSystemsGraph & DSG) =0 ;

  /** get the number of index sets required for the simulation
   * \return unsigned int
   */
  virtual unsigned int numberOfIndexSets() const=0;

  virtual unsigned int levelMinForOutput()
  {
    return _levelMinForOutput;
  }
  virtual unsigned int levelMaxForOutput()
  {
    return _levelMaxForOutput;
  }
  virtual unsigned int levelMinForInput()
  {
    return _levelMinForInput;
  }
  virtual unsigned int levelMaxForInput()
  {
    return _levelMaxForInput;
  }

  /** compute the initial state of the Newton loop.
   */
  virtual void computeInitialNewtonState();

  /** return the maximum of all norms for the discretized residus of DS
   *  \return a double
   */
  virtual double computeResidu();

  /** integrates the Dynamical System linked to this integrator, without taking constraints
   * into account.
   */
  virtual void computeFreeState();

  /** integrates the Interaction linked to this integrator, without taking non-smooth effects into account
   * \param vertex_inter of the interaction graph
   * \param osnsp pointer to OneStepNSProblem
   */
  virtual void computeFreeOutput(InteractionsGraph::VDescriptor& vertex_inter, OneStepNSProblem* osnsp);

  /** integrate the system, between tinit and tend (->iout=true), with possible stop at tout (->iout=false)
   *  \param tinit initial time
   *  \param tend end time
   *  \param tout real end time
   *  \param idid flag used in EventDriven schemes
   */
  virtual void integrate(double& tinit, double& tend, double& tout, int& idid) = 0;

  /** set to zero all the r vectors of the DynamicalSystems of the present OSI
   */
  void resetNonSmoothPart();

  /** set to zero all the r vectors of the DynamicalSystems of the present OSI for a given level
   * \param level
   */
  void resetNonSmoothPart(unsigned int level);

  /** update the state of the DynamicalSystem attached to this Integrator
   *  \param level level of interest for the dynamics
   * level is set to 0 by default since in all time-stepping schemes we update all the state
   * whatever the value of level
   */
  virtual void updateState(const unsigned int level) = 0;

  /** update the state of the DynamicalSystem attached to this Integrator
   * level is set to 0 by default since in all time-stepping schemes we update all the state
   * whatever the value of level
   */
  void updateState() { updateState(0); }

  /** update the output of the Interaction attached to this Integrator
   */
  void updateOutput(double time);

  /** update the input of the Interaction attached to this Integrator
   */
  void updateInput(double time);

  /** update the output of the Interaction attached to this Integrator
   *  \param level level of interest for the dynamics
   */
  void updateOutput(double time, unsigned int level);

  /** update the input of the Interaction attached to this Integrator
   *  \param level level of interest for the dynamics
   */
  void updateInput(double time, unsigned int level);

  /** print the data to the screen
   */
  virtual void display() = 0;

  /**
   */
  virtual void prepareNewtonIteration(double time) = 0;

  /** Apply the rule to one Interaction to known if is it should be included
   * in the IndexSet of level i
   * \param inter
   * \param i
   * \return bool
   */
  virtual bool addInteractionInIndexSet(SP::Interaction inter, unsigned int i)
  {
    RuntimeException::selfThrow("OneStepIntegrator::addInteractionInIndexSet - Should be called at this level");
    return 0;
  }
  ;

  /** Apply the rule to one Interaction to know if is it should be removed
   * from the IndexSet of level i
   * \param inter
   * \param i
   * \return bool
   */
  virtual bool removeInteractionInIndexSet(SP::Interaction inter, unsigned int i)
  {
    RuntimeException::selfThrow("OneStepIntegrator::removeInteractionInIndexSet - Should not be called at this level");
    return 0;
  };

  /** get the ExtraAdditionalTerms.
   * \return the ExtraAdditionalTerms
   */
  inline SP::ExtraAdditionalTerms extraAdditionalTerms()
  {
    return _extraAdditionalTerms;
  }

  /** set the ExtraAdditionalTerms to add smooth terms for the integration process.
   * Useful when a control loop is added to a DynamicalSystem.
   * \param eat the ExtraAdditionalTerms to use
   */
  inline void setExtraAdditionalTerms(SP::ExtraAdditionalTerms eat)
  {
    _extraAdditionalTerms = eat;
  }

  /** visitors hook
   */
  VIRTUAL_ACCEPT_VISITORS(OneStepIntegrator);

};

#endif // ONESTEPINTEGRATOR_H
<|endoftext|>