<commit_before>
// STL includes
#include <algorithm>
#include <cmath>
#include <cassert>

// hyperion includes
#include <hyperion/ImageToLedsMap.h>

using namespace hyperion;

ImageToLedsMap::ImageToLedsMap(
		const unsigned width,
		const unsigned height,
		const unsigned horizontalBorder,
		const unsigned verticalBorder,
		const std::vector<Led>& leds) :
	_width(width),
	_height(height),
	mColorsMap()
{
	// Sanity check of the size of the borders (and width and height)
	assert(width  > 2*verticalBorder);
	assert(height > 2*horizontalBorder);

	// Reserve enough space in the map for the leds
	mColorsMap.reserve(leds.size());

	const unsigned xOffset = verticalBorder;
	const unsigned actualWidth  = width  - 2 * verticalBorder;
	const unsigned yOffset = horizontalBorder;
	const unsigned actualHeight = height - 2 * horizontalBorder;

	for (const Led& led : leds)
	{
		// Compute the index boundaries for this led
		const unsigned minX_idx = xOffset + unsigned(std::round((actualWidth-1)  * led.minX_frac));
		const unsigned maxX_idx = xOffset + unsigned(std::round((actualWidth-1)  * led.maxX_frac));
		const unsigned minY_idx = yOffset + unsigned(std::round((actualHeight-1) * led.minY_frac));
		const unsigned maxY_idx = yOffset + unsigned(std::round((actualHeight-1) * led.maxY_frac));

		// Add all the indices in the above defined rectangle to the indices for this led
		std::vector<unsigned> ledColors;
		for (unsigned y = minY_idx; y<=maxY_idx && y<height; ++y)
		{
			for (unsigned x = minX_idx; x<=maxX_idx && x<width; ++x)
			{
				ledColors.push_back(y*width + x);
			}
		}

		// Add the constructed vector to the map
		mColorsMap.push_back(ledColors);
	}
}

unsigned ImageToLedsMap::width() const
{
	return _width;
}

unsigned ImageToLedsMap::height() const
{
	return _height;
}
<commit_msg>Fix led mapping boundaries<commit_after>// STL includes
#include <algorithm>
#include <cmath>
#include <cassert>

// hyperion includes
#include <hyperion/ImageToLedsMap.h>

using namespace hyperion;

ImageToLedsMap::ImageToLedsMap(
		const unsigned width,
		const unsigned height,
		const unsigned horizontalBorder,
		const unsigned verticalBorder,
		const std::vector<Led>& leds) :
	_width(width),
	_height(height),
	mColorsMap()
{
	// Sanity check of the size of the borders (and width and height)
	assert(width  > 2*verticalBorder);
	assert(height > 2*horizontalBorder);

	// Reserve enough space in the map for the leds
	mColorsMap.reserve(leds.size());

	const unsigned xOffset = verticalBorder;
	const unsigned actualWidth  = width  - 2 * verticalBorder;
	const unsigned yOffset = horizontalBorder;
	const unsigned actualHeight = height - 2 * horizontalBorder;

	for (const Led& led : leds)
	{
		// skip leds without area
		if ((led.maxX_frac-led.minX_frac) < 1e-6 || (led.maxY_frac-led.minY_frac) < 1e-6)
		{
			continue;
		}

		// Compute the index boundaries for this led
		unsigned minX_idx = xOffset + unsigned(std::round(actualWidth  * led.minX_frac));
		unsigned maxX_idx = xOffset + unsigned(std::round(actualWidth  * led.maxX_frac));
		unsigned minY_idx = yOffset + unsigned(std::round(actualHeight * led.minY_frac));
		unsigned maxY_idx = yOffset + unsigned(std::round(actualHeight * led.maxY_frac));

		// make sure that the area is at least a single led large
		minX_idx = std::min(minX_idx, xOffset + actualWidth - 1);
		if (minX_idx == maxX_idx)
		{
			maxX_idx = minX_idx + 1;
		}
		minY_idx = std::min(minY_idx, yOffset + actualHeight - 1);
		if (minY_idx == maxY_idx)
		{
			maxY_idx = minY_idx + 1;
		}

		// Add all the indices in the above defined rectangle to the indices for this led
		std::vector<unsigned> ledColors;
		for (unsigned y = minY_idx; y<maxY_idx && y<(yOffset+actualHeight); ++y)
		{
			for (unsigned x = minX_idx; x<maxX_idx && x<(xOffset+actualWidth); ++x)
			{
				ledColors.push_back(y*width + x);
			}
		}

		// Add the constructed vector to the map
		mColorsMap.push_back(ledColors);
	}
}

unsigned ImageToLedsMap::width() const
{
	return _width;
}

unsigned ImageToLedsMap::height() const
{
	return _height;
}
<|endoftext|>


<commit_before>/*!
 *
 */

#pragma once

#include "../typeinfo.h"
#include "convert_utils.h"
#include "../element.h"
#include <string>
#include <vector>

namespace bson
{
  template<>
  TypeInfo default_type<std::vector<Element>>()
  {
    return ARRAY;
  }

  template<>
  std::string to_string<std::vector<Element>>()
  {
    return "std::vector<bson::Element>";
  }

  template<>
  bool Element::check_convert<std::vector<Element>>() const
  {
    return m_type == ARRAY;
  }

  template<>
  unsigned Element::deserialize_bytes<std::vector<Element>>(const char* bytes)
  {
    TypeInfo ti;
    Element e;
    int32_t size, consumed = 4, added;
    memcpy(&size, bytes, 4);
    std::unique_ptr<char> str(new char[size]);
    std::memcpy(str.get(), bytes, size);
    char* iter = str.get() + 4;
    size --;
    m_data = std::shared_ptr<std::vector<Element>>(new std::vector<Element>);
    while (consumed < size)
    {
      ti = static_cast<TypeInfo>(*(iter++));
      std::string index(iter); //ignore this, we know it will be the index;
      iter += index.size() + 1;
      added = e.decode(iter, ti);
      iter += added;
      consumed += (added + index.size() + 2);
      std::static_pointer_cast<std::vector<Element>>(m_data) -> push_back(e);
    }
    return consumed + 1;
  }

  template<>
  void Element::serialize_bson<std::vector<Element>>(std::ostringstream& oss) const
  {
    int size = std::static_pointer_cast<std::vector<Element>>(m_data) -> size();
    int index = 0;
    std::ostringstream data_ser;
    for (const Element & e: *(std::static_pointer_cast<std::vector<Element>>(m_data)))
    {
      data_ser << to_char(e.m_type) << itos(index++) << X00;
      e.encode(data_ser);
    }
    _to_stream(oss, static_cast<int>(5 + data_ser.tellp()));
    oss << data_ser.str() << X00;
    return;
  }

  template <>
  std::string Element::_to_std_str<std::vector<Element>>() const
  {
    std::ostringstream oss;
    int size = std::static_pointer_cast<std::vector<Element>>(m_data) -> size();
    oss << "[ ";
    if (size > 0)
      oss << static_cast<std::string>((*(std::static_pointer_cast<std::vector<Element>>(m_data)))[0]);
    for (int i=0; i < size; i++)
    {
      oss << ", " << static_cast<std::string>((*(std::static_pointer_cast<std::vector<Element>>(m_data)))[i]);
    }
    oss << " ]";
    return oss.str();
  }
}<commit_msg>header info for vectors<commit_after>/*!
 * \file vectors.hpp
 * \author Nathan Eloe
 * \brief std::vector<Element> template specializations
 */

#pragma once

#include "../typeinfo.h"
#include "convert_utils.h"
#include "../element.h"
#include <string>
#include <vector>

namespace bson
{
  template<>
  TypeInfo default_type<std::vector<Element>>()
  {
    return ARRAY;
  }

  template<>
  std::string to_string<std::vector<Element>>()
  {
    return "std::vector<bson::Element>";
  }

  template<>
  bool Element::check_convert<std::vector<Element>>() const
  {
    return m_type == ARRAY;
  }

  template<>
  unsigned Element::deserialize_bytes<std::vector<Element>>(const char* bytes)
  {
    TypeInfo ti;
    Element e;
    int32_t size, consumed = 4, added;
    memcpy(&size, bytes, 4);
    std::unique_ptr<char> str(new char[size]);
    std::memcpy(str.get(), bytes, size);
    char* iter = str.get() + 4;
    size --;
    m_data = std::shared_ptr<std::vector<Element>>(new std::vector<Element>);
    while (consumed < size)
    {
      ti = static_cast<TypeInfo>(*(iter++));
      std::string index(iter); //ignore this, we know it will be the index;
      iter += index.size() + 1;
      added = e.decode(iter, ti);
      iter += added;
      consumed += (added + index.size() + 2);
      std::static_pointer_cast<std::vector<Element>>(m_data) -> push_back(e);
    }
    return consumed + 1;
  }

  template<>
  void Element::serialize_bson<std::vector<Element>>(std::ostringstream& oss) const
  {
    int size = std::static_pointer_cast<std::vector<Element>>(m_data) -> size();
    int index = 0;
    std::ostringstream data_ser;
    for (const Element & e: *(std::static_pointer_cast<std::vector<Element>>(m_data)))
    {
      data_ser << to_char(e.m_type) << itos(index++) << X00;
      e.encode(data_ser);
    }
    _to_stream(oss, static_cast<int>(5 + data_ser.tellp()));
    oss << data_ser.str() << X00;
    return;
  }

  template <>
  std::string Element::_to_std_str<std::vector<Element>>() const
  {
    std::ostringstream oss;
    int size = std::static_pointer_cast<std::vector<Element>>(m_data) -> size();
    oss << "[ ";
    if (size > 0)
      oss << static_cast<std::string>((*(std::static_pointer_cast<std::vector<Element>>(m_data)))[0]);
    for (int i=0; i < size; i++)
    {
      oss << ", " << static_cast<std::string>((*(std::static_pointer_cast<std::vector<Element>>(m_data)))[i]);
    }
    oss << " ]";
    return oss.str();
  }
}<|endoftext|>


