Example #1
0
    void testValues ()
    {
        testcase ("values");

        checkValues ("0.1.2", 0, 1, 2);
        checkValues ("1.2.3", 1, 2, 3);
        checkValues ("1.2.3-rc1", 1, 2, 3, ids ("rc1"));
        checkValues ("1.2.3-rc1.debug", 1, 2, 3, ids ("rc1", "debug"));
        checkValues ("1.2.3-rc1.debug.asm", 1, 2, 3, ids ("rc1", "debug", "asm"));
        checkValues ("1.2.3+full", 1, 2, 3, ids (), ids ("full"));
        checkValues ("1.2.3+full.prod", 1, 2, 3, ids (), ids ("full", "prod"));
        checkValues ("1.2.3+full.prod.x86", 1, 2, 3, ids (), ids ("full", "prod", "x86"));
        checkValues ("1.2.3-rc1.debug.asm+full.prod.x86", 1, 2, 3,
            ids ("rc1", "debug", "asm"), ids ("full", "prod", "x86"));
    }
Example #2
0
void VisIntegrator::integrate()
{
	const size_t samp_dim = 8;

	RNG rng;
	ImageSampler image_sampler(spp, image->width, image->height);

	// Sample array
	Array<float> samps;
	samps.resize(RAYS_AT_A_TIME * samp_dim);

	// Sample pixel coordinate array
	Array<uint16_t> coords;
	coords.resize(RAYS_AT_A_TIME * 2);

	// Light path array
	Array<VisPath> paths;
	paths.resize(RAYS_AT_A_TIME);

	// Ray and Intersection arrays
	Array<Ray> rays(RAYS_AT_A_TIME);
	Array<Intersection> intersections(RAYS_AT_A_TIME);

	// ids corresponding to the rays
	Array<uint32_t> ids(RAYS_AT_A_TIME);

	bool last = false;
	while (true) {
		// Generate a bunch of samples
		std::cout << "\t--------\n\tGenerating samples" << std::endl;
		std::cout.flush();
		for (int i = 0; i < RAYS_AT_A_TIME; i++) {
			if (!image_sampler.get_next_sample(samp_dim, &(samps[i*samp_dim]), &(coords[i*2]))) {
				samps.resize(i*samp_dim);
				paths.resize(i);
				last = true;
				break;
			} else {
				paths[i].done = false;
			}
		}
		uint32_t ssize = samps.size() / samp_dim;


		// Size the ray buffer appropriately
		rays.resize(ssize);

		// Generate a bunch of camera rays
		std::cout << "\tGenerating camera rays" << std::endl;
		std::cout.flush();
		for (uint32_t i = 0; i < ssize; i++) {
			float rx = (samps[i*samp_dim] - 0.5) * (image->max_x - image->min_x);
			float ry = (0.5 - samps[i*samp_dim+1]) * (image->max_y - image->min_y);
			float dx = (image->max_x - image->min_x) / image->width;
			float dy = (image->max_y - image->min_y) / image->height;
			rays[i] = scene->camera->generate_ray(rx, ry, dx, dy, samps[i*samp_dim+4], samps[i*samp_dim+2], samps[i*samp_dim+3]);
			rays[i].finalize();
			ids[i] = i;
		}


		// Trace the camera rays
		std::cout << "\tTracing camera rays" << std::endl;
		std::cout.flush();
		tracer->trace(rays, &intersections);


		// Update paths
		std::cout << "\tUpdating paths" << std::endl;
		std::cout.flush();
		uint32_t rsize = rays.size();
		for (uint32_t i = 0; i < rsize; i++) {
			if (intersections[i].hit) {
				// Ray hit something!  Store intersection data
				paths[ids[i]].done = true;
				paths[ids[i]].col = intersections[i].col;
			} else {
				// Ray didn't hit anything, done and black background
				paths[ids[i]].done = true;
				paths[ids[i]].col = Color(0.0, 0.0, 0.0);
			}
		}


		// Accumulate the samples
		std::cout << "\tAccumulating samples" << std::endl;
		std::cout.flush();
		for (size_t i = 0; i < ssize; i++) {
			image->add_sample(paths[i].col, coords[i*2], coords[i*2+1]);
		}

		// Print percentage complete
		static int32_t last_perc = -1;
		int32_t perc = image_sampler.percentage() * 100;
		if (perc > last_perc) {
			std::cout << perc << "%" << std::endl;
			last_perc = perc;
		}

		if (callback)
			callback();

		if (last)
			break;
	}
}
Example #3
0
ErrorCode ReadGmsh::load_file(const char* filename,
                              const EntityHandle*,
                              const FileOptions&,
                              const ReaderIface::SubsetList* subset_list,
                              const Tag* file_id_tag)
{
  int num_material_sets = 0;
  const int* material_set_list = 0;
  int zero = 0;
  if (subset_list) {
    if (subset_list->tag_list_length > 1 && 
        !strcmp(subset_list->tag_list[0].tag_name, MATERIAL_SET_TAG_NAME)) {
      MB_SET_ERR(MB_UNSUPPORTED_OPERATION, "GMsh supports subset read only by material ID");
    }
    material_set_list = subset_list->tag_list[0].tag_values;
    num_material_sets = subset_list->tag_list[0].num_tag_values;
  }

  geomSets.clear();
  ErrorCode result = mdbImpl->tag_get_handle(GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER,
                                             globalId, MB_TAG_DENSE | MB_TAG_CREAT, &zero);
  if (MB_SUCCESS != result)
    return result;

  // Create set for more convenient check for material set ids
  std::set<int> blocks;
  for (const int* mat_set_end = material_set_list + num_material_sets;
       material_set_list != mat_set_end; ++material_set_list)
    blocks.insert(*material_set_list);
  
  // Map of ID->handle for nodes
  std::map<long, EntityHandle> node_id_map;
  int data_size = 8;

  // Open file and hand off pointer to tokenizer
  FILE* file_ptr = fopen(filename, "r");
  if (!file_ptr) {
    MB_SET_ERR(MB_FILE_DOES_NOT_EXIST, filename << ": " << strerror(errno));
  }
  FileTokenizer tokens(file_ptr, readMeshIface);

  // Determine file format version
  const char* const start_tokens[] = {"$NOD", "$MeshFormat", 0};
  int format_version = tokens.match_token(start_tokens);
  if (!format_version)
    return MB_FILE_DOES_NOT_EXIST;

  // If version 2.0, read additional header info
  if (2 == format_version) {
    double version;
    if (!tokens.get_doubles(1, &version))
      return MB_FILE_WRITE_ERROR;

    if (version != 2.0 && version != 2.1 && version != 2.2) {
      MB_SET_ERR(MB_FILE_DOES_NOT_EXIST, filename << ": unknown format version: " << version);
      return MB_FILE_DOES_NOT_EXIST;
    }

    int file_format;
    if (!tokens.get_integers(1, &file_format) || !tokens.get_integers(1,
        &data_size) || !tokens.match_token("$EndMeshFormat"))
           return MB_FILE_WRITE_ERROR;
           // If physical entities in the gmsh file -> discard this
    const char* const phys_tokens[] = { "$Nodes", "$PhysicalNames", 0 };
    int hasPhys = tokens.match_token(phys_tokens);

    if (hasPhys == 2) {
      long num_phys;
      if (!tokens.get_long_ints(1, &num_phys))
        return MB_FILE_WRITE_ERROR;
      for (long loop_phys = 0; loop_phys < num_phys; loop_phys++) {
        long physDim;
        long physGroupNum;
        //char const * physName;
        if (!tokens.get_long_ints(1, &physDim))
          return MB_FILE_WRITE_ERROR;
        if (!tokens.get_long_ints(1, &physGroupNum))
          return MB_FILE_WRITE_ERROR;
        const char * ptc = tokens.get_string();
        if (!ptc)
          return MB_FILE_WRITE_ERROR;
        // try to get to the end of the line, without reporting errors
        // really, we need to skip this
        while(!tokens.get_newline(false))
          ptc = tokens.get_string();
      }
      if (!tokens.match_token("$EndPhysicalNames") || !tokens.match_token(
          "$Nodes"))
        return MB_FILE_WRITE_ERROR;
    }
  }

  // Read number of nodes
  long num_nodes;
  if (!tokens.get_long_ints(1, &num_nodes))
    return MB_FILE_WRITE_ERROR;

  // Allocate nodes
  std::vector<double*> coord_arrays;
  EntityHandle handle = 0;
  result = readMeshIface->get_node_coords(3, num_nodes, MB_START_ID,
                                          handle, coord_arrays);
  if (MB_SUCCESS != result)
    return result;

  // Read nodes
  double *x = coord_arrays[0],
         *y = coord_arrays[1],
         *z = coord_arrays[2];
  for (long i = 0; i < num_nodes; ++i, ++handle) {
    long id;
    if (!tokens.get_long_ints(1, &id) ||
        !tokens.get_doubles(1, x++) ||
        !tokens.get_doubles(1, y++) ||
        !tokens.get_doubles(1, z++))
      return MB_FILE_WRITE_ERROR;

    if (!node_id_map.insert(std::pair<long, EntityHandle>(id, handle)).second) {
      MB_SET_ERR(MB_FILE_WRITE_ERROR, "Duplicate node ID at line " << tokens.line_number());
    }
  }

  // Create reverse map from handle to id
  std::vector<int> ids(num_nodes);
  std::vector<int>::iterator id_iter = ids.begin();
  std::vector<EntityHandle> handles(num_nodes);
  std::vector<EntityHandle>::iterator h_iter = handles.begin();
  for (std::map<long, EntityHandle>::iterator i = node_id_map.begin();
      i != node_id_map.end(); ++i, ++id_iter, ++h_iter) {
    *id_iter = i->first;
    * h_iter = i->second;
  }
  // Store IDs in tags
  result = mdbImpl->tag_set_data(globalId, &handles[0], num_nodes, &ids[0]);
  if (MB_SUCCESS != result)
    return result;
  if (file_id_tag) {
    result = mdbImpl->tag_set_data(*file_id_tag, &handles[0], num_nodes, &ids[0]);
    if (MB_SUCCESS != result) 
      return result;
  }
  ids.clear();
  handles.clear();

  // Get tokens signifying end of node data and start of elements
  if (!tokens.match_token(format_version == 1 ? "$ENDNOD" : "$EndNodes") ||
      !tokens.match_token(format_version == 1 ? "$ELM" : "$Elements"))
    return MB_FILE_WRITE_ERROR;

  // Get element count
  long num_elem;
  if (!tokens.get_long_ints(1, &num_elem))
    return MB_FILE_WRITE_ERROR;

  // Lists of data accumulated for elements
  std::vector<EntityHandle> connectivity;
  std::vector<int> mat_set_list, geom_set_list, part_set_list, id_list;
  // Temporary, per-element data
  std::vector<int> int_data(5), tag_data(2);
  std::vector<long> tmp_conn;
  int curr_elem_type = -1;
  for (long i = 0; i < num_elem; ++i) {
    // Read element description
    // File format 1.0
    if (1 == format_version) {
      if (!tokens.get_integers(5, &int_data[0]))
        return MB_FILE_WRITE_ERROR;
      tag_data[0] = int_data[2];
      tag_data[1] = int_data[3];
      if ((unsigned)tag_data[1] < GmshUtil::numGmshElemType &&
           GmshUtil::gmshElemTypes[tag_data[1]].num_nodes != (unsigned)int_data[4]) {
        MB_SET_ERR(MB_FILE_WRITE_ERROR, "Invalid node count for element type at line " << tokens.line_number());
      }
    }
    // File format 2.0
    else {
      if (!tokens.get_integers(3, &int_data[0]))
        return MB_FILE_WRITE_ERROR;
      tag_data.resize(int_data[2]);
      if (!tokens.get_integers(tag_data.size(), &tag_data[0]))
        return MB_FILE_WRITE_ERROR;
    }

    // If a list of material sets was specified in the
    // argument list, skip any elements for which the
    // material set is not specified or is not in the
    // passed list.
    if (!blocks.empty() && (tag_data.empty() ||
        blocks.find(tag_data[0]) != blocks.end()))
      continue;

    // If the next element is not the same type as the last one,
    // create a sequence for the block of elements we've read
    // to this point (all of the same type), and clear accumulated
    // data.
    if (int_data[1] != curr_elem_type) {
      if (!id_list.empty()) { // First iteration
        result = create_elements(GmshUtil::gmshElemTypes[curr_elem_type],
                                 id_list,
                                 mat_set_list,
                                 geom_set_list,
                                 part_set_list,
                                 connectivity,
                                 file_id_tag);
        if (MB_SUCCESS != result)
          return result;
      }

      id_list.clear();
      mat_set_list.clear();
      geom_set_list.clear();
      part_set_list.clear();
      connectivity.clear();
      curr_elem_type = int_data[1];
      if ((unsigned)curr_elem_type >= GmshUtil::numGmshElemType ||
          GmshUtil::gmshElemTypes[curr_elem_type].mb_type == MBMAXTYPE) {
        MB_SET_ERR(MB_FILE_WRITE_ERROR, "Unsupported element type " << curr_elem_type << " at line " << tokens.line_number());
      }
      tmp_conn.resize(GmshUtil::gmshElemTypes[curr_elem_type].num_nodes);
    }

    // Store data from element description
    id_list.push_back(int_data[0]);
    part_set_list.push_back(tag_data.size() > 2 ? tag_data[2] : 0);
    geom_set_list.push_back(tag_data.size() > 1 ? tag_data[1] : 0);
     mat_set_list.push_back(tag_data.size() > 0 ? tag_data[0] : 0);

    // Get element connectivity
    if (!tokens.get_long_ints(tmp_conn.size(), &tmp_conn[0]))
      return MB_FILE_WRITE_ERROR;

    // Convert connectivity from IDs to handles
    for (unsigned j = 0; j < tmp_conn.size(); ++j) {
      std::map<long, EntityHandle>::iterator k = node_id_map.find(tmp_conn[j]);
      if (k == node_id_map.end()) {
        MB_SET_ERR(MB_FILE_WRITE_ERROR, "Invalid node ID at line " << tokens.line_number());
      }
      connectivity.push_back(k->second);
    }
  } // for (num_nodes)

  // Create entity sequence for last element(s).
  if (!id_list.empty()) {
    result = create_elements(GmshUtil::gmshElemTypes[curr_elem_type],
                             id_list,
                             mat_set_list,
                             geom_set_list,
                             part_set_list,
                             connectivity,
                             file_id_tag);
    if (MB_SUCCESS != result)
      return result;
  }

  // Construct parent-child relations for geometric sets.
  // Note:  At the time this comment was written, the following
  //        function was not implemented.
  result = create_geometric_topology();
  geomSets.clear();
  return result;
}
void DirectLightingIntegrator::integrate()
{
	const size_t samp_dim = 8;

	RNG rng;
	ImageSampler image_sampler(spp, image->width, image->height);

	// Sample array
	Array<float> samps(RAYS_AT_A_TIME * samp_dim);

	// Sample pixel coordinate array
	Array<uint16_t> coords(RAYS_AT_A_TIME * 2);

	// Light path array
	Array<DLPath> paths(RAYS_AT_A_TIME);

	// Ray and Intersection arrays
	Array<Ray> rays(RAYS_AT_A_TIME);
	Array<Intersection> intersections(RAYS_AT_A_TIME);

	// ids corresponding to the rays
	Array<uint32_t> ids(RAYS_AT_A_TIME);

	bool last = false;
	while (true) {
		// Generate a bunch of samples
		std::cout << "\t--------\n\tGenerating samples" << std::endl;
		std::cout.flush();
		for (int i = 0; i < RAYS_AT_A_TIME; i++) {
			if (!image_sampler.get_next_sample(samp_dim, &(samps[i*samp_dim]), &(coords[i*2]))) {
				samps.resize(i*samp_dim);
				paths.resize(i);
				last = true;
				break;
			} else {
				paths[i].done = false;
			}
		}
		uint32_t ssize = samps.size() / samp_dim;


		// Size the ray buffer appropriately
		rays.resize(ssize);


		// Generate a bunch of camera rays
		std::cout << "\tGenerating camera rays" << std::endl;
		std::cout.flush();
		for (uint32_t i = 0; i < ssize; i++) {
			float rx = (samps[i*samp_dim] - 0.5) * (image->max_x - image->min_x);
			float ry = (0.5 - samps[i*samp_dim+1]) * (image->max_y - image->min_y);
			float dx = (image->max_x - image->min_x) / image->width;
			float dy = (image->max_y - image->min_y) / image->height;
			rays[i] = scene->camera->generate_ray(rx, ry, dx, dy, samps[i*samp_dim+4], samps[i*samp_dim+2], samps[i*samp_dim+3]);
			rays[i].finalize();
			ids[i] = i;
		}


		// Trace the camera rays
		std::cout << "\tTracing camera rays" << std::endl;
		std::cout.flush();
		tracer->trace(rays, &intersections);


		// Update paths
		std::cout << "\tUpdating paths" << std::endl;
		std::cout.flush();
		uint32_t rsize = rays.size();
		for (uint32_t i = 0; i < rsize; i++) {
			if (intersections[i].hit) {
				// Ray hit something!  Store intersection data
				paths[ids[i]].inter = intersections[i];
			} else {
				// Ray didn't hit anything, done and black background
				paths[ids[i]].done = true;
				paths[ids[i]].col = Color(0.0, 0.0, 0.0);
			}
		}


		// Generate a bunch of shadow rays
		std::cout << "\tGenerating shadow rays" << std::endl;
		std::cout.flush();
		uint32_t sri = 0; // Shadow ray index
		for (uint32_t i = 0; i < ssize; i++) {
			if (!paths[i].done) {
				// Select a light and store the normalization factor for it's output
				Light *lighty = scene->finite_lights[(uint32_t)(samps[i*samp_dim+5] * scene->finite_lights.size()) % scene->finite_lights.size()];

				// Sample the light source
				Vec3 ld;
				paths[i].lcol = lighty->sample(intersections[i].p, samps[i*samp_dim+6], samps[i*samp_dim+7], rays[i].time, &ld)
				                * (float)(scene->finite_lights.size());

				// Create a shadow ray for this path
				float d = ld.length();
				ld.normalize();
				rays[sri].o = paths[i].inter.p + paths[i].inter.offset;
				rays[sri].d = ld;
				rays[sri].time = samps[i*samp_dim+4];
				rays[sri].is_shadow_ray = true;
				rays[sri].ow = paths[i].inter.owp();
				rays[sri].dw = 0.0f;
				//rays[sri].has_differentials = false;
				rays[sri].max_t = d;
				rays[sri].finalize();

				ids[sri] = i;

				// Increment shadow ray index
				sri++;
			}
		}
		rays.resize(sri);


		// Trace the shadow rays
		std::cout << "\tTracing shadow rays" << std::endl;
		std::cout.flush();
		tracer->trace(rays, &intersections);


		// Calculate sample colors
		std::cout << "\tCalculating sample colors" << std::endl;
		std::cout.flush();
		rsize = rays.size();
		for (uint32_t i = 0; i < rsize; i++) {
			uint32_t id = ids[i];
			if (intersections[i].hit) {
				// Sample was shadowed
				paths[id].done = true;
				paths[id].col = Color(0.0, 0.0, 0.0);
			} else {
				// Sample was lit
				paths[id].inter.n.normalize();
				float lambert = dot(rays[i].d, paths[id].inter.n);
				if (lambert < 0.0) lambert = 0.0;

				paths[id].col = paths[id].lcol * lambert;
			}
		}


		// Print percentage complete
		static int32_t last_perc = -1;
		int32_t perc = image_sampler.percentage() * 100;
		if (perc > last_perc) {
			std::cout << perc << "%" << std::endl;
			last_perc = perc;
		}

		if (!Config::no_output) {
			// Accumulate the samples
			std::cout << "\tAccumulating samples" << std::endl;
			std::cout.flush();
			for (size_t i = 0; i < ssize; i++) {
				image->add_sample(paths[i].col, coords[i*2], coords[i*2+1]);
			}

			if (callback)
				callback();
		}

		if (last)
			break;
	}
}
//---------------------------------------------------------
DMat& NDG2D::ConformingHrefine2D(IMat& edgerefineflag, const DMat& Qin)
//---------------------------------------------------------
{
#if (0)
  OutputNodes(false); // volume nodes
//OutputNodes(true);  // face nodes
#endif


  // function newQ = ConformingHrefine2D(edgerefineflag, Q)
  // Purpose: apply edge splits as requested by edgerefineflag

  IVec v1("v1"), v2("v2"), v3("v3"), tvi;
  DVec x1("x1"), x2("x2"), x3("x3"), y1("y1"), y2("y2"), y3("y3");
  DVec a1("a1"), a2("a2"), a3("a3");

  // count vertices
  assert (VX.size() == Nv);

  // find vertex triplets for elements to be refined
  v1 = EToV(All,1);  v2 = EToV(All,2);  v3 = EToV(All,3);
  x1 = VX(v1);       x2 = VX(v2);       x3 = VX(v3);
  y1 = VY(v1);       y2 = VY(v2);       y3 = VY(v3);

  // find angles at each element vertex (in radians)
  VertexAngles(x1,x2,x3,y1,y2,y3, a1,a2,a3);

  // absolute value of angle size
  a1.set_abs(); a2.set_abs(); a3.set_abs();

  int k=0,k1=0,f1=0,k2=0,f2=0, e1=0,e2=0,e3=0, b1=0,b2=0,b3=0, ref=0;
  IVec m1,m2,m3; DVec mx1, my1, mx2, my2, mx3, my3;

  // create new vertices at edge centers of marked elements 
  // (use unique numbering derived from unique edge number))
  m1 = max(IVec(Nv*(v1-1)+v2+1), IVec(Nv*(v2-1)+v1+1)); mx1=0.5*(x1+x2); my1=0.5*(y1+y2);
  m2 = max(IVec(Nv*(v2-1)+v3+1), IVec(Nv*(v3-1)+v2+1)); mx2=0.5*(x2+x3); my2=0.5*(y2+y3);
  m3 = max(IVec(Nv*(v1-1)+v3+1), IVec(Nv*(v3-1)+v1+1)); mx3=0.5*(x3+x1); my3=0.5*(y3+y1);

  // ensure that both elements sharing an edge are split
  for (k1=1; k1<=K; ++k1) {
    for (f1=1; f1<=Nfaces; ++f1) {
      if (edgerefineflag(k1,f1)) {
        k2 = EToE(k1,f1); 
        f2 = EToF(k1,f1);
        edgerefineflag(k2,f2) = 1;
      }
    }
  }

  // store old data
  IMat oldEToV = EToV;  DVec oldVX = VX, oldVY = VY; 

  // count the number of elements in the refined mesh
  int newK = countrefinefaces(edgerefineflag);
  EToV.resize(newK, Nfaces, true, 0);
  IMat newBCType(newK,3, "newBCType");
  
  //   kold = [];
  IVec kold(newK, "kold");  Index1D KI,KIo;

  int sk=1, skstart=0, skend=0;

  for (k=1; k<=K; ++k)
  {
    skstart = sk;

    e1 = edgerefineflag(k,1); b1 = BCType(k,1);
    e2 = edgerefineflag(k,2); b2 = BCType(k,2);
    e3 = edgerefineflag(k,3); b3 = BCType(k,3);
    ref = e1 + 2*e2 + 4*e3;
    
    switch (ref) {

    case 0: 
      EToV(sk, All) = IVec(v1(k),v2(k),v3(k));    newBCType(sk,All) = IVec(b1, b2, b3); ++sk;
      break;

    case 1:
      EToV(sk, All) = IVec(v1(k),m1(k),v3(k));    newBCType(sk,All) = IVec(b1,  0, b3); ++sk;
      EToV(sk, All) = IVec(m1(k),v2(k),v3(k));    newBCType(sk,All) = IVec(b1, b2,  0); ++sk;
      break;

    case 2:
      EToV(sk, All) = IVec(v2(k),m2(k),v1(k));    newBCType(sk,All) = IVec(b2,  0, b1); ++sk;
      EToV(sk, All) = IVec(m2(k),v3(k),v1(k));    newBCType(sk,All) = IVec(b2, b3,  0); ++sk;
      break;

    case 4:
      EToV(sk, All) = IVec(v3(k),m3(k),v2(k));    newBCType(sk,All) = IVec(b3,  0, b2); ++sk;
      EToV(sk, All) = IVec(m3(k),v1(k),v2(k));    newBCType(sk,All) = IVec(b3, b1,  0); ++sk;
      break;

    case 3:
      EToV(sk, All) = IVec(m1(k),v2(k),m2(k));    newBCType(sk,All) = IVec(b1, b2,  0); ++sk;
      if (a1(k) > a3(k)) { // split largest angle
        EToV(sk, All) = IVec(v1(k),m1(k),m2(k));  newBCType(sk,All) = IVec(b1,  0,  0); ++sk;
        EToV(sk, All) = IVec(v1(k),m2(k),v3(k));  newBCType(sk,All) = IVec( 0, b2, b3); ++sk;
      } else {
        EToV(sk, All) = IVec(v3(k),m1(k),m2(k));  newBCType(sk,All) = IVec( 0,  0, b2); ++sk;
        EToV(sk, All) = IVec(v3(k),v1(k),m1(k));  newBCType(sk,All) = IVec(b3, b1,  0); ++sk;
      }
      break;

    case 5:
      EToV(sk, All) = IVec(v1(k),m1(k),m3(k));    newBCType(sk,All) = IVec(b1,  0, b3); ++sk;
      if (a2(k) > a3(k)) { 
        // split largest angle
        EToV(sk, All) = IVec(v2(k),m3(k),m1(k));  newBCType(sk,All) = IVec( 0,  0, b1); ++sk;
        EToV(sk, All) = IVec(v2(k),v3(k),m3(k));  newBCType(sk,All) = IVec(b2, b3,  0); ++sk;
      } else {
        EToV(sk, All) = IVec(v3(k),m3(k),m1(k));  newBCType(sk,All) = IVec(b3,  0,  0); ++sk;
        EToV(sk, All) = IVec(v3(k),m1(k),v2(k));  newBCType(sk,All) = IVec( 0, b1, b2); ++sk;
      }
      break;

    case 6:
      EToV(sk, All) = IVec(v3(k),m3(k),m2(k));    newBCType(sk,All) = IVec(b3,  0, b2); ++sk;
      if (a1(k) > a2(k)) { 
        // split largest angle
        EToV(sk, All) = IVec(v1(k),m2(k),m3(k));  newBCType(sk,All) = IVec( 0, 0, b3); ++sk;
        EToV(sk, All) = IVec(v1(k),v2(k),m2(k));  newBCType(sk,All) = IVec(b1, b2,  0); ++sk;
      } else {
        EToV(sk, All) = IVec(v2(k),m2(k),m3(k));  newBCType(sk,All) = IVec(b2,  0,  0); ++sk;
        EToV(sk, All) = IVec(v2(k),m3(k),v1(k));  newBCType(sk,All) = IVec( 0 , b3, b1); ++sk;
      }
      break;

    default:
      // split all 
      EToV(sk, All) = IVec(m1(k),m2(k),m3(k)); newBCType(sk, All) = IVec( 0, 0,  0); ++sk;
      EToV(sk, All) = IVec(v1(k),m1(k),m3(k)); newBCType(sk, All) = IVec(b1, 0, b3); ++sk;
      EToV(sk, All) = IVec(v2(k),m2(k),m1(k)); newBCType(sk, All) = IVec(b2, 0, b1); ++sk;
      EToV(sk, All) = IVec(v3(k),m3(k),m2(k)); newBCType(sk, All) = IVec(b3, 0, b2); ++sk;
      break;
    }
    
    skend = sk;

    // kold = [kold; k*ones(skend-skstart, 1)];

    // element k is to be refined into (1:4) child elements.
    // store parent element numbers in array "kold" to help 
    // with accessing parent vertex data during refinement.

    KI.reset(skstart, skend-1); // ids of child elements
    kold(KI) = k;               // mark as children of element k
  }

  // Finished with edgerefineflag.  Delete if OBJ_temp
  if (edgerefineflag.get_mode() == OBJ_temp) { 
    delete (&edgerefineflag); 
  }


  // renumber new nodes contiguously
  // ids = unique([v1;v2;v3;m1;m2;m3]);
  bool unique=true; IVec IDS, ids;
  IDS = concat( concat(v1,v2,v3), concat(m1,m2,m3) );
  ids = sort(IDS, unique);
  Nv = ids.size();

  int max_id = EToV.max_val();
  umMSG(1, "max id in EToV is %d\n", max_id);

  //         M     N   nnz vals triplet
  CSi newids(max_id,1, Nv,  1,    1  );
  //  newids = sparse(max(max(EToV)),1);

  int i=0, j=1;
  for (i=1; i<=Nv; ++i) {
  //     newids(ids)= (1:Nv);
    newids.set1(ids(i),j, i);   // load 1-based triplets
  }          // row   col x
  newids.compress();            // convert to csc form


  // Matlab -----------------------------------------------
  // v1 = newids(v1); v2 = newids(v2); v3 = newids(v3);
  // m1 = newids(m1); m2 = newids(m2); m3 = newids(m3);
  //-------------------------------------------------------

  int KVi=v1.size(), KMi=m1.size();
  // read from copies, overwrite originals 
  
  // 1. reload ids for new vertices
  tvi = v1;  for (i=1;i<=KVi;++i) {v1(i) = newids(tvi(i), 1);}
  tvi = v2;  for (i=1;i<=KVi;++i) {v2(i) = newids(tvi(i), 1);}
  tvi = v3;  for (i=1;i<=KVi;++i) {v3(i) = newids(tvi(i), 1);}

  // 2. load ids for new (midpoint) vertices
  tvi = m1;  for (i=1;i<=KMi;++i) {m1(i) = newids(tvi(i), 1);}
  tvi = m2;  for (i=1;i<=KMi;++i) {m2(i) = newids(tvi(i), 1);}
  tvi = m3;  for (i=1;i<=KMi;++i) {m3(i) = newids(tvi(i), 1);}

  VX.resize(Nv); VY.resize(Nv);
  VX(v1) =  x1; VX(v2) =  x2; VX(v3) =  x3;
  VY(v1) =  y1; VY(v2) =  y2; VY(v3) =  y3;
  VX(m1) = mx1; VX(m2) = mx2; VX(m3) = mx3;
  VY(m1) = my1; VY(m2) = my2; VY(m3) = my3;


  if (newK != (sk-1)) {
    umERROR("NDG2D::ConformingHrefine2D", "Inconsistent element count: expect %d, but sk = %d", newK, (sk-1));
  } else {
    K = newK; // sk-1;
  }

  // dumpIMat(EToV, "EToV (before)");

  // EToV = newids(EToV);
  for (j=1; j<=3; ++j) {
    for (k=1; k<=K; ++k) {
      EToV(k,j) = newids(EToV(k,j), 1);
    }
  }

#if (0)
  dumpIMat(EToV, "EToV (after)");
  // umERROR("Checking ids", "Nigel, check EToV");
#endif


  BCType = newBCType;

  Nv = VX.size();
  // xold = x; yold = y;

  StartUp2D();


#if (1)
  OutputNodes(false); // volume nodes
//OutputNodes(true);  // face nodes
//umERROR("Exiting early", "Check adapted {volume,face} nodes");
#endif


  // allocate return object
  int Nfields = Qin.num_cols();
  DMat* tmpQ = new DMat(Np*K, Nfields, "newQ", OBJ_temp);
  DMat& newQ = *tmpQ;  // use a reference for syntax

  // quick return, if no interpolation is required
  if (Qin.size()<1) {
    return newQ;
  }

  
  DVec rOUT(Np),sOUT(Np),xout,yout,xy1(2),xy2(2),xy3(2),tmp(2),rhs;
  int ko=0,kv1=0,kv2=0,kv3=0,n=0;  DMat A(2,2), interp;
  DMat oldQ = const_cast<DMat&>(Qin);

  for (k=1; k<=K; ++k)
  {
    ko = kold(k); xout = x(All,k); yout = y(All,k);
    kv1=oldEToV(ko,1); kv2=oldEToV(ko,2); kv3=oldEToV(ko,3);
    xy1.set(oldVX(kv1), oldVY(kv1));
    xy2.set(oldVX(kv2), oldVY(kv2));
    xy3.set(oldVX(kv3), oldVY(kv3));
    A.set_col(1, xy2-xy1); A.set_col(2, xy3-xy1);
    
    for (i=1; i<=Np; ++i) {
      tmp.set(xout(i), yout(i));
      rhs = 2.0*tmp - xy2 - xy3;
      tmp = A|rhs;
      rOUT(i) = tmp(1);
      sOUT(i) = tmp(2);
    }

    KI.reset (Np*(k -1)+1, Np*k );  // nodes in new element k
    KIo.reset(Np*(ko-1)+1, Np*ko);  // nodes in old element ko

    interp = Vandermonde2D(N, rOUT, sOUT)*invV;

    for (n=1; n<=Nfields; ++n) 
    {
    //newQ(:,k,n)= interp*  Q(:,ko,n);
      //DVec tm1 = interp*oldQ(KIo,n);
      //dumpDVec(tm1, "tm1");
      newQ(KI,n) = interp*oldQ(KIo,n);
    }
  }
    
  return newQ;
}
void 
ICUServiceTest::testAPI_Two()
{
    UErrorCode status = U_ZERO_ERROR;
    TestStringService service;
    service.registerFactory(new AnonymousStringFactory(), status);

    // anonymous factory will still handle the id
    {
        UErrorCode status = U_ZERO_ERROR;
        const UnicodeString en_US = "en_US";
        UnicodeString* result = (UnicodeString*)service.get(en_US, status);
        confirmEqual("21) locale", result, &en_US);
        delete result;
    }

    // still normalizes id
    {
        UErrorCode status = U_ZERO_ERROR;
        const UnicodeString en_US_BAR = "en_US_BAR";
        UnicodeString resultID;
        UnicodeString* result = (UnicodeString*)service.get("EN_us_bar", &resultID, status);
        confirmEqual("22) locale", &resultID, &en_US_BAR);
        delete result;
    }

    // we can override for particular ids
    UnicodeString* singleton0 = new UnicodeString("Zero");
    service.registerInstance(singleton0, "en_US_BAR", status);
    {
        UErrorCode status = U_ZERO_ERROR;
        UnicodeString* result = (UnicodeString*)service.get("en_US_BAR", status);
        confirmEqual("23) override super", result, singleton0);
        delete result;
    }

    // empty service should not recognize anything 
    service.reset();
    {
        UErrorCode status = U_ZERO_ERROR;
        UnicodeString* result = (UnicodeString*)service.get("en_US", status);
        confirmIdentical("24) empty", result, NULL);
    }

    // create a custom multiple key factory
    {
        UnicodeString xids[] = {
            "en_US_VALLEY_GIRL", 
            "en_US_VALLEY_BOY",
            "en_US_SURFER_GAL",
            "en_US_SURFER_DUDE"
        };
        int32_t count = sizeof(xids)/sizeof(UnicodeString);

        ICUServiceFactory* f = new TestMultipleKeyStringFactory(xids, count, "Later");
        service.registerFactory(f, status);
    }

    // iterate over the visual ids returned by the multiple factory
    {
        UErrorCode status = U_ZERO_ERROR;
        UVector ids(uhash_deleteUnicodeString, uhash_compareUnicodeString, 0, status);
        service.getVisibleIDs(ids, status);
        for (int i = 0; i < ids.size(); ++i) {
            const UnicodeString* id = (const UnicodeString*)ids[i];
            UnicodeString* result = (UnicodeString*)service.get(*id, status);
            if (result) {
                logln("  " + *id + " --> " + *result);
                delete result;
            } else {
                errln("could not find " + *id);
            }
        }
        // four visible ids
        confirmIdentical("25) visible ids", ids.size(), 4);
    }

    // iterate over the display names
    {
        UErrorCode status = U_ZERO_ERROR;
        UVector names(status);
        service.getDisplayNames(names, status);
        for (int i = 0; i < names.size(); ++i) {
            const StringPair* pair = (const StringPair*)names[i];
            logln("  " + pair->displayName + " --> " + pair->id);
        }
        confirmIdentical("26) display names", names.size(), 4);
    }

    // no valid display name
    {
        UnicodeString name;
        service.getDisplayName("en_US_VALLEY_GEEK", name);
        confirmBoolean("27) get display name", name.isBogus());
    }

    {
        UnicodeString name;
        service.getDisplayName("en_US_SURFER_DUDE", name, Locale::getEnglish());
        confirmStringsEqual("28) get display name", name, "English (United States, SURFER_DUDE)");
    }

    // register another multiple factory
    {
        UnicodeString xids[] = {
            "en_US_SURFER", 
            "en_US_SURFER_GAL", 
            "en_US_SILICON", 
            "en_US_SILICON_GEEK",
        };
        int32_t count = sizeof(xids)/sizeof(UnicodeString);

        ICUServiceFactory* f = new TestMultipleKeyStringFactory(xids, count, "Rad dude");
        service.registerFactory(f, status);
    }

    // this time, we have seven display names
    // Rad dude's surfer gal 'replaces' Later's surfer gal
    {
        UErrorCode status = U_ZERO_ERROR;
        UVector names(status);
        service.getDisplayNames(names, Locale("es"), status);
        for (int i = 0; i < names.size(); ++i) {
            const StringPair* pair = (const StringPair*)names[i];
            logln("  " + pair->displayName + " --> " + pair->id);
        }
        confirmIdentical("29) display names", names.size(), 7);
    }

    // we should get the display name corresponding to the actual id
    // returned by the id we used.
    {
        UErrorCode status = U_ZERO_ERROR;
        UnicodeString actualID;
        UnicodeString id = "en_us_surfer_gal";
        UnicodeString* gal = (UnicodeString*)service.get(id, &actualID, status);
        if (gal != NULL) {
            UnicodeString displayName;
            logln("actual id: " + actualID);
            service.getDisplayName(actualID, displayName, Locale::getEnglish());
            logln("found actual: " + *gal + " with display name: " + displayName);
            confirmBoolean("30) found display name for actual", !displayName.isBogus());

            service.getDisplayName(id, displayName, Locale::getEnglish());
            logln("found actual: " + *gal + " with display name: " + displayName);
            confirmBoolean("31) found display name for query", displayName.isBogus());

            delete gal;
        } else {
            errln("30) service could not find entry for " + id);
        }
    }

    // this should be handled by the 'dude' factory, since it overrides en_US_SURFER.
    {
        UErrorCode status = U_ZERO_ERROR;
        UnicodeString actualID;
        UnicodeString id = "en_US_SURFER_BOZO";
        UnicodeString* bozo = (UnicodeString*)service.get(id, &actualID, status);
        if (bozo != NULL) {
            UnicodeString displayName;
            service.getDisplayName(actualID, displayName, Locale::getEnglish());
            logln("found actual: " + *bozo + " with display name: " + displayName);
            confirmBoolean("32) found display name for actual", !displayName.isBogus());

            service.getDisplayName(id, displayName, Locale::getEnglish());
            logln("found actual: " + *bozo + " with display name: " + displayName);
            confirmBoolean("33) found display name for query", displayName.isBogus());

            delete bozo;
        } else {
            errln("32) service could not find entry for " + id);
        }
    }

    // certainly not default...
    {
        confirmBoolean("34) is default ", !service.isDefault());
    }

    {
        UErrorCode status = U_ZERO_ERROR;
        UVector ids(uhash_deleteUnicodeString, uhash_compareUnicodeString, 0, status);
        service.getVisibleIDs(ids, status);
        for (int i = 0; i < ids.size(); ++i) {
            const UnicodeString* id = (const UnicodeString*)ids[i];
            msgstr(*id + "? ", service.get(*id, status));
        }

        logstr("valleygirl?  ", service.get("en_US_VALLEY_GIRL", status));
        logstr("valleyboy?   ", service.get("en_US_VALLEY_BOY", status));
        logstr("valleydude?  ", service.get("en_US_VALLEY_DUDE", status));
        logstr("surfergirl?  ", service.get("en_US_SURFER_GIRL", status));
    }
}
JSObject *
GlobalObject::initFunctionAndObjectClasses(JSContext *cx)
{
    JS_THREADSAFE_ASSERT(cx->compartment != cx->runtime->atomsCompartment);
    JS_ASSERT(isNative());

    /*
     * Calling a function from a cleared global triggers this (yeah, I know).
     * Uncomment this once bug 470510 is fixed (if that bug doesn't remove
     * isCleared entirely).
     */
    // JS_ASSERT(!isCleared());

    /* If cx has no global object, make this the global object. */
    if (!cx->globalObject)
        JS_SetGlobalObject(cx, this);

    /*
     * Create |Object.prototype| first, mirroring CreateBlankProto but for the
     * prototype of the created object.
     */
    JSObject *objectProto = NewObjectWithGivenProto(cx, &ObjectClass, NULL, this);
    if (!objectProto || !objectProto->setSingletonType(cx))
        return NULL;

    /*
     * The default 'new' type of Object.prototype is required by type inference
     * to have unknown properties, to simplify handling of e.g. heterogenous
     * objects in JSON and script literals.
     */
    if (!objectProto->setNewTypeUnknown(cx))
        return NULL;

    /* Create |Function.prototype| next so we can create other functions. */
    JSFunction *functionProto;
    {
        JSObject *proto = NewObjectWithGivenProto(cx, &FunctionClass, objectProto, this);
        if (!proto)
            return NULL;

        /*
         * Bizarrely, |Function.prototype| must be an interpreted function, so
         * give it the guts to be one.
         */
        functionProto = js_NewFunction(cx, proto, NULL, 0, JSFUN_INTERPRETED, this, NULL);
        if (!functionProto)
            return NULL;
        JS_ASSERT(proto == functionProto);
        functionProto->flags |= JSFUN_PROTOTYPE;

        JSScript *script =
            JSScript::NewScript(cx, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, JSVERSION_DEFAULT);
        if (!script)
            return NULL;
        script->noScriptRval = true;
        script->code[0] = JSOP_STOP;
        script->code[1] = SRC_NULL;
        functionProto->initScript(script);
        functionProto->getType(cx)->interpretedFunction = functionProto;
        script->setFunction(functionProto);

        if (!proto->setSingletonType(cx))
            return NULL;

        /*
         * The default 'new' type of Function.prototype is required by type
         * inference to have unknown properties, to simplify handling of e.g.
         * CloneFunctionObject.
         */
        if (!proto->setNewTypeUnknown(cx))
            return NULL;
    }

    /* Create the Object function now that we have a [[Prototype]] for it. */
    jsid objectId = ATOM_TO_JSID(CLASS_ATOM(cx, Object));
    JSFunction *objectCtor;
    {
        JSObject *ctor = NewObjectWithGivenProto(cx, &FunctionClass, functionProto, this);
        if (!ctor)
            return NULL;
        objectCtor = js_NewFunction(cx, ctor, js_Object, 1, JSFUN_CONSTRUCTOR, this,
                                    JSID_TO_ATOM(objectId));
        if (!objectCtor)
            return NULL;
        JS_ASSERT(ctor == objectCtor);

        objectCtor->setConstructorClass(&ObjectClass);
    }

    /*
     * Install |Object| and |Object.prototype| for the benefit of subsequent
     * code that looks for them.
     */
    setObjectClassDetails(objectCtor, objectProto);

    /* Create |Function| so it and |Function.prototype| can be installed. */
    jsid functionId = ATOM_TO_JSID(CLASS_ATOM(cx, Function));
    JSFunction *functionCtor;
    {
        JSObject *ctor =
            NewObjectWithGivenProto(cx, &FunctionClass, functionProto, this);
        if (!ctor)
            return NULL;
        functionCtor = js_NewFunction(cx, ctor, Function, 1, JSFUN_CONSTRUCTOR, this,
                                      JSID_TO_ATOM(functionId));
        if (!functionCtor)
            return NULL;
        JS_ASSERT(ctor == functionCtor);

        functionCtor->setConstructorClass(&FunctionClass);
    }

    /*
     * Install |Function| and |Function.prototype| so that we can freely create
     * functions and objects without special effort.
     */
    setFunctionClassDetails(functionCtor, functionProto);

    /*
     * The hard part's done: now go back and add all the properties these
     * primordial values have.
     */
    if (!LinkConstructorAndPrototype(cx, objectCtor, objectProto) ||
        !DefinePropertiesAndBrand(cx, objectProto, object_props, object_methods) ||
        !DefinePropertiesAndBrand(cx, objectCtor, NULL, object_static_methods) ||
        !LinkConstructorAndPrototype(cx, functionCtor, functionProto) ||
        !DefinePropertiesAndBrand(cx, functionProto, NULL, function_methods) ||
        !DefinePropertiesAndBrand(cx, functionCtor, NULL, NULL))
    {
        return NULL;
    }

    /* Add the global Function and Object properties now. */
    if (!addDataProperty(cx, objectId, JSProto_Object + JSProto_LIMIT * 2, 0))
        return NULL;
    if (!addDataProperty(cx, functionId, JSProto_Function + JSProto_LIMIT * 2, 0))
        return NULL;

    /* Heavy lifting done, but lingering tasks remain. */

    /* ES5 15.1.2.1. */
    jsid id = ATOM_TO_JSID(cx->runtime->atomState.evalAtom);
    JSObject *evalobj = js_DefineFunction(cx, this, id, eval, 1, JSFUN_STUB_GSOPS);
    if (!evalobj)
        return NULL;
    setOriginalEval(evalobj);

    /* ES5 13.2.3: Construct the unique [[ThrowTypeError]] function object. */
    JSFunction *throwTypeError = js_NewFunction(cx, NULL, ThrowTypeError, 0, 0, this, NULL);
    if (!throwTypeError)
        return NULL;
    AutoIdVector ids(cx);
    if (!throwTypeError->preventExtensions(cx, &ids))
        return NULL;
    setThrowTypeError(throwTypeError);

    /*
     * The global object should have |Object.prototype| as its [[Prototype]].
     * Eventually we'd like to have standard classes be there from the start,
     * and thus we would know we were always setting what had previously been a
     * null [[Prototype]], but right now some code assumes it can set the
     * [[Prototype]] before standard classes have been initialized.  For now,
     * only set the [[Prototype]] if it hasn't already been set.
     */
    if (shouldSplicePrototype(cx) && !splicePrototype(cx, objectProto))
        return NULL;

    /*
     * Notify any debuggers about the creation of the script for
     * |Function.prototype| -- after all initialization, for simplicity.
     */
    js_CallNewScriptHook(cx, functionProto->script(), functionProto);
    return functionProto;
}
TEST_F(InstanceTest, Set_construction) {
    SetInstance ids("String", "create:", std::vector<std::string>({"ids"}));
    EXPECT_EQ(ids.type(), "Set");
    EXPECT_EQ(ids.name(), "ids");
    EXPECT_EQ(ids.representation(), "{}");
}
void
passwd_cache::loadConfig() {
		// initialize cache with any configured mappings
	char *usermap_str = param("USERID_MAP");
	if( !usermap_str ) {
		return;
	}

		// format is "username=uid,gid,gid2,gid3,... user2=uid2,gid2,..."
		// first split on spaces, which separate the records
		// If gid2 is "?", then we assume that supplemental groups
		// are unknown.
	StringList usermap(usermap_str," ");
	free( usermap_str );

	char *username;
	usermap.rewind();
	while( (username=usermap.next()) ) {
		char *userids = strchr(username,'=');
		ASSERT( userids );
		*userids = '\0';
		userids++;

			// the user ids are separated by commas
		StringList ids(userids,",");
		ids.rewind();

		struct passwd pwent;

		char const *idstr = ids.next();
		uid_t uid;
		gid_t gid;
		if( !idstr || !parseUid(idstr,&uid) ) {
			EXCEPT("Invalid USERID_MAP entry %s=%s",username,userids);
		}
		idstr = ids.next();
		if( !idstr || !parseGid(idstr,&gid) ) {
			EXCEPT("Invalid USERID_MAP entry %s=%s",username,userids);
		}
		pwent.pw_name = username;
		pwent.pw_uid = uid;
		pwent.pw_gid = gid;
		cache_uid(&pwent);

		idstr = ids.next();
		if( idstr && !strcmp(idstr,"?") ) {
			continue; // no information about supplemental groups
		}

		ids.rewind();
		ids.next(); // go to first group id

		group_entry *group_cache_entry;
		if ( group_table->lookup(username, group_cache_entry) < 0 ) {
			init_group_entry(group_cache_entry);
		}

			/* now get the group list */
		if ( group_cache_entry->gidlist != NULL ) {
			delete[] group_cache_entry->gidlist;
			group_cache_entry->gidlist = NULL;
		}
		group_cache_entry->gidlist_sz = ids.number()-1;
		group_cache_entry->gidlist = new
			gid_t[group_cache_entry->gidlist_sz];

		unsigned g;
		for(g=0; g<group_cache_entry->gidlist_sz; g++) {
			idstr = ids.next();
			ASSERT( idstr );

			if( !parseGid(idstr,&group_cache_entry->gidlist[g]) ) {
				EXCEPT("Invalid USERID_MAP entry %s=%s",username,userids);
			}
		}

			/* finally, insert info into our cache */
		group_cache_entry->lastupdated = time(NULL);
		group_table->insert(username, group_cache_entry);
	}
}
void loadcontainers()
{

	cScpIterator*	iter = NULL;
	std::string	script1,
			script2;
	SI32 		gump = INVALID;
	BasicPosition	uprleft = {INVALID,INVALID};
	BasicPosition	dwnrght = {INVALID,INVALID};
	UI32VECTOR	*vet = new UI32VECTOR;

	int cont=0;

	int loopexit=0;
	do
	{
		safedelete(iter);
		iter = Scripts::Containers->getNewIterator("SECTION CONTAINER %i", cont++);
		if( iter==NULL ) continue;

		gump = INVALID;
		uprleft.x = INVALID;
		uprleft.y = INVALID;
		dwnrght.x = INVALID;
		dwnrght.y = INVALID;
		vet->clear();

		do
		{

			iter->parseLine(script1, script2);
			if ( script1[0]!='}' && script1[0]!='{' )
			{
				if	( "ID" == script1 )
					vet->push_back( str2num( script2 ) );
				else if ( "GUMP" == script1 )
					gump = str2num( script2 );
				else if ( "X1" == script1 )
					uprleft.x= str2num( script2 );
				else if ( "Y1" == script1 )
					uprleft.y= str2num( script2 );
				else if ( "X2" == script1 )
					dwnrght.x= str2num( script2 );
				else if ( "Y2" == script1 )
					dwnrght.y= str2num( script2 );
				else
					WarnOut("[ERROR] wrong line ( %s ) parsed on containers.xss", script1.c_str() );
			}
		}
		while ( script1[0] !='}' && ++loopexit < MAXLOOPS );

		if( (gump!=INVALID) && (uprleft.x!=INVALID) && (dwnrght.x!=INVALID) && (uprleft.y!=INVALID) && (dwnrght.y!=INVALID) )
		{
			cont_gump_st dummy;

			dummy.downright = dwnrght;
			dummy.upperleft = uprleft;
			dummy.gump	= gump;

			contInfoGump[gump] = dummy;

			CONTINFOGUMPMAP::iterator iter( contInfoGump.find(gump) );
			if( iter != contInfoGump.end() )
			{
				UI32VECTOR::iterator ids( vet->begin() ), end( vet->end() );
				for(; ids != end; ++ids )
					contInfo[(*ids)] = iter;
			}
			else
				ConOut("[ERROR] on parse of containers.xss" );
		}
		else
			ConOut("[ERROR] on parse of containers.xss" );
	}
	while ( script1 != "EOF" && ++loopexit < MAXLOOPS );

	safedelete(iter);

//	ConOut("\n");
//	for(CONTINFOMAP::iterator debug=contInfo.begin(); debug!=contInfo.end(); debug++ )
//		ConOut( "id %i ha gump %i \n ", debug->first, (debug->second)->second.gump);



}
Example #11
0
//---------------------------------------------------------
void NDG3D::Hrefine3D(IVec& refineflag)
//---------------------------------------------------------
{
  DVec lVX("lVX"), lVY("lVY"), lVZ("lVZ");

  int a=1, b=2, c=3, d=4, e=5, 
      f=6, g=7, h=8, i=9, j=10;

  //             a b c d  e    f    g    h    i    j
  lVX.load(10, " 0 1 0 0  0.5  0.5  0.0  0.0  0.5  0.0 ");
  lVY.load(10, " 0 0 1 0  0.0  0.5  0.5  0.0  0.0  0.5 ");
  lVZ.load(10, " 0 0 0 1  0.0  0.0  0.0  0.5  0.5  0.5 ");

  assert(4 == Nfaces);

  IMat lEToV(8,4, "lEToV"), im84(8,4, "im84"), oFnodes(4,6, "oFnodes");

  set84(lEToV, 8,4, 
           a, e, g, h,
	         e, b, f, i,
	         g, f, c, j,
	         h, i, j, d,
	         e, g, h, i,
	         h, i, g, j,
	         e, f, g, i,
	         g, i, f, j);

  set46(oFnodes, 4,6, 
           a, e, b, f, c, g,
	         a, e, b, i, d, h,
	         b, f, c, j, d, i,
	         a, g, c, j, d, h);

  IMat vnum(gRowData, 4,3, "1 2 3  1 2 4  2 3 4  3 1 4");

  int lK = lEToV.num_rows();
  IMat lBCType(lK, Nfaces), tm1, tm2;
  IVec tv(3),tv1,tv2, oFn,vnp,ksids;
  int kk=0,ff=0,oo=0;
  for (kk=1; kk<=lK; ++kk) {
    for (ff=1; ff<=Nfaces; ++ff) {
      for (oo=1; oo<=Nfaces; ++oo) 
      {
        oFn = oFnodes.get_row(oo);
        vnp = vnum.get_row(ff);
        tm1 = lEToV(kk, vnp);  const IVec& knodes = dynamic_cast<const IVec&>(tm1);

      //tv = intersect(lEToV(k, vnum(p,All)), oFnodes(o,All));
        tv = intersect(knodes, oFn);

        if ( tv.length()==3 ) {
	        lBCType(kk, ff) = oo;
        }
      }
    }
  }

  int NV = VX.length()+1;
  int sp_len = NV + NV*NV;

  // sparse buffers   nnz  vals,triplet
  CSd newVX(sp_len,1,  NV,    1,  1);
  CSd newVY(sp_len,1,  NV,    1,  1);
  CSd newVZ(sp_len,1,  NV,    1,  1);

  Index1D II(1, NV-1);
  newVX(II,1) = VX;
  newVY(II,1) = VY;
  newVZ(II,1) = VZ;

  IVec ids("ids");
  int oldK = K, f1=0;

  for (int k1=1; k1<=oldK; ++k1) {
    if (refineflag(k1)) 
    {
      a = EToV(k1,1); 
      b = EToV(k1,2); 
      c = EToV(k1,3); 
      d = EToV(k1,4);

      e = NV + std::max(a*NV+b, b*NV + a);
      f = NV + std::max(b*NV+c, c*NV + b);
      g = NV + std::max(a*NV+c, c*NV + a);
      h = NV + std::max(a*NV+d, d*NV + a);
      i = NV + std::max(b*NV+d, d*NV + b);
      j = NV + std::max(c*NV+d, d*NV + c);

    //ks = [k1, K+1:K+7];
      IVec ks(1, k1);  ks.append(Range(K+1,K+7));

      //--------------------------
      // EToV(ks,:) = [a e g h;
		  //               e b f i;
		  //               g f c j;
		  //               h i j d;
		  //               e g h i;
		  //               h i g j;
		  //               e f g i;
		  //               g i f j];
      //--------------------------

      set84(im84, 8,4, 
            a, e, g, h,
		        e, b, f, i,
		        g, f, c, j,
		        h, i, j, d,
		        e, g, h, i,
		        h, i, g, j,
		        e, f, g, i,
		        g, i, f, j);

    //EToV(ks,All) = im84;
      EToV.merge_rows(ks, im84);

      for (f1=1; f1<=Nfaces; ++f1) 
      {
        tv = lBCType(All,f1);
        ids = find(tv, '!', 0);
        ksids = ks(ids);
        tm1 = lBCType(ids,f1);
        tm2 = BCType(k1, (const IVec&)tm1);

        // expand BCType to accommodate new range
        int maxI=ksids.max_val(), maxR=BCType.num_rows();
        if (maxI>maxR) {BCType.realloc(maxI, BCType.num_cols());}

        BCType(ksids,f1) = trans(tm2);
      }

      K += 7;

      newVX.set1(e,1, 0.5*(VX(a)+VX(b))); 
      newVX.set1(f,1, 0.5*(VX(b)+VX(c)));
      newVX.set1(g,1, 0.5*(VX(c)+VX(a)));
      newVX.set1(h,1, 0.5*(VX(a)+VX(d)));
      newVX.set1(i,1, 0.5*(VX(b)+VX(d)));
      newVX.set1(j,1, 0.5*(VX(c)+VX(d)));

      newVY.set1(e,1, 0.5*(VY(a)+VY(b)));
      newVY.set1(f,1, 0.5*(VY(b)+VY(c)));
      newVY.set1(g,1, 0.5*(VY(c)+VY(a)));
      newVY.set1(h,1, 0.5*(VY(a)+VY(d)));
      newVY.set1(i,1, 0.5*(VY(b)+VY(d)));
      newVY.set1(j,1, 0.5*(VY(c)+VY(d)));

      newVZ.set1(e,1, 0.5*(VZ(a)+VZ(b)));
      newVZ.set1(f,1, 0.5*(VZ(b)+VZ(c)));
      newVZ.set1(g,1, 0.5*(VZ(c)+VZ(a)));
      newVZ.set1(h,1, 0.5*(VZ(a)+VZ(d)));
      newVZ.set1(i,1, 0.5*(VZ(b)+VZ(d)));
      newVZ.set1(j,1, 0.5*(VZ(c)+VZ(d)));
    }
  }

  //-------------------------------------
  // drop duplicates and sort
  //-------------------------------------
  newVX.compress(true);
  newVY.compress(true);
  newVZ.compress(true);

//ids = sort(unique(EToV(:)), 'ascend');
  ids = unique(EToV);


  int len=ids.max_val(); 
  IVec gnum(len);
  gnum(ids) = Range(1,ids.length());

  VX = full( newVX, ids );
  VY = full( newVY, ids );
  VZ = full( newVZ, ids );

  // EToV = gnum(EToV);
  EToV.set_map(EToV, gnum);

  int NV_old = NV-1;        // local counters
  this->Nv = VX.length();   // update member variable

  umLOG(1, "Hrefine3D [%d] : old Nv = %4d, new Nv = %4d\n", ++refine_count, NV_old, Nv);
  umLOG(1, "                old K  = %4d, new K  = %4d\n\n", oldK, K);


#if (0)
  tetramesh(EToV, [VX', VY', VZ'])
#endif

}
ExportTranslationNotes::ExportTranslationNotes(const ustring & filename, const vector < unsigned int >&ids_to_display, bool export_all)
// Exports the notes from the database.
/*
The exported xml file will look so:

<?xml version="1.0" encoding="UTF-8"?>
<bibledit-notes version="3">
  <note>
    <reference>
    </reference>
    <project>
    </project>
    <category>
    </category>
    <text>
    </text>
    <date-created>
    </date-created>
    <date-modified>
    </date-modified>
    <user>
    </user>
  </note>
</bibledit-notes>

This is subject to change as bibledit's notes system develops.
*/
:progresswindow("Exporting notes", true)
{
  // Save variables.
  my_export_all = export_all;

  // Start process.
  try {

    // Write to outputfile.
    WriteText wt(filename);
    my_wt = &wt;

    // Opening lines.
    wt.text("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    wt.text("<bibledit-notes version=\"4\">\n");

    // Connect to index database.
    // Note: The index is not the source of the notes.
    // This implies that, if the index is not up-to-date, 
    // then the export will not be correct.
    error = NULL;
    rc = sqlite3_open(notes_index_filename().c_str(), &db);
    if (rc)
      throw runtime_error(sqlite3_errmsg(db));
    sqlite3_busy_timeout(db, 1000);
    
    // Currently this is the notes table schema:
    // id integer, reference text, project text, category text, casefolded text, created integer, modified integer

    // Get the number of notes.
    SqliteReader sqlitereader(0);
    rc = sqlite3_exec(db, "select count(*) from notes;", sqlitereader.callback, &sqlitereader, &error);
    if (rc != SQLITE_OK) {
      throw runtime_error(error);
    }
    if (!sqlitereader.ustring0.empty()) {
      notes_count = convert_to_int (sqlitereader.ustring0[0]);
    }
    progresswindow.set_iterate(0, 1, notes_count);

    // Exporting everything or a selection?
    set < gint > ids(ids_to_display.begin(), ids_to_display.end());
    my_ids = &ids;

    // Go through all the notes.
    note_counter = 0;
    rc = sqlite3_exec(db, "select reference, project, category, casefolded, created, modified from notes;", data_callback, this, &error);
    if (rc != SQLITE_OK) {
      throw runtime_error(error);
    }
    // Closing lines.
    wt.text("</bibledit-notes>\n");

  }
  catch(exception & ex) {
    if (!progresswindow.cancel) {
      gtkw_dialog_error(NULL, ex.what());
      gw_critical(ex.what());
    }
  }
}
void
PlanarAdjacencyAnnotator::annotate(Crag& crag) {

	if (optionCragType.as<std::string>() == "empty")
		return;

	UTIL_TIME_METHOD;

	util::box<float, 3> cragBB = crag.getBoundingBox();

	util::point<float, 3> resolution;
	for (Crag::NodeIt n(crag); n != lemon::INVALID; ++n) {

		if (!crag.isLeafNode(n))
			continue;

		resolution = crag.getVolume(n).getResolution();
		break;
	}

	// no nodes?
	if (resolution.isZero())
		return;

	// create a vigra multi-array large enough to hold all volumes
	vigra::MultiArray<3, int> ids(
			vigra::Shape3(
				cragBB.width() /resolution.x(),
				cragBB.height()/resolution.y(),
				cragBB.depth() /resolution.z()),
			std::numeric_limits<int>::max());

	for (Crag::NodeIt n(crag); n != lemon::INVALID; ++n) {

		if (!crag.isLeafNode(n))
			continue;

		const util::point<float, 3>&      volumeOffset     = crag.getVolume(n).getOffset();
		const util::box<unsigned int, 3>& volumeDiscreteBB = crag.getVolume(n).getDiscreteBoundingBox();

		util::point<unsigned int, 3> begin = (volumeOffset - cragBB.min())/resolution;
		util::point<unsigned int, 3> end   = begin +
				util::point<unsigned int, 3>(
						volumeDiscreteBB.width(),
						volumeDiscreteBB.height(),
						volumeDiscreteBB.depth());

		vigra::combineTwoMultiArrays(
				crag.getVolume(n).data(),
				ids.subarray(
						vigra::Shape3(
								begin.x(),
								begin.y(),
								begin.z()),
						vigra::Shape3(
								end.x(),
								end.y(),
								end.z())),
				ids.subarray(
						vigra::Shape3(
								begin.x(),
								begin.y(),
								begin.z()),
						vigra::Shape3(
								end.x(),
								end.y(),
								end.z())),
				vigra::functor::ifThenElse(
						vigra::functor::Arg1() == vigra::functor::Param(1),
						vigra::functor::Param(crag.id(n)),
						vigra::functor::Arg2()
				));
	}

	//vigra::exportImage(
			//ids.bind<2>(0),
			//vigra::ImageExportInfo("debug/ids.tif"));

	typedef vigra::GridGraph<3>       GridGraphType;
	typedef vigra::AdjacencyListGraph RagType;

	GridGraphType grid(
			ids.shape(),
			_neighborhood == Direct ? vigra::DirectNeighborhood : vigra::IndirectNeighborhood);
	RagType rag;
	RagType::EdgeMap<std::vector<GridGraphType::Edge>> affiliatedEdges;

	vigra::makeRegionAdjacencyGraph(
			grid,
			ids,
			rag,
			affiliatedEdges,
			std::numeric_limits<int>::max());

	unsigned int numAdded = 0;
	crag.setGridGraph(grid);
	for (RagType::EdgeIt e(rag); e != lemon::INVALID; ++e) {

		int u = rag.id(rag.u(*e));
		int v = rag.id(rag.v(*e));

		Crag::Edge newEdge = crag.addAdjacencyEdge(
				crag.nodeFromId(u),
				crag.nodeFromId(v));
		crag.setAffiliatedEdges(
				newEdge,
				affiliatedEdges[*e]);
		numAdded++;

		LOG_ALL(planaradjacencyannotatorlog)
				<< "adding leaf node adjacency between "
				<< u << " and " << v << std::endl;
	}

	LOG_USER(planaradjacencyannotatorlog)
			<< "added " << numAdded << " leaf node adjacency edges"
			<< std::endl;

	if (optionCragType.as<std::string>() == "full")
		propagateLeafAdjacencies(crag);
}
Example #14
0
void NETWORK::get_coordinates( double _z, double _dx, double _dy, std::vector<double>& _lrc, std::vector<double>& _x, std::vector<double>& _y ) const
{
  /// create reachable set sizes
  std::vector<double> rss( Order, 0.0 );
  for(int i=0; i<Order; i++)
    rss[i] = (double)Order * _lrc[i];

  /// make levels
  // sort local reaching centralities
  std::vector<int> ids( Order, 0 );
  for(int i=0; i<Order; i++)
    ids[i] = i;
  int len = Order;
  double rss_elem;
  int id;
  bool swapped = false;
  do
  {
    swapped = false;
    for(int i=1; i<len; i++)
    {
      if( rss[i-1] > rss[i] )
      {
        rss_elem = rss[i-1];
        rss[i-1] = rss[i];
        rss[i] = rss_elem;
        id = ids[i-1];
        ids[i-1] = ids[i];
        ids[i] = id;
        swapped = true;
      }
    }
    len--;
  } while( swapped );

  // network reaching centrality mean and variance
  double global_av = 0.0;
  double global_sd = 0.0;
  double threshold = 0.0;
  for(int i=0; i<Order; i++)
  {
    global_av += rss[i];
    global_sd += rss[i]*rss[i];
  }
  global_av /= (double)Order;
  global_sd = sqrt( fabs(global_sd/(double)Order - global_av*global_av) );
  threshold = _z * global_sd + 0.00001; // in case of GRC = 0

  // sort nodes in levels
  int number_of_levels = 0;
  int level_first_node = 0;
  int current_node = 1;
  std::vector<int> levels( Order, -1 );
  levels[0] = 0;
  // start putting nodes in level until we reach last node
  while( current_node < Order )
  {
    // pick the next node and calculate level average and standard deviation
    double level_av = 0.0;
    double level_sd = 0.0;
    for(int i=level_first_node; i<=current_node; i++)
    {
      level_av += rss[i];
      level_sd += rss[i]*rss[i];
    }
    level_av /= 1 + current_node - level_first_node;
    level_sd = sqrt( fabs(level_sd/double(1+current_node-level_first_node) - level_av*level_av) );

    // if level deviation is lower than the threshold, keep node, otherwise start new level and put node there
    if( level_sd < threshold )
    {
      levels[current_node] = number_of_levels;
      current_node++;
    }
    else
    {
      levels[current_node] = number_of_levels + 1;
      number_of_levels++;
      level_first_node = current_node;
      current_node++;
    }
  }
  number_of_levels++;

  /// set y coordinates
  std::vector<int> nodes_per_level( number_of_levels, 0 );
  // calculate level averages
  std::vector<double> averages( number_of_levels, 0.0 );
  for(int i=0; i<Order; i++)
  {
    averages[levels[i]] += rss[i];
    nodes_per_level[levels[i]]++;
  }
  for(int i=0; i<number_of_levels; i++)
    averages[i] /= nodes_per_level[i];

  std::vector<double> y_differences( number_of_levels, 0.0 );
  std::vector<double> y_coordinates( number_of_levels, 0.0 );
  y_differences[0] = 0.0;
  y_coordinates[0] = 0.0;
  double minimum_difference = _dy * (double)Order;
  for(int i=1; i<number_of_levels; i++)
  {
    y_differences[i] = log( averages[i]-averages[i-1] + 1.0 );

    if( y_differences[i] < minimum_difference )
      minimum_difference = y_differences[i];
  }
  for(int i=1; i<number_of_levels; i++)
    y_coordinates[i] = y_coordinates[i-1] + _dy*y_differences[i]/minimum_difference;

  _y.assign( Order, 0.0 );
  for(int i=0; i<Order; i++)
    _y[ids[i]] = y_coordinates[levels[i]];

  /// set x coordinates
  std::vector<double> x_coordinate_starts( number_of_levels, 0.0 );
  for(int i=0; i<number_of_levels; i++)
  {
    x_coordinate_starts[i] = -0.5 * _dx * (nodes_per_level[i] - 1);
    nodes_per_level[i] = 0;
  }
  _x.assign( Order, 0.0 );
  for(int i=0; i<Order; i++)
  {
    _x[ids[i]] = x_coordinate_starts[levels[i]] + _dx * nodes_per_level[levels[i]];
    nodes_per_level[levels[i]]++;
  }
}
//---------------------------------------------------------
void NDG2D::MakeCylinder2D
(
  const IMat& faces, 
  double ra,
  double xo,
  double yo
)
//---------------------------------------------------------
{
  // Function: MakeCylinder2D(faces, ra, xo, yo)
  // Purpose:  Use Gordon-Hall blending with an isoparametric  
  //           map to modify a list of faces so they conform 
  //           to a cylinder of radius r centered at (xo,yo)

  int NCurveFaces = faces.num_rows();
  IVec vflag(VX.size()); IMat VFlag(EToV.num_rows(),EToV.num_cols());
  int n=0,k=0,f=0,v1=0,v2=0;
  double theta1=0.0,theta2=0.0,x1=0.0,x2=0.0,y1=0.0,y2=0.0;
  double newx1=0.0,newx2=0.0,newy1=0.0,newy2=0.0;
  DVec vr, fr, theta, fdx,fdy, vdx, vdy, blend,numer,denom;
  IVec va,vb,vc, ks, Fm_f, ids;  DMat Vface, Vvol;

  for (n=1; n<=NCurveFaces; ++n)
  {
    // move vertices of faces to be curved onto circle
    k = faces(n,1); f = faces(n,2);
    v1 = EToV(k, f); v2 = EToV(k, umMOD(f,Nfaces)+1);
    theta1 = atan2(VY(v1),VX(v1)); theta2 = atan2(VY(v2),VX(v2));
    newx1 = xo + ra*cos(theta1); newy1 = yo + ra*sin(theta1);
    newx2 = xo + ra*cos(theta2); newy2 = yo + ra*sin(theta2);
    
    // update mesh vertex locations
    VX(v1) = newx1; VX(v2) = newx2; VY(v1) = newy1; VY(v2) = newy2; 

    // store modified vertex numbers
    vflag(v1) = 1;  vflag(v2) = 1;
  }

  // map modified vertex flag to each element
//vflag = vflag(EToV);
  VFlag.set_map(EToV, vflag); // (map, values)

  // locate elements with at least one modified vertex
//ks = find(sum(vflag,2)>0);
  ks = find(VFlag.row_sums(), '>', 0);

  // build coordinates of all the corrected nodes
  IMat VA=EToV(ks,1), VB=EToV(ks,2), VC=EToV(ks,3);

  // FIXME: loading 2D mapped data into 1D vectors
  int Nr=VA.num_rows(); 
  va.copy(Nr,VA.data());
  vb.copy(Nr,VB.data());
  vc.copy(Nr,VC.data());

  // Note: outer products of (Vector,MappedRegion1D)
  x(All,ks) = 0.5*(-(r+s)*VX(va)+(1.0+r)*VX(vb)+(1.0+s)*VX(vc));
  y(All,ks) = 0.5*(-(r+s)*VY(va)+(1.0+r)*VY(vb)+(1.0+s)*VY(vc));

  // deform specified faces
  for (n=1; n<=NCurveFaces; ++n)
  {
    k = faces(n,1); f = faces(n,2);

    // find vertex locations for this face and tangential coordinate
    if      (f==1) { v1=EToV(k,1); v2=EToV(k,2); vr=r; }
    else if (f==2) { v1=EToV(k,2); v2=EToV(k,3); vr=s; }
    else if (f==3) { v1=EToV(k,1); v2=EToV(k,3); vr=s; }

    fr = vr(Fmask(All,f));
    x1 = VX(v1); y1 = VY(v1); x2 = VX(v2); y2 = VY(v2);

    // move vertices at end points of this face to the cylinder
    theta1 = atan2(y1-yo, x1-xo); theta2 = atan2(y2-yo, x2-xo);

    // check to make sure they are in the same quadrant
    if ((theta2 > 0.0) && (theta1 < 0.0)) { theta1 += 2*pi; }
    if ((theta1 > 0.0) && (theta2 < 0.0)) { theta2 += 2*pi; }

    // distribute N+1 nodes by arc-length along edge
    theta = 0.5*theta1*(1.0-fr) + 0.5*theta2*(1.0+fr);

    // evaluate deformation of coordinates
    fdx = xo + ra*apply(cos,theta) - x(Fmask(All,f),k); 
    fdy = yo + ra*apply(sin,theta) - y(Fmask(All,f),k);

    // build 1D Vandermonde matrix for face nodes and volume nodes
    Vface = Vandermonde1D(N, fr); Vvol = Vandermonde1D(N, vr);

    // compute unblended volume deformations 
    vdx = Vvol * (Vface|fdx); vdy = Vvol * (Vface|fdy);

    // blend deformation and increment node coordinates
    ids = find(abs(1.0-vr), '>', 1e-7); // warp and blend

    denom = 1.0-vr(ids);
    if      (1==f) { numer = -(r(ids)+s(ids));  }
    else if (2==f) { numer =  (r(ids)+1.0   );  }
    else if (3==f) { numer = -(r(ids)+s(ids));  }
    blend = numer.dd(denom);

    //-----------------------------------
    // x(ids,k) += blend.dm(vdx(ids));    // VC++ compiler specific?
    // y(ids,k) += blend.dm(vdy(ids));
    //-----------------------------------
    // unroll the above operator
    int Nr = ids.size(), id=0;
    for (int m=1; m<=Nr; ++m) { 
      id=ids(m); 
      x(id,k) += blend(m)*vdx(id);
      y(id,k) += blend(m)*vdy(id);
    }
  }

  // repair other coordinate dependent information
  Fx = x(Fmask, All); Fy = y(Fmask, All);
  ::GeometricFactors2D(x,y,Dr,Ds,  rx,sx,ry,sy,J);
  Normals2D(); Fscale = sJ.dd(J(Fmask,All));
}
Example #16
0
af::Msg* threadProcessMsgCase( ThreadArgs * i_args, af::Msg * i_msg)
{
    //i_msg->stdOut();
    //printf("IM=%d LM=%d MM=%d\n", i_msg->getMagicNumber(), af::Msg::Magic, af::Environment::getMagicMode());
    af::Msg * o_msg_response = NULL;

    switch( i_msg->type())
    {
    case af::Msg::TVersionMismatch:
    {
        AFCommon::QueueLogError( i_msg->v_generateInfoString( false));
        o_msg_response = new af::Msg( af::Msg::TVersionMismatch, 1);
        break;
    }
    case af::Msg::TMagicMismatch:
    {
        std::string err = "Magick number mismatch: recieved ";
        err += af::itos( i_msg->getMagicNumber()) + " != " + af::itos( af::Msg::Magic) += " local.";
        AFCommon::QueueLogError( err);
        o_msg_response = new af::Msg( af::Msg::TMagicMismatch, 1);
        break;
    }
    case af::Msg::TMagicNumber:
    {
        std::string msg = "Magick Number " + af::itos( af::Msg::Magic)
                          + " changed to " + af::itos( i_msg->int32());
        AFCommon::QueueLog( msg);
        o_msg_response = new af::Msg();
        o_msg_response->setString( msg);
        af::Msg::Magic = i_msg->int32();
        break;
    }
    case af::Msg::TInvalid:
    {
        AFCommon::QueueLogError( std::string("Invalid message recieved: ") + i_msg->v_generateInfoString( false));
        break;
    }
    case af::Msg::TNULL:
    case af::Msg::TDATA:
    case af::Msg::TTESTDATA:
    case af::Msg::TStringList:
    {
        i_msg->stdOutData();
        break;
    }
    case af::Msg::THTTP:
    case af::Msg::TJSON:
    {
        return threadProcessJSON( i_args, i_msg);
    }
    case af::Msg::TString:
    {
        std::string str = i_msg->getString();
        if( str.empty()) break;

        AFCommon::QueueLog( str);
        AfContainerLock mLock( i_args->monitors, AfContainerLock::WRITELOCK);
        i_args->monitors->sendMessage( str);
        break;
    }
    case af::Msg::TStatRequest:
    {
        o_msg_response = new af::Msg;
        af::statwrite( o_msg_response);
        break;
    }
    case af::Msg::TConfirm:
    {
        printf("Thread process message: Msg::TConfirm: %d\n", i_msg->int32());
        i_args->msgQueue->pushMsg( new af::Msg( af::Msg::TConfirm, 1));
        o_msg_response = new af::Msg( af::Msg::TConfirm, 1 - i_msg->int32());
        break;
    }
    case af::Msg::TConfigLoad:
    {
        AfContainerLock jlock( i_args->jobs,	 AfContainerLock::WRITELOCK);
        AfContainerLock rlock( i_args->renders, AfContainerLock::WRITELOCK);
        AfContainerLock tlock( i_args->talks,	AfContainerLock::WRITELOCK);
        AfContainerLock ulock( i_args->users,	AfContainerLock::WRITELOCK);
        printf("\n	========= RELOADING CONFIG =========\n\n");
        std::string message;
        if( af::Environment::reload())
        {
            message = "Reloaded successfully.";
            printf("\n	========= CONFIG RELOADED SUCCESSFULLY =========\n\n");
        }
        else
        {
            message = "Failed, see server logs fo details.";
            printf("\n	========= CONFIG RELOADING FAILED =========\n\n");
        }
        o_msg_response = new af::Msg();
        o_msg_response->setString( message);
        break;
    }
    case af::Msg::TFarmLoad:
    {
        AfContainerLock mLock( i_args->monitors, AfContainerLock::WRITELOCK);
        AfContainerLock rlock( i_args->renders,  AfContainerLock::WRITELOCK);

        printf("\n	========= RELOADING FARM =========\n\n");
        std::string message;
        if( af::loadFarm( true))
        {
            RenderContainerIt rendersIt( i_args->renders);
            for( RenderAf *render = rendersIt.render(); render != NULL; rendersIt.next(), render = rendersIt.render())
            {
                render->getFarmHost();
                i_args->monitors->addEvent( af::Msg::TMonitorRendersChanged, render->getId());
            }
            message = "Reloaded successfully.";
            printf("\n	========= FARM RELOADED SUCCESSFULLY =========\n\n");
        }
        else
        {
            message = "Failed, see server logs fo details. Check farm with \"afcmd fcheck\" at first.";
            printf("\n	========= FARM RELOADING FAILED =========\n\n");
        }
        o_msg_response = new af::Msg();
        o_msg_response->setString( message);
        break;
    }

// ---------------------------------- Monitor ---------------------------------//
    case af::Msg::TMonitorRegister:
    {
        AfContainerLock lock( i_args->monitors, AfContainerLock::WRITELOCK);

        MonitorAf * newMonitor = new MonitorAf( i_msg);
        newMonitor->setAddressIP( i_msg->getAddress());
        o_msg_response = i_args->monitors->addMonitor( newMonitor);
        break;
    }
    case af::Msg::TMonitorUpdateId:
    {
        AfContainerLock lock( i_args->monitors, AfContainerLock::READLOCK);

        if( i_args->monitors->updateId( i_msg->int32()))
        {
            o_msg_response = new af::Msg( af::Msg::TMonitorId, i_msg->int32());
        }
        else
        {
            o_msg_response = new af::Msg( af::Msg::TMonitorId, 0);
        }
        break;
    }
    case af::Msg::TMonitorsListRequest:
    {
        AfContainerLock lock( i_args->monitors, AfContainerLock::READLOCK);

        o_msg_response = i_args->monitors->generateList( af::Msg::TMonitorsList);
        break;
    }
    case af::Msg::TMonitorsListRequestIds:
    {
        AfContainerLock lock( i_args->monitors, AfContainerLock::READLOCK);

        af::MCGeneral ids( i_msg);
        o_msg_response = i_args->monitors->generateList( af::Msg::TMonitorsList, ids);
        break;
    }
    case af::Msg::TMonitorLogRequestId:
    {
        AfContainerLock lock( i_args->monitors,  AfContainerLock::READLOCK);

        MonitorContainerIt it( i_args->monitors);
        MonitorAf* node = it.getMonitor( i_msg->int32());
        if( node == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg();
        o_msg_response->setStringList( node->getLog());
        break;
    }

// ---------------------------------- Talk ---------------------------------//
    case af::Msg::TTalkRegister:
    {
        AfContainerLock mlock( i_args->monitors, AfContainerLock::WRITELOCK);
        AfContainerLock tlock( i_args->talks,	 AfContainerLock::WRITELOCK);

        TalkAf * newTalk = new TalkAf( i_msg);
        newTalk->setAddressIP( i_msg->getAddress());
        o_msg_response = i_args->talks->addTalk( newTalk, i_args->monitors);
        break;
    }
    case af::Msg::TTalksListRequest:
    {
        AfContainerLock lock( i_args->talks, AfContainerLock::READLOCK);

        o_msg_response = i_args->talks->generateList( af::Msg::TTalksList);
        break;
    }
    case af::Msg::TTalksListRequestIds:
    {
        AfContainerLock lock( i_args->talks, AfContainerLock::READLOCK);

        af::MCGeneral ids( i_msg);
        o_msg_response = i_args->talks->generateList( af::Msg::TTalksList, ids);
        break;
    }
    case af::Msg::TTalkUpdateId:
    {
        AfContainerLock lock( i_args->talks, AfContainerLock::READLOCK);

        if( i_args->talks->updateId( i_msg->int32()))
        {
            o_msg_response = i_args->talks->generateList( af::Msg::TTalksList);
        }
        else
        {
            o_msg_response = new af::Msg( af::Msg::TTalkId, 0);
        }
        break;
    }
    case af::Msg::TTalkDistributeData:
    {
        AfContainerLock lock( i_args->talks, AfContainerLock::READLOCK);

        i_args->talks->distributeData( i_msg);
        break;
    }

// ---------------------------------- Render -------------------------------//
    case af::Msg::TRenderRegister:
    {
//printf("case af::Msg::TRenderRegister:\n");
        AfContainerLock mLock( i_args->monitors, AfContainerLock::WRITELOCK);
        AfContainerLock rLock( i_args->renders,  AfContainerLock::WRITELOCK);

        RenderAf * newRender = new RenderAf( i_msg);
        newRender->setAddressIP( i_msg->getAddress());
        o_msg_response = i_args->renders->addRender( newRender, i_args->monitors);
        break;
    }
    case af::Msg::TRenderUpdate:
    {
//printf("case af::Msg::TRenderUpdate:\n");
        AfContainerLock lock( i_args->renders, AfContainerLock::READLOCK);

        af::Render render_up( i_msg);
//printf("Msg::TRenderUpdate: %s - %s\n", render_up.getName().toUtf8().data(), time2Qstr( time(NULL)).toUtf8().data());
        RenderContainerIt rendersIt( i_args->renders);
        RenderAf* render = rendersIt.getRender( render_up.getId());

        int id = 0;
        // If there is not such render, a zero id will be send.
        // It is a signal for client to register again (may be server was restarted).
        if((render != NULL) && ( render->update( &render_up)))
        {
            id = render->getId();
        }
        o_msg_response = new af::Msg( af::Msg::TRenderId, id);
        break;
    }
    case af::Msg::TRendersListRequest:
    {
        AfContainerLock lock( i_args->renders, AfContainerLock::READLOCK);

        o_msg_response = i_args->renders->generateList( af::Msg::TRendersList);
        break;
    }
    case af::Msg::TRendersListRequestIds:
    {
        AfContainerLock lock( i_args->renders, AfContainerLock::READLOCK);

        af::MCGeneral ids( i_msg);
        o_msg_response = i_args->renders->generateList( af::Msg::TRendersList, ids);
        break;
    }
    case af::Msg::TRendersResourcesRequestIds:
    {
        AfContainerLock lock( i_args->renders, AfContainerLock::READLOCK);

        af::MCGeneral ids( i_msg);
        o_msg_response = i_args->renders->generateList( af::Msg::TRendersResources, ids);
        break;
    }
    case af::Msg::TRenderLogRequestId:
    {
        AfContainerLock lock( i_args->renders,  AfContainerLock::READLOCK);

        RenderContainerIt rendersIt( i_args->renders);
        RenderAf* render = rendersIt.getRender( i_msg->int32());
        if( render == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg;
        o_msg_response->setStringList( render->getLog());
        break;
    }
    case af::Msg::TRenderTasksLogRequestId:
    {
        AfContainerLock lock( i_args->renders,  AfContainerLock::READLOCK);

        RenderContainerIt rendersIt( i_args->renders);
        RenderAf* render = rendersIt.getRender( i_msg->int32());
        if( render == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg;
        if( render->getTasksLog().empty())
        {
            o_msg_response->setString("No tasks execution log.");
        }
        else
        {
            o_msg_response->setStringList( render->getTasksLog());
        }
        break;
    }
    case af::Msg::TRenderInfoRequestId:
    {
        AfContainerLock lock( i_args->renders,  AfContainerLock::READLOCK);

        RenderContainerIt rendersIt( i_args->renders);
        RenderAf* render = rendersIt.getRender( i_msg->int32());
        if( render == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = render->writeFullInfo();
        break;
    }

// ---------------------------------- Users -------------------------------//
    case af::Msg::TUserIdRequest:
    {
        AfContainerLock lock( i_args->users, AfContainerLock::READLOCK);

        af::MsgClassUserHost usr( i_msg);
        std::string name = usr.getUserName();
        int id = 0;
        UserContainerIt usersIt( i_args->users);
        for( af::User *user = usersIt.user(); user != NULL; usersIt.next(), user = usersIt.user())
        {
            if( user->getName() == name)
            {
                id = user->getId();
            }
        }
        o_msg_response = new af::Msg( af::Msg::TUserId, id);
        break;
    }
    case af::Msg::TUsersListRequest:
    {
        AfContainerLock lock( i_args->users, AfContainerLock::READLOCK);

        o_msg_response = i_args->users->generateList( af::Msg::TUsersList);
        break;
    }
    case af::Msg::TUsersListRequestIds:
    {
        AfContainerLock lock( i_args->users, AfContainerLock::READLOCK);

        af::MCGeneral ids( i_msg);
        o_msg_response = i_args->users->generateList( af::Msg::TUsersList, ids);
        break;
    }
    case af::Msg::TUserLogRequestId:
    {
        AfContainerLock lock( i_args->users,  AfContainerLock::READLOCK);

        UserContainerIt usersIt( i_args->users);
        UserAf* user = usersIt.getUser( i_msg->int32());
        if( user == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg();
        o_msg_response->setStringList( user->getLog());
        break;
    }
    case af::Msg::TUserJobsOrderRequestId:
    {
        AfContainerLock lock( i_args->users,  AfContainerLock::READLOCK);

        UserContainerIt usersIt( i_args->users);
        UserAf* user = usersIt.getUser( i_msg->int32());
        if( user == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        af::MCGeneral ids;
        ids.setId( user->getId());
        ids.setList( user->generateJobsIds());
        o_msg_response = new af::Msg( af::Msg::TUserJobsOrder, &ids);
        break;
    }

// ------------------------------------- Job -------------------------------//
    case af::Msg::TJobRequestId:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( i_msg->int32());
        if( job == NULL )
        {
            o_msg_response = new af::Msg( af::Msg::TJobRequestId, 0);
            break;
        }
        o_msg_response = new af::Msg( af::Msg::TJob, job);
        break;
    }
    case af::Msg::TJobLogRequestId:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( i_msg->int32());
        if( job == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg();
        o_msg_response->setStringList( job->getLog());
        break;
    }
    case af::Msg::TJobErrorHostsRequestId:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( i_msg->int32());
        if( job == NULL )
        {   // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg();
        o_msg_response->setString( job->v_getErrorHostsListString());
        break;
    }
    case af::Msg::TJobProgressRequestId:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( i_msg->int32());
        if( job == NULL )
        {
            // FIXME: Send back the same message on error - is it good?
            o_msg_response = new af::Msg( af::Msg::TJobProgressRequestId, 0);
            break;
        }
        o_msg_response = new af::Msg;
        job->writeProgress( *o_msg_response);
        break;
    }
    case af::Msg::TJobsListRequest:
    {
        AfContainerLock lock( i_args->jobs, AfContainerLock::READLOCK);

        o_msg_response = i_args->jobs->generateList( af::Msg::TJobsList);
        break;
    }
    case af::Msg::TJobsListRequestIds:
    {
        AfContainerLock lock( i_args->jobs, AfContainerLock::READLOCK);

        af::MCGeneral ids( i_msg);
        o_msg_response = i_args->jobs->generateList( af::Msg::TJobsList, ids);
        break;
    }
    case af::Msg::TJobsListRequestUserId:
    {
        AfContainerLock jLock( i_args->jobs,  AfContainerLock::READLOCK);
        AfContainerLock uLock( i_args->users, AfContainerLock::READLOCK);

        o_msg_response = i_args->users->generateJobsList( i_msg->int32());
        if( o_msg_response == NULL )
        {
            o_msg_response = new af::Msg( af::Msg::TUserId, 0);
        }
        break;
    }
    case af::Msg::TJobsListRequestUsersIds:
    {
        AfContainerLock jLock( i_args->jobs,  AfContainerLock::READLOCK);
        AfContainerLock uLock( i_args->users, AfContainerLock::READLOCK);

        af::MCGeneral mcids( i_msg);
        std::string type_name;
        o_msg_response = i_args->users->generateJobsList( mcids.getList(), type_name);
        break;
    }
    case af::Msg::TTaskRequest:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        af::MCTaskPos mctaskpos( i_msg);
        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( mctaskpos.getJobId());
        if( job == NULL )
        {
            o_msg_response = new af::Msg();
            std::ostringstream stream;
            stream << "Msg::TTaskRequest: No job with id=" << mctaskpos.getJobId();
            o_msg_response->setString( stream.str());
            break;
        }
        af::TaskExec * task = job->generateTask( mctaskpos.getNumBlock(), mctaskpos.getNumTask());
        if( task )
        {
            o_msg_response = new af::Msg( af::Msg::TTask, task);
            delete task;
        }
        else
        {
            o_msg_response = new af::Msg();
            std::ostringstream stream;
            stream << "Msg::TTaskRequest: No such task[" << mctaskpos.getJobId() << "][" << mctaskpos.getNumBlock() << "][" << mctaskpos.getNumTask() << "]";
            o_msg_response->setString( stream.str());
        }
        break;
    }
    case af::Msg::TTaskLogRequest:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        af::MCTaskPos mctaskpos( i_msg);
        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( mctaskpos.getJobId());
        if( job == NULL )
        {
            o_msg_response = new af::Msg();
            std::ostringstream stream;
            stream << "Msg::TTaskLogRequest: No job with id=" << mctaskpos.getJobId();
            o_msg_response->setString( stream.str());
            break;
        }
        const std::list<std::string> * list = &(job->getTaskLog( mctaskpos.getNumBlock(), mctaskpos.getNumTask()));
        if( list == NULL )
        {
            // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg();
        if( list->size() == 0)
        {
            std::list<std::string> list;
            list.push_back("Task log is empty.");
            o_msg_response->setStringList( list);
        }
        else
        {
            o_msg_response->setStringList( *list);
        }
        break;
    }
    case af::Msg::TTaskErrorHostsRequest:
    {
        AfContainerLock lock( i_args->jobs,  AfContainerLock::READLOCK);

        af::MCTaskPos mctaskpos( i_msg);
        JobContainerIt jobsIt( i_args->jobs);
        JobAf* job = jobsIt.getJob( mctaskpos.getJobId());
        if( job == NULL )
        {
            // FIXME: Better to return some message in any case.
            break;
        }
        o_msg_response = new af::Msg();
        o_msg_response->setString( job->v_getErrorHostsListString( mctaskpos.getNumBlock(), mctaskpos.getNumTask()));
        break;
    }
    case af::Msg::TTaskOutputRequest:
    {
        af::Msg * msg_request_render = NULL;
        std::string filename, error;
        af::MCTaskPos tp( i_msg);
//printf("ThreadReadMsg::msgCase: case af::Msg::TJobTaskOutputRequest: job=%d, block=%d, task=%d, number=%d\n", tp.getJobId(), tp.getNumBlock(), tp.getNumTask(), tp.getNumber());
        {
            AfContainerLock jLock( i_args->jobs,	 AfContainerLock::READLOCK);
            AfContainerLock rLock( i_args->renders, AfContainerLock::READLOCK);

            JobContainerIt jobsIt( i_args->jobs);
            JobAf* job = jobsIt.getJob( tp.getJobId());
            if( job == NULL )
            {
                o_msg_response = af::msgString("Error: Job is NULL.");
                AFCommon::QueueLogError("Jobs is NULL");
                break;
            }

            // Trying to set message to request output from running remote host.
            msg_request_render = job->v_getTaskStdOut( tp.getNumBlock(), tp.getNumTask(), tp.getNumber(),
                                 i_args->renders, filename, error);

            if( error.size())
            {
                if( msg_request_render )
                    delete msg_request_render;
                o_msg_response = af::msgString( error);
                AFCommon::QueueLogError( error);
                break;
            }
        }
        if( filename.size())
        {
            //
            //	 Retrieving output from file
            //
            int readsize = -1;
            char * data = af::fileRead( filename, readsize, af::Msg::SizeDataMax, &error);
            if( data )
            {
                o_msg_response = new af::Msg();
                o_msg_response->setData( readsize, data);
                delete [] data;
            }
            else if( error.size())
            {
                error = std::string("Getting task output: ") + error;
                AFCommon::QueueLogError( error);
                o_msg_response = af::msgString( error);
            }
        }
        else if( msg_request_render)
        {
            //
            //	 Retrieving output from render
            //
            msg_request_render->setReceiving();
            bool ok;
            o_msg_response = af::msgsend( msg_request_render, ok, af::VerboseOn);
            if( o_msg_response == NULL )
            {
                error = "Retrieving output from render failed. See server logs for details.";
                o_msg_response = af::msgString( error);
                AFCommon::QueueLogError( error);
            }
            delete msg_request_render;
        }
        else
        {
            if( error.size())
            {
                o_msg_response = af::msgString( error);
                AFCommon::QueueLogError("TTaskOutputRequest: Neiter message nor filename\n" + error);
            }
            else
                AFCommon::QueueLogError("TTaskOutputRequest: Neiter message nor filename.");
        }
        break;
    }
    case af::Msg::TJobsWeightRequest:
    {
        AfContainerLock jLock( i_args->jobs,	 AfContainerLock::READLOCK);

        af::MCJobsWeight jobsWeight;
        i_args->jobs->getWeight( jobsWeight);
        o_msg_response = new af::Msg( af::Msg::TJobsWeight, &jobsWeight);
        break;
    }
    // Cases for run cycle thread:
    case af::Msg::TTaskUpdateState:
    {
        af::MCTaskUp taskup( i_msg);
        af::MCTaskPos taskpos( taskup.getNumJob(), taskup.getNumBlock(), taskup.getNumTask(), taskup.getNumber());
        o_msg_response = new af::Msg( af::Msg::TRenderCloseTask, &taskpos);
    }
    case af::Msg::TTaskUpdatePercent:
    case af::Msg::TTaskListenOutput:
    case af::Msg::TRenderDeregister:
    case af::Msg::TTalkDeregister:
    /*	{
    		// Check magic number mismatch mode:
    		// All message types above are not allowed in "GetOnly" mode.
    		if( i_msg->isMagicInvalid() && ( af::Environment::getMagicMode() <= af::MMM_GetOnly ))
    		{
    			std::string err = "Magic Mismatch Mode: \"";
    			err += af::Environment::getMagicModeName();
    			err += "\"";
    			err += "\nMessage type not allowed: \"";
    			err += af::Msg::TNAMES[i_msg->type()];
    			err += "\"";
    			AFCommon::QueueLogError( err);
    			delete i_msg;
    			return o_msg_response;
    		}
    		// Only Monitor message types are allowed in "GetOnly" mode.
    	}*/
    case af::Msg::TMonitorSubscribe:
    case af::Msg::TMonitorUnsubscribe:
    case af::Msg::TMonitorDeregister:
    case af::Msg::TMonitorUsersJobs:
    case af::Msg::TMonitorJobsIdsAdd:
    case af::Msg::TMonitorJobsIdsSet:
    case af::Msg::TMonitorJobsIdsDel:
    case af::Msg::TMonitorMessage:
    {
        // Push message for run cycle thread.
        i_args->msgQueue->pushMsg( i_msg);
        // Need to return here to not to delete input message (i_msg) later.
        return o_msg_response;
        //  ( o_msg_response is NULL in all cases except Msg::TTaskUpdateState,
        //	 in that case render should recieve an answer to close task
        //	 and finish sending any updates for the task )
    }
    // -------------------------------------------------------------------------//
    default:
    {
        AFCommon::QueueLogError( std::string("Unknown message recieved: ") + i_msg->v_generateInfoString( false));
        break;
    }
    }

    // Deleting input message as it not needed any more.
    delete i_msg;

    // Returning an answer
    return o_msg_response;
}
Example #17
0
void 
ICUServiceTest::testAPI_One() 
{
    // create a service using locale keys,
    TestIntegerService service;

    // register an object with one locale, 
    // search for an object with a more specific locale
    // should return the original object
    UErrorCode status = U_ZERO_ERROR;
    Integer* singleton0 = new Integer(0);
    service.registerInstance(singleton0, "en_US", status);
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_FOO", status);
        confirmEqual("1) en_US_FOO -> en_US", result, singleton0);
        delete result;
    }

    // register a new object with the more specific locale
    // search for an object with that locale
    // should return the new object
    Integer* singleton1 = new Integer(1);
    service.registerInstance(singleton1, "en_US_FOO", status);
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_FOO", status);
        confirmEqual("2) en_US_FOO -> en_US_FOO", result, singleton1);
        delete result;
    }

    // search for an object that falls back to the first registered locale
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_BAR", status);
        confirmEqual("3) en_US_BAR -> en_US", result, singleton0);
        delete result;
    }

    // get a list of the factories, should be two
    {
        confirmIdentical("4) factory size", service.countFactories(), 2);
    }

    // register a new object with yet another locale
    Integer* singleton2 = new Integer(2);
    service.registerInstance(singleton2, "en", status);
    {
        confirmIdentical("5) factory size", service.countFactories(), 3);
    }

    // search for an object with the new locale
    // stack of factories is now en, en_US_FOO, en_US
    // search for en_US should still find en_US object
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_BAR", status);
        confirmEqual("6) en_US_BAR -> en_US", result, singleton0);
        delete result;
    }

    // register a new object with an old id, should hide earlier factory using this id, but leave it there
    Integer* singleton3 = new Integer(3);
    URegistryKey s3key = service.registerInstance(singleton3, "en_US", status);
    {
        confirmIdentical("9) factory size", service.countFactories(), 4);
    }

    // should get data from that new factory
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_BAR", status);
        confirmEqual("10) en_US_BAR -> (3)", result, singleton3);
        delete result;
    }

    // remove new factory
    // should have fewer factories again
    // singleton3 dead!
    {
        UErrorCode status = U_ZERO_ERROR;
        service.unregister(s3key, status);
        confirmIdentical("11) factory size", service.countFactories(), 3);
    }

    // should get original data again after remove factory
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_BAR", status);
        confirmEqual("12) en_US_BAR -> (3)", result, singleton0);
        delete result;
    }

    // shouldn't find unregistered ids
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("foo", status);
        confirmIdentical("13) foo -> null", result, NULL);
        delete result;
    }

    // should find non-canonical strings
    {
        UnicodeString resultID;
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("EN_us_fOo", &resultID, status);
        confirmEqual("14a) find-non-canonical", result, singleton1);
        confirmStringsEqual("14b) find non-canonical", resultID, "en_US_FOO");
        delete result;
    }

    // should be able to register non-canonical strings and get them canonicalized
    Integer* singleton4 = new Integer(4);
    service.registerInstance(singleton4, "eN_ca_dUde", status);
    {
        UnicodeString resultID;
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("En_Ca_DuDe", &resultID, status);
        confirmEqual("15a) find-non-canonical", result, singleton4);
        confirmStringsEqual("15b) register non-canonical", resultID, "en_CA_DUDE");
        delete result;
    }

    // should be able to register invisible factories, these will not
    // be visible by default, but if you know the secret password you
    // can still access these services...
    Integer* singleton5 = new Integer(5);
    service.registerInstance(singleton5, "en_US_BAR", FALSE, status);
    {
        UErrorCode status = U_ZERO_ERROR;
        Integer* result = (Integer*)service.get("en_US_BAR", status);
        confirmEqual("17) get invisible", result, singleton5);
        delete result;
    }
    
    // should not be able to locate invisible services
    {
        UErrorCode status = U_ZERO_ERROR;
        UVector ids(uhash_deleteUnicodeString, uhash_compareUnicodeString, status);
        service.getVisibleIDs(ids, status);
        UnicodeString target = "en_US_BAR";
        confirmBoolean("18) find invisible", !ids.contains(&target));
    }

    // clear factory and caches
    service.reset();
    confirmBoolean("19) is default", service.isDefault());
}
Example #18
0
//*****************************************************************************
void CDbMessageText::ExportText(CStretchyBuffer& buf, const char* pTagName)
//Outputs message (language) texts for this message ID as XML tags.
{
	ASSERT(pTagName);

	const Language::LANGUAGE eLanguage = Language::GetLanguage();
	CCoordSet ids(GetMessageTextIDs(this->eMessageID));
	bool bActiveLanguageFound = false;
	for (CCoordSet::const_iterator id = ids.begin(); id != ids.end(); ++id)
	{
		//Append XML fields for each message text for this messageID.
		const UINT wLanguageIndex = id->wY;
		if (!wLanguageIndex || wLanguageIndex >= Language::LanguageCount)
			continue; //not a valid language ID -- skip it

		buf += "<";
		buf += pTagName;

		if (eLanguage == wLanguageIndex)
			bActiveLanguageFound = true;
		buf += " lang='";
		buf += Language::GetCode(wLanguageIndex);

		BYTE* pbOutStr = NULL;
		c4_Bytes MessageTextBytes = p_MessageText(GetRowRef(V_MessageTexts, id->wX));
		const WCHAR *pText = GetMessageText(MessageTextBytes);
		const UINT wSize = to_utf8(pText, pbOutStr);
		buf += "' text=\"";
		if (wSize)
		{
			//Replace characters that are illegal in XML strings with entities.
			string outstr;
			for (UINT wIndex = 0; wIndex < wSize; ++wIndex)
				switch (pbOutStr[wIndex])
				{
					case 10:  outstr += "&#10;"; break;
					case 13:  outstr += "&#13;"; break;
					case '"': outstr += "&quot;"; break;
					case '<': outstr += "&lt;"; break;
					case '>': outstr += "&gt;"; break;
					case '&': outstr += "&amp;"; break;
					case '\'': //allow apostrophes in text
					default: outstr += pbOutStr[wIndex]; break;
				}
			buf.Append((const BYTE*)outstr.c_str(), outstr.size());
		}
		delete[] pbOutStr;

		buf += "\"/>" NEWLINE;
	}

	//Add an empty language tag for the active language when texts for other
	//languages, but not this one, are found.
	if (!bActiveLanguageFound && !ids.empty())
	{
		buf += "<";
		buf += pTagName;
		buf += " lang='";
		buf += Language::GetCode(eLanguage);
		buf += "' text=\"\"/>" NEWLINE;
	}
}
Example #19
0
void
ICUServiceTest::testRBF()
{
    // resource bundle factory.
    UErrorCode status = U_ZERO_ERROR;
    TestStringService service;
    service.registerFactory(new ICUResourceBundleFactory(), status);

    // list all of the resources 
    {
        UErrorCode status = U_ZERO_ERROR;
        UVector ids(uhash_deleteUnicodeString, uhash_compareUnicodeString, 0, status);
        service.getVisibleIDs(ids, status);
        logln("all visible ids:");
        for (int i = 0; i < ids.size(); ++i) {
            const UnicodeString* id = (const UnicodeString*)ids[i];
            logln(*id);
        }
    }

    // get all the display names of these resources
    // this should be fast since the display names were cached.
    {
        UErrorCode status = U_ZERO_ERROR;
        UVector names(status);
        service.getDisplayNames(names, Locale::getGermany(), status);
        logln("service display names for de_DE");
        for (int i = 0; i < names.size(); ++i) {
            const StringPair* pair = (const StringPair*)names[i];
            logln("  " + pair->displayName + " --> " + pair->id);
        }
    }

    service.registerFactory(new CalifornioLanguageFactory(), status);

    // get all the display names of these resources
    {
        logln("californio language factory:");
        const char* idNames[] = {
            CalifornioLanguageFactory::californio, 
            CalifornioLanguageFactory::valley, 
            CalifornioLanguageFactory::surfer, 
            CalifornioLanguageFactory::geek,
        };
        int32_t count = sizeof(idNames)/sizeof(idNames[0]);

        for (int i = 0; i < count; ++i) {
            logln(UnicodeString("\n  --- ") + idNames[i] + " ---");
            {
                UErrorCode status = U_ZERO_ERROR;
                UVector names(status);
                service.getDisplayNames(names, idNames[i], status);
                for (int i = 0; i < names.size(); ++i) {
                    const StringPair* pair = (const StringPair*)names[i];
                    logln("  " + pair->displayName + " --> " + pair->id);
                }
            }
        }
    }
    CalifornioLanguageFactory::cleanup();
}
/*----------------------------------------------------------------------*
 |  finalize construction of this interface                             |
 *----------------------------------------------------------------------*/
