Example #1
0
void read_binary(const std::string &filename, int n_cols, int *n_rows,
                 float **values)
{
  std::ifstream in(filename.c_str(), std::ios::binary);
  if (!in)
    throw std::runtime_error("File '" + filename + "' can't be opened.");

  in.seekg(0, in.end); // jump to the end of the file
  int length = in.tellg(); // total length of the file in bytes
  int n_values = length / sizeof(float); // number of values
  *n_rows = n_values / n_cols; // number of rows of the matrix in the binary file

  if (length % sizeof(float) != 0)
    throw std::runtime_error("The number of bytes in the file '" + filename +
                             "' is not divisible by " + d2s(sizeof(float)));

  if (n_values % n_cols != 0)
    throw std::runtime_error("The number of values in the file '" + filename +
                             "' is not divisible by the number of columns " +
                             d2s(n_cols));

  in.seekg(0, in.beg); // jump to the beginning of the file

  *values = new float[n_values];
  in.read(reinterpret_cast<char*>(*values), length); // read all at once

  if(length != static_cast<int>(in.gcount()))
    throw std::runtime_error("The number of successfully read bytes (" +
                             d2s(in.gcount()) + ") is different from the "
                             "expected one (" + d2s(length) + ")");
}
Example #2
0
void window::updateResults(double aprox, double bee) {
  working = false;
  
  widget.resultAprox->setText(d2s(aprox));
  widget.resultBee->setText(d2s(bee));
  widget.startButton->setEnabled(true);
  widget.stopButton->setEnabled(false);
}
void get_properties(const std::string &filename,
                    std::map<int, std::vector<double> > &properties)
{
  std::cout << "Getting properties..." << std::endl;
  double t_begin = get_wall_time();

  std::ifstream in(filename.c_str());
  require(in, "File " + filename + " can't be opened");

  int materialID;
  std::vector<double> values;
  int n_values = 0; // default value

  std::string line;

  while (getline(in, line)) // read the file line-by-line
  {
    // if the line is empty or starts with '#' (a comment), we skip it
    if (line.empty() || line[0] == '#') continue;

    values.clear();
    if (n_values == 0) // first run
      values.reserve(10); // we don't expect more than 10 parameters by default
    else
      values.reserve(n_values);

    std::istringstream instr(line);
    instr >> materialID;
    double val;
    while (instr >> val)
      values.push_back(val);

    if (n_values == 0)
      n_values = values.size();
    else
      require(n_values == (int)values.size(), "The number of parameters in the "
              "first appearance was " + d2s(n_values) + ", but in some line "
              "there are " + d2s(values.size()) + " of them");

    // insert the vector into the map
    std::pair<std::map<int, std::vector<double> >::const_iterator, bool> res =
        properties.insert(std::pair<int, std::vector<double> >(materialID, values));

    // check that the insertion was successfull
    require(res.second, "Insertion of the values for the material with ID =" +
            d2s(materialID) + " failed. Check the data (file = " + filename +
            ")");
  }

  in.close();

  std::cout << "Getting properties is done. Time = "
            << get_wall_time() - t_begin << std::endl;
}
int RectangularMesh::find_element(const Point2 &point,
                                  bool throw_exception) const
{
  const double px = point.x(); // coordinates of the point of interest
  const double pz = point.z();

  const double x0 = _min_coord.x(); // limits of the rect mesh
  const double x1 = _max_coord.x();
  const double z0 = _min_coord.z();
  const double z1 = _max_coord.z();

  // check that the point is within the mesh
  const double tol = FIND_CELL_TOLERANCE;
  if (px < x0 - tol || px > x1 + tol ||
      pz < z0 - tol || pz > z1 + tol)
  {
    if (throw_exception)
      require(false, "The given point " + d2s(point) + " doesn't belong "
              "to the rectangular mesh");

    return -1; // to show that the point in not here
  }

  // since the elements of the rectangular mesh are numerated in the following
  // way:
  // -----------
  // | 0  | 1  |
  // -----------
  // | 2  | 3  |
  // -----------
  // we can simplify the search of the element containing the given point:

  const double hx = (x1 - x0) / _n_elements_x;
  const double hz = (z1 - z0) / _n_elements_z;

  const int nx = std::min(static_cast<int>((px-x0)/hx), _n_elements_x-1);
  const int nz = std::min(static_cast<int>((pz-z0)/hz), _n_elements_z-1);

  if (nx < 0 || nx >= _n_elements_x ||
      nz < 0 || nz >= _n_elements_z)
  {
    if (throw_exception)
      require(false, "The rectangular element for the point " + d2s(point) +
              " wasn't found");

    return -1; // to show that the point in not here
  }

  return (nz*_n_elements_x + nx);
}
void RectangularMesh::
write_binary_files_in_cells(const std::string &prop_filename,
                            std::vector<std::string> &filenames_out) const
{
  std::cout << "Writing binary files in cells..." << std::endl;
  double t_begin = get_wall_time();

  // Create the map between the material IDs and the media properties. The
  // material IDs must exactly the same as in the given triangular mesh.
  std::map<int, std::vector<double> > properties;

  get_properties(prop_filename, properties);

  const int n_properties = properties.begin()->second.size();

  filenames_out.resize(n_properties);

  std::ofstream *out = new std::ofstream[n_properties];
  for (int i = 0; i < n_properties; ++i)
  {
    filenames_out[i] = "property" + d2s(i) + "_cells.bin";
    out[i].open(filenames_out[i].c_str(), std::ios::binary);
    require(out[i], "File '" + filenames_out[i] + "' can't be opened");
  }

  for (int i = 0; i < _n_elements_x*_n_elements_z; ++i)
  {
    const int matID = _cells_ID[i];
    std::map<int, std::vector<double> >::const_iterator iter =
        properties.find(matID);
    require(iter != properties.end(), "The material ID " + d2s(matID) +
            " wasn't found in the properties file");
    const std::vector<double> values = iter->second;

    for (int p = 0; p < n_properties; ++p)
    {
      OUT_FLOAT_TYPE val = values[p];
      out[p].write(reinterpret_cast<char*>(&val), sizeof(OUT_FLOAT_TYPE));
    }
  }

  for (int i = 0; i < n_properties; ++i)
    out[i].close();

  delete[] out;

  std::cout << "Writing binary files in cells is done. Time = "
            << get_wall_time() - t_begin << std::endl;
}
Example #6
0
void initActors(){
	for(int i=0; i<32*1024; i++){
		twi64k[i].real = d2s(32768.5*cos(-2*M_PI*i/(64*1024)));
		twi64k[i].imag = d2s(32768.5*sin(-2*M_PI*i/(64*1024)));
	}
	gen_twiddle_fft16x16_imre((short*)gen_twi32k, 32*1024);
	gen_twiddle_fft16x16_imre((short*)gen_twi16k, 16*1024);
	gen_twiddle_fft16x16_imre((short*)gen_twi8k,   8*1024);
	gen_twiddle_fft16x16_imre((short*)gen_twi4k,   4*1024);
	gen_twiddle_fft16x16_imre((short*)gen_twi2k,   2*1024);
	gen_twiddle_fft16x16_imre((short*)gen_twi1k,     1024);
	gen_twiddle_fft16x16_imre((short*)gen_twi512,     512);
	gen_twiddle_fft16x16_imre((short*)gen_twi256,     256);
	gen_twiddle_fft16x16_imre((short*)gen_twi128,     128);
}
Example #7
0
/* ======================================================================== */
void d2s_vec(double *d_vec,short *s_vec, int n)
{
 int i;
 for(i=0;i<n;i++){  
    *(s_vec+i)= d2s(*(d_vec+i));
  }
}
void RectangularMesh::
write_ASCII_files_at_nodes(const std::string &prop_filename) const
{
  std::cout << "Writing ASCII files at nodes..." << std::endl;
  double t_begin = get_wall_time();

  // Create the map between the material IDs and the media properties. The
  // material IDs must exactly the same as in the given triangular mesh.
  std::map<int, std::vector<double> > properties;

  get_properties(prop_filename, properties);

  const int n_properties = properties.begin()->second.size();

  std::vector<std::string> filenames_out(n_properties);

  std::ofstream *out = new std::ofstream[n_properties];
  for (int i = 0; i < n_properties; ++i)
  {
    filenames_out[i] = "property" + d2s(i) + "_nodes.txt";
    out[i].open(filenames_out[i].c_str(), std::ios::binary);
    require(out[i], "File '" + filenames_out[i] + "' can't be opened");
  }

  for (int i = 0; i < (_n_elements_x+1)*(_n_elements_z+1); ++i)
  {
    const int matID = _verts_ID[i];
    std::map<int, std::vector<double> >::const_iterator iter =
        properties.find(matID);
    require(iter != properties.end(), "The material ID " + d2s(matID) +
            " wasn't found in the properties file");
    const std::vector<double> values = iter->second;

    for (int p = 0; p < n_properties; ++p)
      out[p] << values[p] << "\n";
  }

  for (int i = 0; i < n_properties; ++i)
    out[i].close();

  delete[] out;

  std::cout << "Writing ASCII files at nodes is done. Time = "
            << get_wall_time() - t_begin << std::endl;
}
RectangularMesh::RectangularMesh(const Point2 &beg,
                                 const Point2 &end,
                                 int nx_,
                                 int nz_)
  : _min_coord(beg),
    _max_coord(end),
    _n_elements_x(nx_),
    _n_elements_z(nz_),
    _verts_ID(nullptr),
    _cells_ID(nullptr)
{
  require(_min_coord < _max_coord, "The max point of the mesh (" +
          d2s(_max_coord) + ") must be bigger than the min point (" +
          d2s(_min_coord) + ")");
  require(_n_elements_x > 0, "The number of elements in x-direction (" +
          d2s(_n_elements_x) + ") must be >0");
  require(_n_elements_z > 0, "The number of elements in z-direction (" +
          d2s(_n_elements_z) + ") must be >0");
}
Example #10
0
void initActors2(){
    double M = 32767.5;
//	for(int i=0; i<64*1024; i++){
//		twi64k[2*i  ] = d2s(-M*sin(-2*M_PI*i/(64*1024))/2);
//		twi64k[2*i+1] = d2s(M*cos(-2*M_PI*i/(64*1024))/2);
//	}
//	for(int i=0; i<64*1024; i++){
//		twi64k[i].real = d2s(M*cos(-2*M_PI*i/(64*1024)));
//		twi64k[i].imag = d2s(M*sin(-2*M_PI*i/(64*1024)));
//	}

    for(int r=0; r<256; r++){
    	for(int c=0; c<256; c++){
    		twi64k[r*256+c].real =  d2s(M*cos(-2*M_PI*r*c/(64*1024))/2);
    		twi64k[r*256+c].imag =  d2s(M*sin(-2*M_PI*r*c/(64*1024))/2);
    	}
    }

//    gen_twiddle_fft16x16(twi64k, 64*1024);
}
Example #11
0
void read_binary(const std::string &filename, int n_values, double *values)
{
  std::ifstream in(filename.c_str(), std::ios::binary);
  if (!in)
    throw std::runtime_error("File '" + filename + "' can't be opened.");

  in.seekg(0, in.end); // jump to the end of the file
  int length = in.tellg(); // total length of the file in bytes
  int size_value = length / n_values; // size (in bytes) of one value

  if (length % n_values != 0)
    throw std::runtime_error("The number of bytes in the file '" + filename +
                             "' is not divisible by the number of elements " +
                             d2s(n_values));

  in.seekg(0, in.beg); // jump to the beginning of the file

  if (size_value == sizeof(double))
  {
    in.read((char*)values, n_values*size_value); // read all at once

    if(n_values != static_cast<int>(in.gcount()))
      throw std::runtime_error("The number of successfully read elements is "
                               "different from the expected one");
  }
  else if (size_value == sizeof(float))
  {
    float val;
    for (int i = 0; i < n_values; ++i)  // read element-by-element
    {
      in.read((char*)&val, size_value); // read a 'float' value
      values[i] = val;                  // convert it to a 'double' value
    }
  }
  else
    throw std::runtime_error("Unknown size of an element (" + d2s(size_value) +
                             ") in bytes. Expected one is either sizeof(float) "
                             "= " + d2s(sizeof(float)) + ", or sizeof(double) "
                             "= " + d2s(sizeof(double)));
}
Example #12
0
//------------------------------------------------------------------------------
//
// Get an absolute path according to the given relative one
//
//------------------------------------------------------------------------------
std::string absolute_path(const std::string &rel_path)
{
#if defined(__linux__) || defined(__APPLE__)
  char abs_path[PATH_MAX];
  char *res = realpath(rel_path.c_str(), abs_path);
  require(res != NULL, "The function realpath() failed with the input "
          "(relative path) = '" + rel_path + "'. errno is set to " + d2s(errno)+
          " which means '" + std::string(strerror(errno)) + "'");
  return std::string(abs_path);
#else
  require(false, "absolute_path() is not implemented for this OS");
#endif
}
void RectangularMesh::
assign_material_id_at_nodes(const TriangularMesh &tri_mesh)
{
  double t0 = get_wall_time();
  std::cout << "Assigning material IDs at nodes..." << std::endl;

  _verts_ID = new int[(_n_elements_x+1)*(_n_elements_z+1)];

  const double x0 = _min_coord.x(); // limits in x-direction
  const double x1 = _max_coord.x();
  const double z0 = _min_coord.z(); // limits in z-direction
  const double z1 = _max_coord.z();
  const double hx = (x1 - x0) / _n_elements_x; // step in x-direction
  const double hz = (z1 - z0) / _n_elements_z; // step in z-direction

  const bool throw_exception = false;

  for (int iz = 0; iz < _n_elements_z+1; ++iz)
  {
    const double z = (iz == _n_elements_z ? z1 : z0 + iz*hz);
    int triangle_index = 0; // reset the index from the previous search
    for (int ix = 0; ix < _n_elements_x+1; ++ix)
    {
      const double x = (ix == _n_elements_x ? x1 : x0 + ix*hx);
      Point2 vertex(x, z);
      require(tri_mesh.contains_point(vertex), "The triangular mesh doesn't "
              "contain the point: " + d2s(vertex));

      // every search along the x-line at the same z-coordinate starts with the
      // previously found triangle
      triangle_index = tri_mesh.find_element(vertex,
                                             triangle_index,
                                             throw_exception);

      if (triangle_index < 0) // if it wasn't found
      {
        std::cout << "  full search for point " << vertex << std::endl;
        triangle_index = tri_mesh.full_search(vertex);
      }

      const int mat_ID = tri_mesh.element(triangle_index).material_id();
      _verts_ID[iz*(_n_elements_x+1)+ix] = mat_ID;
    }
  }

  std::cout << "Assigning material IDs at nodes is done. Time = "
            << get_wall_time() - t0 << std::endl;
}
void RectangularMesh::
assign_material_id_in_cells(const TriangularMesh &tri_mesh)
{
  double t0 = get_wall_time();
  std::cout << "Assigning material IDs in cells..." << std::endl;

  _cells_ID = new int[_n_elements_x*_n_elements_z];

  const double x0 = _min_coord.x(); // limits in x-direction
  const double x1 = _max_coord.x();
  const double z0 = _min_coord.z(); // limits in z-direction
  const double z1 = _max_coord.z();
  const double hx = (x1 - x0) / _n_elements_x; // step in x-direction
  const double hz = (z1 - z0) / _n_elements_z; // step in z-direction

  const bool throw_exception = false;

  for (int iz = 0; iz < _n_elements_z; ++iz)
  {
    const double zcen = z0 + (iz+0.5)*hz; // z-coord of a cell center
    int triangle_index = 0; // reset the index from the previous search
    for (int ix = 0; ix < _n_elements_x; ++ix)
    {
      const double xcen = x0 + (ix+0.5)*hx; // x-coord of a cell center
      Point2 cell_center(xcen, zcen);
      require(tri_mesh.contains_point(cell_center), "The triangular mesh "
              "doesn't contain the point: " + d2s(cell_center));

      // every search along the x-line at the same z-coordinate starts with the
      // previously found triangle
      triangle_index = tri_mesh.find_element(cell_center,
                                             triangle_index,
                                             throw_exception);

      if (triangle_index < 0) // if it wasn't found
      {
        std::cout << "  full search for point " << cell_center << std::endl;
        triangle_index = tri_mesh.full_search(cell_center);
      }

      const int mat_ID = tri_mesh.element(triangle_index).material_id();
      _cells_ID[iz*_n_elements_x + ix] = mat_ID;
    }
  }

  std::cout << "Assigning material IDs in cells is done. Time = "
            << get_wall_time() - t0 << std::endl;
}
char* Simulation::text_activeBodyRotation() {
    string outputString;
    if (ActiveBody_Type == SPHERE) {
        outputString = "Quaternion: (" + 
                d2s(Sphere_Bodies[ActiveBody_Index].quat()[0]) + ", " +
                d2s(Sphere_Bodies[ActiveBody_Index].quat()[1]) + ", " + 
                d2s(Sphere_Bodies[ActiveBody_Index].quat()[2]) + ", " + 
                d2s(Sphere_Bodies[ActiveBody_Index].quat()[3]) + ")"; 
    }
    else if (ActiveBody_Type == TRIMESH) {
         outputString = "Quaternion: (" + 
                d2s(Trimesh_Bodies[ActiveBody_Index].quat()[0]) + ", " + 
                d2s(Trimesh_Bodies[ActiveBody_Index].quat()[1]) + ", " +
                d2s(Trimesh_Bodies[ActiveBody_Index].quat()[2]) + ", " + 
                d2s(Trimesh_Bodies[ActiveBody_Index].quat()[3]) + ")"; 
    }
    return (char*)outputString.c_str();     
}
Example #16
0
//------------------------------------------------------------------------------
//
// Time measurement (wall time)
//
//------------------------------------------------------------------------------
double get_wall_time()
{
#if defined(__linux__) || defined(__APPLE__)
  struct timeval time;
  const int ierr = gettimeofday(&time, NULL);
  require(ierr == 0, "gettimeofday returned an error code " + d2s(ierr));

  return (1.0*time.tv_sec + 1.0e-6*time.tv_usec);

#elif(_WIN32)
  require(false, "Not implemented for Windows");
  return 0.;
#else
  require(false, "Not implemented for this unknown OS");
  return 0.;
#endif
}
Example #17
0
//------------------------------------------------------------------------------
//
// expect and require
//
//------------------------------------------------------------------------------
void requirement_fails(const char *file,
                       unsigned int line,
                       std::string message)
{
  std::string exc = "Exception:\nfile = " + std::string(file) +
                    "\nline = " + d2s(line) +
                    "\nmessage = " + message + "\n";

#if defined(__linux__)
  const int backtraceSize = 20;
  void *array[backtraceSize];
  int size = backtrace(array, backtraceSize);
  char **strings = backtrace_symbols(array, size);

  exc += "backtrace:\nsize = " + d2s<int>(size) + "\n";
  for (int i = 0; i < size; ++i)
    exc += std::string(strings[i]) + "\n";

  free(strings);
#endif

  throw std::runtime_error(exc);
}
Example #18
0
/* ======================================================================== */
int gen_twiddle16(short *w, int n, double scale)
{
  int i, j, k;
  
  for (j = 1, k = 0; j < n >> 2; j = j << 2)
    {
      for (i = 0; i < n >> 2; i += j << 1)
        {
	  w[k + 11] = d2s(scale * cos(6.0 * PI * (i + j) / n));
	  w[k + 10] = d2s(scale * sin(6.0 * PI * (i + j) / n));
	  w[k +  9] = d2s(scale * cos(6.0 * PI * (i    ) / n));
	  w[k +  8] = d2s(scale * sin(6.0 * PI * (i    ) / n));
	  
	  w[k +  7] = d2s(scale * cos(4.0 * PI * (i + j) / n));
	  w[k +  6] = d2s(scale * sin(4.0 * PI * (i + j) / n));
	  w[k +  5] = d2s(scale * cos(4.0 * PI * (i    ) / n));
	  w[k +  4] = d2s(scale * sin(4.0 * PI * (i    ) / n));
	  
	  w[k +  3] = d2s(scale * cos(2.0 * PI * (i + j) / n));
	  w[k +  2] = d2s(scale * sin(2.0 * PI * (i + j) / n));
	  w[k +  1] = d2s(scale * cos(2.0 * PI * (i    ) / n));
	  w[k +  0] = d2s(scale * sin(2.0 * PI * (i    ) / n));
	  
	  k += 12;
        }
    }
  
  return k;
}
Example #19
0
int
malloc_vsnprintf(char *str, size_t size, const char *format, va_list ap)
{
	int ret;
	size_t i;
	const char *f;

#define	APPEND_C(c) do {						\
	if (i < size)							\
		str[i] = (c);						\
	i++;								\
} while (0)
#define	APPEND_S(s, slen) do {						\
	if (i < size) {							\
		size_t cpylen = (slen <= size - i) ? slen : size - i;	\
		memcpy(&str[i], s, cpylen);				\
	}								\
	i += slen;							\
} while (0)
#define	APPEND_PADDED_S(s, slen, width, left_justify) do {		\
	/* Left padding. */						\
	size_t pad_len = (width == -1) ? 0 : ((slen < (size_t)width) ?	\
	    (size_t)width - slen : 0);					\
	if (left_justify == false && pad_len != 0) {			\
		size_t j;						\
		for (j = 0; j < pad_len; j++)				\
			APPEND_C(' ');					\
	}								\
	/* Value. */							\
	APPEND_S(s, slen);						\
	/* Right padding. */						\
	if (left_justify && pad_len != 0) {				\
		size_t j;						\
		for (j = 0; j < pad_len; j++)				\
			APPEND_C(' ');					\
	}								\
} while (0)
#define GET_ARG_NUMERIC(val, len) do {					\
	switch (len) {							\
	case '?':							\
		val = va_arg(ap, int);					\
		break;							\
	case '?' | 0x80:						\
		val = va_arg(ap, unsigned int);				\
		break;							\
	case 'l':							\
		val = va_arg(ap, long);					\
		break;							\
	case 'l' | 0x80:						\
		val = va_arg(ap, unsigned long);			\
		break;							\
	case 'q':							\
		val = va_arg(ap, long long);				\
		break;							\
	case 'q' | 0x80:						\
		val = va_arg(ap, unsigned long long);			\
		break;							\
	case 'j':							\
		val = va_arg(ap, intmax_t);				\
		break;							\
	case 't':							\
		val = va_arg(ap, ptrdiff_t);				\
		break;							\
	case 'z':							\
		val = va_arg(ap, ssize_t);				\
		break;							\
	case 'z' | 0x80:						\
		val = va_arg(ap, size_t);				\
		break;							\
	case 'p': /* Synthetic; used for %p. */				\
		val = va_arg(ap, uintptr_t);				\
		break;							\
	default: not_reached();						\
	}								\
} while (0)

	i = 0;
	f = format;
	while (true) {
		switch (*f) {
		case '\0': goto label_out;
		case '%': {
			bool alt_form = false;
			bool zero_pad = false;
			bool left_justify = false;
			bool plus_space = false;
			bool plus_plus = false;
			int prec = -1;
			int width = -1;
			unsigned char len = '?';

			f++;
			if (*f == '%') {
				/* %% */
				APPEND_C(*f);
				break;
			}
			/* Flags. */
			while (true) {
				switch (*f) {
				case '#':
					assert(alt_form == false);
					alt_form = true;
					break;
				case '0':
					assert(zero_pad == false);
					zero_pad = true;
					break;
				case '-':
					assert(left_justify == false);
					left_justify = true;
					break;
				case ' ':
					assert(plus_space == false);
					plus_space = true;
					break;
				case '+':
					assert(plus_plus == false);
					plus_plus = true;
					break;
				default: goto label_width;
				}
				f++;
			}
			/* Width. */
			label_width:
			switch (*f) {
			case '*':
				width = va_arg(ap, int);
				f++;
				break;
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9': {
				uintmax_t uwidth;
				set_errno(0);
				uwidth = malloc_strtoumax(f, (char **)&f, 10);
				assert(uwidth != UINTMAX_MAX || get_errno() !=
				    ERANGE);
				width = (int)uwidth;
				if (*f == '.') {
					f++;
					goto label_precision;
				} else
					goto label_length;
				break;
			} case '.':
				f++;
				goto label_precision;
			default: goto label_length;
			}
			/* Precision. */
			label_precision:
			switch (*f) {
			case '*':
				prec = va_arg(ap, int);
				f++;
				break;
			case '0': case '1': case '2': case '3': case '4':
			case '5': case '6': case '7': case '8': case '9': {
				uintmax_t uprec;
				set_errno(0);
				uprec = malloc_strtoumax(f, (char **)&f, 10);
				assert(uprec != UINTMAX_MAX || get_errno() !=
				    ERANGE);
				prec = (int)uprec;
				break;
			}
			default: break;
			}
			/* Length. */
			label_length:
			switch (*f) {
			case 'l':
				f++;
				if (*f == 'l') {
					len = 'q';
					f++;
				} else
					len = 'l';
				break;
			case 'j':
				len = 'j';
				f++;
				break;
			case 't':
				len = 't';
				f++;
				break;
			case 'z':
				len = 'z';
				f++;
				break;
			default: break;
			}
			/* Conversion specifier. */
			switch (*f) {
				char *s;
				size_t slen;
			case 'd': case 'i': {
				intmax_t val JEMALLOC_CC_SILENCE_INIT(0);
				char buf[D2S_BUFSIZE];

				GET_ARG_NUMERIC(val, len);
				s = d2s(val, (plus_plus ? '+' : (plus_space ?
				    ' ' : '-')), buf, &slen);
				APPEND_PADDED_S(s, slen, width, left_justify);
				f++;
				break;
			} case 'o': {
				uintmax_t val JEMALLOC_CC_SILENCE_INIT(0);
				char buf[O2S_BUFSIZE];

				GET_ARG_NUMERIC(val, len | 0x80);
				s = o2s(val, alt_form, buf, &slen);
				APPEND_PADDED_S(s, slen, width, left_justify);
				f++;
				break;
			} case 'u': {
				uintmax_t val JEMALLOC_CC_SILENCE_INIT(0);
				char buf[U2S_BUFSIZE];

				GET_ARG_NUMERIC(val, len | 0x80);
				s = u2s(val, 10, false, buf, &slen);
				APPEND_PADDED_S(s, slen, width, left_justify);
				f++;
				break;
			} case 'x': case 'X': {
				uintmax_t val JEMALLOC_CC_SILENCE_INIT(0);
				char buf[X2S_BUFSIZE];

				GET_ARG_NUMERIC(val, len | 0x80);
				s = x2s(val, alt_form, *f == 'X', buf, &slen);
				APPEND_PADDED_S(s, slen, width, left_justify);
				f++;
				break;
			} case 'c': {
				unsigned char val;
				char buf[2];

				assert(len == '?' || len == 'l');
				assert_not_implemented(len != 'l');
				val = va_arg(ap, int);
				buf[0] = val;
				buf[1] = '\0';
				APPEND_PADDED_S(buf, 1, width, left_justify);
				f++;
				break;
			} case 's':
				assert(len == '?' || len == 'l');
				assert_not_implemented(len != 'l');
				s = va_arg(ap, char *);
				slen = (prec == -1) ? strlen(s) : prec;
				APPEND_PADDED_S(s, slen, width, left_justify);
				f++;
				break;
			case 'p': {
				uintmax_t val;
				char buf[X2S_BUFSIZE];

				GET_ARG_NUMERIC(val, 'p');
				s = x2s(val, true, false, buf, &slen);
				APPEND_PADDED_S(s, slen, width, left_justify);
				f++;
				break;
			}
			default: not_implemented();
			}
			break;
		} default: {
			APPEND_C(*f);
			f++;
			break;
		}}
	}
	label_out:
	if (i < size)
		str[i] = '\0';
	else
		str[size - 1] = '\0';
	ret = i;