<commit_before>#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <unistd.h>  // usleep
#include <sys/types.h>  // for kill
#include <signal.h>     // for kill

using namespace RooFit;

// call from command line like, for instance:
// root -l 'unbinned_scaling2.cpp()'

// timing_flag is used to activate only selected timing statements [1-7]

void unbinned_scaling2(int num_cpu=1, bool force_num_int=false,
                       bool time_num_ints=false, int optConst=2,
                       int N_gaussians=1, int N_observables=1, int N_parameters=2,
                       int N_events=100000,
                       int parallel_interleave=0,
                       int seed=1,
                       int print_level=0,
                       int timing_flag=1,
                       bool cpu_affinity=true,
                       bool fork_timer = false,
                       int fork_timer_sleep_us = 100000,
                       bool debug=true
                       ) {
  //gSystem->Exec("top -n1 -b");
  // num_cpu: -1 is special option -> overhead communicatie protocol vergelijken (vgl met 1 cpu)
  // parallel_interleave: 0 = blokken gelijke grootte, 1 = interleave
  //
  //             binned:         generateBinned ipv generate -> als je aantal events ongeveer even groot is als aantal bins krijg je load balancing problemen, dat zou interleave beetje moeten ondervangen
  // verwachtingen
  // - historisch: tot ~8 cpu gaat het goed
  // - weinig data en veel parameters: comm overhead belangrijk (fit snel, veel tijd in oversturen params)
  // - weinig parameters, veel data: scalability hoort beter te zijn (minder comm overhead) -> bottom line van wat de software kan
  // - observables even op 1 houden, alles optellen klopt conceptueel-statistisch niet

  if (debug) {
    RooMsgService::instance().addStream(DEBUG);
    // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
  }

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges

  if (timing_flag > 0) {
    RooJsonListFile outfile;

    outfile.open("timing_meta.json");
    std::string names[13] = {"N_gaussians", "N_observables", "N_parameters",
                             "N_events", "num_cpu", "parallel_interleave",
                             "seed", "pid", "force_num_int", "time_num_ints",
                             "optConst", "print_level", "timing_flag"};
    outfile.set_member_names(names, names + 13);

    outfile << N_gaussians << N_observables << N_parameters
            << N_events << num_cpu << parallel_interleave
            << seed << getpid() << force_num_int << time_num_ints
            << optConst << print_level << timing_flag;
  }

  RooTrace::timing_flag = timing_flag;
  if (time_num_ints) {
    RooTrace::set_time_numInts(kTRUE);
  }

  // plotting configuration
  int obs_plot_x(3);
  int obs_plot_y(2);
  int obs_plot_x_px(1200);
  int obs_plot_y_px(800);

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  gRandom->SetSeed(seed);

  // some sanity checks
  if (obs_plot_x * obs_plot_y < N_observables) {
    std::cout << "WARNING: obs_plot_x * obs_plot_y < N_observables,"
                 " won't be able to plot all observables!"
              << std::endl << std::endl;
  }
  if (N_parameters % 2 != 0) {
    std::cout << "set N_parameters to an even number!" << std::endl;
    exit(2);
  }

  // here we go!

  RooWorkspace w("w", 1) ;

  RooArgSet obs_set;

  // create gaussian parameters
  float mean[N_parameters/2], sigma[N_parameters/2];
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    mean[ix] = gRandom->Gaus(0, 2);
    sigma[ix] = 0.1 + abs(gRandom->Gaus(0, 2));
  }

  // create gaussians and also the observables and parameters they depend on
  RooAbsReal* gaussian_ix;
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::cout << ix << std::endl;
    std::ostringstream os;
    // int ix_p = (ix/2) % N_parameters;
    int ix_p = ix % (N_parameters / 2);
    os << "Gaussian::g" << ix
       << "(x" << ix % N_observables << "[-10,10],"
       << "m" << ix_p << "[" << mean[ix_p] << ",-10,10],"
       << "s" << ix_p << "[" << sigma[ix_p] << ",0.1,10])";
    std::string s = os.str();
    gaussian_ix = dynamic_cast<RooAbsReal *>(w.factory(s.c_str()));

    if (force_num_int) {
      // force it
      if (gaussian_ix) {
        gaussian_ix->forceNumInt(kTRUE);
      } else {
        std::cout << "GAUSSIAN_IX " << ix << " GOT NULL PTR!!" << std::endl;
        exit(1);
      }
    }
  }

  // create uniform background signals on each observable
  for (int ix = 0; ix < N_observables; ++ix) {
    {
      std::ostringstream os;
      os << "Uniform::u" << ix << "(x" << ix << ")";
      std::string s = os.str();
      w.factory(s.c_str());
    }

    // gather the observables in a list for data generation below
    {
      std::ostringstream os;
      os << "x" << ix;
      std::string s = os.str();
      obs_set.add(*w.arg(s.c_str()));
    }
  }

  RooArgSet pdf_set = w.allPdfs();

  // create event counts for all pdfs
  RooArgSet count_set;

  // ... for the gaussians
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os, os2;
    os << "Nsig" << ix;
    std::string s = os.str();
    os2 << "#signal events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os;
    os << "Nsig" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }
  // ... and for the uniform background components
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os, os2;
    os << "Nbkg" << ix;
    std::string s = os.str();
    os2 << "#background events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os;
    os << "Nbkg" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }

  RooAddPdf sum("sum", "gaussians+uniforms", pdf_set, count_set);

  // --- Generate a toyMC sample from composite PDF ---
  RooDataSet *data = sum.generate(obs_set, N_events);
/*
  // OR reload previously written out sample:
  // wegschrijven:
  data.write("roofit_demo_random_data_values.dat");
  // om het weer in te lezen:
  RooDataSet *data = RooDataSet::read("../roofit_demo_random_data_values.dat", RooArgList(mes));
*/

  // --- Perform extended ML fit of composite PDF to toy data ---
  // sum.fitTo(*data,"Extended") ;
  // instead of full fitTo, only do the fit, leave out error matrix, using
  // run style of run_higgs.C

  RooJsonListFile outfile;
  RooWallTimer timer;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json");
    std::string names[2] = {"full_minimize_wall_s", "pid"};
    outfile.set_member_names(names, names + 2);
  }

  Bool_t cpuAffinity;
  if (cpu_affinity) {
    cpuAffinity = kTRUE;
  } else {
    cpuAffinity = kFALSE;
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* nll = sum.createNLL(*data, NumCPU(num_cpu, parallel_interleave),
                                    CPUAffinity(cpuAffinity));//, "Extended");
    RooMinimizer m(*nll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    int pid = -1;

    if (fork_timer) {
      pid = fork();
    }
    if (pid == 0) {
      /* child */
      timer.start();
      while (true) {
        timer.stop();
        std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
        usleep(fork_timer_sleep_us);
      }
    }
    else {
      /* parent */
      if (timing_flag == 1) {
        timer.start();
      }
      // m.hesse();

      m.minimize("Minuit2", "migrad");

      if (timing_flag == 1) {
        timer.stop();
        std::cout << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << getpid();
      }

      if (pid > 0) {
        // a child exists
        kill(pid, SIGKILL);
      }
    }
  }

  // print the "true" values for comparison
  std::cout << "--- values of PDF parameters used for data generation:"
            << std::endl;
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    std::cout << "    gauss " << ix << ": m = " << mean[ix] << ", s = "
              << sigma[ix] << std::endl;
  }

  // --- Plot toy data and composite PDF overlaid ---
  TCanvas* c = new TCanvas("unbinned_scaling", "unbinned_scaling",
                           obs_plot_x_px, obs_plot_y_px);
  c->Divide(obs_plot_x, obs_plot_y);
  for (int ix = 0; ix < N_observables && ix < obs_plot_x * obs_plot_y; ++ix) {
    std::ostringstream os;
    os << "x" << ix;
    std::string s = os.str();
    RooPlot* frame = w.var(s.c_str())->frame();
    data->plotOn(frame);
    sum.plotOn(frame);
    c->cd(ix+1);
    frame->Draw();
  }
}
<commit_msg>Debug messages default set to false<commit_after>#include <chrono>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <unistd.h>  // usleep
#include <sys/types.h>  // for kill
#include <signal.h>     // for kill

using namespace RooFit;

// call from command line like, for instance:
// root -l 'unbinned_scaling2.cpp()'

// timing_flag is used to activate only selected timing statements [1-7]