bool MOERTEL::Interface::Complete()
{ 
  if (IsComplete())
  {
    if (OutLevel()>0)
      std::cout << "MOERTEL: ***WRN*** MOERTEL::Interface::InterfaceComplete:\n"
           << "MOERTEL: ***WRN*** InterfaceComplete() was called before, do nothing\n"
           << "MOERTEL: ***WRN*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
    return true;
  }
  
  //-------------------------------------------------------------------
  // check for NULL entries in maps
  bool ok = true;
  for (int i=0; i<2; ++i)
  {
	std::map<int,Teuchos::RCP<MOERTEL::Node> >::const_iterator curr;
    for (curr=node_[i].begin(); curr!=node_[i].end(); ++curr)
    {
      if (curr->second == Teuchos::null)
      {
        std::cout << "***ERR*** MOERTEL::Interface::Complete:\n"
             << "***ERR*** Interface # " << Id_ << ":\n"
             << "***ERR*** found NULL entry in map of nodes\n"
             << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
        ok = false;
      }
    }
  }
  for (int i=0; i<2; ++i)
  {
	std::map<int,Teuchos::RCP<MOERTEL::Segment> >::const_iterator curr;
    for (curr=seg_[i].begin(); curr!=seg_[i].end(); ++curr)
    {
      if (curr->second == Teuchos::null)
      {
        std::cout << "***ERR*** MOERTEL::Interface::Complete:\n"
             << "***ERR*** Interface # " << Id_ << ":\n"
             << "***ERR*** found NULL entry in map of segments\n"
             << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
        ok = false;
      }
    }
  }
  int lok = ok;
  int gok = 1;
  gcomm_.MinAll(&lok,&gok,1);  
  if (!gok) return false;
  
  //-------------------------------------------------------------------
  // check whether all nodes for segments are present
  // (take in account that node might be on different processor)
  // this test is expensive and does not scale. It is therefore only performed
  // when user requests a high output level
#if 1
  if (OutLevel()>9)
  {
    for (int proc=0; proc<gcomm_.NumProc(); ++proc)
    {
      for (int side=0; side<2; ++side)
      {
        // create length of list of all nodes adjacent to segments on proc
        int sendsize =  0;
        if (proc==gcomm_.MyPID())
        {
		  std::map<int,Teuchos::RCP<MOERTEL::Segment> >::const_iterator curr;
          for (curr=seg_[side].begin(); curr!=seg_[side].end(); ++curr)
            sendsize += curr->second->Nnode();
        }
        gcomm_.Broadcast(&sendsize,1,proc);
        
        // create list of all nodes adjacent to segments on proc
		std::vector<int> ids(sendsize);
        if (proc==gcomm_.MyPID())
        {
		  std::map<int,Teuchos::RCP<MOERTEL::Segment> >::const_iterator curr;
          int counter=0;
          for (curr=seg_[side].begin(); curr!=seg_[side].end(); ++curr)
          {
            const int* segids = curr->second->NodeIds();
            for (int i=0; i<curr->second->Nnode(); ++i)
              ids[counter++] = segids[i];
          }
        }
        gcomm_.Broadcast(&ids[0],sendsize,proc);
        
        // check on all processors for nodes in ids
		std::vector<int> foundit(sendsize);
		std::vector<int> gfoundit(sendsize);
        for (int i=0; i<sendsize; ++i) 
        {
          foundit[i] = 0;
          if (node_[side].find(ids[i]) != node_[side].end()) 
            foundit[i] = 1;
        }
        gcomm_.MaxAll(&foundit[0],&gfoundit[0],sendsize);
        for (int i=0; i<sendsize; ++i)
        {
          if (gfoundit[i]!=1)
          {
            if (gcomm_.MyPID()==proc)
            std::cout << "***ERR*** MOERTEL::Interface::Complete:\n"
                 << "***ERR*** cannot find segment's node # " << ids[i] << "\n"
                 << "***ERR*** in map of all nodes on all procs\n"
                 << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
            ids.clear();
            foundit.clear();
            gfoundit.clear();
            gcomm_.Barrier();
            return false;
          }
        }
        
        // tidy up
        ids.clear();
        foundit.clear();
        gfoundit.clear();
      } // for (int size=0; side<2; ++side)
    } // for (int proc=0; proc<gcomm_.NumProc(); ++proc)
  }
#endif  
  //-------------------------------------------------------------------
  // find all procs that have business on this interface (own nodes/segments)
  // build a Epetra_comm that contains only those procs
  // this intra-communicator will be used to handle most stuff on this 
  // interface so the interface will not block all other procs
  {
#ifdef EPETRA_MPI
	std::vector<int> lin(gcomm_.NumProc());
	std::vector<int> gin(gcomm_.NumProc());
    for (int i=0; i<gcomm_.NumProc(); ++i) lin[i] = 0;
    
    // check ownership of any segments
    for (int i=0; i<2; ++i)
      if (seg_[i].size() != 0)
      {
        lin[gcomm_.MyPID()] = 1;
        break;
      }
    // check ownership of any nodes
    for (int i=0; i<2; ++i)
      if (node_[i].size() != 0)
      {
        lin[gcomm_.MyPID()] = 1;
        break;
      }
    gcomm_.MaxAll(&lin[0],&gin[0],gcomm_.NumProc());
    lin.clear();
    
    // typecast the Epetra_Comm to Epetra_MpiComm
    Epetra_MpiComm* epetrampicomm = dynamic_cast<Epetra_MpiComm*>(&gcomm_);
    if (!epetrampicomm)
    {
	  std::stringstream oss;
			oss << "***ERR*** MOERTEL::Interface::Complete:\n"
           << "***ERR*** Interface " << Id() << ": Epetra_Comm is not an Epetra_MpiComm\n"
           << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
      throw ReportError(oss);
    }

    // split the communicator into participating and none-participating procs
    int color;
    int key = gcomm_.MyPID();
    // I am taking part in the new comm if I have any ownership 
    if (gin[gcomm_.MyPID()]) 
      color = 0; 
    // I am not taking part in the new comm
    else                    
      color = MPI_UNDEFINED;
      
    // tidy up
    gin.clear();

    // create the local communicator   
    MPI_Comm  mpi_global_comm = epetrampicomm->GetMpiComm();
    MPI_Comm* mpi_local_comm  = new MPI_Comm();
    MPI_Comm_split(mpi_global_comm,color,key,mpi_local_comm);

    // create the new Epetra_MpiComm
    if (*mpi_local_comm == MPI_COMM_NULL)
      lcomm_ = Teuchos::null;
    else
      lcomm_ = Teuchos::rcp(new Epetra_MpiComm(*mpi_local_comm)); // FIXME: who destroys the MPI_Comm inside?

#if 0
    // test this stuff on the mpi level
    int grank,lrank;
    MPI_Comm_rank(mpi_global_comm,&grank);
    if (*mpi_local_comm != MPI_COMM_NULL)
      MPI_Comm_rank(*mpi_local_comm,&lrank);
    else
      lrank = -1;
    for (int proc=0; proc<gcomm_.NumProc(); ++proc)
    {
      if (proc==gcomm_.MyPID())
      std::cout << "using mpi    comms: I am global rank " << grank << " and local rank " << lrank << std::endl;
      gcomm_.Barrier();
    }
    // test this stuff on the epetra level
    if (lComm())
      for (int proc=0; proc<lcomm_->NumProc(); ++proc)
      {
        if (proc==lcomm_->MyPID())
        std::cout << "using epetra comms: I am global rank " << gcomm_.MyPID() << " and local rank " << lcomm_->MyPID() << std::endl;
        lcomm_->Barrier();
      }
    gcomm_.Barrier();
#endif


    
#else  // the easy serial case
    Epetra_SerialComm* serialcomm = dynamic_cast<Epetra_SerialComm*>(&gcomm_);
    if (!serialcomm)
    {
	  std::stringstream oss;
			oss << "***ERR*** MOERTEL::Interface::Complete:\n"
           << "***ERR*** Interface " << Id() << ": Epetra_Comm is not an Epetra_SerialComm\n"
           << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
      throw ReportError(oss);
    }
    lcomm_ = Teuchos::rcp(new Epetra_SerialComm(*serialcomm));
#endif // end of #ifdef PARALLEL    
  }
  
  //-------------------------------------------------------------------
  // create a map of all nodes to there PID (process id)
  if (lComm())
    for (int proc=0; proc<lcomm_->NumProc(); ++proc)
    {
      int lnnodes = 0;
      if (proc==lcomm_->MyPID())
        lnnodes = node_[0].size() + node_[1].size();
      lcomm_->Broadcast(&lnnodes,1,proc);
	  std::vector<int> ids(lnnodes);
      if (proc==lcomm_->MyPID())
      {
		std::map<int,Teuchos::RCP<MOERTEL::Node> >::const_iterator curr;
        int counter=0;
        for (int side=0; side<2; ++side)
          for (curr=node_[side].begin(); curr!=node_[side].end(); ++curr)
            ids[counter++] = curr->first;
      }
      lcomm_->Broadcast(&ids[0],lnnodes,proc);
      for (int i=0; i<lnnodes; ++i)
        nodePID_.insert(std::pair<int,int>(ids[i],proc));
      ids.clear();
    }
  
  //-------------------------------------------------------------------
  // create a map of all segments to there PID (process id)
  if (lComm())
    for (int proc=0; proc<lcomm_->NumProc(); ++proc)
    {
      int lnsegs = 0;
      if (proc==lcomm_->MyPID())
        lnsegs = seg_[0].size() + seg_[1].size();
      lcomm_->Broadcast(&lnsegs,1,proc);
	  std::vector<int> ids(lnsegs);
      if (proc==lcomm_->MyPID())
      {
		std::map<int,Teuchos::RCP<MOERTEL::Segment> >::const_iterator curr;
        int counter=0;
        for (int side=0; side<2; ++side)
          for (curr=seg_[side].begin(); curr!=seg_[side].end(); ++curr)
            ids[counter++] = curr->first;
      }
      lcomm_->Broadcast(&ids[0],lnsegs,proc);
      for (int i=0; i<lnsegs; ++i)
        segPID_.insert(std::pair<int,int>(ids[i],proc));
      ids.clear();
    }
  
  //-------------------------------------------------------------------
  // set isComplete_ flag
  // we set it here already as we will be using some methods that require it
  // from now on
  isComplete_ = true;
  
  //-------------------------------------------------------------------
  // make the nodes know there adjacent segments
  // find max number of nodes to a segment
  if (lComm())
  {
    int lmaxnnode = 0;
    int gmaxnnode = 0;
    for (int side=0; side<2; ++side)
    {
	  std::map<int,Teuchos::RCP<MOERTEL::Segment> >::const_iterator scurr;
      for (scurr=seg_[side].begin(); scurr!=seg_[side].end(); ++scurr)
        if (lmaxnnode < scurr->second->Nnode())
          lmaxnnode = scurr->second->Nnode();
    }
    lcomm_->MaxAll(&lmaxnnode,&gmaxnnode,1);
    
    // loop all procs and broadcast their adjacency
    for (int proc=0; proc<lcomm_->NumProc(); ++proc)
    {
      // local number of segments
      int lnseg = 0;
      if (proc==lcomm_->MyPID())
        lnseg = seg_[0].size() + seg_[1].size();
      lcomm_->Broadcast(&lnseg,1,proc);
      
      // allocate vector to hold adjacency
      int offset = gmaxnnode+2;
      int size   = lnseg*offset;
	  std::vector<int> adj(size);
      
      // proc fills adjacency vector adj and broadcasts
      if (proc==lcomm_->MyPID())
      {
        int count = 0;
        for (int side=0; side<2; ++side)
        {
		  std::map<int,Teuchos::RCP<MOERTEL::Segment> >::const_iterator scurr;
          for (scurr=seg_[side].begin(); scurr!=seg_[side].end(); ++scurr)
          {
			Teuchos::RCP<MOERTEL::Segment> seg = scurr->second;
            adj[count]   = seg->Id();
            adj[count+1] = seg->Nnode();
            const int* ids = seg->NodeIds();
            for (int i=0; i<seg->Nnode(); ++i)
              adj[count+2+i] = ids[i];
            count += offset;
          }
        }
      }
      lcomm_->Broadcast(&adj[0],size,proc);
      
      // all procs read adj and add segment to the nodes they own
      int count = 0;
      for (int i=0; i<lnseg; ++i)
      {
        int segid = adj[count];
        int nnode = adj[count+1];
        for (int j=0; j<nnode; ++j)
        {
          int nid = adj[count+2+j];
          if (lcomm_->MyPID() == NodePID(nid))
          {
            // I own this node, so set the segment segid in it
			Teuchos::RCP<MOERTEL::Node> node = GetNodeViewLocal(nid);
            if (node == Teuchos::null)
            {
				std::stringstream oss;
					oss << "***ERR*** MOERTEL::Interface::Complete:\n"
						<< "***ERR*** cannot find node " << nid << "\n"
                   << "***ERR*** in map of all nodes on this proc\n"
                   << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
				throw ReportError(oss);
            }
            node->AddSegment(segid);
          }
          else
            continue;
        }
        count += offset;
      }
      adj.clear();
    } // for (int proc=0; proc<lcomm_->NumProc(); ++proc)
  } // if (lComm())
  
  //-------------------------------------------------------------------
  // build redundant segments and nodes
  if (lComm())
  {
    int ok = 0;
    ok += RedundantSegments(0);  
    ok += RedundantSegments(1);  
    ok += RedundantNodes(0);
    ok += RedundantNodes(1);
    if (ok != 4)
    {
		std::stringstream oss;
			oss << "***ERR*** MOERTEL::Interface::Complete:\n"
           << "***ERR*** building of redundant information failed\n"
           << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n";
		throw ReportError(oss);
    }
  }

  //-------------------------------------------------------------------
  // make topology segments <-> nodes for each side
  if (lComm())
    BuildNodeSegmentTopology(); 

  //-------------------------------------------------------------------
  // delete distributed nodes and segments
  for (int i=0; i<2; ++i)
  {
    seg_[i].clear();
    node_[i].clear();
  }


  //-------------------------------------------------------------------
  // we are done
  // note that there might not be any functions on the interface yet
  // they still have to be set
  
  return ok;
}
Example #21
0
BlkResTestDiffusion::BlkResTestDiffusion(const InputParameters & parameters)
  : Kernel(modifyParams(parameters))
{

  // Get an test enum from the kernel parameters
  MooseEnum test = parameters.get<MooseEnum>("test");

  // test that hasBlocks is working
  if (test == "hasBlocks")
  {
    // Define a SubdomainName vector for testing against
    std::vector<SubdomainName> id_names(2);
    id_names[0] = "1";
    id_names[1] = "2";

    // Define a SubdomainID vector for testing against
    std::vector<SubdomainID> ids(2);
    ids[0] = 1;
    ids[1] = 2;

    // Define a SubdomainID set for testing against
    std::set<SubdomainID> id_set(ids.begin(), ids.end());

    // Test true single SudomainName input
    if (!hasBlocks("1"))
      mooseError("Test 1: hasBlocks(SubdomainName) = true failed");

    // Test false of single Subdomain input
    if (hasBlocks("3"))
      mooseError("Test 2: hasBlocks(SubdomainName) = false failed");

    // Test true vector SubdomainName input
    if (!hasBlocks(id_names))
      mooseError("Test 3: hasBlocks(std::vector<SubdomainName>) = true failed");

    // Test false vector SudomainName input
    id_names.push_back("3");
    if (hasBlocks(id_names))
      mooseError("Test 4: hasBlocks(std::vector<SubdomainName>) = false failed");

    // Test true single SubdomainID input
    if (!hasBlocks(1))
      mooseError("Test 5: hasBlocks(SubdomainID) = true failed");

    // Test false single SubdomainID input
    if (hasBlocks(5))
      mooseError("Test 6: hasBlocks(SubdomainID) = false failed");

    // Test true for std::vector<SubdomainID>
    if (!hasBlocks(ids))
      mooseError("Test 7: hasBlocks(std::vector<SubdomainID>) = true failed");

    // Test false for std::vector<SubdomainID>
    ids.push_back(4);
    if (hasBlocks(ids))
      mooseError("Test 8: hasBlocks(std::vector<SubdomainID>) = false failed");

    // Test true for std::set<SubdomainID>
    if (!hasBlocks(id_set))
      mooseError("Test 9: hasBlocks(std::set<SubdomainID) = true failed");

    // Test false for std::set<SubdomainID>
    id_set.insert(12);
    if (hasBlocks(id_set))
      mooseError("Test 10: hasBlocks(std::set<SubdomainID>) = false failed");

    // This is the expected error, all the above tests passed
    mooseError("hasBlocks testing passed");
  }

  // Test of stored ANY_BLOCK_ID on object
  else if (test == "hasBlocks_ANY_BLOCK_ID")
  {
    // Test that ANY_BLOCK_ID is working
    if (hasBlocks(1))
      mooseError("hasBlocks_ANY_BLOCK_ID test passed");
    else
      mooseError("hasBlocks_ANY_BLOCK_ID test failed");
  }

  // Test that the blocks() method is working
  else if (test == "blocks")
  {
    const std::vector<SubdomainName> & blks = blocks();
    if (blks[0] == "1" && blks[1] == "2" && blks.size() == 2)
      mooseError("Blocks testing passed"); // expected error
    else
      mooseError("Blocks testing failed");
  }

  // Test that the getSubdomains() is working
  else if (test == "blockIDs")
  {
    const std::set<SubdomainID> & ids = blockIDs();
    if (ids.count(1) == 1 && ids.count(2) == 1)
      mooseError("blockIDs testing passed"); // expected error
    else
      mooseError("blockIDs testing failed");
  }

  // Test that the isSubset() is working
  else if (test == "isBlockSubset")
  {
    std::set<SubdomainID> sub_id;
    sub_id.insert(10);
    sub_id.insert(1);
    sub_id.insert(4);
    sub_id.insert(2);
    if (isBlockSubset(sub_id))
      mooseError("isBlockSubset testing passed"); // expected error
    else
      mooseError("isBlockSubset testing failed");
  }

  // Test that hasMaterialPropertyBlock is working properly
  else if (test == "hasBlockMaterialProperty_true")
  {
    if (hasBlockMaterialProperty<Real>("a"))
      mooseError("hasBlockMaterialProperty is true, test passed"); // expected error
    else
      mooseError("hasBlockMaterialProperty is false, test failed");
  }

  else if (test == "hasBlockMaterialProperty_false")
  {
    if (hasBlockMaterialProperty<Real>("b"))
      mooseError("hasBlockMaterialProperty is true, test failed");
    else
      mooseError("hasBlockMaterialProperty is false, test passed"); // expected error
  }
}
Example #22
0
void LevelParser::parseTileLayer(TiXmlElement* pTileElement, std::vector<Layer*> *pLayers, const std::vector<Tileset>* pTilesets, std::vector<TileLayer*> *pCollisionLayers)
{
    TileLayer* pTileLayer = new TileLayer(m_tileSize, m_width, m_height, *pTilesets);
    
    bool collidable = false;
    
    // tile data
    std::vector<std::vector<int>> data;
    
    std::string decodedIDs;
    TiXmlElement* pDataNode;
    
    for(TiXmlElement* e = pTileElement->FirstChildElement(); e != NULL; e = e->NextSiblingElement())
    {
        if(e->Value() == std::string("properties"))
        {
            for(TiXmlElement* property = e->FirstChildElement(); property != NULL; property = property->NextSiblingElement())
            {
                if(property->Value() == std::string("property"))
                {
                    if(property->Attribute("name") == std::string("collidable"))
                    {
                        collidable = true;
                    }
                }
            }
        }
        
        if(e->Value() == std::string("data"))
        {
            pDataNode = e;
        }
    }
    
    for(TiXmlNode* e = pDataNode->FirstChild(); e != NULL; e = e->NextSibling())
    {
        TiXmlText* text = e->ToText();
        std::string t = text->Value();
        decodedIDs = base64_decode(t);
    }
    
    // uncompress zlib compression
    uLongf sizeofids = m_width * m_height * sizeof(int);
    std::vector<int> ids(m_width * m_height);
    uncompress((Bytef*)&ids[0], &sizeofids,(const Bytef*)decodedIDs.c_str(), decodedIDs.size());
    
    std::vector<int> layerRow(m_width);
    
    for(int j = 0; j < m_height; j++)
    {
        data.push_back(layerRow);
    }
    
    for(int rows = 0; rows < m_height; rows++)
    {
        for(int cols = 0; cols < m_width; cols++)
        {
            data[rows][cols] = ids[rows * m_width + cols];
        }
    }
    
    pTileLayer->setTileIDs(data);
    
    if(collidable)
    {
        pCollisionLayers->push_back(pTileLayer);
    }
    
    pLayers->push_back(pTileLayer);
}
	static CSeenIds* NewL(RDbDatabase& aDb) {
		auto_ptr<CSeenIds> ids(new (ELeave) CSeenIds(aDb));
		ids->ConstructL();
		return ids.release();
	}
