Beispiel #1
0
void binary::do_append(arguments &arg) {
  vector_type &out = v_data;
  for (arguments::iterator it = arg.begin(); it != arg.end(); ++it) {
    value el = *it;
    if (el.is_int()) {
      int x = el.get_int();
      if (x < 0 || x > 255)
        throw exception("Outside byte range", "Range error");
      out.push_back(element_type(x));
    } else if (el.is_object()) {
      object o = el.get_object();
      if (o.is_array()) {
        array a(o);
        std::size_t n = a.length();
        out.reserve(out.size() + n);
        for (std::size_t i = 0; i < n; ++i) {
          value v = a.get_element(i);
          if (!v.is_int())
            throw exception("Must be Array of Numbers");
          int x = v.get_int();
          if (x < 0 || x > 255)
            throw exception("Outside byte range", "RangeError");
          out.push_back(element_type(x));
        }
      } else {
        binary &x = flusspferd::get_native<binary>(o);
        out.insert(out.end(), x.v_data.begin(), x.v_data.end());
      }
    }
  }
}
Beispiel #2
0
		BrdfSlice(const arguments& args,
              int width, int height, int slice,
              double* content)
        : data(brdf_slice_parameters(args),
               width * height * slice),
          _width(width), _height(height), _slice(slice),
          _data(content)
		{
			// Allocate data
      if (args.is_defined("param") && parametrization().dimX() == 3)
          _phi = (M_PI / 180.0) * args.get_float("phi", 90);
      else
          _phi = 0.5*M_PI;

			// Is the position of the slice componnent (third coordinate)
			// reversed? This ensure that some params can be displayed.
      auto in_param = parametrization().input_parametrization();
			_reverse = in_param == params::ISOTROPIC_TL_TV_PROJ_DPHI ||
          in_param == params::SCHLICK_TL_TK_PROJ_DPHI   ||
          in_param == params::RETRO_TL_TVL_PROJ_DPHI;

			// Update the domain
			_max = max();
			_min = min();
		}
Beispiel #3
0
void rational_fitter_parsec_multi::set_parameters(const arguments& args)
{
    _max_np = args.get_float("np", 10);
    _max_nq = args.get_float("nq", _max_np);
    _min_np = args.get_float("min-np", _max_np);
    _min_nq = args.get_float("min-nq", _min_np);
 
    _max_np = std::max<int>(_max_np, _min_np);
    _max_nq = std::max<int>(_max_nq, _min_nq);
    
    _boundary = args.get_float("boundary-constraint", 1.0f);
    _nbcores = args.get_int( "nbcores", 2 );
    _args = &args;

    {
	int argc = 1;
	char **argv = (char**)malloc((argc+1)*sizeof(char*));

	argv[0] = strdup( "./manao" );
	argv[1] = NULL;

	_dague = dague_init(_nbcores, &argc, &argv);

	free(argv[0]);
	free(argv);
    }
}
Beispiel #4
0
        bool call(const arguments & args_, std::string & result) {
            //LOG(INFO) << "Calling [" << args_.as_string(0) << "]";

            if (_modules.find(args_.as_string(0)) == _modules.end()) {
                return false;
            }

            result = "";
            result.resize(4096);

            std::string function_str;
            std::vector<std::string> temp = ace::split(args_.get(), ',');

            if (temp.size() < 3) {
                function_str = temp[1];
            } else {
                for (int x = 1; x < temp.size(); x++)
                    function_str = function_str + temp[x] + ",";
            }
            _modules[args_.as_string(0)].function((char *)result.c_str(), 4096, (const char *)function_str.c_str());
#ifdef _DEBUG
            //if (args_.as_string(0) != "fetch_result" && args_.as_string(0) != "ready") {
            //    LOG(INFO) << "Called [" << args_.as_string(0) << "], with {" << function_str << "} result={" << result << "}";
            //}
#endif
            return true;
        }