void unbinned_scaling2(int num_cpu=1, bool force_num_int=false,
                       bool time_num_ints=false, int optConst=2,
                       int N_gaussians=1, int N_observables=1, int N_parameters=2,
                       int N_events=100000,
                       int parallel_interleave=0,
                       int seed=1,
                       int print_level=0,
                       int timing_flag=1,
                       bool cpu_affinity=true,
                       bool fork_timer = false,
                       int fork_timer_sleep_us = 100000,
                       bool debug=false
                       ) {
  //gSystem->Exec("top -n1 -b");
  // num_cpu: -1 is special option -> overhead communicatie protocol vergelijken (vgl met 1 cpu)
  // parallel_interleave: 0 = blokken gelijke grootte, 1 = interleave
  //
  //             binned:         generateBinned ipv generate -> als je aantal events ongeveer even groot is als aantal bins krijg je load balancing problemen, dat zou interleave beetje moeten ondervangen
  // verwachtingen
  // - historisch: tot ~8 cpu gaat het goed
  // - weinig data en veel parameters: comm overhead belangrijk (fit snel, veel tijd in oversturen params)
  // - weinig parameters, veel data: scalability hoort beter te zijn (minder comm overhead) -> bottom line van wat de software kan
  // - observables even op 1 houden, alles optellen klopt conceptueel-statistisch niet

  if (debug) {
    RooMsgService::instance().addStream(DEBUG);
    // extra possible options: Topic(Generation) Topic(RooFit::Eval), ClassName("RooAbsTestStatistic")
  }

  // int N_parameters(8);  // must be even, means and sigmas have diff ranges

  if (timing_flag > 0) {
    RooJsonListFile outfile;

    outfile.open("timing_meta.json");
    std::string names[13] = {"N_gaussians", "N_observables", "N_parameters",
                             "N_events", "num_cpu", "parallel_interleave",
                             "seed", "pid", "force_num_int", "time_num_ints",
                             "optConst", "print_level", "timing_flag"};
    outfile.set_member_names(names, names + 13);

    outfile << N_gaussians << N_observables << N_parameters
            << N_events << num_cpu << parallel_interleave
            << seed << getpid() << force_num_int << time_num_ints
            << optConst << print_level << timing_flag;
  }

  RooTrace::timing_flag = timing_flag;
  if (time_num_ints) {
    RooTrace::set_time_numInts(kTRUE);
  }

  // plotting configuration
  int obs_plot_x(3);
  int obs_plot_y(2);
  int obs_plot_x_px(1200);
  int obs_plot_y_px(800);

  // other stuff
  int printlevel(print_level);
  int optimizeConst(optConst);
  // int N_timing_loops(3); // not used

  gRandom->SetSeed(seed);

  // some sanity checks
  if (obs_plot_x * obs_plot_y < N_observables) {
    std::cout << "WARNING: obs_plot_x * obs_plot_y < N_observables,"
                 " won't be able to plot all observables!"
              << std::endl << std::endl;
  }
  if (N_parameters % 2 != 0) {
    std::cout << "set N_parameters to an even number!" << std::endl;
    exit(2);
  }

  // here we go!

  RooWorkspace w("w", 1) ;

  RooArgSet obs_set;

  // create gaussian parameters
  float mean[N_parameters/2], sigma[N_parameters/2];
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    mean[ix] = gRandom->Gaus(0, 2);
    sigma[ix] = 0.1 + abs(gRandom->Gaus(0, 2));
  }

  // create gaussians and also the observables and parameters they depend on
  RooAbsReal* gaussian_ix;
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::cout << ix << std::endl;
    std::ostringstream os;
    // int ix_p = (ix/2) % N_parameters;
    int ix_p = ix % (N_parameters / 2);
    os << "Gaussian::g" << ix
       << "(x" << ix % N_observables << "[-10,10],"
       << "m" << ix_p << "[" << mean[ix_p] << ",-10,10],"
       << "s" << ix_p << "[" << sigma[ix_p] << ",0.1,10])";
    std::string s = os.str();
    gaussian_ix = dynamic_cast<RooAbsReal *>(w.factory(s.c_str()));

    if (force_num_int) {
      // force it
      if (gaussian_ix) {
        gaussian_ix->forceNumInt(kTRUE);
      } else {
        std::cout << "GAUSSIAN_IX " << ix << " GOT NULL PTR!!" << std::endl;
        exit(1);
      }
    }
  }

  // create uniform background signals on each observable
  for (int ix = 0; ix < N_observables; ++ix) {
    {
      std::ostringstream os;
      os << "Uniform::u" << ix << "(x" << ix << ")";
      std::string s = os.str();
      w.factory(s.c_str());
    }

    // gather the observables in a list for data generation below
    {
      std::ostringstream os;
      os << "x" << ix;
      std::string s = os.str();
      obs_set.add(*w.arg(s.c_str()));
    }
  }

  RooArgSet pdf_set = w.allPdfs();

  // create event counts for all pdfs
  RooArgSet count_set;

  // ... for the gaussians
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os, os2;
    os << "Nsig" << ix;
    std::string s = os.str();
    os2 << "#signal events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_gaussians; ++ix) {
    std::stringstream os;
    os << "Nsig" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }
  // ... and for the uniform background components
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os, os2;
    os << "Nbkg" << ix;
    std::string s = os.str();
    os2 << "#background events comp " << ix;
    std::string s2 = os2.str();
    RooRealVar a(s.c_str(), s2.c_str(), 100, 0., 10*N_events);
    w.import(a);
  }
  // gather them in count_set
  for (int ix = 0; ix < N_observables; ++ix) {
    std::stringstream os;
    os << "Nbkg" << ix;
    std::string s = os.str();
    count_set.add(*w.arg(s.c_str()));
  }

  RooAddPdf sum("sum", "gaussians+uniforms", pdf_set, count_set);

  // --- Generate a toyMC sample from composite PDF ---
  RooDataSet *data = sum.generate(obs_set, N_events);
/*
  // OR reload previously written out sample:
  // wegschrijven:
  data.write("roofit_demo_random_data_values.dat");
  // om het weer in te lezen:
  RooDataSet *data = RooDataSet::read("../roofit_demo_random_data_values.dat", RooArgList(mes));
*/

  // --- Perform extended ML fit of composite PDF to toy data ---
  // sum.fitTo(*data,"Extended") ;
  // instead of full fitTo, only do the fit, leave out error matrix, using
  // run style of run_higgs.C

  RooJsonListFile outfile;
  RooWallTimer timer;

  if (timing_flag == 1) {
    outfile.open("timing_full_minimize.json");
    std::string names[2] = {"full_minimize_wall_s", "pid"};
    outfile.set_member_names(names, names + 2);
  }

  Bool_t cpuAffinity;
  if (cpu_affinity) {
    cpuAffinity = kTRUE;
  } else {
    cpuAffinity = kFALSE;
  }

  // for (int it = 0; it < N_timing_loops; ++it)
  {
    RooAbsReal* nll = sum.createNLL(*data, NumCPU(num_cpu, parallel_interleave),
                                    CPUAffinity(cpuAffinity));//, "Extended");
    RooMinimizer m(*nll);
    // m.setVerbose(1);
    m.setStrategy(0);
    m.setProfile(1);
    m.setPrintLevel(printlevel);
    m.optimizeConst(optimizeConst);

    int pid = -1;

    if (fork_timer) {
      pid = fork();
    }
    if (pid == 0) {
      /* child */
      timer.start();
      while (true) {
        timer.stop();
        std::cout << "TIME: " << timer.timing_s() << "s" << std::endl;
        usleep(fork_timer_sleep_us);
      }
    }
    else {
      /* parent */
      if (timing_flag == 1) {
        timer.start();
      }
      // m.hesse();

      m.minimize("Minuit2", "migrad");

      if (timing_flag == 1) {
        timer.stop();
        std::cout << timer.timing_s() << "s" << std::endl;
        outfile << timer.timing_s() << getpid();
      }

      if (pid > 0) {
        // a child exists
        kill(pid, SIGKILL);
      }
    }
  }

  // print the "true" values for comparison
  std::cout << "--- values of PDF parameters used for data generation:"
            << std::endl;
  for (int ix = 0; ix < N_parameters/2; ++ix) {
    std::cout << "    gauss " << ix << ": m = " << mean[ix] << ", s = "
              << sigma[ix] << std::endl;
  }

  // --- Plot toy data and composite PDF overlaid ---
  TCanvas* c = new TCanvas("unbinned_scaling", "unbinned_scaling",
                           obs_plot_x_px, obs_plot_y_px);
  c->Divide(obs_plot_x, obs_plot_y);
  for (int ix = 0; ix < N_observables && ix < obs_plot_x * obs_plot_y; ++ix) {
    std::ostringstream os;
    os << "x" << ix;
    std::string s = os.str();
    RooPlot* frame = w.var(s.c_str())->frame();
    data->plotOn(frame);
    sum.plotOn(frame);
    c->cd(ix+1);
    frame->Draw();
  }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ocomponentaccess.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: as $ $Date: 2001-06-11 10:28:21 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_
#include <helper/ocomponentaccess.hxx>
#endif

#ifndef __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_
#include <helper/ocomponentenumeration.hxx>
#endif

#ifndef _FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_FRAMESEARCHFLAG_HPP_
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

using namespace ::com::sun::star::container     ;
using namespace ::com::sun::star::frame         ;
using namespace ::com::sun::star::lang          ;
using namespace ::com::sun::star::uno           ;
using namespace ::cppu                          ;
using namespace ::osl                           ;
using namespace ::rtl                           ;

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
OComponentAccess::OComponentAccess( const Reference< XDesktop >& xOwner )
        //  Init baseclasses first
        :   ThreadHelpBase  ( &Application::GetSolarMutex() )
        ,   OWeakObject     (                               )
        // Init member
        ,   m_xOwner        ( xOwner                        )
{
    // Safe impossible cases
    LOG_ASSERT( impldbg_checkParameter_OComponentAccessCtor( xOwner ), "OComponentAccess::OComponentAccess()\nInvalid parameter detected!\n" )
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
OComponentAccess::~OComponentAccess()
{
}

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_3(    OComponentAccess                        ,
                        OWeakObject                             ,
                        DIRECT_INTERFACE(XTypeProvider      )   ,
                        DIRECT_INTERFACE(XEnumerationAccess )   ,
                        DIRECT_INTERFACE(XElementAccess     )   )

DEFINE_XTYPEPROVIDER_3( OComponentAccess                        ,
                        XTypeProvider                           ,
                        XEnumerationAccess                      ,
                        XElementAccess                          )

//*****************************************************************************************************************
//  XEnumerationAccess
//*****************************************************************************************************************
Reference< XEnumeration > SAL_CALL OComponentAccess::createEnumeration() throw( RuntimeException )
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Set default return value, if method failed.
    // If no desktop exist and there is no task container - return an empty enumeration!
    Reference< XEnumeration > xReturn = Reference< XEnumeration >();

    // Try to "lock" the desktop for access to task container.
    Reference< XInterface > xLock = m_xOwner.get();
    if ( xLock.is() == sal_True )
    {
        // Desktop exist => pointer to task container must be valid.
        // Initialize a new enumeration ... if some tasks and his components exist!
        // (OTasksEnumeration will make an assert, if we initialize the new instance without valid values!)

        Sequence< Reference< XComponent > > seqComponents;
        impl_collectAllChildComponents( Reference< XFramesSupplier >( xLock, UNO_QUERY ), seqComponents );
        OComponentEnumeration* pEnumeration = new OComponentEnumeration( seqComponents );
        xReturn = Reference< XEnumeration >( (OWeakObject*)pEnumeration, UNO_QUERY );
    }

    // Return result of this operation.
    return xReturn;
}