Example #24
0
int main()
{
  // LOAD DATA
  arma::mat X;

  // A) Toy Data
  //  char inputFile[] = "../data_files/toyclusters/toyclusters.dat";
  
  // B) X4.dat
  //char inputFile[] = "./X4.dat";
  
  // C) fisher data
  //char inputFile[] = "./fisher.dat";

  // D) MNIST data
  //char inputFile[] = "../data_files/MNIST/MNIST.dat";
  
  // E) Reduced MNIST (5000x400)
  //char inputFile[] = "../data_files/MNIST/MNISTreduced.dat";
  
  // F) Reduced MNIST (0 and 1) (1000x400)
  //char inputFile[] = "../data_files/MNIST/MNISTlittle.dat";

  // G) Girl.png (512x768, RGB, already unrolled)
  //char inputFile[] = "girl.dat";

  // H) Pool.png (383x512, RGB, already unrolled)
  //char inputFile[] = "pool.dat";

  // I) Cat.png (733x490, RGB, unrolled)
  //char inputFile[] = "cat.dat";
  
  // J) Airplane.png (512x512, RGB, unrolled)
  //char inputFile[] = "airplane.dat";

  // K) Monarch.png (512x768, RGB, unrolled)
  //char inputFile[] = "monarch.dat";

  // L) tulips.png (512x768 ,RGB, unrolled)
  //char inputFile[] = "tulips.dat";
  
  // M) demo.dat (2d data)
  char inputFile[] = "demo.dat";

  // INITIALIZE PARAMETERS
  X.load(inputFile);
  const arma::uword N = X.n_rows;
  const arma::uword D = X.n_cols;

  arma::umat ids(N,1);	// needed to shuffle indices later
  arma::umat shuffled_ids(N,1);
  for (arma::uword i = 0; i < N; ++i) {
    ids(i,0) = i;
  }
  
  arma::arma_rng::set_seed_random(); // set arma rng
  // int seed = time(NULL);	// set RNG seed to current time
  // srand(seed);

  arma::uword initial_K = 32;   // initial number of clusters
  arma::uword K = initial_K;
  
  arma::umat clusters(N,1); // contains cluster assignments for each data point
  for (arma::uword i = 0; i < N; ++i) {
    clusters(i, 0) = i%K;		// initialize as [0,1,...,K-1,0,1,...,K-1,0,...]
  }

  arma::umat cluster_sizes(N,1,arma::fill::zeros); // contains num data points in cluster k
  for (arma::uword i = 0; i < N; ++i) {
    cluster_sizes(clusters(i,0), 0) += 1;
  }

  arma::mat mu(N, D, arma::fill::zeros); // contains cluster mean parameters
  arma::mat filler(D,D,arma::fill::eye);
  std::vector<arma::mat> sigma(N,filler); // contains cluster covariance parameters

  if (K < N) {			// set parameters not belonging to any cluster to -999
    mu.rows(K,N-1).fill(-999);
    for (arma::uword k = K; k < N; ++k) {
      sigma[k].fill(-999);
    }
  }

  arma::umat uword_dummy(1,1);	// dummy 1x1 matrix;
  // for (arma::uword i = 0; i <N; ++i) {
  //   std::cout << sigma[i] << std::endl;
  // }
  // std::cout << X << std::endl
  // 	    << N << std::endl
  // 	    << D << std::endl
  // 	    << K << std::endl
  // 	    << clusters << std::endl
  // 	    << cluster_sizes << std::endl
  //	    << ids << std::endl;

  // INITIALIZE HYPER PARAMETERS
  // Dirichlet Process concentration parameter is alpha:
  double alpha = 1;
  // Dirichlet Process base distribution (i.e. prior) is 
  // H(mu,sigma) = NIW(mu,Sigma|m_0,k_0,S_0,nu_0) = N(mu|m_0,Sigma/k_0)IW(Sigma|S_0,nu_0)
  arma::mat perturbation(D,D,arma::fill::eye);
  perturbation *= 0.000001;
  //const arma::mat S_0 = arma::cov(X,X,1) + perturbation; // S_xbar / N
  const arma::mat S_0(D,D,arma::fill::eye);
  const double nu_0 = D + 2;
  const arma::mat m_0 = mean(X).t();
  const double k_0 = 0.01;
  // std::cout << "S_0" << S_0 << std::endl;
  // std::cout << S_0 << std::endl
  // 	    << nu_0 << std::endl
  // 	    << m_0 << std::endl
  // 	    << k_0 << std::endl;


  // INITIALIZE SAMPLING PARAMETERS
  arma::uword NUM_SWEEPS = 250;	// number of Gibbs iterations
  bool SAVE_CHAIN = false;	// save output of each Gibbs iteration?
  // arma::uword BURN_IN = NUM_SWEEPS - 10;
  // arma::uword CHAINSIZE = NUM_SWEEPS - BURN_IN;
  // std::vector<arma::uword> chain_K(CHAINSIZE, K); // Initialize chain variable to initial parameters for convinience
  // std::vector<arma::umat> chain_clusters(CHAINSIZE, clusters);
  // std::vector<arma::umat> chain_clusterSizes(CHAINSIZE, cluster_sizes);
  // std::vector<arma::mat> chain_mu(CHAINSIZE, mu);
  // std::vector<std::vector<arma::mat> > chain_sigma(CHAINSIZE, sigma);
  
  // for (arma::uword sweep = 0; sweep < CHAINSIZE; ++sweep) {
  //   std::cout << sweep << " K\n" << chain_K[sweep] << std::endl
  // 		<< sweep << " clusters\n" << chain_clusters[sweep] << std::endl
  // 		<< sweep << " sizes\n" << chain_clusterSizes[sweep] << std::endl
  // 		<< sweep << " mu\n" << chain_mu[sweep] << std::endl;
  //   for (arma::uword i = 0; i < N; ++i) { 
  // 	std::cout << sweep << " " << i << " sigma\n" << chain_sigma[sweep][i] << std::endl;
  //   }
  // }
  

  // START CHAIN
  std::cout << "Starting Algorithm with K = " << K << std::endl;
  for (arma::uword sweep = 0; sweep < NUM_SWEEPS; ++sweep) { 
    // shuffle indices
    shuffled_ids = shuffle(ids);
    // std::cout << shuffled_ids << std::endl;

    // SAMPLE CLUSTERS
    for (arma::uword j = 0; j < N; ++j){
      //      std::cout << "j = " << j << std::endl;
      arma::uword i = shuffled_ids(j);
      arma::mat x = X.row(i).t(); // current data point
      
      // Remove i's statistics and any empty clusters
      arma::uword c = clusters(i,0); // current cluster
      cluster_sizes(c,0) -= 1;
      //std::cout << "old c = " << c << std::endl;

      if (cluster_sizes(c,0) == 0) { // remove empty cluster
      	cluster_sizes(c,0) = cluster_sizes(K-1,0); // move entries for K onto position c
	mu.row(c) = mu.row(K-1);
      	sigma[c] = sigma[K-1];
      	uword_dummy(0,0) = c;
	arma::uvec idx = find(clusters == K - 1);
      	clusters.each_row(idx) = uword_dummy;
	cluster_sizes(K-1,0) = 0;
	mu.row(K-1).fill(-999);
	sigma[K-1].fill(-999);
	--K;
      }

      // quick test of logMvnPdf:
      // arma::mat m_(2,1);
      // arma::mat s_(2,2);
      // arma::mat t_(2,1);
      // m_ << 1 << arma::endr << 2;
      // s_ << 3 << -0.2 << arma::endr << -0.2 << 1;
      // t_ << -3 << arma::endr << -3;
      // double lpdf = logMvnPdf(t_, m_, s_);
      // std::cout << lpdf << std::endl; // śhould be -19.1034 (works)


      
      // Find categorical distribution over clusters (tested)
      arma::mat logP(K+1, 1, arma::fill::zeros);
      
      // quick test of logInvWishPdf
      // arma::mat si_(2,2), s_(2,2);
      // double nu_ = 4;
      // si_ << 1 << 0.5 << arma::endr << 0.5 << 4;
      // s_ << 3 << -0.2 << arma::endr << -0.2 << 1;
      // double lpdf = logInvWishPdf(si_, s_, nu_);
      // std::cout << lpdf << std::endl; // should be -7.4399 (it is)

      // quick test for logNormInvWishPdf
      // arma::mat si_(2,2), s_(2,2);
      // arma :: mat mu_(2,1), m_(2,1);
      // double k_ = 0.5, nu_ = 4;
      // si_ << 1 << 0.5 << arma::endr << 0.5 << 4;
      // s_ << 3 << -0.2 << arma::endr << -0.2 << 1;
      // mu_ << -3 << arma::endr << -3;
      // m_ << 1 << arma::endr << 2;
      // double lp = logNormInvWishPdf(mu_,si_,m_,k_,s_,nu_);
      // std::cout << lp << std::endl; // should equal -15.2318 (it is)
      
      // p(existing clusters) (tested)
      for (arma::uword k = 0; k < K; ++k) {
	arma::mat m_ = mu.row(k).t();
	arma::mat s_ = sigma[k];
	logP(k,0) = log(cluster_sizes(k,0)) - log(N-1+alpha) + logMvnPdf(x,m_,s_);
      }

      // p(new cluster): find partition function (tested)
      // arma::mat dummy_mu(D, 1, arma::fill::zeros);
      // arma::mat dummy_sigma(D, D, arma::fill::eye);
      // double logPrior, logLklihd, logPstr, logPartition; 
      // posterior hyperparameters (tested)
      arma::mat m_1(D,1), S_1(D,D);
      double k_1, nu_1;
      k_1 = k_0 + 1;
      nu_1 = nu_0 + 1;
      m_1 = (k_0*m_0 + x) / k_1;
      S_1 = S_0 + x * x.t() + k_0 * (m_0 * m_0.t()) - k_1 * (m_1 * m_1.t());
      // std::cout << k_1 << std::endl
      // 		<< nu_1 << std::endl
      // 		<< m_1 << std::endl
      // 		<< S_1 << std::endl;
      
      // // partition = likelihood*prior/posterior (tested)
      // // (perhaps a direct computation of the partition function would be better)
      // logPrior = logNormInvWishPdf(dummy_mu, dummy_sigma, m_0, k_0, S_0, nu_0);
      // logLklihd = logMvnPdf(x, dummy_mu, dummy_sigma);
      // logPstr = logNormInvWishPdf(dummy_mu, dummy_sigma, m_1, k_1, S_1, nu_1);
      // logPartition = logPrior + logLklihd - logPstr;      
      // std::cout << "log  Prior = " << logPrior << std::endl
      // 		<< "log Likelihood = " << logLklihd << std::endl
      // 		<< "log Posterior = " << logPstr << std::endl
      // 		<< "log Partition = " << logPartition << std::endl;
      
      // Computing partition directly
      double logS0,signS0,logS1,signS1;
      arma::log_det(logS0,signS0,S_0);
      arma::log_det(logS1,signS1,S_1);
      /*std::cout << "log(det(S_0)) = " << logS0 << std::endl
	<< "log(det(S_1)) = " << logS1 << std::endl;*/
      double term1 = 0.5*D*(log(k_0)-log(k_1));
      double term2 = -0.5*D*log(arma::datum::pi);
      double term3 = 0.5*(nu_0*logS0 - nu_1*logS1);
      double term4 = lgamma(0.5*nu_1);
      double term5 = -lgamma(0.5*(nu_1-D));
      double logPartition = term1+term2+term3+term4+term5;
      /*double logPartition = 0.5*D*(log(k_0)-log(k_1)-log(arma::datum::pi)) \
	/+0.5*(nu_0*logS0 - nu_1*logS1) + lgamma(0.5*nu_1) - lgamma(0.5*(nu_1-D));*/
      
      /*      std::cout << "term1 = " << term1 << std::endl
		<< "term2 = " << term2 << std::endl
		<< "term3 = " << term3 << std::endl
		<< "term4 = " << term4 << std::endl
		<< "term5 = " << term5 << std::endl;*/
      
      //std::cout << "logP = " << logPartition << std::endl;

      // p(new cluster): (tested)
      logP(K,0) = log(alpha) - log(N - 1 + alpha) + logPartition;
      //      std::cout << "logP(new cluster) = " << logP(K,0) << std::endl;
      //if(i == 49)
      //assert(false);
      // sample cluster for i
      
      

      arma::uword c_ = logCatRnd(logP);
      clusters(i,0) = c_;
      
      //if (j % 10 == 0){
      //std::cout << "New c = " << c_ << std::endl;
      //std::cout << "logP = \n" << logP << std::endl;
      //}
      // quick test for mvnRnd
      // arma::mat mu, si;
      // mu << 1 << arma::endr << 2;
      // si << 1 << 0.9 << arma::endr << 0.9 << 1;
      // arma::mat m = mvnRnd(mu, si);
      // std::cout << m << std::endl;

      // quick test for invWishRnd
      // double df = 4;
      // arma::mat si(2,2);
      // si << 1 << 1 << arma::endr << 1 << 1;
      // arma::mat S = invWishRnd(si,df);
      // std::cout << S << std::endl;

      if (c_ == K) {	// Sample parameters for any new-born clusters from posterior
	cluster_sizes(K, 0) = 1;
	arma::mat si_ = invWishRnd(S_1, nu_1);
	//arma::mat si_ = S_1;
	arma::mat mu_ = mvnRnd(m_1, si_/k_1);
	//arma::mat mu_ = m_1;
	mu.row(K) = mu_.t();
	sigma[K] = si_;
	K += 1;
      } else {
	cluster_sizes(c_,0) += 1;
      }
      // if (sweep == 0)
      // 	std::cout << " K = " << K << std::endl;
      // // if (j == N-1) {
      // // 	std::cout << logP << std::endl;
      // // 	std::cout << K << std::endl;
      // // 	assert(false);
      // // }
      // std::cout << "K = " << K << "\n" << std::endl;
    }
    
    // sample CLUSTER PARAMETERS FROM POSTERIOR
    for (arma::uword k = 0; k < K; ++k) {
      // std::cout << "k = " << k << std::endl;
      // cluster data
      arma::mat Xk = X.rows(find(clusters == k));
      arma::uword Nk = cluster_sizes(k,0);

      // posterior hyperparameters
      arma::mat m_Nk(D,1), S_Nk(D,D);
      double k_Nk, nu_Nk;
      
      arma::mat sum_k = sum(Xk,0).t();
      arma::mat cov_k(D, D, arma::fill::zeros);
      for (arma::uword l = 0; l < Nk; ++l) { 
	cov_k += Xk.row(l).t() * Xk.row(l);
      }
      
      k_Nk = k_0 + Nk;
      nu_Nk = nu_0 + Nk;
      m_Nk = (k_0 * m_0 + sum_k) / k_Nk;
      S_Nk = S_0 + cov_k + k_0 * (m_0 * m_0.t()) - k_Nk * (m_Nk * m_Nk.t());
      
      // sample fresh parameters
      arma::mat si_ = invWishRnd(S_Nk, nu_Nk);
      //arma::mat si_ = S_Nk;
      arma::mat mu_ = mvnRnd(m_Nk, si_/k_Nk);
      //arma::mat mu_ = m_Nk;
      mu.row(k) = mu_.t();
      sigma[k] = si_;
    }
    std::cout << "Iteration " << sweep + 1 << "/" << NUM_SWEEPS<< " done. K = " << K << std::endl;
        
    // // STORE CHAIN
    // if (SAVE_CHAIN) {
    //   if (sweep >= BURN_IN) { 
    // 	chain_K[sweep - BURN_IN] = K;
    // 	chain_clusters[sweep - BURN_IN] = clusters;
    // 	chain_clusterSizes[sweep - BURN_IN] = cluster_sizes;
    // 	chain_mu[sweep - BURN_IN] = mu;
    // 	chain_sigma[sweep - BURN_IN] = sigma;
    //   }
    // }
	
  }
  std::cout << "Final cluster sizes: " << std::endl
	    << cluster_sizes.rows(0, K-1) << std::endl;






  
  // WRITE OUPUT DATA TO FILE
  arma::mat MU = mu.rows(0,K-1);
  arma::mat SIGMA(D*K,D);
  for (arma::uword k = 0; k < K; ++k) { 
    SIGMA.rows(k*D,(k+1)*D-1) = sigma[k];
  }
  arma::umat IDX = clusters;

  // A) toycluster data
  // char MuFile[] = "../data_files/toyclusters/dpmMU.out";
  // char SigmaFile[] = "../data_files/toyclusters/dpmSIGMA.out";
  // char IdxFile[] = "../data_files/toyclusters/dpmIDX.out";

  // B) X4.dat
  char MuFile[] = "dpmMU.out";
  char SigmaFile[] = "dpmSIGMA.out";
  char IdxFile[] = "dpmIDX.out";
  std::ofstream KFile("K.out");
  
  MU.save(MuFile, arma::raw_ascii);
  SIGMA.save(SigmaFile, arma::raw_ascii);
  IDX.save(IdxFile, arma::raw_ascii);
  KFile << "K = " << K << std::endl;
  
  if (SAVE_CHAIN) {}
  //   std::ofstream chainKFile("chainK.out");
  //   std::ofstream chainClustersFile("chainClusters.out");
  //   std::ofstream chainClusterSizesFile("chainClusterSizes.out");
  //   std::ofstream chainMuFile("chainMu.out");
  //   std::ofstream chainSigmaFile("chainSigma.out");
    
  //   chainKFile << "Dirichlet Process Mixture Model.\nInput: " << inputFile << std::endl
  // 	       << "Number of iterations of Gibbs Sampler: " << NUM_SWEEPS << std::endl
  // 	       << "Burn-In: " << BURN_IN << std::endl
  // 	       << "Initial number of clusters: " << initial_K << std::endl
  // 	       << "Output: Number of cluster (K)\n" << std::endl; 
  //   chainClustersFile << "Dirichlet Process Mixture Model.\nInput: " << inputFile << std::endl
  // 		      << "Number of iterations of Gibbs Sampler: " << NUM_SWEEPS << std::endl
  // 		      << "Burn-In: " << BURN_IN << std::endl
  // 		      << "Initial number of clusters: " << initial_K << std::endl
  // 		      << "Output: Cluster identities (clusters)\n" << std::endl; 
  //   chainClusterSizesFile << "Dirichlet Process Mixture Model.\nInput: " << inputFile << std::endl
  // 			  << "Number of iterations of Gibbs Sampler: " << NUM_SWEEPS << std::endl
  // 			  << "Burn-In: " << BURN_IN << std::endl
  // 			  << "Initial number of clusters: " << initial_K << std::endl
  // 			  << "Output: Size of clusters (cluster_sizes)\n" << std::endl; 
  //   chainMuFile << "Dirichlet Process Mixture Model.\nInput: " << inputFile << std::endl
  // 		<< "Number of iterations of Gibbs Sampler: " << NUM_SWEEPS << std::endl
  // 		<< "Burn-In: " << BURN_IN << std::endl
  // 		<< "Initial number of clusters: " << initial_K << std::endl
  // 		<< "Output: Samples for cluster mean parameters (mu. Note: means stored in rows)\n" << std::endl; 
  //   chainSigmaFile << "Dirichlet Process Mixture Model.\nInput: " << inputFile << std::endl
  // 		   << "Number of iterations of Gibbs Sampler: " << NUM_SWEEPS << std::endl
  // 		   << "Burn-In " << BURN_IN << std::endl
  // 		   << "Initial number of clusters: " << initial_K << std::endl
  // 		   << "Output: Samples for cluster covariances (sigma)\n" << std::endl; 


  //   for (arma::uword sweep = 0; sweep < CHAINSIZE; ++sweep) {
  //     arma::uword K = chain_K[sweep];
  //     chainKFile << "Sweep #" << BURN_IN + sweep + 1 << "\n" << chain_K[sweep] << std::endl;
  //     chainClustersFile << "Sweep #" << BURN_IN + sweep + 1 << "\n" << chain_clusters[sweep]  << std::endl;
  //     chainClusterSizesFile << "Sweep #" << BURN_IN + sweep + 1 << "\n" << chain_clusterSizes[sweep].rows(0, K - 1) << std::endl;
  //     chainMuFile << "Sweep #" << BURN_IN + sweep + 1 << "\n" << chain_mu[sweep].rows(0, K - 1) << std::endl;
  //     chainSigmaFile << "Sweep #" << BURN_IN + sweep + 1<< "\n";
  //     for (arma::uword i = 0; i < K; ++i) { 
  // 	chainSigmaFile << chain_sigma[sweep][i] << std::endl;
  //     }
  //     chainSigmaFile << std::endl;
  //   }
  // }

  return 0;
}
int main (int argc, char* argv[])
{
	ApplicationsLib::LogogSetup logog_setup;

	TCLAP::CmdLine cmd(
		"Creates boundary conditions for mesh nodes along polylines."
		"The documentation is available at https://docs.opengeosys.org/docs/tools/model-preparation/create-boundary-conditions-along-a-polyline",
		' ',
		"0.1");
	TCLAP::ValueArg<bool> gml_arg("", "gml",
		"if switched on write found nodes to file in gml format", false, 0, "bool");
	cmd.add(gml_arg);

	TCLAP::ValueArg<std::string> output_base_fname("o", "output-base-file-name",
		"the base name of the file the output (geometry (gli) and boundary"\
		"condition (bc)) will be written to", true,
		"", "file name");
	cmd.add(output_base_fname);

	TCLAP::ValueArg<std::string> bc_type("t", "type",
		"the process type the boundary condition will be written for "\
		"currently LIQUID_FLOW (primary variable PRESSURE1) and "\
		"GROUNDWATER_FLOW (primary variable HEAD, default) are supported", true,
		"",
		"process type as string (LIQUID_FLOW or GROUNDWATER_FLOW (default))");
	cmd.add(bc_type);

	TCLAP::ValueArg<double> search_length_arg("s", "search-length",
		"The size of the search length. The default value is "
		"std::numeric_limits<double>::epsilon()", false,
		std::numeric_limits<double>::epsilon(), "floating point number");
	cmd.add(search_length_arg);

	TCLAP::ValueArg<std::string> geometry_fname("i", "input-geometry",
		"the name of the file containing the input geometry", true,
		"", "file name");
	cmd.add(geometry_fname);

	TCLAP::ValueArg<std::string> mesh_arg("m", "mesh-file",
		"the name of the file containing the mesh", true,
		"", "file name");
	cmd.add(mesh_arg);

	cmd.parse(argc, argv);

	// *** read mesh
	INFO("Reading mesh \"%s\" ... ", mesh_arg.getValue().c_str());
	MeshLib::Mesh * subsurface_mesh(FileIO::readMeshFromFile(mesh_arg.getValue()));
	INFO("done.");
	INFO("Extracting top surface of mesh \"%s\" ... ",
		mesh_arg.getValue().c_str());
	const MathLib::Vector3 dir(0,0,-1);
	double const angle(90);
	std::unique_ptr<MeshLib::Mesh> surface_mesh(
	    MeshLib::MeshSurfaceExtraction::getMeshSurface(*subsurface_mesh, dir,
	                                                   angle));
	INFO("done.");
	delete subsurface_mesh;
	subsurface_mesh = nullptr;

	// *** read geometry
	GeoLib::GEOObjects geometries;
	FileIO::readGeometryFromFile(geometry_fname.getValue(), geometries);

	std::string geo_name;
	{
		std::vector<std::string> geo_names;
		geometries.getGeometryNames(geo_names);
		geo_name = geo_names[0];
	}

	// *** check if the data is usable
	// *** get vector of polylines
	std::vector<GeoLib::Polyline*> const* plys(geometries.getPolylineVec(geo_name));
	if (!plys) {
		ERR("Could not get vector of polylines out of geometry \"%s\".",
			geo_name.c_str());
		return -1;
	}

	MeshGeoToolsLib::SearchLength search_length_strategy;
	if (search_length_arg.isSet()) {
		search_length_strategy =
			MeshGeoToolsLib::SearchLength(search_length_arg.getValue());
	}

	GeoLib::GEOObjects geometry_sets;
	MeshGeoToolsLib::MeshNodeSearcher mesh_searcher(*surface_mesh,
		search_length_strategy);
	for(std::size_t k(0); k<plys->size(); k++) {
		std::vector<std::size_t> ids
			(mesh_searcher.getMeshNodeIDsAlongPolyline(*((*plys)[k])));
		if (ids.empty())
			continue;
		std::string geo_name("Polyline-"+std::to_string(k));
		convertMeshNodesToGeometry(surface_mesh->getNodes(), ids, geo_name,
			geometry_sets);
	}

	// merge all together
	std::vector<std::string> geo_names;
	geometry_sets.getGeometryNames(geo_names);
	if (geo_names.empty()) {
		ERR("Did not find mesh nodes along polylines.");
		return -1;
	}

	std::string merge_name("AllMeshNodesAlongPolylines");
	if (geometry_sets.mergeGeometries(geo_names, merge_name) == 2)
		merge_name = geo_names[0];

	GeoLib::PointVec const* pnt_vec(geometry_sets.getPointVecObj(merge_name));
	std::vector<GeoLib::Point*> const* merged_pnts(pnt_vec->getVector());

	std::vector<GeoLib::Point> pnts_with_id;
	const std::size_t n_merged_pnts(merged_pnts->size());
	for(std::size_t k(0); k<n_merged_pnts; ++k) {
		pnts_with_id.emplace_back(*((*merged_pnts)[k]), k);
	}

	std::sort(pnts_with_id.begin(), pnts_with_id.end(),
		[](GeoLib::Point const& p0, GeoLib::Point const& p1)
			{ return p0 < p1; }
	);

	double const eps (std::numeric_limits<double>::epsilon());
	auto surface_pnts = std::unique_ptr<std::vector<GeoLib::Point*>>(
	    new std::vector<GeoLib::Point*>);
	std::map<std::string, std::size_t> *name_id_map(
		new std::map<std::string, std::size_t>
	);

	// insert first point
	surface_pnts->push_back(
		new GeoLib::Point(pnts_with_id[0], surface_pnts->size()));
	std::string element_name;
	pnt_vec->getNameOfElementByID(0, element_name);
	name_id_map->insert(
		std::pair<std::string, std::size_t>(element_name,0)
	);
	for (std::size_t k(1); k < n_merged_pnts; ++k) {
		const GeoLib::Point& p0 (pnts_with_id[k-1]);
		const GeoLib::Point& p1 (pnts_with_id[k]);
		if (std::abs (p0[0] - p1[0]) > eps || std::abs (p0[1] - p1[1]) > eps) {
			surface_pnts->push_back(new GeoLib::Point(pnts_with_id[k],
				surface_pnts->size()));
			std::string element_name;
			pnt_vec->getNameOfElementByID(k, element_name);
			name_id_map->insert(
				std::pair<std::string, std::size_t>(element_name,
				surface_pnts->size()-1)
			);
		}
	}

	std::string surface_name(BaseLib::dropFileExtension(mesh_arg.getValue())+"-MeshNodesAlongPolylines");
	geometry_sets.addPointVec(std::move(surface_pnts), surface_name, name_id_map, 1e-6);

	// write the BCs and the merged geometry set to file
	std::string const base_fname(
	    BaseLib::dropFileExtension(output_base_fname.getValue()));
	writeBCsAndGeometry(geometry_sets, surface_name, base_fname,
	                    bc_type.getValue(), gml_arg.getValue());
	return 0;
}
Example #26
0
TEUCHOS_UNIT_TEST(DirBC, DirBCManager_finalizeBCEqns)
{
  MPI_Comm comm = MPI_COMM_WORLD;

  int numProcs = 1;
#ifndef FEI_SER
  MPI_Comm_size(comm, &numProcs);
#endif

  if (numProcs > 1) {
    FEI_COUT << "skipping test of fei::DirichletBCManager::finalizeBCEqn, which only"
     << " runs on 1 proc." << FEI_ENDL;
    return;
  }

  int idtype = 0;
  int fieldID = 0;
  int fieldSize = 2;
  int offsetIntoField = 1;
  std::vector<int> ids(5);
  std::vector<double> vals(5);

  ids[0] = 2; vals[0] = 2.0;
  ids[1] = 1; vals[1] = 1.0;
  ids[2] = 3; vals[2] = 3.0;
  ids[3] = 4; vals[3] = 4.0;
  ids[4] = 0; vals[4] = 0.0;


  fei::SharedPtr<fei::VectorSpace> vspace(new fei::VectorSpace(comm));

  vspace->defineFields(1, &fieldID, &fieldSize);
  vspace->defineIDTypes(1, &idtype);

  fei::SharedPtr<fei::MatrixGraph> mgraph(new fei::MatrixGraph_Impl2(vspace, vspace));

  int numIDs = 1;

  int patternID = mgraph->definePattern(numIDs, idtype);

  int blockID = 0;

  mgraph->initConnectivityBlock(blockID, ids.size(), patternID);

  for(size_t i = 0; i<ids.size(); ++i) {
    mgraph->initConnectivity(blockID, i, &ids[i]);
  }

  mgraph->initComplete();


  fei::DirichletBCManager bcmgr(mgraph->getRowSpace());

  bcmgr.addBCRecords(5, idtype, fieldID, offsetIntoField,
                     &ids[0], &vals[0]);
 
  fei::SharedPtr<fei::FillableMat> inner(new fei::FillableMat);
  fei::SharedPtr<fei::Matrix_Impl<fei::FillableMat> > feimat(new fei::Matrix_Impl<fei::FillableMat>(inner, mgraph, ids.size()));

  TEUCHOS_TEST_EQUALITY(bcmgr.finalizeBCEqns(*feimat, false), 0, out, success);

  TEUCHOS_TEST_EQUALITY(feimat->getGlobalNumRows(), feimat->getLocalNumRows(),out,success);
  TEUCHOS_TEST_EQUALITY(feimat->getGlobalNumRows(), (int)ids.size(), out, success);
}
Example #27
0
Containers::Array<ALuint> sourceIds(const std::vector<std::reference_wrapper<Source>>& sources) {
    Containers::Array<ALuint> ids(sources.size());
    for(auto it = sources.begin(); it != sources.end(); ++it)
        ids[it-sources.begin()] = it->get().id();
    return ids;
}
Example #28
0
TEUCHOS_UNIT_TEST(DirBC, DirBCManager_addBCRecords)
{
  MPI_Comm comm = MPI_COMM_WORLD;
  int idtype = 0;
  int fieldID = 0;
  int fieldSize = 2;
  int offsetIntoField = 1;
  std::vector<int> ids(5);
  std::vector<double> vals(5);

  ids[0] = 2; vals[0] = 2.0;
  ids[1] = 1; vals[1] = 1.0;
  ids[2] = 3; vals[2] = 3.0;
  ids[3] = 4; vals[3] = 4.0;
  ids[4] = 0; vals[4] = 0.0;


  fei::SharedPtr<fei::VectorSpace> vspace(new fei::VectorSpace(comm));

  vspace->defineFields(1, &fieldID, &fieldSize);
  vspace->defineIDTypes(1, &idtype);

  fei::SharedPtr<fei::MatrixGraph> mgraph(new fei::MatrixGraph_Impl2(vspace, vspace));

  int numIDs = 1;

  int patternID = mgraph->definePattern(numIDs, idtype, fieldID);

  int blockID = 0;

  mgraph->initConnectivityBlock(blockID, ids.size(), patternID);

  for(size_t i = 0; i<ids.size(); ++i) {
    mgraph->initConnectivity(blockID, i, &ids[i]);
  }

  mgraph->initComplete();

  fei::DirichletBCManager bcmgr(mgraph->getRowSpace());

  bcmgr.addBCRecords(5, idtype, fieldID, offsetIntoField,
                     &ids[0], &vals[0]);
 
  if (bcmgr.getNumBCRecords() != 5) {
    throw std::runtime_error("test_DirBCManager test 1 failed.");
  }

  std::vector<int> offsetsIntoField(5, 1);

  bcmgr.addBCRecords(5, idtype, fieldID, &ids[0],
                     &offsetsIntoField[0], &vals[0]);
 
  if (bcmgr.getNumBCRecords() != 5) {
    throw std::runtime_error("test_DirBCManager test 2 failed.");
  }

  offsetsIntoField[1] = 0;
  offsetsIntoField[3] = 0;
  offsetsIntoField[4] = 0;

  bcmgr.addBCRecords(5, idtype, fieldID, &ids[0],
                     &offsetsIntoField[0], &vals[0]);
 
  if (bcmgr.getNumBCRecords() != 8) {
    throw std::runtime_error("test_DirBCManager test 3 failed.");
  }
}
	static CAcceptedMsgs* NewL(RDbDatabase& aDb) {
		auto_ptr<CAcceptedMsgs> ids(new (ELeave) CAcceptedMsgs(aDb));
		ids->ConstructL();
		return ids.release();
	}