void FileSystem::createFile(arguments str, outputStream out)
{
    checkArgumentsCount(str, 2);
    std::ofstream::pos_type  size = std::stoll(str.at(1));     // 1234asd321 -> 1234, its ok?
    if(_fsFile->create(str.at(0), size)) {
        out << "File created";
    } else {
        out << "file not created";
    }
    out << "\n";
}
Beispiel #6
0
        bool load(const arguments & args_, std::string & result) {
            HMODULE dllHandle;
            RVExtension function;

            LOG(INFO) << "Load requested [" << args_.as_string(0) << "]";

            if (_modules.find(args_.as_string(0)) != _modules.end()) {
                LOG(ERROR) << "Module already loaded [" << args_.as_string(0) << "]";
                return true;
            }

#ifdef _WINDOWS
            // Make a copy of the file to temp, and load it from there, referencing the current path name
            char tmpPath[MAX_PATH +1], buffer[MAX_PATH + 1];

            if(!GetTempPathA(MAX_PATH, tmpPath)) {
                LOG(ERROR) << "GetTempPath() failed, e=" << GetLastError();
                return false;
            }
            if(!GetTempFileNameA(tmpPath, "ace_dynload", TRUE, buffer)) {
                LOG(ERROR) << "GetTempFileName() failed, e=" << GetLastError();
                return false;
            }
            std::string temp_filename = buffer;
            if (!CopyFileA(args_.as_string(0).c_str(), temp_filename.c_str(), FALSE)) {
                DeleteFile(temp_filename.c_str());
                if (!CopyFileA(args_.as_string(0).c_str(), temp_filename.c_str(), FALSE)) {
                    LOG(ERROR) << "CopyFile() , e=" << GetLastError();
                    return false;
                }
            }
#else
            std::string temp_filename = args_.as_string(0);
#endif

            dllHandle = LoadLibrary(temp_filename.c_str());
            if (!dllHandle) {
                LOG(ERROR) << "LoadLibrary() failed, e=" << GetLastError() << " [" << args_.as_string(0) << "]";
                return false;
            }

            function = (RVExtension)GetProcAddress(dllHandle, "_RVExtension@12");
            if (!function) {
                LOG(ERROR) << "GetProcAddress() failed, e=" << GetLastError() << " [" << args_.as_string(0) << "]";
                FreeLibrary(dllHandle);
                return false;
            }

            LOG(INFO) << "Load completed [" << args_.as_string(0) << "]";

            _modules[args_.as_string(0)] = module(args_.as_string(0), dllHandle, function, temp_filename);

            return false;
        }
void FileSystem::cd(arguments arg)
{
    checkArgumentsCount(arg, 1);
    _currentFolder = getLastPathElementHandle(arg.at(0))
            .descriptorHandle();
//    auto v = p.getParsedPath();
}
void debug_script( const arguments &args )
{
    const path script( absolute( path( args[ 2 ] ), cwd() ) );

    Config config( get_config() );

    const string exe( get_executable( config, script, debug ).string() );

    const string debug_script( debug_script_path( config, script ).string() );

    ofstream stream( debug_script.c_str() );

    stream << "file " << exe << endl
                 << "r ";
    for ( size_t i = 3; i < args.size(); ++i )
    {
        stream << args[ i ] << ' ';
    }
    stream << endl << "q" << endl;

    stream.close();

    // for some reason, lldb won't start in execv
    exit( system( ( config.debugCommand() + " -s " + debug_script ).c_str() ) );
//	execv( config.debugCommand().c_str(), argv + 1 );
}
void FileSystem::filestat(arguments arg, outputStream out)
{
    checkArgumentsCount(arg, 1);
    uint64_t descriptorId = std::stoll(arg.at(0));

    FSDescriptor descriptor;
    try {
        descriptor = _descriptors.getDescriptor(descriptorId);
    } catch(const std::invalid_argument &) {
        out << "Bad descriptor\n";
        return;
    }

    if(descriptor.type == DescriptorVariant::None) {
        out << "Descriptor does not exist\n";
        return;
    }

    using std::to_string;

    out << "File statistic: \n\tid: " << descriptorId;
    if(descriptor.type == DescriptorVariant::File) {
        out << descriptor.fileSize;
    }
    out << "\n\tType: "     << to_string(descriptor.type) <<
           "\n\tReferences: " << descriptor.referencesCount <<
           "\n\tHas extended blocks: " << (descriptor.nextDataSegment == Constants::HEADER_ADDRESS() ? "false" : "true") << "\n";
}
Beispiel #10
0
// Allow for a different parametrization depending on the arguments provided.
static const alta::parameters
brdf_slice_parameters(const arguments& args)
{
    auto result = alta::parameters(2, 3,
                                   params::STARK_2D, params::RGB_COLOR);

    if(args.is_defined("param")) {
				params::input param = params::parse_input(args["param"]);

				// The param is a 2D param
				if(params::dimension(param) == 2) {
            std::cout << "<<INFO>> Specified param \"" << args["param"] << "\"" << std::endl;
            result = alta::parameters(result.dimX(), result.dimY(),
                                      param, result.output_parametrization());

            // The oaram is a 3D param
				} else if(params::dimension(param) == 3) {
            std::cout << "<<INFO>> Specified param \"" << args["param"] << "\"" << std::endl;
            result = alta::parameters(3, result.dimY(),
                                      param, result.output_parametrization());

				} else {
            std::cout << "<<ERROR>> Invalid specified param \"" << args["param"] << "\"" << std::endl;
            std::cout << "<<ERROR>> Must have 2D input dimension" << std::endl;
				}
    }

    return result;
}
Beispiel #11
0
        bool call(const std::string & name_, arguments & args_, std::string & result_, bool threaded) {
            if (_methods.find(name_) == _methods.end()) {
                // @TODO: Exceptions
                return false;
            }
            if (threaded) {
                std::lock_guard<std::mutex> lock(_messages_lock);
                _messages.push(dispatch_message(name_, args_, _message_id));
                
                // @TODO: We should provide an interface for this serialization.
                std::stringstream ss;
                ss << "[\"result_id\", " << _message_id << "]";
                result_ = ss.str();

                _message_id = _message_id + 1;
            } else {
#ifdef _DEBUG
                if (name_ != "fetch_result") {
                    LOG(TRACE) << "dispatch[immediate]:\t[" << name_ << "] { " << args_.get() << " }";
                }
#endif
                return dispatcher::call(name_, args_, result_);
            }

            return true;
        }