//*****************************************************************************************************************
//  XElementAccess
//*****************************************************************************************************************
Type SAL_CALL OComponentAccess::getElementType() throw( RuntimeException )
{
    // Elements in list an enumeration are components!
    // Return the uno-type of XComponent.
    return ::getCppuType((const Reference< XComponent >*)NULL);
}

//*****************************************************************************************************************
//  XElementAccess
//*****************************************************************************************************************
sal_Bool SAL_CALL OComponentAccess::hasElements() throw( RuntimeException )
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Set default return value, if method failed.
    sal_Bool bReturn = sal_False;

    // Try to "lock" the desktop for access to task container.
    Reference< XFramesSupplier > xLock( m_xOwner.get(), UNO_QUERY );
    if ( xLock.is() == sal_True )
    {
        // Ask container of owner for existing elements.
        bReturn = xLock->getFrames()->hasElements();
    }

    // Return result of this operation.
    return bReturn;
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
void OComponentAccess::impl_collectAllChildComponents(  const   Reference< XFramesSupplier >&           xNode           ,
                                                                 Sequence< Reference< XComponent > >&   seqComponents   )
{
    // If valid node was given ...
    if( xNode.is() == sal_True )
    {
        // ... continue collection at these.

        // Get the container of current node, collect the components of existing child frames
        // and go down to next level in tree (recursive!).

        sal_Int32 nComponentCount = seqComponents.getLength();

        const Reference< XFrames >              xContainer  = xNode->getFrames();
        const Sequence< Reference< XFrame > >   seqFrames   = xContainer->queryFrames( FrameSearchFlag::CHILDREN );

        const sal_Int32 nFrameCount = seqFrames.getLength();
        for( sal_Int32 nFrame=0; nFrame<nFrameCount; ++nFrame )
        {
            Reference< XComponent > xComponent = impl_getFrameComponent( seqFrames[nFrame] );
            if( xComponent.is() == sal_True )
            {
                nComponentCount++;
                seqComponents.realloc( nComponentCount );
                seqComponents[nComponentCount-1] = xComponent;
            }

            impl_collectAllChildComponents( Reference< XFramesSupplier>( seqFrames[nFrame], UNO_QUERY ), seqComponents );
        }
    }
    // ... otherwise break a recursive path and go back at current stack!
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
Reference< XComponent > OComponentAccess::impl_getFrameComponent( const Reference< XFrame >& xFrame ) const
{
    // Set default return value, if method failed.
    Reference< XComponent > xComponent = Reference< XComponent >();
    // Does no controller exists?
    Reference< XController > xController = xFrame->getController();
    if ( xController.is() == sal_False )
    {
        // Controller not exist - use the VCL-component.
        xComponent = Reference< XComponent >( xFrame->getComponentWindow(), UNO_QUERY );
    }
    else
    {
        // Does no model exists?
        Reference< XModel > xModel( xController->getModel(), UNO_QUERY );
        if ( xModel.is() == sal_True )
        {
            // Model exist - use the model as component.
            xComponent = Reference< XComponent >( xModel, UNO_QUERY );
        }
        else
        {
            // Model not exist - use the controller as component.
            xComponent = Reference< XComponent >( xController, UNO_QUERY );
        }
    }

    return xComponent;
}

//_________________________________________________________________________________________________________________
//  debug methods
//_________________________________________________________________________________________________________________

/*-----------------------------------------------------------------------------------------------------------------
    The follow methods checks the parameter for other functions. If a parameter or his value is non valid,
    we return "sal_False". (else sal_True) This mechanism is used to throw an ASSERT!

    ATTENTION

        If you miss a test for one of this parameters, contact the autor or add it himself !(?)
        But ... look for right testing! See using of this methods!
-----------------------------------------------------------------------------------------------------------------*/

#ifdef ENABLE_ASSERTIONS

//*****************************************************************************************************************
sal_Bool OComponentAccess::impldbg_checkParameter_OComponentAccessCtor( const   Reference< XDesktop >&      xOwner  )
{
    // Set default return value.
    sal_Bool bOK = sal_True;
    // Check parameter.
    if  (
            ( &xOwner       ==  NULL        )   ||
            ( xOwner.is()   ==  sal_False   )
        )
    {
        bOK = sal_False ;
    }
    // Return result of check.
    return bOK ;
}

#endif  //  #ifdef ENABLE_ASSERTIONS

}       //  namespace framework
<commit_msg>#100518# create a correct enumeration<commit_after>/*************************************************************************
 *
 *  $RCSfile: ocomponentaccess.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: mav $ $Date: 2002-07-24 08:28:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_OCOMPONENTACCESS_HXX_
#include <helper/ocomponentaccess.hxx>
#endif

#ifndef __FRAMEWORK_HELPER_OCOMPONENTENUMERATION_HXX_
#include <helper/ocomponentenumeration.hxx>
#endif

#ifndef _FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_FRAME_FRAMESEARCHFLAG_HPP_
#include <com/sun/star/frame/FrameSearchFlag.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

using namespace ::com::sun::star::container     ;
using namespace ::com::sun::star::frame         ;
using namespace ::com::sun::star::lang          ;
using namespace ::com::sun::star::uno           ;
using namespace ::cppu                          ;
using namespace ::osl                           ;
using namespace ::rtl                           ;

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
OComponentAccess::OComponentAccess( const Reference< XDesktop >& xOwner )
        //  Init baseclasses first
        :   ThreadHelpBase  ( &Application::GetSolarMutex() )
        ,   OWeakObject     (                               )
        // Init member
        ,   m_xOwner        ( xOwner                        )
{
    // Safe impossible cases
    LOG_ASSERT( impldbg_checkParameter_OComponentAccessCtor( xOwner ), "OComponentAccess::OComponentAccess()\nInvalid parameter detected!\n" )
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
OComponentAccess::~OComponentAccess()
{
}

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_3(    OComponentAccess                        ,
                        OWeakObject                             ,
                        DIRECT_INTERFACE(XTypeProvider      )   ,
                        DIRECT_INTERFACE(XEnumerationAccess )   ,
                        DIRECT_INTERFACE(XElementAccess     )   )

DEFINE_XTYPEPROVIDER_3( OComponentAccess                        ,
                        XTypeProvider                           ,
                        XEnumerationAccess                      ,
                        XElementAccess                          )

//*****************************************************************************************************************
//  XEnumerationAccess
//*****************************************************************************************************************
Reference< XEnumeration > SAL_CALL OComponentAccess::createEnumeration() throw( RuntimeException )
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Set default return value, if method failed.
    // If no desktop exist and there is no task container - return an empty enumeration!
    Reference< XEnumeration > xReturn = Reference< XEnumeration >();

    // Try to "lock" the desktop for access to task container.
    Reference< XInterface > xLock = m_xOwner.get();
    if ( xLock.is() == sal_True )
    {
        // Desktop exist => pointer to task container must be valid.
        // Initialize a new enumeration ... if some tasks and his components exist!
        // (OTasksEnumeration will make an assert, if we initialize the new instance without valid values!)

        Sequence< Reference< XComponent > > seqComponents;
        impl_collectAllChildComponents( Reference< XFramesSupplier >( xLock, UNO_QUERY ), seqComponents );
        OComponentEnumeration* pEnumeration = new OComponentEnumeration( seqComponents );
        xReturn = Reference< XEnumeration >( (OWeakObject*)pEnumeration, UNO_QUERY );
    }

    // Return result of this operation.
    return xReturn;
}

//*****************************************************************************************************************
//  XElementAccess
//*****************************************************************************************************************
Type SAL_CALL OComponentAccess::getElementType() throw( RuntimeException )
{
    // Elements in list an enumeration are components!
    // Return the uno-type of XComponent.
    return ::getCppuType((const Reference< XComponent >*)NULL);
}

//*****************************************************************************************************************
//  XElementAccess
//*****************************************************************************************************************
sal_Bool SAL_CALL OComponentAccess::hasElements() throw( RuntimeException )
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Set default return value, if method failed.
    sal_Bool bReturn = sal_False;

    // Try to "lock" the desktop for access to task container.
    Reference< XFramesSupplier > xLock( m_xOwner.get(), UNO_QUERY );
    if ( xLock.is() == sal_True )
    {
        // Ask container of owner for existing elements.
        bReturn = xLock->getFrames()->hasElements();
    }

    // Return result of this operation.
    return bReturn;
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
void OComponentAccess::impl_collectAllChildComponents(  const   Reference< XFramesSupplier >&           xNode           ,
                                                                 Sequence< Reference< XComponent > >&   seqComponents   )
{
    // If valid node was given ...
    if( xNode.is() == sal_True )
    {
        // ... continue collection at these.

        // Get the container of current node, collect the components of existing child frames
        // and go down to next level in tree (recursive!).

        sal_Int32 nComponentCount = seqComponents.getLength();

        const Reference< XFrames >              xContainer  = xNode->getFrames();
        const Sequence< Reference< XFrame > >   seqFrames   = xContainer->queryFrames( FrameSearchFlag::CHILDREN );

        const sal_Int32 nFrameCount = seqFrames.getLength();
        for( sal_Int32 nFrame=0; nFrame<nFrameCount; ++nFrame )
        {
            Reference< XComponent > xComponent = impl_getFrameComponent( seqFrames[nFrame] );
            if( xComponent.is() == sal_True )
            {
                nComponentCount++;
                seqComponents.realloc( nComponentCount );
                seqComponents[nComponentCount-1] = xComponent;
            }
        }
    }
    // ... otherwise break a recursive path and go back at current stack!
}