Example #30
0
BOOL ReadWindowPos(
    LPTSTR pszKeyName,
    PINT px,
    PINT py,
    PINT pcx,
    PINT pcy,
    BOOL *pfMaximized)
{
    static CHAR szSep[] = " ,";
    TCHAR szBuf[CCHTEXTMAX];
    CHAR szBufAnsi[CCHTEXTMAX];
    PSTR psz;
    BOOL fDefCharUsed;

    if (!GetPrivateProfileString(ids(IDS_APPNAME),
            pszKeyName, szEmpty, szBuf, CCHTEXTMAX, ids(IDS_DLGEDITINI)))
        return FALSE;

    WideCharToMultiByte(CP_ACP, 0, szBuf, -1, szBufAnsi, CCHTEXTMAX,
            NULL, &fDefCharUsed);

    if (!(psz = strtok(szBufAnsi, szSep)))
        return FALSE;

    *px = atoi(psz);

    if (!(psz = strtok(NULL, szSep)))
        return FALSE;

    *py = atoi(psz);

    if (!(psz = strtok(NULL, szSep)))
        return FALSE;

    *pcx = atoi(psz);

    if (!(psz = strtok(NULL, szSep)))
        return FALSE;

    *pcy = atoi(psz);

    /*
     * If there is a "1" following the coordinates, the window was
     * maximized when it was saved.
     */
    *pfMaximized = FALSE;
    if ((psz = strtok(NULL, szSep)) && atoi(psz) == 1)
        *pfMaximized = TRUE;

    /*
     * Don't allow a zero sized window.
     */
    if (*pcx == 0 || *pcy == 0)
        return FALSE;

    /*
     * Return success.
     */
    return TRUE;

#if 0
    static TCHAR szSep[] = L" ,";
    TCHAR szBuf[CCHTEXTMAX];
    LPTSTR psz;

    if (!GetPrivateProfileString(ids(IDS_APPNAME),
            pszKeyName, szEmpty, szBuf, CCHTEXTMAX, ids(IDS_DLGEDITINI)))
        return FALSE;

    if (!(psz = wcstok(szBuf, szSep)))
        return FALSE;

    *px = awtoi(psz);

    if (!(psz = wcstok(NULL, szSep)))
        return FALSE;

    *py = awtoi(psz);

    if (!(psz = wcstok(NULL, szSep)))
        return FALSE;

    *pcx = awtoi(psz);

    if (!(psz = wcstok(NULL, szSep)))
        return FALSE;

    *pcy = awtoi(psz);

    /*
     * If there is a "1" following the coordinates, the window was
     * maximized when it was saved.
     */
    *pfMaximized = FALSE;
    if ((psz = wcstok(NULL, szSep)) && awtoi(psz) == 1)
        *pfMaximized = TRUE;

    /*
     * Don't allow a zero sized window.
     */
    if (*pcx == 0 || *pcy == 0)
        return FALSE;

    /*
     * Return success.
     */
    return TRUE;
#endif //BUGBUG UNICODE
}