Beispiel #12
0
void FileSystem::create(arguments arg)
{
    checkArgumentsCount(arg, 1);
    FSDescriptor fileDescriptor;
    fileDescriptor.initFile();
    allocAndAppendDescriptorToCurrentFolder(fileDescriptor, arg.at(0));
}
Beispiel #13
0
void FileSystem::mkdir(arguments arg)
{
    checkArgumentsCount(arg, 1);
    FSDescriptor fileDescriptor;
    fileDescriptor.initDirectory(currentDirectory());
    string name = arg.at(0);
    allocAndAppendDescriptorToCurrentFolder(fileDescriptor, name);
}
Beispiel #14
0
void fostlib::standard_arguments(
    const loaded_settings &settings,
    ostream &out,
    arguments &args
) {
    args.commandSwitch( L"b", settings.name, L"Banner" );
    if ( settings.c_banner.value() )
        out << settings.banner << std::endl;

    args.commandSwitch( L"s", settings.name, L"Settings" );
    if ( settings.c_settings.value() )
        setting< json >::printAllOn( out );

    args.commandSwitch( L"e", settings.name, L"Environment" );
    if ( settings.c_environment.value() )
        args.printOn( out );
}
Beispiel #15
0
void FileSystem::mount(arguments str)
{
    checkArgumentsCount(str, 1);
    _fsFile->open(str.at(0));
    if(_fsFile->isFormatedFS()) {
        fileFormatChanged();
    } else {
    }
}
Beispiel #16
0
void FileSystem::rmdir(arguments arg, outputStream out)
{
    checkArgumentsCount(arg, 1);
    string name = arg.at(0);
    if(removeDescriptorFromDirectory(currentDirectory(), DescriptorVariant::Directory, name)) {
        out << "Directory deleted\n";
    } else {
        out << "Directory not found\n";
    }
}
Beispiel #17
0
void FileSystem::unlink(arguments arg, outputStream out)
{
    checkArgumentsCount(arg, 1);
    string name = arg.at(0);
    descriptorIndex_tp dir = currentDirectory();
    if(removeDescriptorFromDirectory(dir, DescriptorVariant::File | DescriptorVariant::SymLink, name)) {
        out << "Descriptor deleted\n";
    } else {
        out << "Descriptor not found\n";
    }
}
Beispiel #18
0
void FileSystem::close(arguments arg)
{
    checkArgumentsCount(arg, 1);
    uint64_t openedDescriptor = std::stoull(arg.at(1));

    auto findResult = _opennedFiles.find(openedDescriptor);
    if(findResult  == _opennedFiles.end()) {
        throw file_system_exception("Descriptor currently not open.");
    } else {
        _opennedFiles.erase(findResult);
    }
}
Beispiel #19
0
void FileSystem::link(arguments arg)
{
    checkArgumentsCount(arg, 2);
    string srcName  = arg.at(0);
    string destName = arg.at(1);

    descriptorIndex_tp destDir = currentDirectory();

    descriptorIndex_tp srcDir = currentDirectory();
    auto it = getDirectoryDescriptorIterator(srcDir);
    while(it.hasNext()) {
        ++it;
        if(it->name(header().filenameLength) == srcName) {
            addDescriptorToDirectory(destDir, it->descriptor, destName);
        }
    }
}
Beispiel #20
0
        bool unload(const arguments & args_, std::string & result) {

            LOG(INFO) << "Unload requested [" << args_.as_string(0) << "]";

            if (_modules.find(args_.as_string(0)) == _modules.end()) {
                LOG(INFO) << "Unload failed, module not loaded [" << args_.as_string(0) << "]";
                return true;
            }

            if (!FreeLibrary(_modules[args_.as_string(0)].handle)) {
                LOG(INFO) << "FreeLibrary() failed during unload, e=" << GetLastError();
                return false;
            }
            //if (!DeleteFileA(_modules[args_.as_string(0)].temp_filename.c_str())) {
            //    LOG(INFO) << "DeleteFile() failed during unload, e=" << GetLastError();
            //    return false;
            //}

            _modules.erase(args_.as_string(0));

            LOG(INFO) << "Unload complete [" << args_.as_string(0) << "]";

            return true;
        }