//*****************************************************************************************************************
//  private method
//*****************************************************************************************************************
Reference< XComponent > OComponentAccess::impl_getFrameComponent( const Reference< XFrame >& xFrame ) const
{
    // Set default return value, if method failed.
    Reference< XComponent > xComponent = Reference< XComponent >();
    // Does no controller exists?
    Reference< XController > xController = xFrame->getController();
    if ( xController.is() == sal_False )
    {
        // Controller not exist - use the VCL-component.
        xComponent = Reference< XComponent >( xFrame->getComponentWindow(), UNO_QUERY );
    }
    else
    {
        // Does no model exists?
        Reference< XModel > xModel( xController->getModel(), UNO_QUERY );
        if ( xModel.is() == sal_True )
        {
            // Model exist - use the model as component.
            xComponent = Reference< XComponent >( xModel, UNO_QUERY );
        }
        else
        {
            // Model not exist - use the controller as component.
            xComponent = Reference< XComponent >( xController, UNO_QUERY );
        }
    }

    return xComponent;
}

//_________________________________________________________________________________________________________________
//  debug methods
//_________________________________________________________________________________________________________________

/*-----------------------------------------------------------------------------------------------------------------
    The follow methods checks the parameter for other functions. If a parameter or his value is non valid,
    we return "sal_False". (else sal_True) This mechanism is used to throw an ASSERT!

    ATTENTION

        If you miss a test for one of this parameters, contact the autor or add it himself !(?)
        But ... look for right testing! See using of this methods!
-----------------------------------------------------------------------------------------------------------------*/

#ifdef ENABLE_ASSERTIONS

//*****************************************************************************************************************
sal_Bool OComponentAccess::impldbg_checkParameter_OComponentAccessCtor( const   Reference< XDesktop >&      xOwner  )
{
    // Set default return value.
    sal_Bool bOK = sal_True;
    // Check parameter.
    if  (
            ( &xOwner       ==  NULL        )   ||
            ( xOwner.is()   ==  sal_False   )
        )
    {
        bOK = sal_False ;
    }
    // Return result of check.
    return bOK ;
}

#endif  //  #ifdef ENABLE_ASSERTIONS

}       //  namespace framework
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: threads.C,v 1.41.16.3 2007/05/28 13:35:28 amoll Exp $
//

#include <BALL/VIEW/KERNEL/threads.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/KERNEL/representation.h>
#include <BALL/VIEW/DIALOGS/FDPBDialog.h>
#include <BALL/VIEW/DATATYPE/standardDatasets.h>

#include <BALL/MOLMEC/COMMON/forceField.h>
#include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h>
#include <BALL/MOLMEC/MDSIMULATION/molecularDynamics.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>

#include <BALL/STRUCTURE/DOCKING/dockingAlgorithm.h>
#include <BALL/FORMAT/DCDFile.h>

#include <QtGui/qapplication.h>

namespace BALL
{
	namespace VIEW
	{

		BALLThread::BALLThread()
			: QThread(),
				main_control_(0),
				composite_(0)
		{
		}

		void BALLThread::output_(const String& string, bool important)
		{
			LogEvent* su = new LogEvent;
			su->setMessage(string + String("\n"));
			su->setImportant(important);
			qApp->postEvent(main_control_, su);  // Qt will delete it when done
		}

		void BALLThread::waitForUpdateOfRepresentations_()
		{
			RepresentationManager& pm = main_control_->getRepresentationManager();
			while (!main_control_->stopedSimulation() &&
					   (pm.still_to_notify_ || pm.updateRunning()))

			{
				msleep(10);
			}
		}

		void BALLThread::updateStructure_()
		{
			RepresentationManager& pm = main_control_->getRepresentationManager();
			pm.still_to_notify_ = true;
			// notify MainControl to update all Representations for the Composite
			sendMessage_(new CompositeMessage(*composite_,
																				CompositeMessage::CHANGED_COMPOSITE,
																				true));
		}

		void BALLThread::sendMessage_(Message* msg)
		{
			if (main_control_ == 0) return;
			// Qt will delete the MessageEvent when done
			qApp->postEvent(main_control_, new MessageEvent(msg));
		}

		// ==========================================

		UpdateRepresentationThread::UpdateRepresentationThread()
			: BALLThread(),
				rep_(0)
		{
			setTerminationEnabled(true);
		}

		void UpdateRepresentationThread::run()
		{
			if (main_control_ == 0) return;

			RepresentationManager& pm = main_control_->getRepresentationManager();
			Representation* rep = 0;
			while (!main_control_->isAboutToQuit())
			{
				if (!main_control_->useMultithreading())
				{
					msleep(50);
					continue;
				}

				rep = pm.popRepresentationToUpdate();
				if (rep == 0)
				{
					msleep(10);
					continue;
				}

				rep->update_();

				sendMessage_(new RepresentationMessage(*rep, RepresentationMessage::FINISHED_UPDATE));
			}
		}

		// ==========================================

		SimulationThread::SimulationThread()
			: BALLThread(),
				steps_between_updates_(0),
				dcd_file_(0)
		{
			setTerminationEnabled(true);
		}

		void SimulationThread::exportSceneToPNG_()
		{
			if (main_control_->stopedSimulation()) return;

			sendMessage_(new SceneMessage(SceneMessage::EXPORT_PNG));
		}

		void SimulationThread::finish_()
		{
			if (dcd_file_ != 0)
			{
				dcd_file_->close();
				String filename = dcd_file_->getName();
				delete dcd_file_;
				dcd_file_ = 0;
				// we will reopen the file to prevent problems when a user runs an other sim
				SnapShotManagerDataset* set = new SnapShotManagerDataset;
				set->setName(filename);
				set->setType(TrajectoryController::type);
				set->setComposite(getComposite());
				SnapShotManager* manager = new SnapShotManager((System*)getComposite(), 0,
																					new DCDFile(filename, std::ios::in));
				set->setData(manager);
				sendMessage_(new DatasetMessage(set, DatasetMessage::ADD));
			}
			sendMessage_(new FinishedSimulationMessage);
		}

		// =====================================================================
		void EnergyMinimizerThread::run()
		{
			if (main_control_ == 0) return;

			try
			{
				if (minimizer_ == 0 															||
						minimizer_->getForceField() == 0 							||
						minimizer_->getForceField()->getSystem() == 0 ||
						main_control_ == 0)
				{
					throw Exception::NullPointer(__FILE__, __LINE__);
				}

				ForceField& ff = *minimizer_->getForceField();
				bool ok = true;
				bool converged = false;
				// iterate until done and refresh the screen every "steps" iterations
				while (!main_control_->stopedSimulation() &&
								minimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() &&
								!converged && ok)
				{
					converged = minimizer_->minimize(steps_between_updates_, true);
					ok = !minimizer_->wasAborted();

					updateStructure_();
					waitForUpdateOfRepresentations_();

					QString message;
					message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A",
													minimizer_->getNumberOfIterations(),
													ff.getEnergy(), ff.getRMSGradient());
					output_(ascii(message));
				}

				updateStructure_();

				output_(ff.getResults());
				output_("final RMS gradient    : " + String(ff.getRMSGradient()) + " kJ/(mol A)   after "
								+ String(minimizer_->getNumberOfIterations()) + " iterations\n",
								true);

				if (converged) output_("converged!");
				if (!ok) output_("aborted!");
				if (minimizer_->getNumberOfIterations() == minimizer_->getMaxNumberOfIterations()) output_("max number of iterations reached!");

				finish_();

				if (!ok)
				{
					output_("Aborted minimization because convergence could not be reached. Try to restart the minimization.", true);
					return;
				}
			}
			catch(Exception::GeneralException& e)
			{
				delete dcd_file_;
				dcd_file_ = 0;

				String txt = String("Exception was thrown during minimization: ") + __FILE__ + ": " + String(__LINE__) + " :\n"
											+ e.getMessage();
				output_(txt, true);

				finish_();
			}
		}

		EnergyMinimizerThread::EnergyMinimizerThread()
			: SimulationThread(),
				minimizer_(0)
		{
		}

		EnergyMinimizerThread::~EnergyMinimizerThread()
		{
			if (minimizer_ != 0)
			{
				delete minimizer_;
			}
		}

		void EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer)
		{
			if (minimizer_ != 0)
			{
				delete minimizer_;
			}
			minimizer_ = minimizer;
		}

		// =====================================================
		void MDSimulationThread::run()
			throw(Exception::NullPointer)
		{
			if (main_control_ == 0) return;

			try
			{
				if (md_ == 0 ||
						md_->getForceField() == 0 ||
						md_->getForceField()->getSystem() == 0 ||
						main_control_ == 0)
				{
					throw Exception::NullPointer(__FILE__, __LINE__);
				}
				ForceField& ff = *md_->getForceField();

				SnapShotManager manager(ff.getSystem(), &ff, dcd_file_);
				manager.setFlushToDiskFrequency(10);
				bool ok = true;

				// iterate until done and refresh the screen every "steps" iterations
				while (ok &&
							 md_->getNumberOfIterations() < steps_ &&
							 !main_control_->stopedSimulation())
				{
					ok = md_->simulateIterations(steps_between_updates_, true);
					updateStructure_();

					waitForUpdateOfRepresentations_();

					QString message;
					message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A",
													md_->getNumberOfIterations(), ff.getEnergy(),
													ff.getRMSGradient());
					output_(ascii(message));

					if (save_images_) exportSceneToPNG_();
					if (dcd_file_) 		manager.takeSnapShot();
				}

				if (dcd_file_) manager.flushToDisk();

 				output_(ff.getResults());
				output_("final RMS gradient    : " + String(ff.getRMSGradient()) + " kJ/(mol A)   after "
								+ String(md_->getNumberOfIterations()) + " iterations\n",
								true);

				if (!ok)
				{
					output_("Simulation aborted to to strange energy values.", true);
				}

				finish_();
			}
			catch(Exception::GeneralException& e)
			{
				String txt = String("Exception was thrown during MD simulation: ")
											+ __FILE__ + ": " + String(__LINE__) + " \n" + e.getMessage();
				output_(txt, true);

				if (dcd_file_ != 0)
				{
					dcd_file_->close();
					delete dcd_file_;
					dcd_file_ = 0;
				}

				finish_();
			}
		}

		MDSimulationThread::MDSimulationThread()
			: SimulationThread(),
				md_(0),
				save_images_(false)
		{
		}

		MDSimulationThread::~MDSimulationThread()
		{
			if (md_ != 0) delete md_;
		}

		void MDSimulationThread::setMolecularDynamics(MolecularDynamics* md)
		{
			if (md_ != 0) delete md_;

			md_ = md;
		}

		// =================================================0

		CalculateFDPBThread::CalculateFDPBThread()
			: BALLThread(),
				dialog_(0)
		{}

		void CalculateFDPBThread::run()
		{
			if (dialog_ == 0) return;
			dialog_->calculate_();
		}

		// =========================== implementation of class DockingThread ================

		///
		DockingThread::DockingThread()
			: BALLThread(),
				dock_alg_(0)
		{}

		///
		DockingThread::~DockingThread()
		{
			output_("delete thread", true);

			// docking algorithm is deleted in DockingController
		}

		// Assignment operator
		const DockingThread& DockingThread::operator =(const DockingThread& dock_thread)
		{
			if (&dock_thread != this)
			{
				dock_alg_ = dock_thread.dock_alg_;
			}
			return *this;
		}

		//
		void DockingThread::setDockingAlgorithm(DockingAlgorithm* dock_alg)
		{
			dock_alg_ = dock_alg;
		}

		///
		void DockingThread::run()
			throw(Exception::NullPointer)
		{
				if (dock_alg_ == 0 ||
						main_control_ == 0)
				{
					throw Exception::NullPointer(__FILE__, __LINE__);
				}

				output_("starting docking...", true);

				dock_alg_->start();

				DockingFinishedMessage* msg = new DockingFinishedMessage(dock_alg_->wasAborted());
				// conformation set is deleted in DockResult
				msg->setConformationSet(new ConformationSet(dock_alg_->getConformationSet()));
				sendMessage_(msg);

				output_("Docking finished.", true);
		}

		// =================================================0

	} // namespace VIEW
} // namespace BALL