#undef APPEND_C
#undef APPEND_S
#undef APPEND_PADDED_S
#undef GET_ARG_NUMERIC
	return (ret);
}
Example #20
0
void FitterUtils::prepare_PDFs(string trigStr, string BDTVar, double BDTcut,
      string signalfile, string partrecofile, string combfile, string JpsiLeakfile,
      double minBMass, double maxBMass,
      string signaltree, string partrecotree, string combtree, string JpsiLeaktree)
{


   //***********Get the datasets
   TFile* fSignal = new TFile(signalfile.c_str());
   TTree* tSignal = (TTree*)fSignal->Get(signaltree.c_str());
   TFile* fPartReco = new TFile(partrecofile.c_str());
   TTree* tPartReco = (TTree*)fPartReco->Get(partrecotree.c_str());
   TFile* fComb = new TFile(combfile.c_str());
   TTree* tComb = (TTree*)fComb->Get(combtree.c_str()); 
   TFile* fJpsiLeak = new TFile(JpsiLeakfile.c_str());
   TTree* tJpsiLeak = (TTree*)fJpsiLeak->Get(JpsiLeaktree.c_str()); 


   //**********Define variables
   RooRealVar trigVar(trigStr.c_str(), trigStr.c_str(), -10, 10);
   RooRealVar BDTRooRealVar(BDTVar.c_str(), BDTVar.c_str(), -1,1);
   RooRealVar B_plus_M("B_plus_M", "M_{visible}", minBMass, maxBMass, "MeV");
   RooRealVar misPT("misPT", "p_{#perp}", 0, 5000, "MeV");
   RooRealVar B_plus_DTFM_M_zero("B_plus_DTFM_M_zero", "M_{constr}", 0, 20000, "MeV"); 
   RooRealVar e_plus_BremMultiplicity("e_plus_BremMultiplicity","e_plus_BremMultiplicity", -1,2);
   RooRealVar e_minus_BremMultiplicity("e_minus_BremMultiplicity","e_minus_BremMultiplicity", -1,2);

   RooRealVar weightPartReco("weightPartReco", "weightPartReco", 0, 10);
   RooRealVar weightLeakage("weightLeakage", "weightLeakage", 0, 10);
   RooRealVar dataMCWeightee("DataMCWeightee", "DataMCWeightee",0, 30);


   //***********Set only variables needed

   tSignal->SetBranchStatus("*", 0); tSignal->SetBranchStatus("B_plus_M", 1); tSignal->SetBranchStatus("misPT", 1); tSignal->SetBranchStatus("B_plus_DTFM_M_zero", 1); tSignal->SetBranchStatus(BDTVar.c_str(),1);
   tSignal->SetBranchStatus("e_plus_BremMultiplicity", 1); tSignal->SetBranchStatus("e_minus_BremMultiplicity", 1); tSignal->SetBranchStatus(trigStr.c_str()); tSignal->SetBranchStatus("DataMCWeightee",1);

   tPartReco->SetBranchStatus("*", 0); tPartReco->SetBranchStatus("B_plus_M", 1); tPartReco->SetBranchStatus("misPT", 1); tPartReco->SetBranchStatus("B_plus_DTFM_M_zero", 1);tPartReco->SetBranchStatus(BDTVar.c_str(),1);
   tPartReco->SetBranchStatus("e_plus_BremMultiplicity", 1); tPartReco->SetBranchStatus("e_minus_BremMultiplicity", 1); tPartReco->SetBranchStatus(trigStr.c_str()); tPartReco->SetBranchStatus("weightPartReco",1);

   tComb->SetBranchStatus("*", 0); tComb->SetBranchStatus("B_plus_M", 1); tComb->SetBranchStatus("misPT", 1); tComb->SetBranchStatus("B_plus_DTFM_M_zero", 1);tComb->SetBranchStatus(BDTVar.c_str(),1);
   tComb->SetBranchStatus("e_plus_BremMultiplicity", 1); tComb->SetBranchStatus("e_minus_BremMultiplicity", 1); tComb->SetBranchStatus(trigStr.c_str());

   tJpsiLeak->SetBranchStatus("*", 0); tJpsiLeak->SetBranchStatus("B_plus_M", 1); tJpsiLeak->SetBranchStatus("misPT", 1); 
   tJpsiLeak->SetBranchStatus("B_plus_DTFM_M_zero", 1);tJpsiLeak->SetBranchStatus(BDTVar.c_str(),1);
   tJpsiLeak->SetBranchStatus("e_plus_BremMultiplicity", 1); tJpsiLeak->SetBranchStatus("e_minus_BremMultiplicity", 1); tJpsiLeak->SetBranchStatus(trigStr.c_str()); 
   tJpsiLeak->SetBranchStatus("weightLeakage",1);


   //***********Set Binning


   RooBinning defaultMBins(floor((maxBMass-minBMass)/(40.)), B_plus_M.getMin(), B_plus_M.getMax() ); 
   RooBinning defaultMisPTBins(floor(40), misPT.getMin(), misPT.getMax()); 
   RooBinning broaderMBins(floor((maxBMass-minBMass)/(80.)), B_plus_M.getMin(), B_plus_M.getMax()); 
   RooBinning broaderMisPTBins(floor(40), misPT.getMin(), misPT.getMax()); 

   B_plus_M.setBinning( defaultMBins);
   misPT.setBinning( defaultMisPTBins );
   B_plus_M.setBinning( broaderMBins, "broaderBins");
   misPT.setBinning( broaderMisPTBins, "broaderBins" );

   B_plus_DTFM_M_zero.setBins(100);

   RooArgSet argset(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity);
   RooArgSet argsetPartReco(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, weightPartReco);
   RooArgSet argsetLeakage(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, weightLeakage);
   RooArgSet argsetSignal(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, dataMCWeightee);

   cout<<"getting the datasets:"<<endl;

   RooDataSet* dataSetSignalZeroGamma;
   RooDataSet* dataSetSignalOneGamma;
   RooDataSet* dataSetSignalTwoGamma;
   RooDataSet* dataSetPartReco;
   RooDataSet* dataSetJpsiLeak;
   RooDataSet* dataSetComb;

   TFile* fw(NULL);

   string BDTCutString( ("("+BDTVar+">"+d2s(BDTcut)+")").c_str()  );

   dataSetSignalZeroGamma = new RooDataSet("dataSetSignalZeroGamma", "dataSetSignalZeroGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > -0.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 0.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );

   dataSetSignalOneGamma = new RooDataSet("dataSetSignalOneGamma", "dataSetSignalOneGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > 0.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 1.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );

   dataSetSignalTwoGamma = new RooDataSet("dataSetSignalTwoGamma", "dataSetSignalTwoGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > 1.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 2.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );


   dataSetPartReco = new RooDataSet("dataSetPartReco", "dataSetPartReco",  argsetPartReco, Import(*tPartReco),Cut(("("+trigStr+"  > 0.9) && "+BDTCutString+ " && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("weightPartReco"));

   dataSetJpsiLeak = new RooDataSet("dataSetJpsiLeak", "dataSetJpsiLeak",  argsetLeakage, Import(*tJpsiLeak),Cut(("B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("weightLeakage"));

    // dataSetComb = new RooDataSet("dataSetComb", "dataSetComb", tComb, argset, ("("+trigStr+"  > 0.9) && (UBDT3R > "+d2s(BDTcut-0.03)+")  && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());
   dataSetComb = new RooDataSet("dataSetComb", "dataSetComb", tComb, argset, ("("+trigStr+"  > 0.9) && "+BDTCutString+"  && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());

   cout<<"Number of zero: "<< dataSetSignalZeroGamma->sumEntries()<<endl;
   cout<<"Number of one: "<< dataSetSignalOneGamma->sumEntries()<<endl;
   cout<<"Number of two: "<< dataSetSignalTwoGamma->sumEntries()<<endl;
   cout<<"Number of PartReco: "<< dataSetPartReco->sumEntries()<<endl;
   cout<<"Number of Jpsi leaking:"<< dataSetJpsiLeak->sumEntries()<<endl;
   cout<<"Number of combinatorial events:"<< dataSetComb->sumEntries()<<endl;


   cout<<"binning the datasets:"<<endl;

   RooArgSet argset2(B_plus_M);
   if (fit2D) argset2.add(misPT);

   RooDataHist dataHistSignalZeroGamma("dataHistSignalZeroGamma", "dataHistSignalZeroGamma", argset2, *dataSetSignalZeroGamma); 
   RooDataHist dataHistSignalOneGamma("dataHistSignalOneGamma", "dataHistSignalOneGamma", argset2, *dataSetSignalOneGamma); 
   RooDataHist dataHistSignalTwoGamma("dataHistSignalTwoGamma", "dataHistSignalTwoGamma", argset2, *dataSetSignalTwoGamma); 
   RooDataHist dataHistComb("dataHistComb", "dataHistComb", argset2, *dataSetComb); 
   RooDataHist dataHistPartReco("dataHistPartReco", "dataHistPartReco", argset2, *dataSetPartReco); 
   RooDataHist dataHistJpsiLeak("dataHistJpsiLeak", "dataHistJpsiLeak", argset2, "broaderBins");
   dataHistJpsiLeak.add(*dataSetJpsiLeak); 

   //*************** Compute Error on J/psi leak

   double ErrorJpsi(0);
   if(dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()) > 0) ErrorJpsi = 1./sqrt(dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()));
   RooRealVar fractionalErrorJpsiLeak("fractionalErrorJpsiLeak", "fractionalErrorJpsiLeak", ErrorJpsi);
   cout<<"JPSI LEAK: "<<dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());
   cout<<"JPSI LEAK fractional Error: "<<ErrorJpsi<<endl;


   //***************Create 2D histogram estimates from data


   cout<<"Preparing the 3 2D histPdf: 1";
   //   RooArgSet argset2(B_plus_M);
   RooHistPdf histPdfSignalZeroGamma("histPdfSignalZeroGamma", "histPdfSignalZeroGamma", argset2, dataHistSignalZeroGamma,2); cout<<" 2";
   RooHistPdf histPdfSignalOneGamma("histPdfSignalOneGamma", "histPdfSignalOneGamma", argset2, dataHistSignalOneGamma,2); cout<<" 3";
   RooHistPdf histPdfSignalTwoGamma("histPdfSignalTwoGamma", "histPdfSignalTwoGamma", argset2, dataHistSignalTwoGamma,2); cout<<" 4";
   RooHistPdf histPdfPartReco("histPdfPartReco", "histPdfPartReco", argset2, dataHistPartReco,2); cout<<" 5";
   RooHistPdf histPdfJpsiLeak("histPdfJpsiLeak", "histPdfJpsiLeak", argset2, dataHistJpsiLeak,2); cout<<" 6";


   //***************Create combinatorial from fit to data

   RooRealVar expoConst("expoConst", "expoConst", -1e-3, -1, 1);
   RooRealVar T("T", "T", 97, 0, 200);
   RooRealVar n("n", "n", 3.5, 1., 5.5);
   RooAbsPdf *combPDF;

   if (fit2D)
   {  
      combPDF =  new RooPTMVis("PTMVis", "PTMVis", misPT, B_plus_M, T, n, expoConst);
   }
   else
   {
      combPDF =  new RooExponential("histPdfComb", "histPdfComb", B_plus_M, expoConst);
   }



   combPDF->fitTo(*dataSetComb); // 


   if (fit2D)
   {
      T.setConstant(true);
      n.setConstant(true);
      std::cout<<"T generated is: "<<T.getVal()<<std::endl;
   }

   RooRealVar trueExp("trueExp","trueExp", expoConst.getVal(), -1000, 1000);
   trueExp.setError(expoConst.getError());

   RooRealVar trueT("trueT","trueT", T.getVal(), -1000, 1000);
   trueT.setError(T.getError());
   RooRealVar trueN("trueN","trueN", n.getVal(), -1000, 1000);
   trueN.setError(n.getError());


   //***************Save everything on a workspace
   RooWorkspace workspace("workspace", "workspace");
   workspace.import(B_plus_DTFM_M_zero);
   workspace.import(B_plus_M);
   workspace.import(misPT);
   workspace.import(expoConst);
   workspace.import(trueExp);
   workspace.import(T);
   workspace.import(n);
   workspace.import(*dataSetSignalZeroGamma);
   workspace.import(*dataSetSignalOneGamma);
   workspace.import(*dataSetSignalTwoGamma);
   workspace.import(*dataSetPartReco);
   workspace.import(*dataSetComb);
   workspace.import(*dataSetJpsiLeak);
   workspace.import(histPdfSignalZeroGamma);
   workspace.import(histPdfSignalOneGamma);
   workspace.import(histPdfSignalTwoGamma);
   workspace.import(histPdfPartReco);
   workspace.import(histPdfJpsiLeak);
   workspace.import(fractionalErrorJpsiLeak);
   workspace.import(trueT);
   workspace.import(trueN);
   workspace.writeToFile(workspacename.c_str());



   delete fComb;
   delete fSignal;
   delete fPartReco;
   if(fw!=0 && fw != NULL) delete fw;
   delete combPDF;

   delete dataSetSignalZeroGamma; 
   delete dataSetSignalOneGamma;
   delete dataSetSignalTwoGamma;
   delete dataSetPartReco;
   delete dataSetJpsiLeak;
   delete dataSetComb;
}
Example #21
0
int gen_twiddle_fft16x16(short *w, int n)
{
    int i, j, k;
    double M = 32767.5;
    const double PI = 3.141592654;

    for (j = 1, k = 0; j < n >> 2; j = j << 2) {
        for (i = 0; i < n >> 2; i += j << 1) {
            w[k + 11] =  d2s(M * cos(6.0 * PI * (i + j) / n));
            w[k + 10] =  d2s(M * sin(6.0 * PI * (i + j) / n));
            w[k +  9] =  d2s(M * cos(6.0 * PI * (i    ) / n));
            w[k +  8] =  d2s(M * sin(6.0 * PI * (i    ) / n));

            w[k +  7] = -d2s(M * cos(4.0 * PI * (i + j) / n));
            w[k +  6] = -d2s(M * sin(4.0 * PI * (i + j) / n));
            w[k +  5] = -d2s(M * cos(4.0 * PI * (i    ) / n));
            w[k +  4] = -d2s(M * sin(4.0 * PI * (i    ) / n));

            w[k +  3] =  d2s(M * cos(2.0 * PI * (i + j) / n));
            w[k +  2] =  d2s(M * sin(2.0 * PI * (i + j) / n));
            w[k +  1] =  d2s(M * cos(2.0 * PI * (i    ) / n));
            w[k +  0] =  d2s(M * sin(2.0 * PI * (i    ) / n));

            k += 12;
        }
    }
    return k;
}
Example #22
0
bool EmdL1::GreedySolution2()
{
	//- Prepare auxiliary array, D=H1-H2
	int		c,r;
	EMDTYPEArray2D D(m_n1);
	for(r=0;r<m_n1;++r)	{
		D[r].resize(m_n2);
		for(c=0;c<m_n2;++c)		D[r][c]	= m_Nodes[r][c].d;
	}


	// compute integrated values along each dimension
	std::vector<EMDTYPE>	d2s(m_n2);
	d2s[0]	= 0;
	for(c=0; c<m_n2-1; ++c)	{
		d2s[c+1]	= d2s[c];
		for(r=0; r<m_n1; ++r)	d2s[c+1]-= D[r][c];
	}

	std::vector<EMDTYPE>	d1s(m_n1);
	d1s[0]	= 0;
	for(r=0; r<m_n1-1; ++r)	{
		d1s[r+1]	= d1s[r];
		for(c=0; c<m_n2; ++c)		d1s[r+1]-= D[r][c];
	}

	//- Greedy algorithm for initial solution
	PEmdEdge	pBV;
	EMDTYPE	dFlow;
	bool	bUpward	= false;
	m_nNBV	= 0;		// number of NON-BV edges

	for(c=0; c<m_n2-1; ++c)
	for(r=0; r<m_n1; ++r) 
	{
		dFlow	= D[r][c];
		bUpward	= (r<m_n1-1) && (abs(dFlow+d2s[c+1]) > abs(dFlow+d1s[r+1]));	// Move upward or right

		// modify basic variables, record BV and related values
		if(bUpward)	{
			// move to up
			pBV	= &(m_EdgesUp[r][c]);
			m_NBVEdges[m_nNBV++]	= &(m_EdgesRight[r][c]);
			
			D[r+1][c]	+= dFlow;		// auxilary matrix maintanence
			d1s[r+1]	+= dFlow;		// auxilary matrix maintanence
		}
		else{
			// move to right, no other choice
			pBV	= &(m_EdgesRight[r][c]);
			if(r<m_n1-1)	
				m_NBVEdges[m_nNBV++]	= &(m_EdgesUp[r][c]);

			D[r][c+1]	+= dFlow;		// auxilary matrix maintanence
			d2s[c+1]	+= dFlow;		// auxilary matrix maintanence
		}

		pBV->pParent->pChild= pBV;
		pBV->flow	= abs(dFlow);
		pBV->iDir	= dFlow>0;		// 1:outward, 0:inward
	}
	
	//- rightmost column, no choice but move upward
	c	= m_n2-1;
	for(r=0; r<m_n1-1; ++r) {
		dFlow		= D[r][c];
		pBV			= &(m_EdgesUp[r][c]);

		D[r+1][c]	+= dFlow;		// auxilary matrix maintanence

		pBV->pParent->pChild= pBV;
		pBV->flow	= abs(dFlow);
		pBV->iDir	= dFlow>0;		// 1:outward, 0:inward
	}

	return true;
}
Example #23
0
bool EmdL1::GreedySolution3()
{
	//- Prepare auxiliary array, D=H1-H2
	int		i1,i2,i3;
	std::vector<EMDTYPEArray2D> D(m_n1);
	for(i1=0; i1<m_n1; ++i1) {
		D[i1].resize(m_n2);
		for(i2=0; i2<m_n2; ++i2) {
			D[i1][i2].resize(m_n3);
			for(i3=0; i3<m_n3; ++i3)	
				D[i1][i2][i3]	= m_3dNodes[i1][i2][i3].d;
		}
	}

	// compute integrated values along each dimension
	std::vector<EMDTYPE>	d1s(m_n1);
	d1s[0]	= 0;
	for(i1=0; i1<m_n1-1; ++i1)	{
		d1s[i1+1]	= d1s[i1];
		for(i2=0; i2<m_n2; ++i2)
		for(i3=0; i3<m_n3; ++i3)
			d1s[i1+1]	-= D[i1][i2][i3];
	}

	std::vector<EMDTYPE>	d2s(m_n2);
	d2s[0]	= 0;
	for(i2=0; i2<m_n2-1; ++i2)	{
		d2s[i2+1]	= d2s[i2];
		for(i1=0; i1<m_n1; ++i1)
		for(i3=0; i3<m_n3; ++i3)
			d2s[i2+1]	-= D[i1][i2][i3];
	}

	std::vector<EMDTYPE>	d3s(m_n3);
	d3s[0]	= 0;
	for(i3=0; i3<m_n3-1; ++i3)	{
		d3s[i3+1]	= d3s[i3];
		for(i1=0; i1<m_n1; ++i1)
		for(i2=0; i2<m_n2; ++i2)
			d3s[i3+1]	-= D[i1][i2][i3];
	}

	//- Greedy algorithm for initial solution
	PEmdEdge	pBV;
	EMDTYPE	dFlow, f1,f2,f3;
	m_nNBV	= 0;		// number of NON-BV edges

	for(i3=0; i3<m_n3; ++i3)
	for(i2=0; i2<m_n2; ++i2)
	for(i1=0; i1<m_n1; ++i1)
	{
		if(i3==m_n3-1 && i2==m_n2-1 && i1==m_n1-1)	break;

		//- determine which direction to move, either right or upward
		dFlow		= D[i1][i2][i3];
		f1	= i1<m_n1-1 ? abs(dFlow+d1s[i1+1]) : EMDINF;
		f2	= i2<m_n2-1 ? abs(dFlow+d2s[i2+1]) : EMDINF;
		f3	= i3<m_n3-1 ? abs(dFlow+d3s[i3+1]) : EMDINF;

		if(f1<f2 && f1<f3)	{
			pBV	= &(m_3dEdgesUp[i1][i2][i3]);				// up
			if(i2<m_n2-1)	m_NBVEdges[m_nNBV++]	= &(m_3dEdgesRight[i1][i2][i3]);	// right
			if(i3<m_n3-1)	m_NBVEdges[m_nNBV++]	= &(m_3dEdgesDeep[i1][i2][i3]);		// deep
			D[i1+1][i2][i3]	+= dFlow;						// maintain auxilary matrix
			d1s[i1+1]		+= dFlow;
		}
		else if(f2<f3)		{
			pBV	= &(m_3dEdgesRight[i1][i2][i3]);			// right
			if(i1<m_n1-1)	m_NBVEdges[m_nNBV++]	= &(m_3dEdgesUp[i1][i2][i3]);		// up
			if(i3<m_n3-1)	m_NBVEdges[m_nNBV++]	= &(m_3dEdgesDeep[i1][i2][i3]);		// deep
			D[i1][i2+1][i3]	+= dFlow;						// maintain auxilary matrix
			d2s[i2+1]		+= dFlow;
		}
		else				{
			pBV	= &(m_3dEdgesDeep[i1][i2][i3]);				// deep
			if(i2<m_n2-1)	m_NBVEdges[m_nNBV++]	= &(m_3dEdgesRight[i1][i2][i3]);	// right
			if(i1<m_n1-1)	m_NBVEdges[m_nNBV++]	= &(m_3dEdgesUp[i1][i2][i3]);		// up
			D[i1][i2][i3+1]	+= dFlow;						// maintain auxilary matrix
			d3s[i3+1]		+= dFlow;
		}

		pBV->flow	= abs(dFlow);
		pBV->iDir	= dFlow>0;		// 1:outward, 0:inward
		pBV->pParent->pChild= pBV;
	}

	return true;
}