Beispiel #21
0
    bool controller::export_ptr_list(const arguments &args_, std::string &) const {
        std::ofstream pointers("sqf_pointers_declaration.hpp");
        std::ofstream pointers_def("sqf_pointers_definitions.hpp");

        std::ofstream assignments("sqf_assignments.hpp");
        pointers << "//Exported Pointer Definitions For: " << args_.as_string(0) << "\n\n";
        assignments << "//Exported Pointer Assignments For: " << args_.as_string(0) << "\n\n";

        pointers << "\n// Unary Functions\n";
        pointers_def << "\n// Unary Functions\n";

        assignments << "\n// Unary Functions\n";

        auto unary_list = loader::get().unary();
        std::list<std::string> sorted_unary_list;
        for (auto unary : unary_list) {
            sorted_unary_list.push_back(unary.first);
        }
        sorted_unary_list.sort();

        for (auto unary_entry : sorted_unary_list) {
            std::string op_name = unary_entry;
            std::regex name_test = std::regex("[a-z]+?.*");
            if (std::regex_match(op_name, name_test)) {
                for (auto op : unary_list[unary_entry]) {
                    std::string arg_types = op.op->arg_type.type_str();
                    std::transform(arg_types.begin(), arg_types.end(), arg_types.begin(), ::tolower);
                    std::string return_type = op.op->return_type.type_str();
                    std::transform(return_type.begin(), return_type.end(), return_type.begin(), ::tolower);
                    std::string first_arg_type = *op.op->arg_type.type().begin();
                    std::string pointer_name = "unary__" + op_name + "__" + arg_types + "__ret__" + return_type;
                    pointers_def << "unary_function __sqf::" << pointer_name << ";\n";
                    pointers << "static unary_function " << pointer_name << ";\n";
                    //__sqf::unary_random_scalar_raw = (unary_function)functions.get_unary_function_typed("random", "SCALAR");
                    assignments << "__sqf::" << pointer_name << " = " << "(unary_function)host::functions.get_unary_function_typed(\"" << op_name << "\"_sv, \"" << first_arg_type << "\"_sv);\n";
                }
            }
        }

        pointers << "\n// Binary Functions\n";
        pointers_def << "\n// Binary Functions\n";

        assignments << "\n// Binary Functions\n";

        auto binary_list = loader::get().binary();
        std::list<std::string> sorted_binary_list;
        for (auto binary : binary_list) {
            sorted_binary_list.push_back(binary.first);
        };
        sorted_binary_list.sort();

        for (auto binary_entry : sorted_binary_list) {
            std::string op_name = binary_entry;
            std::regex name_test = std::regex("[a-z]+?.*");
            if (std::regex_match(op_name, name_test)) {
                for (auto op : binary_list[binary_entry]) {
                    std::string arg1_types = op.op->arg1_type.type_str();
                    std::transform(arg1_types.begin(), arg1_types.end(), arg1_types.begin(), ::tolower);
                    std::string arg2_types = op.op->arg2_type.type_str();
                    std::transform(arg2_types.begin(), arg2_types.end(), arg2_types.begin(), ::tolower);

                    std::string return_type = op.op->return_type.type_str();
                    std::transform(return_type.begin(), return_type.end(), return_type.begin(), ::tolower);

                    std::string first_arg1_type = *op.op->arg1_type.type().begin();
                    std::string first_arg2_type = *op.op->arg2_type.type().begin();

                    std::string pointer_name = "binary__" + op_name + "__" + arg1_types + "__" + arg2_types + "__ret__" + return_type;
                    pointers_def << "binary_function __sqf::" << pointer_name << ";\n";
                    pointers << "static binary_function " << pointer_name << ";\n";

                    assignments << "__sqf::" << pointer_name << " = " << "(binary_function)host::functions.get_binary_function_typed(\"" << op_name << 
                        "\"_sv, \"" << first_arg1_type << "\"_sv, \"" << first_arg2_type << "\"_sv);\n";
                }
            }
        }

        pointers << "\n// Nular Functions\n";
        pointers_def << "\n// Nular Functions\n";

        assignments << "\n// Nular Functions\n";

        auto nular_list = loader::get().nular();
        std::list<std::string> sorted_nular_list;
        for (auto nular : nular_list) {
            sorted_nular_list.push_back(nular.first);
        };
        sorted_nular_list.sort();

        for (auto nular_entry : sorted_nular_list) {
            std::string op_name = nular_entry;
            std::regex name_test = std::regex("[a-z]+?.*");
            if (std::regex_match(op_name, name_test)) {
                for (auto op : nular_list[nular_entry]) {
                    std::string return_type = op.op->return_type.type_str();
                    std::transform(return_type.begin(), return_type.end(), return_type.begin(), ::tolower);
                    std::string pointer_name = "nular__" + op_name + "__ret__" + return_type;
                    pointers_def << "nular_function __sqf::" << pointer_name << ";\n";
                    pointers << "static nular_function " << pointer_name << ";\n";

                    //__sqf::unary_random_scalar_raw = (unary_function)functions.get_unary_function_typed("random", "SCALAR");
                    assignments << "__sqf::" << pointer_name << " = " << "(nular_function)host::functions.get_nular_function(\"" << op_name << "\"_sv);\n";
                }
            }
        }

        return true;
    }