<commit_msg>Removed obsolete $ line in source/VIEW/KERNEL<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/VIEW/KERNEL/threads.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/KERNEL/representation.h>
#include <BALL/VIEW/DIALOGS/FDPBDialog.h>
#include <BALL/VIEW/DATATYPE/standardDatasets.h>

#include <BALL/MOLMEC/COMMON/forceField.h>
#include <BALL/MOLMEC/MINIMIZATION/energyMinimizer.h>
#include <BALL/MOLMEC/MDSIMULATION/molecularDynamics.h>
#include <BALL/MOLMEC/COMMON/snapShotManager.h>

#include <BALL/STRUCTURE/DOCKING/dockingAlgorithm.h>
#include <BALL/FORMAT/DCDFile.h>

#include <QtGui/qapplication.h>

namespace BALL
{
	namespace VIEW
	{

		BALLThread::BALLThread()
			: QThread(),
				main_control_(0),
				composite_(0)
		{
		}

		void BALLThread::output_(const String& string, bool important)
		{
			LogEvent* su = new LogEvent;
			su->setMessage(string + String("\n"));
			su->setImportant(important);
			qApp->postEvent(main_control_, su);  // Qt will delete it when done
		}

		void BALLThread::waitForUpdateOfRepresentations_()
		{
			RepresentationManager& pm = main_control_->getRepresentationManager();
			while (!main_control_->stopedSimulation() &&
					   (pm.still_to_notify_ || pm.updateRunning()))

			{
				msleep(10);
			}
		}

		void BALLThread::updateStructure_()
		{
			RepresentationManager& pm = main_control_->getRepresentationManager();
			pm.still_to_notify_ = true;
			// notify MainControl to update all Representations for the Composite
			sendMessage_(new CompositeMessage(*composite_,
																				CompositeMessage::CHANGED_COMPOSITE,
																				true));
		}

		void BALLThread::sendMessage_(Message* msg)
		{
			if (main_control_ == 0) return;
			// Qt will delete the MessageEvent when done
			qApp->postEvent(main_control_, new MessageEvent(msg));
		}

		// ==========================================

		UpdateRepresentationThread::UpdateRepresentationThread()
			: BALLThread(),
				rep_(0)
		{
			setTerminationEnabled(true);
		}

		void UpdateRepresentationThread::run()
		{
			if (main_control_ == 0) return;

			RepresentationManager& pm = main_control_->getRepresentationManager();
			Representation* rep = 0;
			while (!main_control_->isAboutToQuit())
			{
				if (!main_control_->useMultithreading())
				{
					msleep(50);
					continue;
				}

				rep = pm.popRepresentationToUpdate();
				if (rep == 0)
				{
					msleep(10);
					continue;
				}

				rep->update_();

				sendMessage_(new RepresentationMessage(*rep, RepresentationMessage::FINISHED_UPDATE));
			}
		}

		// ==========================================

		SimulationThread::SimulationThread()
			: BALLThread(),
				steps_between_updates_(0),
				dcd_file_(0)
		{
			setTerminationEnabled(true);
		}

		void SimulationThread::exportSceneToPNG_()
		{
			if (main_control_->stopedSimulation()) return;

			sendMessage_(new SceneMessage(SceneMessage::EXPORT_PNG));
		}

		void SimulationThread::finish_()
		{
			if (dcd_file_ != 0)
			{
				dcd_file_->close();
				String filename = dcd_file_->getName();
				delete dcd_file_;
				dcd_file_ = 0;
				// we will reopen the file to prevent problems when a user runs an other sim
				SnapShotManagerDataset* set = new SnapShotManagerDataset;
				set->setName(filename);
				set->setType(TrajectoryController::type);
				set->setComposite(getComposite());
				SnapShotManager* manager = new SnapShotManager((System*)getComposite(), 0,
																					new DCDFile(filename, std::ios::in));
				set->setData(manager);
				sendMessage_(new DatasetMessage(set, DatasetMessage::ADD));
			}
			sendMessage_(new FinishedSimulationMessage);
		}

		// =====================================================================
		void EnergyMinimizerThread::run()
		{
			if (main_control_ == 0) return;

			try
			{
				if (minimizer_ == 0 															||
						minimizer_->getForceField() == 0 							||
						minimizer_->getForceField()->getSystem() == 0 ||
						main_control_ == 0)
				{
					throw Exception::NullPointer(__FILE__, __LINE__);
				}

				ForceField& ff = *minimizer_->getForceField();
				bool ok = true;
				bool converged = false;
				// iterate until done and refresh the screen every "steps" iterations
				while (!main_control_->stopedSimulation() &&
								minimizer_->getNumberOfIterations() < minimizer_->getMaxNumberOfIterations() &&
								!converged && ok)
				{
					converged = minimizer_->minimize(steps_between_updates_, true);
					ok = !minimizer_->wasAborted();

					updateStructure_();
					waitForUpdateOfRepresentations_();

					QString message;
					message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A",
													minimizer_->getNumberOfIterations(),
													ff.getEnergy(), ff.getRMSGradient());
					output_(ascii(message));
				}

				updateStructure_();

				output_(ff.getResults());
				output_("final RMS gradient    : " + String(ff.getRMSGradient()) + " kJ/(mol A)   after "
								+ String(minimizer_->getNumberOfIterations()) + " iterations\n",
								true);

				if (converged) output_("converged!");
				if (!ok) output_("aborted!");
				if (minimizer_->getNumberOfIterations() == minimizer_->getMaxNumberOfIterations()) output_("max number of iterations reached!");

				finish_();

				if (!ok)
				{
					output_("Aborted minimization because convergence could not be reached. Try to restart the minimization.", true);
					return;
				}
			}
			catch(Exception::GeneralException& e)
			{
				delete dcd_file_;
				dcd_file_ = 0;

				String txt = String("Exception was thrown during minimization: ") + __FILE__ + ": " + String(__LINE__) + " :\n"
											+ e.getMessage();
				output_(txt, true);

				finish_();
			}
		}

		EnergyMinimizerThread::EnergyMinimizerThread()
			: SimulationThread(),
				minimizer_(0)
		{
		}

		EnergyMinimizerThread::~EnergyMinimizerThread()
		{
			if (minimizer_ != 0)
			{
				delete minimizer_;
			}
		}

		void EnergyMinimizerThread::setEnergyMinimizer(EnergyMinimizer* minimizer)
		{
			if (minimizer_ != 0)
			{
				delete minimizer_;
			}
			minimizer_ = minimizer;
		}

		// =====================================================
		void MDSimulationThread::run()
			throw(Exception::NullPointer)
		{
			if (main_control_ == 0) return;

			try
			{
				if (md_ == 0 ||
						md_->getForceField() == 0 ||
						md_->getForceField()->getSystem() == 0 ||
						main_control_ == 0)
				{
					throw Exception::NullPointer(__FILE__, __LINE__);
				}
				ForceField& ff = *md_->getForceField();

				SnapShotManager manager(ff.getSystem(), &ff, dcd_file_);
				manager.setFlushToDiskFrequency(10);
				bool ok = true;

				// iterate until done and refresh the screen every "steps" iterations
				while (ok &&
							 md_->getNumberOfIterations() < steps_ &&
							 !main_control_->stopedSimulation())
				{
					ok = md_->simulateIterations(steps_between_updates_, true);
					updateStructure_();

					waitForUpdateOfRepresentations_();

					QString message;
					message.sprintf("Iteration %d: energy = %f kJ/mol, RMS gradient = %f kJ/mol A",
													md_->getNumberOfIterations(), ff.getEnergy(),
													ff.getRMSGradient());
					output_(ascii(message));

					if (save_images_) exportSceneToPNG_();
					if (dcd_file_) 		manager.takeSnapShot();
				}

				if (dcd_file_) manager.flushToDisk();

 				output_(ff.getResults());
				output_("final RMS gradient    : " + String(ff.getRMSGradient()) + " kJ/(mol A)   after "
								+ String(md_->getNumberOfIterations()) + " iterations\n",
								true);

				if (!ok)
				{
					output_("Simulation aborted to to strange energy values.", true);
				}

				finish_();
			}
			catch(Exception::GeneralException& e)
			{
				String txt = String("Exception was thrown during MD simulation: ")
											+ __FILE__ + ": " + String(__LINE__) + " \n" + e.getMessage();
				output_(txt, true);

				if (dcd_file_ != 0)
				{
					dcd_file_->close();
					delete dcd_file_;
					dcd_file_ = 0;
				}

				finish_();
			}
		}

		MDSimulationThread::MDSimulationThread()
			: SimulationThread(),
				md_(0),
				save_images_(false)
		{
		}

		MDSimulationThread::~MDSimulationThread()
		{
			if (md_ != 0) delete md_;
		}

		void MDSimulationThread::setMolecularDynamics(MolecularDynamics* md)
		{
			if (md_ != 0) delete md_;

			md_ = md;
		}

		// =================================================0

		CalculateFDPBThread::CalculateFDPBThread()
			: BALLThread(),
				dialog_(0)
		{}

		void CalculateFDPBThread::run()
		{
			if (dialog_ == 0) return;
			dialog_->calculate_();
		}

		// =========================== implementation of class DockingThread ================

		///
		DockingThread::DockingThread()
			: BALLThread(),
				dock_alg_(0)
		{}

		///
		DockingThread::~DockingThread()
		{
			output_("delete thread", true);

			// docking algorithm is deleted in DockingController
		}

		// Assignment operator
		const DockingThread& DockingThread::operator =(const DockingThread& dock_thread)
		{
			if (&dock_thread != this)
			{
				dock_alg_ = dock_thread.dock_alg_;
			}
			return *this;
		}

		//
		void DockingThread::setDockingAlgorithm(DockingAlgorithm* dock_alg)
		{
			dock_alg_ = dock_alg;
		}

		///
		void DockingThread::run()
			throw(Exception::NullPointer)
		{
				if (dock_alg_ == 0 ||
						main_control_ == 0)
				{
					throw Exception::NullPointer(__FILE__, __LINE__);
				}

				output_("starting docking...", true);

				dock_alg_->start();

				DockingFinishedMessage* msg = new DockingFinishedMessage(dock_alg_->wasAborted());
				// conformation set is deleted in DockResult
				msg->setConformationSet(new ConformationSet(dock_alg_->getConformationSet()));
				sendMessage_(msg);

				output_("Docking finished.", true);
		}

		// =================================================0

	} // namespace VIEW
} // namespace BALL

<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\uti.hpp"
#include <fstream>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

template __declspec( dllexport ) class uti::UTF8String< >;

typedef uti::UTF8String< > String;

//template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( String* str )
//{
//	RETURN_WIDE_STRING( str->c_str() );
//}
template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( const String& str )
{
	RETURN_WIDE_STRING( str.c_str() );
}
//template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString(const String* str )
//{
//	RETURN_WIDE_STRING( str->c_str() );
//}