Beispiel #22
0
bool rational_fitter_parallel::fit_data(const ptr<data>& dat, ptr<function>& fit, const arguments &args)
{
  ptr<rational_function> r = dynamic_pointer_cast<rational_function>(fit) ;
  if(!r)
  {
    std::cerr << "<<ERROR>> not passing the correct function class to the fitter: must be a rational_function" << std::endl ;
    return false ;
  }

  ptr<vertical_segment> d = dynamic_pointer_cast<vertical_segment>(dat) ;
  if(!d
     || d->confidence_interval_kind() != vertical_segment::ASYMMETRICAL_CONFIDENCE_INTERVAL)
  {
    std::cerr << "<<WARNING>> automatic convertion of the data object to vertical_segment," << std::endl;
    std::cerr << "<<WARNING>> we advise you to perform convertion with a separate command." << std::endl;

    size_t elem_size =
        dat->parametrization().dimX() + 3*dat->parametrization().dimY();
    double* content = new double[dat->size() * elem_size];

    for(int i=0; i<dat->size(); ++i)
    {
      const vec x = dat->get(i);

      for(int k=0; k<x.size(); ++k) {
          content[i + k] = x[k];
      }
      for(int k=0; k<dat->parametrization().dimY(); ++k) {
          content[i + k + dat->parametrization().dimX() + dat->parametrization().dimY()] =
              (1.0 - args.get_float("dt", 0.1)) * x[k + dat->parametrization().dimX()];
      }
      for(int k=0; k<dat->parametrization().dimY(); ++k) {
          content[i + k + dat->parametrization().dimX() + 2*dat->parametrization().dimY()] =
              (1.0 + args.get_float("dt", 0.1)) * x[k + dat->parametrization().dimX()];
      }
    }

    ptr<vertical_segment> vs(new vertical_segment(dat->parametrization(),
                                                  dat->size(),
                                                  std::shared_ptr<double>(content)));

    d = vs;
  }

  // XXX: FIT and D may have different values of dimX() and dimY(), but
  // this is fine: we convert values as needed in operator().
  r->setMin(d->min());
  r->setMax(d->max());

  const int _min_np = args.get_int("min-np", 10);
  const int _max_np = args.get_int("np", _min_np);
  std::cout << "<<INFO>> N in  [" << _min_np << ", " << _max_np << "]"  << std::endl ;

  const int nb_starting_points = args.get_int("nb-starting-points", 100);
  std::cout << "<<INFO>> number of data point used in start: " << nb_starting_points << std::endl;

  const int  step      = args.get_int("np-step", 1);
  const bool use_delta = args.is_defined("use_delta");

  for(int i=_min_np; i<=_max_np; i+=step)
  {
    std::cout << "<<INFO>> fit using np+nq = " << i << std::endl ;
    std::cout.flush() ;
    timer time ;
    time.start() ;

#ifdef _OPENMP
      const int nb_cores = args.get_int("nb-cores", omp_get_num_procs());
#ifdef DEBUG
    std::cout << "<<DEBUG>> will use " << nb_cores << " threads to compute the quadratic programs" << std::endl ;
#endif

    omp_set_num_threads(nb_cores) ;
#endif

    double min_delta   = std::numeric_limits<double>::max();
    double min_l2_dist = std::numeric_limits<double>::max();
    double mean_delta = 0.0;
    int nb_sol_found  = 0;
    int nb_sol_tested = 0;

    #pragma omp parallel for shared(r, args, nb_sol_found, nb_sol_tested, min_delta, mean_delta), schedule(dynamic,1)
    for(int j=1; j<i; ++j)
    {
      // Compute the number of coefficients in the numerator and in the denominator
      // from the current number of coefficients i and the current index in the
      // loop j.
      int temp_np = i - j;
      int temp_nq = j;

      //vec p(temp_np*r->dimY()), q(temp_nq*r->dimY());

      // Allocate a rational function and set it to the correct size, dimensions
      // and parametrizations.
      ptr<rational_function> rk(NULL);
      #pragma omp critical (args)
      {
        rk = dynamic_pointer_cast<rational_function>(
            ptr<function>(plugins_manager::get_function(args,
                                                        r->parametrization())));
      }
      if(!rk)
      {
          std::cerr << "<<ERROR>> unable to obtain a rational function from the plugins manager" << std::endl;
          throw;
      }

      rk->setMin(r->min()) ;
      rk->setMax(r->max()) ;

      // Set the rational function size
      rk->setSize(temp_np, temp_nq);

      double delta = 1.0;
      double linf_dist, l2_dist;
      bool is_fitted = fit_data(d, temp_np, temp_nq, rk, args, delta, linf_dist, l2_dist);
      if(is_fitted)
      {
        #pragma omp critical (r)
        {
          ++nb_sol_found ;
          mean_delta += delta ;

          std::cout << "<<INFO>> found a solution with np=" << temp_np
            << ", nq = " << temp_nq << std::endl;
          std::cout << "<<INFO>> Linf error = " << linf_dist << std::endl;
          std::cout << "<<INFO>> L2   error = " << l2_dist << std::endl;
          std::cout << "<<INFO>>      delta = " << delta << std::endl;
          std::cout << std::endl;

          // Get the solution with the minimum delta or the minimum L2 distance,
          // and update the main rational function r.
          if((use_delta && delta < min_delta) || (!use_delta && l2_dist < min_l2_dist))
          {
            min_delta   = delta ;
            min_l2_dist = l2_dist ;
            r->setSize(temp_np, temp_nq);
            r->update(rk);
          }
        }
      }

      #pragma omp critical (nb_sol_tested)
      {
        // Update the solution
        nb_sol_tested++;

        std::cout << "<<DEBUG>> nb solutions tested: " << nb_sol_tested << " / " << i << "\r";
        std::cout.flush();
      }
    }

    if(min_delta < std::numeric_limits<double>::max())
    {
      std::cout << "<<INFO>> mean delta = " << mean_delta/nb_sol_found << std::endl;
      std::cout << "<<INFO>>  min delta = " << min_delta << std::endl;
      std::cout << *(r.get()) << std::endl;

      time.stop();
      std::cout << "<<INFO>> got a fit using N = " << i << std::endl ;
      std::cout << "<<INFO>> it took " << time << std::endl ;
      std::cout << "<<INFO>> I got " << nb_sol_found << " solutions to the QP" << std::endl ;
      return true ;
    }
  }

  return false ;
}
Beispiel #23
0
// dat is the data object, it contains all the points to fit
// np and nq are the degree of the RP to fit to the data
// y is the dimension to fit on the y-data (e.g. R, G or B for RGB signals)
// the function returns a rational BRDF function and a boolean
bool rational_fitter_parallel::fit_data(const ptr<vertical_segment>& d, int np, int nq, int ny,
                                        rational_function_1d* r, const arguments& args,
                                        vec& p, vec& q, double& delta)
{
  const int m = d->size(); // 2*m = number of constraints
  const int n = np+nq;     // n = np+nq

  quadratic_program qp(np, nq, args.is_defined("use_delta"));

  // Starting with only a nb_starting_points vertical segments
  std::list<unsigned int> training_set;
  const int di = std::max((m-1) / (nb_starting_points-1), 1);
  for(int i=0; i<m; ++i)
  {
    if(i % di == 0)
    {
        // Create two vector of constraints
        vec c1(n), c2(n);
        get_constraint(i, np, nq, ny, d, r, c1, c2);

        qp.add_constraints(c1);
        qp.add_constraints(c2);

    }
    else
    {
        training_set.push_back(i);
    }
  }
  qp.set_training_set(training_set);

  do
  {
#ifdef _OPENMP
#ifdef DEBUG
        std::cout << "<<DEBUG>> thread " << omp_get_thread_num() << ", number of intervals tested = " << qp.nb_constraints()/2 << std::endl ;
#endif
#endif
    Eigen::VectorXd x(n);
    bool solves_qp = qp.solve_program(x, delta, p, q);
    r->update(p, q);

    if(solves_qp)
    {
      if(qp.test_constraints(ny, r, d))
      {
#ifdef DEBUG
        std::cout << "<<INFO>> got solution " << *r << std::endl ;
#endif
        return true;
      }
    }
    else
    {
#ifdef DEBUG
      std::cout << "<<DEBUG>> not enough coefficients" << std::endl;
#endif
      return false;
    }
  } while(qp.nb_constraints() < 2*m);

  return false;
}
Beispiel #24
0
int
main (int ac, char *ag[])
{
  int index;
  pth_init ();

  argp_parse (&argp, ac, ag, ARGP_IN_ORDER, &index, &arg);

  // if you ever want this to be fatal, doing it here would be too late
  if (getuid () == 0)
    ERRORPRINTF (arg.tracer(), E_WARNING | 20, 0, "EIBD should not run as root");

  signal (SIGPIPE, SIG_IGN);

  if (arg.daemon)
    {
      int fd = open (arg.daemon, O_WRONLY | O_APPEND | O_CREAT, FILE_MODE);
      if (fd == -1)
	die ("Can not open file %s", arg.daemon);
      int i = fork ();
      if (i < 0)
	die ("fork failed");
      if (i > 0)
	exit (0);
      close (1);
      close (2);
      close (0);
      dup2 (fd, 1);
      dup2 (fd, 2);
      close (fd);
      setsid ();
    }

  FILE *pidf;
  if (arg.pidfile)
    if ((pidf = fopen (arg.pidfile, "w")) != NULL)
      {
	fprintf (pidf, "%d", getpid ());
	fclose (pidf);
      }


  signal (SIGINT, SIG_IGN);
  signal (SIGTERM, SIG_IGN);

  // main loop
#ifdef HAVE_SYSTEMD
  sd_notify(0,"READY=1");
#endif
  int sig;
  if (! arg.stop_now)
    do {
      sigset_t t1;
      sigemptyset (&t1);
      sigaddset (&t1, SIGINT);
      sigaddset (&t1, SIGHUP);
      sigaddset (&t1, SIGTERM);

      pth_sigwait (&t1, &sig);

      if (sig == SIGHUP && arg.daemon)
	{
	  int fd =
	    open (arg.daemon, O_WRONLY | O_APPEND | O_CREAT, FILE_MODE);
	  if (fd == -1)
	    {
	      ERRORPRINTF (arg.tracer(), E_ERROR | 21, 0, "can't open log file %s",
			   arg.daemon);
	      continue;
	    }
	  close (1);
	  close (2);
	  dup2 (fd, 1);
	  dup2 (fd, 2);
	  close (fd);
	}

    } while (sig == SIGHUP);
#ifdef HAVE_SYSTEMD
  sd_notify(0,"STOPPING=1");
#endif

  signal (SIGINT, SIG_DFL);
  signal (SIGTERM, SIG_DFL);

#ifdef HAVE_GROUPCACHE
  DeleteGroupCache ();
#endif

  arg.free_l3();

  if (arg.pidfile)
    unlink (arg.pidfile);

  pth_yield (0);
  pth_yield (0);
  pth_yield (0);
  pth_yield (0);
  pth_exit (0);
  return 0;
}
Beispiel #25
0
bool rational_fitter_parsec_multi::fit_data(const ptr<data>& dat, ptr<function>& fit, const arguments &args)
{
    std::cerr << "Entering first level of fit_data" << std::endl;

    ptr<rational_function> r = dynamic_pointer_cast<rational_function>(fit);
    const ptr<vertical_segment>& d = dynamic_pointer_cast<vertical_segment>(dat);
    if(!r || !d
       || d->confidence_interval_kind() != vertical_segment::ASYMMETRICAL_CONFIDENCE_INTERVAL)
	{
	    std::cerr << "<<ERROR>> not passing the correct class to the fitter" << std::endl;
	    return false;
	}

    // I need to set the dimension of the resulting function to be equal
    // to the dimension of my fitting problem

    // This doesn't work for dimension greater than 1 for now.
    //assert( d->dimY() == 1 );

    r->setDimX(d->dimX());
    r->setDimY(d->dimY());
    r->setMin(d->min());
    r->setMax(d->max());

    std::cout << "<<INFO>> np in  [" << _min_np << ", " << _max_np
	      << "] & nq in [" << _min_nq << ", " << _max_nq << "]" << std::endl;

    const int step = args.get_int("np-step", 1);
    int i;

    for(i=std::max<int>(2,_min_np); i<=_max_np; i+=step )
	{
	    // double min_delta  = std::numeric_limits<double>::max();
	    // double min_l2_dist= std::numeric_limits<double>::max();
	    // double mean_delta = 0.0;
	    // int nb_sol_found  = 0;
	    // int nb_sol_tested = 0;
	    timer time;
	    int np;

	    std::cout << "<<INFO>> fit using np+nq = " << i << std::endl ;
	    std::cout.flush() ;

	    time.start();

	    // i=np+nq => i-1 independant pb
	    std::cout << r.getcounter() << std::endl;
	    if(fit_data(d.get(), i-1, r.get(), np))
		{
		    time.stop();

		    std::cout << r.getcounter() << std::endl;
		    std::cout << "<<INFO>> got a fit using np = " << np << " & nq =  " << i-np << "      " << std::endl;
		    std::cout << "<<INFO>> " << *(r.get()) << std::endl;
		    std::cout << "<<INFO>> it took " << time << std::endl;

		    return true;
		}
	}

    std::cerr << "Exiting first level of fit_data" << std::endl;
    return false;
}
Beispiel #26
0
void FileSystem::checkArgumentsCount(arguments arg, size_t minArgumentsCount) const
{
    if(arg.size() < minArgumentsCount) {
        throw not_enough_arguments_exception(arg.size(), minArgumentsCount);
    }
}