namespace utiTest
{
	TEST_CLASS( UTF8Test )
	{
	public:

		TEST_METHOD( CTorTest )
		{

			try
			{
				String::ReplacementChar = "|";
				const char blah [] = { 0xFFu, 0xC0u, 0x00 };
				String string( blah );

				Assert::AreEqual( '|', string.c_str()[ 0 ] );

				const char excpected [] = "||";

				String test( excpected );

				Assert::AreEqual( test, string );
			}
			catch( ... )
			{
				Assert::Fail();
			}

			try
			{
				const char blah [] = "Some Test";

				String string( blah );

				Assert::AreEqual( 9U, string.CharCount() );
				Assert::AreEqual( 9U, string.Size() );

			}
			catch( ... )
			{
				Assert::Fail();
			}

			try
			{
				const char test [] = "Some Test";

				String string1 = test;
				String string2 = string1;

				String string3;
				string3 = string2;

				Assert::IsTrue( string1 == string2 );
				Assert::IsTrue( string2 == string3 );
				unsigned int iterations = 0;
				for( auto it = string3.Begin(); it != string3.End(); ++it, ++iterations )
				{
					Assert::AreEqual( *it, test[ iterations ] );

				}

				Assert::AreEqual( 9U, iterations );
			}
			catch( ... )
			{
				Assert::Fail();
			}

		}

		TEST_METHOD( CTorFailTest )
		{
			try
			{
				String string( ( const char* )nullptr );

				String string2 = string;

				String string3 = string + string2;

				Assert::IsTrue( string.Size() == 0 );
				Assert::IsTrue( string.CharCount() == 0 );
				Assert::IsTrue( string2.Size() == 0 );
				Assert::IsTrue( string2.CharCount() == 0 );
				Assert::IsTrue( string3.Size() == 0 );
				Assert::IsTrue( string3.CharCount() == 0 );
			}
			catch( ... )
			{
				Assert::Fail( L"Nullptr crashed the string constructor" );
			}
		}

		TEST_METHOD( IteratorTest )
		{
			String bla( "Test" );
			const char test [] = "Test";
			unsigned int iterations = 0;
			auto it = bla.Begin();

#ifdef DEBUG

			try
			{
				it--;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

			for( ; it != bla.End(); ++it, ++iterations )
			{
				Assert::AreEqual( *it, test[ iterations ] );

			}

			Assert::AreEqual( 4U, iterations );

#ifdef DEBUG
			try
			{
				it++;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

		}

		TEST_METHOD( ReverseIterator )
		{
			String bla( "Test" );
			const char* test = "Test";
			unsigned int iterations = 0;
			auto it = bla.rBegin();

#ifdef DEBUG
			try
			{
				it--;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

			for( ; it != bla.rEnd(); ++it, ++iterations )
			{
				Assert::AreEqual( test[ 3U - iterations ], *it );
			}

			Assert::AreEqual( 4U, iterations );

#ifdef DEBUG
			try
			{
				it++;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

		}

		TEST_METHOD( ConcatTest )
		{
			String first( "Some" );
			String second( "Test" );
			String expected( "SomeTest" );
			Assert::IsTrue( ( first + second ) == expected,
				( ToString( first + second ) + ToString( " does not match " ) + ToString( expected ) ).c_str() );
		}

		TEST_METHOD( ValidityTest )
		{
			char surrogate [] = { 0xd8U, 0x00U };

			Assert::AreEqual( String::ValidChar( surrogate ), 0U );
		}

		TEST_METHOD( WCharTest )
		{
			String myString = String::FromUTF16LE( L"" );
			Assert::AreEqual( 0U, myString.CharCount(), L"Converting empty widechar didn't create an empty UTf string!" );
			Assert::AreEqual( '\0', myString.Data()[ 0 ], L"Converting empty widechar didn't has an null terminated character!" );

			myString = String::FromUTF16LE( L"WideChar" );
			String myNotWideString( "WideChar" );

			Assert::AreEqual( myNotWideString.Size(), myString.Size(), L"Converting empty widechar didn't produces correct size" );
			Assert::AreEqual( myNotWideString.CharCount(), myString.CharCount(), L"Converting empty widechar didn't produces correct charCount" );

			Assert::AreEqual( myNotWideString, myString, L"Creating the same ascii text in ascii and unicode did not match" );

		}

		TEST_METHOD( CompleteCodePointTest )
		{
			std::ifstream file;
			file.open( "../test.txt", std::ios::binary );

			if( !file.is_open() )
			{
				Assert::Fail( L"Could not open File 'test.txt'" );
			}
			else
			{
				file.seekg( 0, std::ios::end );

				size_t fileSize = (size_t)file.tellg().seekpos();

				file.seekg( 0, std::ios::beg );

				char* content = new char[ fileSize + 1 ];
				content[ fileSize ] = '\0';

				size_t pos = 0;

				do
				{
					file.read( content + pos, 1000 );
					pos += (size_t)file.gcount();
				 }while( !file.eof() && file.gcount() != 0 );

				if( pos < 4416047U ) //Exact Byte size of test.txt
				{
					Assert::Fail( (
						std::wstring( L"Failed to read " ) +
						std::to_wstring( fileSize ) +
						std::wstring( L" Bytes of data, could only read " ) +
						std::to_wstring( pos ) + std::wstring( L" Bytes!" )
						).c_str() );
					return;
				}

				file.close();

				size_t charCount = 0;

				for( size_t i = 0; i < fileSize; )
				{
					size_t length = String::ValidChar( content + i );
					if( length == 0 )
					{
						Assert::Fail( (std::wstring( L"Invalid Char at position " ) + std::to_wstring( i )).c_str() );
						break;
					}
					else
					{
						i += length;
						charCount++;
					}

				}

				String completeUTF8( content );
				Assert::AreEqual( fileSize, completeUTF8.Size() );

				//TODO check CharCount as soon as its available;

				delete content;
			}
		}

		TEST_METHOD( SubstrTest )
		{
			String string( "Hello World" );
			String expected( "Hello" );

			auto it = string.CharBegin();

			for( size_t i = 0; i < 5; i++ )
			{
				++it;
			}

			String sub = string.Substr( it );

			Assert::AreEqual( expected, sub, L"Substring does not match expected string." );
		}

	};
}
<commit_msg>Added more verification and negative tests for substring.<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\uti.hpp"
#include <fstream>

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

template __declspec( dllexport ) class uti::UTF8String< >;

typedef uti::UTF8String< > String;

//template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( String* str )
//{
//	RETURN_WIDE_STRING( str->c_str() );
//}
template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString( const String& str )
{
	RETURN_WIDE_STRING( str.c_str() );
}
//template<> std::wstring Microsoft::VisualStudio::CppUnitTestFramework::ToString(const String* str )
//{
//	RETURN_WIDE_STRING( str->c_str() );
//}

namespace utiTest
{
	TEST_CLASS( UTF8Test )
	{
	public:

		TEST_METHOD( CTorTest )
		{

			try
			{
				String::ReplacementChar = "|";
				const char blah [] = { 0xFFu, 0xC0u, 0x00 };
				String string( blah );

				Assert::AreEqual( '|', string.c_str()[ 0 ] );

				const char excpected [] = "||";

				String test( excpected );

				Assert::AreEqual( test, string );
			}
			catch( ... )
			{
				Assert::Fail();
			}

			try
			{
				const char blah [] = "Some Test";

				String string( blah );

				Assert::AreEqual( 9U, string.CharCount() );
				Assert::AreEqual( 9U, string.Size() );

			}
			catch( ... )
			{
				Assert::Fail();
			}

			try
			{
				const char test [] = "Some Test";

				String string1 = test;
				String string2 = string1;

				String string3;
				string3 = string2;

				Assert::IsTrue( string1 == string2 );
				Assert::IsTrue( string2 == string3 );
				unsigned int iterations = 0;
				for( auto it = string3.Begin(); it != string3.End(); ++it, ++iterations )
				{
					Assert::AreEqual( *it, test[ iterations ] );

				}

				Assert::AreEqual( 9U, iterations );
			}
			catch( ... )
			{
				Assert::Fail();
			}

		}

		TEST_METHOD( CTorFailTest )
		{
			try
			{
				String string( ( const char* )nullptr );

				String string2 = string;

				String string3 = string + string2;

				Assert::IsTrue( string.Size() == 0 );
				Assert::IsTrue( string.CharCount() == 0 );
				Assert::IsTrue( string2.Size() == 0 );
				Assert::IsTrue( string2.CharCount() == 0 );
				Assert::IsTrue( string3.Size() == 0 );
				Assert::IsTrue( string3.CharCount() == 0 );
			}
			catch( ... )
			{
				Assert::Fail( L"Nullptr crashed the string constructor" );
			}
		}

		TEST_METHOD( IteratorTest )
		{
			String bla( "Test" );
			const char test [] = "Test";
			unsigned int iterations = 0;
			auto it = bla.Begin();

#ifdef DEBUG

			try
			{
				it--;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

			for( ; it != bla.End(); ++it, ++iterations )
			{
				Assert::AreEqual( *it, test[ iterations ] );

			}

			Assert::AreEqual( 4U, iterations );

#ifdef DEBUG
			try
			{
				it++;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

		}

		TEST_METHOD( ReverseIterator )
		{
			String bla( "Test" );
			const char* test = "Test";
			unsigned int iterations = 0;
			auto it = bla.rBegin();

#ifdef DEBUG
			try
			{
				it--;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

			for( ; it != bla.rEnd(); ++it, ++iterations )
			{
				Assert::AreEqual( test[ 3U - iterations ], *it );
			}

			Assert::AreEqual( 4U, iterations );

#ifdef DEBUG
			try
			{
				it++;

				Assert::Fail();
			}
			catch( uti::UTFException& )
			{

			}
#endif // DEBUG

		}

		TEST_METHOD( ConcatTest )
		{
			String first( "Some" );
			String second( "Test" );
			String expected( "SomeTest" );
			Assert::IsTrue( ( first + second ) == expected,
				( ToString( first + second ) + ToString( " does not match " ) + ToString( expected ) ).c_str() );
		}

		TEST_METHOD( ValidityTest )
		{
			char surrogate [] = { 0xd8U, 0x00U };

			Assert::AreEqual( String::ValidChar( surrogate ), 0U );
		}

		TEST_METHOD( WCharTest )
		{
			String myString = String::FromUTF16LE( L"" );
			Assert::AreEqual( 0U, myString.CharCount(), L"Converting empty widechar didn't create an empty UTf string!" );
			Assert::AreEqual( '\0', myString.Data()[ 0 ], L"Converting empty widechar didn't has an null terminated character!" );

			myString = String::FromUTF16LE( L"WideChar" );
			String myNotWideString( "WideChar" );

			Assert::AreEqual( myNotWideString.Size(), myString.Size(), L"Converting empty widechar didn't produces correct size" );
			Assert::AreEqual( myNotWideString.CharCount(), myString.CharCount(), L"Converting empty widechar didn't produces correct charCount" );

			Assert::AreEqual( myNotWideString, myString, L"Creating the same ascii text in ascii and unicode did not match" );

		}

		TEST_METHOD( CompleteCodePointTest )
		{
			std::ifstream file;
			file.open( "../test.txt", std::ios::binary );

			if( !file.is_open() )
			{
				Assert::Fail( L"Could not open File 'test.txt'" );
			}
			else
			{
				file.seekg( 0, std::ios::end );

				size_t fileSize = (size_t)file.tellg().seekpos();

				file.seekg( 0, std::ios::beg );

				char* content = new char[ fileSize + 1 ];
				content[ fileSize ] = '\0';

				size_t pos = 0;

				do
				{
					file.read( content + pos, 1000 );
					pos += (size_t)file.gcount();
				 }while( !file.eof() && file.gcount() != 0 );

				if( pos < 4416047U ) //Exact Byte size of test.txt
				{
					Assert::Fail( (
						std::wstring( L"Failed to read " ) +
						std::to_wstring( fileSize ) +
						std::wstring( L" Bytes of data, could only read " ) +
						std::to_wstring( pos ) + std::wstring( L" Bytes!" )
						).c_str() );
					return;
				}

				file.close();

				size_t charCount = 0;

				for( size_t i = 0; i < fileSize; )
				{
					size_t length = String::ValidChar( content + i );
					if( length == 0 )
					{
						Assert::Fail( (std::wstring( L"Invalid Char at position " ) + std::to_wstring( i )).c_str() );
						break;
					}
					else
					{
						i += length;
						charCount++;
					}

				}

				String completeUTF8( content );
				Assert::AreEqual( fileSize, completeUTF8.Size() );

				//TODO check CharCount as soon as its available;

				delete content;
			}
		}

		TEST_METHOD( SubstrTest )
		{
			String string( "Hello World" );
			String expected( "Hello" );

			auto it = string.CharBegin();

			for( size_t i = 0; i < 5; i++ )
			{
				++it;
			}

			String sub = string.Substr( it );

			Assert::AreNotEqual( string, sub, L"Substring does match original string!" );
			Assert::AreEqual( 5U, sub.CharCount(), L"Char Size of substring does not match!" );
			Assert::AreEqual( 5U, sub.Size(), L"Byte Size of substring does not match!" );
			Assert::AreEqual( expected, sub, L"Substring does not match expected string." );
		}

	};
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#include "i_filter.hh"
#include "fb_utilities.hh"
#include "bytes.hh"
#include "utils/murmur_hash.hh"
#include "core/shared_ptr.hh"
#include <boost/dynamic_bitset.hpp>
#include <array>
#include <cstdlib>
#include "bloom_filter.hh"

namespace utils {
namespace filter {
static thread_local auto reusable_indexes = std::vector<long>();

void bloom_filter::set_indexes(uint64_t base, uint64_t inc, int count, long max, std::vector<long>& results) {
    for (int i = 0; i < count; i++) {
        results[i] = abs(base % max);
        base += inc;
    }
}

std::vector<long> bloom_filter::get_hash_buckets(const bytes_view& key, int hash_count, long max) {
    std::array<uint64_t, 2> h;
    hash(key, 0, h);

    auto indexes = std::make_unique<std::vector<long>>();

    indexes->resize(hash_count);
    set_indexes(h[0], h[1], hash_count, max, *indexes);
    return *(indexes.release());
}

std::vector<long> bloom_filter::indexes(const bytes_view& key) {
    // we use the same array both for storing the hash result, and for storing the indexes we return,
    // so that we do not need to allocate two arrays.
    auto& idx = reusable_indexes;
    std::array<uint64_t, 2> h;
    hash(key, 0, h);

    idx.resize(_hash_count);
    set_indexes(h[0], h[1], _hash_count, _bitset.size(), idx);
    return idx;
}

filter_ptr create_filter(int hash, boost::dynamic_bitset<uint64_t>&& bitset) {
    return std::make_unique<murmur3_bloom_filter>(hash, std::move(bitset));
}

filter_ptr create_filter(int hash, long num_elements, int buckets_per) {
    long num_bits = (num_elements * buckets_per) + bloom_calculations::EXCESS;
    boost::dynamic_bitset<uint64_t> bitset(num_bits);
    return std::make_unique<murmur3_bloom_filter>(hash, std::move(bitset));
}
}
}
<commit_msg>bloom_filter: no need for a unique_ptr<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

/*
 * Copyright 2015 Cloudius Systems
 *
 * Modified by Cloudius Systems
 */

#include "i_filter.hh"
#include "fb_utilities.hh"
#include "bytes.hh"
#include "utils/murmur_hash.hh"
#include "core/shared_ptr.hh"
#include <boost/dynamic_bitset.hpp>
#include <array>
#include <cstdlib>
#include "bloom_filter.hh"

namespace utils {
namespace filter {
static thread_local auto reusable_indexes = std::vector<long>();

void bloom_filter::set_indexes(uint64_t base, uint64_t inc, int count, long max, std::vector<long>& results) {
    for (int i = 0; i < count; i++) {
        results[i] = abs(base % max);
        base += inc;
    }
}

std::vector<long> bloom_filter::get_hash_buckets(const bytes_view& key, int hash_count, long max) {
    std::array<uint64_t, 2> h;
    hash(key, 0, h);

    auto indexes = std::vector<long>();

    indexes.resize(hash_count);
    set_indexes(h[0], h[1], hash_count, max, indexes);
    return indexes;
}

std::vector<long> bloom_filter::indexes(const bytes_view& key) {
    // we use the same array both for storing the hash result, and for storing the indexes we return,
    // so that we do not need to allocate two arrays.
    auto& idx = reusable_indexes;
    std::array<uint64_t, 2> h;
    hash(key, 0, h);

    idx.resize(_hash_count);
    set_indexes(h[0], h[1], _hash_count, _bitset.size(), idx);
    return idx;
}

filter_ptr create_filter(int hash, boost::dynamic_bitset<uint64_t>&& bitset) {
    return std::make_unique<murmur3_bloom_filter>(hash, std::move(bitset));
}

filter_ptr create_filter(int hash, long num_elements, int buckets_per) {
    long num_bits = (num_elements * buckets_per) + bloom_calculations::EXCESS;
    boost::dynamic_bitset<uint64_t> bitset(num_bits);
    return std::make_unique<murmur3_bloom_filter>(hash, std::move(bitset));
}
}
}
<|endoftext|>