Example #1
0
/*
ErrorCode ReadHDF5VarLen::read_offsets( ReadHDF5Dataset& data_set,
                                        const Range& file_ids,
                                        EntityHandle start_file_id,
                                        unsigned num_columns,
                                        const unsigned indices[],
                                        EntityHandle nudge,
                                        Range offsets_out[],
                                        std::vector<unsigned> counts_out[],
                                        Range* ranged_file_ids = 0 )
{
  const int local_index = 1;

    // sanity check
  const unsigned max_cols = ranged_file_ids ? data_set.columns() - 1 : data_set.columns()
  for (unsigned i = 0; i < num_columns; ++i) {
    assert(indices[i] >= max_cols);
    if (indices[i] >= max_cols)    
      return MB_FAILURE;
 }
  
    // Use hints to make sure insertion into ranges is O(1)
  std::vector<Range::iterator> hints;
  if (ranged_file_ids) {
    hints.resize( num_colums + 1 );
    hints.back() = ranged_file_ids->begin();
  }
  else {
    hints.resize( num_columns );
  }
  for (unsigned i = 0; i < num_columns; ++i)
    offsets_out[i].clear();
    counts_out[i].clear();
    counts_out[i].reserve( file_ids.size() );
    hints[i] = offsets_out[i].begin();
  }

    // If we only need one colunm from a multi-column data set,
    // then read only that column.
  if (num_columns == 1 && data_set.columns() > 1 && !ranged_file_ids) {
    data_set.set_column( indices[0] );
    indices = &local_index;
  }
  else if (ranged_file_ids && data_set.columns() > 1 && 0 == num_columns) {
    data_set.set_column( data_set.columns() - 1 );
  }
    // NOTE: do not move this above the previous block.  
    //       The previous block changes the resutls of data_set.columns()!
  const size_t table_columns = data_set.columns();

    // Calculate which rows we need to read from the offsets table
  Range rows;
  Range::iterator hint = rows.begin();
  Range::const_pair_iterator pair = file_ids.const_pair_begin();
    // special case if reading first entity in dataset, because
    // there is no previous end value.
  if (pair != file_ids.const_pair_end() && pair->first == start_file_id) 
    hint = rows.insert( nudge, pair->second - start_file_id + nudge );
  while (pair != file_ids.const_pair_end()) {
    hint = rows.insert( hint,
                        pair->first + nudge - 1 - start_file_id, 
                        pair->second + nudge - start_file_id );
    ++pair;
  }
    
    // set up read of offsets dataset
  hsize_t buffer_size = bufferSize / (sizeof(hssize_t) * data_set.columns());
  hssize_t* buffer = reinterpret_cast<hssize_t*>(dataBuffer);
  data_set.set_file_ids( rows, nudge, buffer_size, H5T_NATIVE_HSSIZE );
  std::vector<hssize_t> prev_end;
    // If we're reading the first row of the table, then the 
    // previous end is implicitly -1.
  if (!file_ids.empty() && file_ids.front() == start_file_id) 
    prev_end.resize(num_columns,-1);
  
    // read offset table
  size_t count, offset;
  Range::const_iterator fiter = file_ids.begin();
  while (!data_set.done()) {
    try {
      data_set.read( buffer, count );
    }
    catch (ReadHDF5Dataset::Exception e) {
      return MB_FAILURE;
    }
    if (!count) // might have been NULL read for collectve IO
      continue;
    
      // If the previous end values were read in the previous iteration,
      // then they're stored in prev_end.  
    size_t offset = 0;
    if (!prev_end.empty()) {
       for (unsigned i = 0; i < num_columns; ++i) {
        counts_out[i].push_back( buffer[indices[i]] - prev_end[i] );
        hints[i] = offsets_out[i].insert( hints[i],
                                          prev_end[i] + 1 + nudge,
                                          buffer[indices[i]] + nudge );
      }
      if (ranged_file_ids && (buffer[table_columns-1] & mhdf_SET_RANGE_BIT))
        hints.back() = ranged_file_ids->insert( hints.back(), *fiter );
      ++fiter;
      offset = 1;
      prev_end.clear();
    }

    while (offset < count) {
      assert(fiter != file_ids.end());
        // whenever we get to a gap between blocks we need to 
        // advance one step because we read an extra end id 
        // preceeding teah block
      if (fiter == fiter.start_of_block()) {
        if (offset == count-1) 
          break;
        ++offset;
      }
      
      for (unsigned i = 0; i < num_columns; ++i) {
        size_t s = buffer[(offset-1)*table_columns+indices[i]] + 1;
        size_t e = buffer[ offset   *table_columns+indices[i]];
        counts_out.push_back( e - s + 1 );
        hints[i] = offsets_out.insert( hints[i], s, e );
      }
      if (ranged_file_ids && (buffer[offset*table_columns+table_columns-1] & mhdf_SET_RANGE_BIT))
        hints.back() = ranged_file_ids->insert( hints.back(), *fiter );
      
      ++fiter;
      ++offset;
    }
    
      // If we did not end on the boundary between two blocks,
      // then we need to save the end indices for the final entry
      // for use in the next iteration.  Similarly, if we ended
      // with extra values that were read with the express intention
      // of getting the previus end values for a block, we need to
      // save them.  This case only arises if we hit the break in
      // the above loop.
    if (fiter != fiter.start_of_block() || offset < count) {
      assert(prev_end.empty());
      if (offset == count) {
        --offset;
        assert(fiter != fiter.start_of_block());
      }
      else {
        assert(offset+1 == count);
        assert(fiter == fiter.start_of_block());
      }
      for (unsigned i = 0; i < num_columns; ++i) 
        prev_end.push_back(buffer[offset*table_columns+indices[i]]);
    }
  }
  assert(prev_end.empty());
  assert(fiter == file_ids.end());
  
  return MB_SUCCESS;
}
*/
ErrorCode ReadHDF5VarLen::read_offsets( ReadHDF5Dataset& data_set,
                                        const Range& file_ids,
                                        EntityHandle start_file_id,
                                        EntityHandle nudge,
                                        Range& offsets_out,
                                        std::vector<unsigned>& counts_out )
{
  
    // Use hints to make sure insertion into ranges is O(1)
  offsets_out.clear();
  counts_out.clear();
  counts_out.reserve( file_ids.size() );
  Range::iterator hint;

    // Calculate which rows we need to read from the offsets table
  Range rows;
  hint = rows.begin();
  Range::const_pair_iterator pair = file_ids.const_pair_begin();
    // special case if reading first entity in dataset, because
    // there is no previous end value.
  if (pair != file_ids.const_pair_end() && pair->first == start_file_id) {
    hint = rows.insert( nudge, pair->second - start_file_id + nudge );
    ++pair;
  }
  while (pair != file_ids.const_pair_end()) {
    hint = rows.insert( hint,
                        pair->first  - start_file_id + nudge - 1, 
                        pair->second - start_file_id + nudge );
    ++pair;
  }
    
    // set up read of offsets dataset
  hsize_t buffer_size = bufferSize / sizeof(hssize_t);
  hssize_t* buffer = reinterpret_cast<hssize_t*>(dataBuffer);
  data_set.set_file_ids( rows, nudge, buffer_size, H5T_NATIVE_HSSIZE );
  hssize_t prev_end;
  bool have_prev_end = false;
    // If we're reading the first row of the table, then the 
    // previous end is implicitly -1.
  if (!file_ids.empty() && file_ids.front() == start_file_id)  {
    prev_end = -1;
    have_prev_end = true;
  }
  
  dbgOut.printf( 3, "Reading %s in %lu chunks\n", data_set.get_debug_desc(), data_set.get_read_count() );
  
    // read offset table
  size_t count, offset;
  Range::const_iterator fiter = file_ids.begin();
  hint = offsets_out.begin();
  int nn = 0;
  while (!data_set.done()) {
    dbgOut.printf( 3, "Reading chunk %d of %s\n", ++nn, data_set.get_debug_desc() );
    try {
      data_set.read( buffer, count );
    }
    catch (ReadHDF5Dataset::Exception ) {
      return MB_FAILURE;
    }
    if (!count) // might have been NULL read for collectve IO
      continue;
    
      // If the previous end values were read in the previous iteration,
      // then they're stored in prev_end.  
    offset = 0;
    if (have_prev_end) {
      counts_out.push_back( buffer[0] - prev_end );
      hint = offsets_out.insert( hint,
                                 prev_end + 1 + nudge,
                                 buffer[0] + nudge );
      ++fiter;
      offset = 1;
      have_prev_end = false;
    }

    while (offset < count) {
      assert(fiter != file_ids.end());
        // whenever we get to a gap between blocks we need to 
        // advance one step because we read an extra end id 
        // preceeding teah block
      if (fiter == fiter.start_of_block()) {
        if (offset == count-1) 
          break;
        ++offset;
      }
      
      size_t s = buffer[offset-1] + 1;
      size_t e = buffer[offset];
      counts_out.push_back( e - s + 1 );
      hint = offsets_out.insert( hint, s + nudge, e + nudge );
      
      ++fiter;
      ++offset;
    }
    
      // If we did not end on the boundary between two blocks,
      // then we need to save the end indices for the final entry
      // for use in the next iteration.  Similarly, if we ended
      // with extra values that were read with the express intention
      // of getting the previus end values for a block, we need to
      // save them.  This case only arises if we hit the break in
      // the above loop.
    if (fiter != fiter.start_of_block() || offset < count) {
      assert(!have_prev_end);
      if (offset == count) {
        --offset;
        assert(fiter != fiter.start_of_block());
      }
      else {
        assert(offset+1 == count);
        assert(fiter == fiter.start_of_block());
      }
      have_prev_end = true;
      prev_end = buffer[offset];
    }
  }
  assert(!have_prev_end);
  assert(fiter == file_ids.end());
  
  return MB_SUCCESS;
}
Example #2
0
void LinearScan::allocRegToInstruction(InstructionList::iterator it) {
  IRInstruction* inst = &*it;
  dumpIR<IRInstruction, kExtraLevel>(inst, "allocating to instruction");

  // Reload all source operands if necessary.
  // Mark registers as unpinned.
  for (int regNo = 0; regNo < kNumRegs; ++regNo) {
    m_regs[regNo].m_pinned = false;
  }
  smart::vector<bool> needsReloading(inst->numSrcs(), true);
  for (uint32_t i = 0; i < inst->numSrcs(); ++i) {
    SSATmp* tmp = inst->src(i);
    int32_t slotId = m_spillSlots[tmp];
    if (slotId == -1) {
      needsReloading[i] = false;
    } else if ((tmp = m_slots[slotId].latestReload)) {
      needsReloading[i] = false;
      inst->setSrc(i, tmp);
    }
    if (!needsReloading[i]) {
      for (int i = 0, n = m_allocInfo[tmp].numAllocatedRegs(); i < n; ++i) {
        m_regs[int(m_allocInfo[tmp].reg(i))].m_pinned = true;
      }
    }
  }
  for (uint32_t i = 0; i < inst->numSrcs(); ++i) {
    if (needsReloading[i]) {
      SSATmp* tmp = inst->src(i);
      int32_t slotId = m_spillSlots[tmp];
      // <tmp> is spilled, and not reloaded.
      // Therefore, We need to reload the value into a new SSATmp.

      // Insert the Reload instruction.
      SSATmp* spillTmp = m_slots[slotId].spillTmp;
      IRInstruction* reload = m_irFactory->gen(Reload, inst->marker(),
                                               spillTmp);
      inst->block()->insert(it, reload);

      // Create <reloadTmp> which inherits <tmp>'s slot ID and
      // <spillTmp>'s last use ID.
      // Replace <tmp> with <reloadTmp> in <inst>.
      SSATmp* reloadTmp = reload->dst();
      m_uses[reloadTmp].lastUse = m_uses[spillTmp].lastUse;
      m_spillSlots[reloadTmp] = slotId;
      inst->setSrc(i, reloadTmp);
      // reloadTmp and tmp share the same type.  Since it was spilled, it
      // must be using its entire needed-count of registers.
      assert(reloadTmp->type() == tmp->type());
      for (int locIndex = 0; locIndex < tmp->numNeededRegs();) {
        locIndex += allocRegToTmp(reloadTmp, locIndex);
      }
      // Remember this reload tmp in case we can reuse it in later blocks.
      m_slots[slotId].latestReload = reloadTmp;
      dumpIR<IRInstruction, kExtraLevel>(reload, "created reload");
    }
  }

  freeRegsAtId(m_linear[inst]);
  // Update next native.
  if (nextNative() == inst) {
    assert(!m_natives.empty());
    m_natives.pop_front();
    computePreColoringHint();
  }

  Range<SSATmp*> dsts = inst->dsts();
  if (dsts.empty()) return;

  Opcode opc = inst->op();
  if (opc == DefMIStateBase) {
    assert(dsts[0].isA(Type::PtrToCell));
    assignRegToTmp(&m_regs[int(rsp)], &dsts[0], 0);
    return;
  }

  for (SSATmp& dst : dsts) {
    for (int numAllocated = 0, n = dst.numNeededRegs(); numAllocated < n; ) {
      // LdRaw, loading a generator's embedded AR, is the only time we have a
      // pointer to an AR that is not in rVmFp.
      const bool abnormalFramePtr =
        (opc == LdRaw &&
          inst->src(1)->getValInt() == RawMemSlot::ContARPtr);

      // Note that the point of StashGeneratorSP is to save a StkPtr
      // somewhere other than rVmSp.  (TODO(#2288359): make rbx not
      // special.)
      const bool abnormalStkPtr = opc == StashGeneratorSP;

      if (!abnormalStkPtr && dst.isA(Type::StkPtr)) {
        assert(opc == DefSP ||
               opc == ReDefSP ||
               opc == ReDefGeneratorSP ||
               opc == Call ||
               opc == CallArray ||
               opc == SpillStack ||
               opc == SpillFrame ||
               opc == CufIterSpillFrame ||
               opc == ExceptionBarrier ||
               opc == RetAdjustStack ||
               opc == InterpOne ||
               opc == InterpOneCF ||
               opc == GenericRetDecRefs ||
               opc == CheckStk ||
               opc == GuardStk ||
               opc == AssertStk ||
               opc == CastStk ||
               opc == CoerceStk ||
               opc == SideExitGuardStk  ||
               MInstrEffects::supported(opc));
        assignRegToTmp(&m_regs[int(rVmSp)], &dst, 0);
        numAllocated++;
        continue;
      }
      if (!abnormalFramePtr && dst.isA(Type::FramePtr)) {
        assignRegToTmp(&m_regs[int(rVmFp)], &dst, 0);
        numAllocated++;
        continue;
      }

      // Generally speaking, StkPtrs are pretty special due to
      // tracelet ABI registers. Keep track here of the allowed uses
      // that don't use the above allocation.
      assert(!dst.isA(Type::FramePtr) || abnormalFramePtr);
      assert(!dst.isA(Type::StkPtr) || abnormalStkPtr);

      if (!RuntimeOption::EvalHHIRDeadCodeElim || m_uses[dst].lastUse != 0) {
        numAllocated += allocRegToTmp(&dst, numAllocated);
      } else {
        numAllocated++;
      }
    }
  }
  if (!RuntimeOption::EvalHHIRDeadCodeElim) {
    // if any outputs were unused, free regs now.
    freeRegsAtId(m_linear[inst]);
  }
}
Example #3
0
RangeList<T> subtract (Range<T> range, RangeList<T> sub)
{
	/* Start with the input range */
	RangeList<T> result;
	result.add (range);

	if (sub.empty () || range.empty()) {
		return result;
	}

	typename RangeList<T>::List s = sub.get ();

	/* The basic idea here is to keep a list of the result ranges, and subtract
	   the bits of `sub' from them one by one.
	*/
	
	for (typename RangeList<T>::List::const_iterator i = s.begin(); i != s.end(); ++i) {

		/* Here's where we'll put the new current result after subtracting *i from it */
		RangeList<T> new_result;

		typename RangeList<T>::List r = result.get ();

		/* Work on all parts of the current result using this range *i */
		for (typename RangeList<T>::List::const_iterator j = r.begin(); j != r.end(); ++j) {

			switch (coverage (j->from, j->to, i->from, i->to)) {
			case OverlapNone:
				/* The thing we're subtracting (*i) does not overlap this bit of the result (*j),
				   so pass it through.
				*/
				new_result.add (*j);
				break;
			case OverlapInternal:
				/* Internal overlap of the thing we're subtracting (*i) from this bit of the result,
				   so we should end up with two bits of (*j) left over, from the start of (*j) to
				   the start of (*i), and from the end of (*i) to the end of (*j).
				*/
				assert (j->from < i->from);
				assert (j->to > i->to);
				new_result.add (Range<T> (j->from, i->from - 1));
				new_result.add (Range<T> (i->to + 1, j->to));
				break;
			case OverlapStart:
				/* The bit we're subtracting (*i) overlaps the start of the bit of the result (*j),
				 * so we keep only the part of of (*j) from after the end of (*i)
				 */
				assert (i->to < j->to);
				new_result.add (Range<T> (i->to + 1, j->to));
				break;
			case OverlapEnd:
				/* The bit we're subtracting (*i) overlaps the end of the bit of the result (*j),
				 * so we keep only the part of of (*j) from before the start of (*i)
				 */
				assert (j->from < i->from);
				new_result.add (Range<T> (j->from, i->from - 1));
				break;
			case OverlapExternal:
				/* total overlap of the bit we're subtracting with the result bit, so the
				   result bit is completely removed; do nothing */
				break;
			}
		}

		new_result.coalesce ();
		result = new_result;
	}

	return result;
}
#include <echo/execution_context/tbb/blocked_range.h>
#include <echo/test.h>

using namespace echo;
using namespace echo::execution_context::intel_tbb;

TEST_CASE("tbb_blocked_range") {
  using Range = BlockedRange<int>;
  Range b1(5, 11, 2);

  SECTION("basic split") {
    Range b2(b1, tbb::split());
    CHECK(b1.begin() == 5);
    CHECK(b1.end() == 8);
    CHECK(b1.size() == 3);
    CHECK(!b1.empty());
    CHECK(b1.is_divisible());

    CHECK(b2.begin() == 8);
    CHECK(b2.end() == 11);

    Range b3(b2, tbb::split());
    CHECK((b3.size() + b2.size()) == 3);
    CHECK((!b3.is_divisible() || !b2.is_divisible()));
    CHECK(b2.end() == b3.begin());
  }

  SECTION("proportional split") {
    Range b2(b1, tbb::proportional_split(2, 1));
    CHECK(b1.begin() == 5);
    CHECK(b1.end() == 9);
Example #5
0
ErrorCode WriteVtk::write_tags(std::ostream& stream,
                               bool nodes,
                               const Range& entities,
                               const Tag* tag_list,
                               int num_tags)
{
  ErrorCode rval;

  // The #$%@#$% MOAB interface does not have a function to retrieve
  // all entities with a tag, only all entities with a specified type
  // and tag. Define types to loop over depending on the if vertex
  // or element tag data is being written. It seems horribly inefficient
  // to have the implementation subdivide the results by type and have
  // to call that function once for each type just to recombine the results.
  // Unfortunately, there doesn't seem to be any other way.
  EntityType low_type, high_type;
  if (nodes) {
    low_type = MBVERTEX;
    high_type = MBEDGE;
  }
  else {
    low_type = MBEDGE;
    high_type = MBENTITYSET;
  }

  // Get all defined tags
  std::vector<Tag> tags;
  std::vector<Tag>::iterator i;
  rval = writeTool->get_tag_list(tags, tag_list, num_tags, false);
  if (MB_SUCCESS != rval)
    return rval;

  // For each tag...
  bool entities_have_tags = false;
  for (i = tags.begin(); i != tags.end(); ++i) {
    // Skip tags holding entity handles -- no way to save them
    DataType dtype;
    rval = mbImpl->tag_get_data_type(*i, dtype);
    if (MB_SUCCESS != rval)
      return rval;
    if (dtype == MB_TYPE_HANDLE)
      continue;

    // If in strict mode, don't write tags that do not fit in any
    // attribute type (SCALAR : 1 to 4 values, VECTOR : 3 values, TENSOR : 9 values)
    if (mStrict) {
      int count;
      rval = mbImpl->tag_get_length(*i, count);
      if (MB_SUCCESS != rval)
        return rval;
      if (count < 1 || (count > 4 && count != 9))
        continue;
    }

    // Get subset of input entities that have the tag set
    Range tagged;
    for (EntityType type = low_type; type < high_type; ++type) {
      Range tmp_tagged;
      rval = mbImpl->get_entities_by_type_and_tag(0, type, &(*i), 0, 1, tmp_tagged);
      if (MB_SUCCESS != rval)
        return rval;
      tmp_tagged = intersect(tmp_tagged, entities);
      tagged.merge(tmp_tagged);
    }

    // If any entities were tagged
    if (!tagged.empty()) {
      // If this is the first tag being written for the
      // entity type, write the label marking the beginning
      // of the tag data.
      if (!entities_have_tags) {
        entities_have_tags = true;
        stream << (nodes ? "POINT_DATA " : "CELL_DATA ") << entities.size() << std::endl;
      }

      // Write the tag
      rval = write_tag(stream, *i, entities, tagged);
      if (MB_SUCCESS != rval)
        return rval;
    }
  }

  return MB_SUCCESS;
}
Example #6
0
void cloth::SwFactory::extractFabricData(const Fabric& fabric, 
	Range<uint32_t> phases, Range<uint32_t> sets, 
	Range<float> restvalues, Range<uint32_t> indices, 
	Range<uint32_t> anchors, Range<float> tetherLengths) const
{
	const SwFabric& swFabric = static_cast<const SwFabric&>(fabric);

	PX_ASSERT(phases.empty() || phases.size() == swFabric.getNumPhases());
	PX_ASSERT(restvalues.empty() || restvalues.size() == swFabric.getNumRestvalues());
	PX_ASSERT(sets.empty() || sets.size() == swFabric.getNumSets());
	PX_ASSERT(indices.empty() || indices.size() == swFabric.getNumIndices());
	PX_ASSERT(anchors.empty() || anchors.size() == swFabric.getNumTethers());
	PX_ASSERT(tetherLengths.empty() || tetherLengths.size() == swFabric.getNumTethers());

	for(uint32_t i=0; !phases.empty(); ++i, phases.popFront())
		phases.front() = swFabric.mPhases[i];

	const uint32_t* sEnd = swFabric.mSets.end(), *sIt;
	const float* rBegin = swFabric.mRestvalues.begin(), *rIt = rBegin;
	const uint16_t* iIt = swFabric.mIndices.begin();

	uint32_t* sDst = sets.begin();
	float* rDst = restvalues.begin();
	uint32_t* iDst = indices.begin();

	uint32_t numConstraints = 0;
	for(sIt = swFabric.mSets.begin(); ++sIt != sEnd; )
	{
		const float* rEnd = rBegin + *sIt;
		for(; rIt != rEnd; ++rIt)
		{
			uint16_t i0 = *iIt++;
			uint16_t i1 = *iIt++;

			if(PxMax(i0, i1) >= swFabric.mNumParticles)
				continue;

			if(!restvalues.empty())
				*rDst++ = *rIt;

			if(!indices.empty())
			{
				*iDst++ = i0;
				*iDst++ = i1;
			}

			++numConstraints;
		}

		if(!sets.empty())
			*sDst++ = numConstraints;
	}
	
	for(uint32_t i=0; !anchors.empty(); ++i, anchors.popFront())
		anchors.front() = swFabric.mTethers[i].mAnchor;

	for(uint32_t i=0; !tetherLengths.empty(); ++i, tetherLengths.popFront())
		tetherLengths.front() = swFabric.mTethers[i].mLength * swFabric.mTetherLengthScale;
}
Example #7
0
	inline bool empty(void) const
	{
		return range.empty();
	}
Example #8
0
ErrorCode TreeValidator::visit( EntityHandle node,
                                  int depth,
                                  bool& descend )
{
  ErrorCode rval;
  descend = true;
  
  Range contents;
  rval = instance->get_entities_by_handle( node, contents );
  if (MB_SUCCESS != rval) 
    return error(node, "Error getting contents of tree node.  Corrupt tree?");
  entity_count += contents.size();
  
  if (surfaces) {
      // if no longer in subtree for previous surface, clear
    if (depth <= surface_depth) 
      surface_depth = -1;
      
    EntityHandle surface = 0;
    Range::iterator surf_iter = contents.lower_bound( MBENTITYSET );
    if (surf_iter != contents.end()) {
      surface = *surf_iter;
      contents.erase( surf_iter );
    }
    
    if (surface) {
      if (surface_depth >=0) {
        ++multiple_surface_count;
        print( node, "Multiple surfaces in encountered in same subtree." );
      }
      else {
        surface_depth = depth;
        surface_handle = surface;
      }
    }
  }
  
  std::vector<EntityHandle> children;
  rval = tool->get_moab_instance()->get_child_meshsets( node, children );
  if (MB_SUCCESS != rval || (!children.empty() && children.size() != 2)) 
    return error(node, "Error getting children.  Corrupt tree?");
  
  OrientedBox box;
  rval = tool->box( node, box );
  if (MB_SUCCESS != rval) 
    return error(node, "Error getting oriented box from tree node.  Corrupt tree?");
  
  if (children.empty() && contents.empty()) {
    ++empty_leaf_count;
    print( node, "Empty leaf node.\n" );
  }
  else if (!children.empty() && !contents.empty()) {
    ++non_empty_non_leaf_count;
    print( node, "Non-leaf node is not empty." );
  }
  
  if (surfaces && children.empty() && surface_depth < 0) {
    ++missing_surface_count;
    print( node, "Reached leaf node w/out encountering any surface set.");
  }
  
  double dot_epsilon = epsilon*(box.axis[0]+box.axis[1]+box.axis[2]).length();
  if (box.axis[0] % box.axis[1] > dot_epsilon ||
      box.axis[0] % box.axis[2] > dot_epsilon ||
      box.axis[1] % box.axis[2] > dot_epsilon ) {
    ++non_ortho_count;
    print (node, "Box axes are not orthogonal");
  }
  
  if (!children.empty()) {
    for (int i = 0; i < 2; ++i) {
      OrientedBox other_box;
      rval = tool->box( children[i], other_box );
      if (MB_SUCCESS != rval) 
        return error( children[i], " Error getting oriented box from tree node.  Corrupt tree?" );
//      else if (!box.contained( other_box, epsilon )) {
//        ++child_outside_count;
//        print( children[i], "Parent box does not contain child box." );
//        char string[64];
//        sprintf(string, "     Volume ratio is %f", other_box.volume()/box.volume() );
//        print( children [i], string );
//      }
        else {
          double vol_ratio = other_box.volume()/box.volume();
          if (vol_ratio > 2.0) {
            char string[64];
            sprintf(string, "child/parent volume ratio is %f", vol_ratio );
            print( children[i], string );
            sprintf(string, "   child/parent area ratio is %f", other_box.area()/box.area() );
            print( children[i], string );
          }
       }
    }
  }
  
  bool bad_element = false;
  bool bad_element_handle = false;
  bool bad_element_conn = false;
  bool duplicate_element = false;
  int num_outside = 0;
  bool boundary[6] = { false, false, false, false, false, false };
  for (Range::iterator it = contents.begin(); it != contents.end(); ++it) {
    EntityType type = instance->type_from_handle( *it );
    int dim = CN::Dimension( type );
    if (dim != 2) {
      bad_element = true;
      continue;
    }
    
    const EntityHandle* conn;
    int conn_len;
    rval = instance->get_connectivity( *it, conn, conn_len );
    if (MB_SUCCESS != rval) {
      bad_element_handle = true;
      continue;
    }
    
    std::vector<CartVect> coords(conn_len);
    rval = instance->get_coords( conn, conn_len, coords[0].array() );
    if (MB_SUCCESS != rval) {
      bad_element_conn = true;
      continue;
    }
    
    bool outside = false;
    for (std::vector<CartVect>::iterator j = coords.begin(); j != coords.end(); ++j) {
      if (!box.contained( *j, epsilon ))
        outside = true;
      else for (int d = 0; d < 3; ++d) {
#if MB_ORIENTED_BOX_UNIT_VECTORS
        double n = box.axis[d] % (*j - box.center);
        if (fabs(n - box.length[d]) <= epsilon)
          boundary[2*d] = true;
        if (fabs(n + box.length[d]) <= epsilon)
          boundary[2*d+1] = true;
#else
        double ln = box.axis[d].length();
        CartVect v1 = *j - box.center - box.axis[d];
        CartVect v2 = *j - box.center + box.axis[d];
        if (fabs(v1 % box.axis[d]) <= ln * epsilon)
          boundary[2*d] = true;
        if (fabs(v2 % box.axis[d]) <= ln * epsilon)
          boundary[2*d+1] = true;
#endif
      }
    }
    if (outside)
      ++num_outside;
      
    if (!seen.insert(*it).second) {
      duplicate_element = true;
      ++duplicate_entity_count;
    }
  }
  
  CartVect alength( box.axis[0].length(), box.axis[1].length(), box.axis[2].length() );
#if MB_ORIENTED_BOX_UNIT_VECTORS
  CartVect length = box.length;
#else
  CartVect length = alength;
#endif
  
  if (length[0] > length[1] || length[0] > length[2] || length[1] > length[2]) {
    ++unsorted_axis_count;
    print( node, "Box axes are not ordered from shortest to longest." );
  }
  
#if MB_ORIENTED_BOX_UNIT_VECTORS
  if (fabs(alength[0] - 1.0) > epsilon ||
      fabs(alength[1] - 1.0) > epsilon ||
      fabs(alength[2] - 1.0) > epsilon) {
    ++non_unit_count;
    print( node, "Box axes are not unit vectors.");
  }
#endif

#if MB_ORIENTED_BOX_OUTER_RADIUS
  if (fabs(length.length() - box.radius) > tolerance) {
    ++bad_outer_radius_count;
    print( node, "Box has incorrect outer radius.");
  }
#endif

  if (depth+1 < settings.max_depth 
      && contents.size() > (unsigned)(4*settings.max_leaf_entities))
  {
    char string[64];
    sprintf(string, "leaf at depth %d with %u entities", depth, (unsigned)contents.size() );
    print( node, string );
  }
    
      
  bool all_boundaries = true;
  for (int f = 0; f < 6; ++f)
    all_boundaries = all_boundaries && boundary[f];
  
  if (bad_element) {
    ++entity_invalid_count;
    print( node, "Set contained an entity with an inappropriate dimension." );
  }
  if (bad_element_handle) {
    ++error_count;
    print( node, "Error querying face contained in set.");
  }
  if (bad_element_conn) {
    ++error_count;
    print( node, "Error querying connectivity of element.");
  }
  if (duplicate_element) {
    print( node, "Elements occur in multiple leaves of tree.");
  }
  if (num_outside > 0) {
    ++entity_outside_count;
    num_entities_outside += num_outside;
    if (printing)
      stream << instance->id_from_handle( node ) << ": "
             << num_outside << " elements outside box." << std::endl;
  }
  else if (!all_boundaries && !contents.empty()) {
    ++loose_box_count;
    print( node, "Box does not fit contained elements tightly." );
  }

  return MB_SUCCESS;
}
Example #9
0
static bool do_file( const char* filename )
{
  ErrorCode rval;
  Core instance;
  Interface* const iface = &instance;
  OrientedBoxTreeTool tool( iface );
  bool haveSurfTree = false;
  
  if (verbosity) 
    std::cout << filename << std::endl
              << "------" << std::endl;
  
  rval = iface->load_mesh( filename );
  if (MB_SUCCESS != rval) {
    if (verbosity)
      std::cout << "Failed to read file: \"" << filename << '"' << std::endl;
     return false;
  }
  
    // IF building from surfaces, get surfaces.
    // If AUTO and less than two surfaces, don't build from surfaces.
  Range surfaces;
  if (surfTree != DISABLE) {
    Tag surftag;
    rval = iface->tag_get_handle( GEOM_DIMENSION_TAG_NAME, 1, MB_TYPE_INTEGER, surftag );
    if (MB_SUCCESS == rval) {
      int dim = 2;
      const void* tagvalues[] = {&dim};
      rval = iface->get_entities_by_type_and_tag( 0, MBENTITYSET,
                                &surftag, tagvalues, 1, surfaces );
      if (MB_SUCCESS != rval && MB_ENTITY_NOT_FOUND != rval)
        return false;
    }
    else if (MB_TAG_NOT_FOUND != rval) 
      return false;
    
    if (ENABLE == surfTree && surfaces.empty()) {
      std::cerr << "No Surfaces found." << std::endl;
      return false;
    }
    
    haveSurfTree = (ENABLE == surfTree) || (surfaces.size() > 1);
  }
  
  EntityHandle root;
  Range entities;
  if (!haveSurfTree) {
    rval = iface->get_entities_by_dimension( 0, 2, entities );
    if (MB_SUCCESS != rval) {
      std::cerr << "get_entities_by_dimension( 2 ) failed." << std::endl;
      return false;
    }
  
    if (entities.empty()) {
      if (verbosity)
        std::cout << "File \"" << filename << "\" contains no 2D elements" << std::endl;
      return false;
    }
  
    if (verbosity) 
      std::cout << "Building tree from " << entities.size() << " 2D elements" << std::endl;

    rval = tool.build( entities, root, &settings );
    if (MB_SUCCESS != rval) {
      if (verbosity)
        std::cout << "Failed to build tree." << std::endl;
      return false;
    }
  }
  else {

    if (verbosity)
      std::cout << "Building tree from " << surfaces.size() << " surfaces" << std::endl;

      // Build subtree for each surface, get list of all entities to use later
    Range surf_trees, surf_tris;
    EntityHandle surf_root;
    for (Range::iterator s = surfaces.begin(); s != surfaces.end(); ++s) {
      surf_tris.clear();
      rval= iface->get_entities_by_dimension( *s, 2, surf_tris );
      if (MB_SUCCESS != rval)
        return false;
      rval = tool.build( surf_tris, surf_root, &settings );
      if (MB_SUCCESS != rval) {
        if (verbosity)
          std::cout << "Failed to build tree for surface." << std::endl;
        return false;
      }
      surf_trees.insert( surf_root );
      entities.merge( surf_tris );
      rval = iface->add_entities( surf_root, &*s, 1 );
      if (MB_SUCCESS != rval)
        return false;
    }
    
    rval = tool.join_trees( surf_trees, root, &settings );
    if (MB_SUCCESS != rval) {
      if (verbosity)
        std::cout << "Failed to build tree." << std::endl;
      return false;
    }
    
    if (verbosity)
      std::cout << "Built tree from " << surfaces.size() << " surfaces" 
                << " (" << entities.size() - surfaces.size() << " elements)" << std::endl;

    entities.merge( surfaces );
  }    

  if (write_cubit) {
    std::string name = filename;
    name += ".boxes.jou";
    FILE* ptr = fopen( name.c_str(), "w+" );
    if (!ptr) {
      perror( name.c_str() );
    }
    else {
      if (verbosity)
        std::cout << "Writing: " << name << std::endl;
      fprintf(ptr,"graphics off\n");
      CubitWriter op( ptr, &tool );
      tool.preorder_traverse( root, op );
      fprintf(ptr,"graphics on\n");
      fclose( ptr );
    }
  }
  
  if (write_vtk) {
    VtkWriter op( filename, iface );
    if (verbosity)
      std::cout << "Writing leaf contents as : " << filename 
                << ".xxx.vtk where 'xxx' is the set id" << std::endl;
    tool.preorder_traverse( root, op );
  }  

  bool print_errors = false, print_contents = false;
  switch (verbosity) {
    default:
      print_contents = true;
    case 4:
      tool.print( root, std::cout, print_contents );
    case 3:
      print_errors = true;
    case 2:
      rval = tool.stats( root, std::cout );
      if (MB_SUCCESS != rval)
        std::cout << "****** Failed to get tree statistics ******" << std::endl;
    case 1:
    case 0:
      ;
  }  
  
  TreeValidator op( iface, &tool, print_errors, std::cout, tolerance, haveSurfTree, settings ); 
  rval = tool.preorder_traverse( root, op );
  bool result = op.is_valid();
  if (MB_SUCCESS != rval) {
    result = false;
    if (verbosity)
      std::cout << "Errors traversing tree.  Corrupt tree?" << std::endl;
  }
  
  bool missing = (op.entity_count != entities.size());
  if (missing)
    result = false;
  
  if (verbosity) {
    if (result)
      std::cout << std::endl << "No errors detected." << std::endl;
    else
      std::cout << std::endl << "*********************** ERROR SUMMARY **********************" << std::endl;
    if (op.child_outside_count)
      std::cout << "* " << op.child_outside_count << " child boxes not contained in parent." << std::endl;
    if (op.entity_outside_count)
      std::cout << "* " << op.entity_outside_count << " nodes containing entities outside of box." << std::endl;
    if (op.num_entities_outside)
      std::cout << "* " << op.num_entities_outside << " entities outside boxes." << std::endl;
    if (op.empty_leaf_count)
      std::cout << "* " << op.empty_leaf_count << " empty leaf nodes." << std::endl;
    if (op.non_empty_non_leaf_count)
      std::cout << "* " << op.non_empty_non_leaf_count << " non-leaf nodes containing entities." << std::endl;
    if (op.duplicate_entity_count)
      std::cout << "* " << op.duplicate_entity_count << " duplicate entities in leaves." << std::endl;
    if (op.missing_surface_count)
      std::cout << "* " << op.missing_surface_count << " leaves outside surface subtrees." << std::endl;
    if (op.multiple_surface_count)
      std::cout << "* " << op.multiple_surface_count << " surfaces within other surface subtrees." << std::endl;
    if (op.non_ortho_count)
      std::cout << "* " << op.non_ortho_count << " boxes with non-orthononal axes." << std::endl;
    if (op.non_unit_count)
      std::cout << "* " << op.non_unit_count << " boxes with non-unit axes." << std::endl;
    if (op.bad_outer_radius_count)
      std::cout << "* " << op.bad_outer_radius_count << " boxes incorrect outer radius." << std::endl;
    if (op.unsorted_axis_count)
      std::cout << "* " << op.unsorted_axis_count << " boxes axes in unsorted order." << std::endl;
    if (op.loose_box_count)
      std::cout << "* " << op.loose_box_count << " boxes that do not fit the contained entities tightly." << std::endl;
    if (op.error_count + op.entity_invalid_count)
      std::cout << "* " << op.error_count + op.entity_invalid_count
                << " other errors while traversing tree." << std::endl;
    if (missing)
      std::cout << "* tree built from " << entities.size() << " entities contains "
                << op.entity_count << " entities." << std::endl;
    if (!result)
      std::cout << "************************************************************" << std::endl;
  }
  
  if (result && save_file_name) {
    if (MB_SUCCESS == save_tree( iface, save_file_name, root ))
      std::cerr << "Wrote '" << save_file_name << "'" << std::endl;
    else
      std::cerr << "FAILED TO WRITE '" << save_file_name << "'" << std::endl;
  }
  
  if (!do_ray_fire_test( tool, root, filename, haveSurfTree )) {
    if (verbosity)
      std::cout << "Ray fire test failed." << std::endl;
    result = false;
  }
  
  if (!do_closest_point_test( tool, root, haveSurfTree )) {
    if (verbosity)
      std::cout << "Closest point test failed" << std::endl;
    result = false;
  }

  rval = tool.delete_tree( root );
  if (MB_SUCCESS != rval) {
    if (verbosity)
      std::cout << "delete_tree failed." << std::endl;
    result = false;
  }
  
  return result;
}
Example #10
0
ErrorCode DeformMeshRemap::read_file(int m_or_s, string &fname, EntityHandle &seth)
{
  // Create meshset
  ErrorCode rval = mbImpl->create_meshset(0, seth);MB_CHK_SET_ERR(rval, "Couldn't create master/slave set");
  ostringstream options;
#ifdef USE_MPI
  ParallelComm *pc = (m_or_s == MASTER ? pcMaster : pcSlave);
  if (pc && pc->size() > 1) {
    if (debug) options << "DEBUG_IO=1;CPUTIME;";
    options << "PARALLEL=READ_PART;PARTITION=PARALLEL_PARTITION;PARALLEL_RESOLVE_SHARED_ENTS;"
            << "PARALLEL_GHOSTS=2.0.1;PARALLEL_COMM=" << pc->get_id();
  }
#endif  
  rval = mbImpl->load_file(fname.c_str(), &seth, options.str().c_str());MB_CHK_SET_ERR(rval, "Couldn't load master/slave mesh");

  if (*solidSetNos[m_or_s].begin() == -1 || *fluidSetNos[m_or_s].begin() == -1) return MB_SUCCESS;

  // Get material sets for solid/fluid
  Tag tagh;
  rval = mbImpl->tag_get_handle(MATERIAL_SET_TAG_NAME, tagh);MB_CHK_SET_ERR(rval, "Couldn't get material set tag name");
  for (set<int>::iterator sit = solidSetNos[m_or_s].begin(); sit != solidSetNos[m_or_s].end(); ++sit) {
    Range sets;
    int set_no = *sit;
    const void *setno_ptr = &set_no;
    rval = mbImpl->get_entities_by_type_and_tag(seth, MBENTITYSET, &tagh, &setno_ptr, 1, sets);
    if (MB_SUCCESS != rval || sets.empty()) {
      MB_SET_ERR(MB_FAILURE, "Couldn't find solid set #" << *sit);
    }
    else
      solidSets[m_or_s].merge(sets);
  }

  // Get solid entities, and dimension
  Range tmp_range;
  for (Range::iterator rit = solidSets[m_or_s].begin(); rit != solidSets[m_or_s].end(); ++rit) {
    rval = mbImpl->get_entities_by_handle(*rit, tmp_range, true);MB_CHK_SET_ERR(rval, "Failed to get entities in solid");
  }
  if (!tmp_range.empty()) {
    int dim = mbImpl->dimension_from_handle(*tmp_range.rbegin());
    assert(dim > 0 && dim < 4);
    solidElems[m_or_s] = tmp_range.subset_by_dimension(dim);
  }

  if (debug)
    cout << "Read " << solidElems[m_or_s].size() << " solid elements from " << solidSets[m_or_s].size() <<
    " sets in " << (m_or_s == MASTER ? "master" : "slave") << " mesh." << endl;

  for (set<int>::iterator sit = fluidSetNos[m_or_s].begin(); sit != fluidSetNos[m_or_s].end(); ++sit) {
    Range sets;
    int set_no = *sit;
    const void *setno_ptr = &set_no;
    rval = mbImpl->get_entities_by_type_and_tag(seth, MBENTITYSET, &tagh, &setno_ptr, 1, sets);
    if (MB_SUCCESS != rval || sets.empty()) {
      MB_SET_ERR(MB_FAILURE, "Couldn't find fluid set #" << *sit);
    }
    else
      fluidSets[m_or_s].merge(sets);
  }

  // Get fluid entities, and dimension
  tmp_range.clear();
  for (Range::iterator rit = fluidSets[m_or_s].begin(); rit != fluidSets[m_or_s].end(); ++rit) {
    rval = mbImpl->get_entities_by_handle(*rit, tmp_range, true);MB_CHK_SET_ERR(rval, "Failed to get entities in fluid");
  }
  if (!tmp_range.empty()) {
    int dim = mbImpl->dimension_from_handle(*tmp_range.rbegin());
    assert(dim > 0 && dim < 4);
    fluidElems[m_or_s] = tmp_range.subset_by_dimension(dim);
  }

  if (debug)
    cout << "Read " << fluidElems[m_or_s].size() << " fluid elements from " << fluidSets[m_or_s].size() <<
      " sets in " << (m_or_s == MASTER ? "master" : "slave") << " mesh." << endl;

  return rval;
}
Example #11
0
//Private methods
bool Decoder::decompose_(ValueInfo &vi, Range &range)
{
    if (range.empty())
    {
        DEBUG_PRINT("Decoder::decompose_(): range is empty");
        return false;
    }
    //We will further alter the content range to be correct at the end
    Range &content = vi.content;
    content = range;
    {
        unsigned char identifier = content[0];
        content.advance_begin(1);
        switch (identifier & 0xc0)
        {
            case 0x00: vi.klass = Class::Universal; break;
            case 0x40: vi.klass = Class::Application; break;
            case 0x80: vi.klass = Class::ContextSpecific; break;
            case 0xc0: vi.klass = Class::Private; break;
        }
        vi.isConstructed = identifier & 0x20;
        vi.tag = identifier & 0x1f;
    }
    //Move content to the actual content (reading length etc.)
    {
        if (content.empty())
        {
            DEBUG_PRINT("Decoder::decompose_(): content is empty");
            return false;
        }
        unsigned char octet = content[0];
        if (octet & 0x80)
        {
            //Length is specified in long form
            octet &= 0x7f;
            if (octet)
            {
                //Definite length
                if (octet > 4)
                    Exception::raise(Error("Cannot handle length of more that 4 octets"));
                unsigned int contentLength = content.size();
                if (contentLength < octet+1)
                {
                    DEBUG_PRINT("Decoder::decompose_(): contentLength is too small: " << contentLength << " (should be at least " << octet+1 << ")");
                    return false;
                }
                unsigned int length = 0;
                for (int i = 0; i < octet; ++i)
                    length = (length << 8) + content[i+1];
                if (contentLength < octet+1+length)
                {
                    DEBUG_PRINT("Decoder::decompose_(): contentLength is too small: " << contentLength << " (should be at least " << octet+1+length << ")");
                    return false;
                }
                auto start = content.begin() + octet+1;
                content = Range(start, start + length);
            }
            else
            {
                //Indefinite length
                Exception::raise(NotImplemented("Cannot handle indefinite lengths yet"));
            }
        }
        else
        {
            //Length is specified in short form
            octet &= 0x7f;
            if (content.size() < octet+1)
            {
                DEBUG_PRINT("Decoder::decompose_(): not enough content, I expected " << octet+1 << " bytes, but I have only " << content.size());
                return false;
            }
            auto start = content.begin()+1;
            content = Range(start, start + octet);
        }
    }
    return true;
}
Example #12
0
ErrorCode MetisPartitioner::assemble_graph(const int dimension,
                                               std::vector<double> &coords,
                                               std::vector<int> &moab_ids,
                                               std::vector<int> &adjacencies, 
                                               std::vector<int> &length,
                                               Range &elems) 
{
  length.push_back(0);
    // assemble a graph with vertices equal to elements of specified dimension, edges
    // signified by list of other elements to which an element is connected

    // get the elements of that dimension
  ErrorCode result = mbImpl->get_entities_by_dimension(0, dimension, elems);
  if (MB_SUCCESS != result || elems.empty()) return result;
  
#ifdef MOAB_HAVE_MPI
    // assign global ids
  result = mbpc->assign_global_ids(0, dimension, 0); 
#endif

    // now assemble the graph, calling MeshTopoUtil to get bridge adjacencies through d-1 dimensional
    // neighbors
  MeshTopoUtil mtu(mbImpl);
  Range adjs;
    // can use a fixed-size array 'cuz the number of lower-dimensional neighbors is limited
    // by MBCN
  int neighbors[5*MAX_SUB_ENTITIES];
  double avg_position[3];
  int moab_id;
  
    // get the global id tag hanlde
  Tag gid;
  result = mbImpl->tag_get_handle(GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER,
                                  gid, MB_TAG_DENSE|MB_TAG_CREAT);MB_CHK_ERR(result);
  
  for (Range::iterator rit = elems.begin(); rit != elems.end(); rit++) {

      // get bridge adjacencies
    adjs.clear();
    result = mtu.get_bridge_adjacencies(*rit, (dimension > 0 ? dimension-1 : 3), 
                                        dimension, adjs);MB_CHK_ERR(result);
    
      // get the graph vertex ids of those
    if (!adjs.empty()) {
      assert(adjs.size() < 5*MAX_SUB_ENTITIES);
      result = mbImpl->tag_get_data(gid, adjs, neighbors);MB_CHK_ERR(result);
    }

      // copy those into adjacencies vector
    length.push_back(length.back()+(int)adjs.size());
    std::copy(neighbors, neighbors+adjs.size(), std::back_inserter(adjacencies));

      // get average position of vertices
    result = mtu.get_average_position(*rit, avg_position);MB_CHK_ERR(result);
    
      // get the graph vertex id for this element
    result = mbImpl->tag_get_data(gid, &(*rit), 1, &moab_id);MB_CHK_ERR(result);

      // copy those into coords vector
    moab_ids.push_back(moab_id);
    std::copy(avg_position, avg_position+3, std::back_inserter(coords));
  }

  if (debug) {
    std::cout << "Length vector: " << std::endl;
    std::copy(length.begin(), length.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    std::cout << "Adjacencies vector: " << std::endl;
    std::copy(adjacencies.begin(), adjacencies.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    std::cout << "Moab_ids vector: " << std::endl;
    std::copy(moab_ids.begin(), moab_ids.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    std::cout << "Coords vector: " << std::endl;
    std::copy(coords.begin(), coords.end(), std::ostream_iterator<double>(std::cout, ", "));
    std::cout << std::endl;
  }

  return MB_SUCCESS;
}
Example #13
0
ErrorCode MetisPartitioner::assemble_taggedsets_graph(const int dimension,
                                                          std::vector<double> &coords,
                                                          std::vector<int> &moab_ids,
                                                          std::vector<int> &adjacencies, 
                                                          std::vector<int> &length,
                                                          Range &elems,
					                  const char *aggregating_tag)
{
  length.push_back(0);
    // assemble a graph with vertices equal to elements of specified dimension, edges
    // signified by list of other elements to which an element is connected

  // get the tagged elements 
  Tag partSetTag;
  ErrorCode result = mbImpl->tag_get_handle(aggregating_tag, 1, MB_TYPE_INTEGER, partSetTag);MB_CHK_ERR(result);
  //ErrorCode result = mbImpl->tag_get_handle("PARALLEL_PARTITION_SET", 1, MB_TYPE_INTEGER, partSetTag);MB_CHK_ERR(result);

  result = mbImpl->get_entities_by_type_and_tag(0 , MBENTITYSET, &partSetTag, 0, 1, elems);
  if (MB_SUCCESS != result || elems.empty()) return result;

  //assign globla ids to elem sets based on aggregating_tag data 
  Tag gid_tag;
  int zero1 = -1;
  result = mbImpl->tag_get_handle("GLOBAL_ID_AGGLO", 1, MB_TYPE_INTEGER, gid_tag, MB_TAG_SPARSE|MB_TAG_CREAT, &zero1);MB_CHK_ERR(result);
  for (Range::iterator rit = elems.begin(); rit != elems.end(); rit++) 
  {
    int partSet;
    result = mbImpl->tag_get_data(partSetTag,&(*rit),1,&partSet);MB_CHK_ERR(result);
    result = mbImpl->tag_set_data(gid_tag, &(*rit), 1, &partSet);MB_CHK_ERR(result);
  }
  // clear aggregating tag data
  TagType type;
  result = mbImpl->tag_get_type(partSetTag, type);MB_CHK_ERR(result);
  if (type == MB_TAG_DENSE)
  {
    result = mbImpl->tag_delete(partSetTag);MB_CHK_ERR(result);
  }
  if (type == MB_TAG_SPARSE)
  {
    result = mbImpl->tag_delete_data(partSetTag, elems);MB_CHK_ERR(result);
  }
  
  // assemble the graph, using Skinner to get d-1 dimensional neighbors and then intersecting to get adjacencies
  std::vector<Range> skin_subFaces(elems.size());
  unsigned int i = 0;
  for (Range::iterator rit = elems.begin(); rit != elems.end(); rit++) 
  {
    Range part_ents;
    result = mbImpl->get_entities_by_handle(*rit, part_ents, false);
    if (mbImpl->dimension_from_handle(*part_ents.rbegin()) != mbImpl->dimension_from_handle(*part_ents.begin())) 
    {
      Range::iterator lower = part_ents.lower_bound(CN::TypeDimensionMap[0].first),
      upper = part_ents.upper_bound(CN::TypeDimensionMap[dimension-1].second);
      part_ents.erase(lower, upper);
    }
    Skinner skinner(mbImpl);
    result = skinner.find_skin(0, part_ents, false, skin_subFaces[i], NULL, false, true, false);MB_CHK_ERR(result);
    i++;
  }
  std::vector<EntityHandle> adjs;
  std::vector<int> neighbors;
  double avg_position[3];
  int moab_id;
  MeshTopoUtil mtu(mbImpl);
  for (unsigned int k = 0; k < i; k++)
  {
      // get bridge adjacencies for element k
    adjs.clear();
    for (unsigned int t = 0; t < i; t++)
    {
      if (t != k)
      {
        Range subFaces = intersect(skin_subFaces[k],skin_subFaces[t]);
        if (subFaces.size() > 0)
  	      adjs.push_back(elems[t]);
      }
    }
    if (!adjs.empty()) 
    {
      neighbors.resize(adjs.size());
      result = mbImpl->tag_get_data(gid_tag, &adjs[0], adjs.size(), &neighbors[0]);MB_CHK_ERR(result); 
    }
      // copy those into adjacencies vector
    length.push_back(length.back()+(int)adjs.size());
    std::copy(neighbors.begin(), neighbors.end(), std::back_inserter(adjacencies));
      // get the graph vertex id for this element
    const EntityHandle& setk = elems[k];
    result = mbImpl->tag_get_data(gid_tag, &setk, 1, &moab_id); 
    moab_ids.push_back(moab_id);
      // get average position of vertices
    Range part_ents;
    result = mbImpl->get_entities_by_handle(elems[k], part_ents, false);MB_CHK_ERR(result);
    result = mtu.get_average_position(part_ents, avg_position);MB_CHK_ERR(result);
    std::copy(avg_position, avg_position+3, std::back_inserter(coords));
  }
  for (unsigned int k = 0; k < i; k++)
  {
    for (unsigned int t = 0; t < k; t++)
    {
      Range subFaces = intersect(skin_subFaces[k],skin_subFaces[t]);
      if (subFaces.size() > 0)
        mbImpl->delete_entities(subFaces);
    }
  }

  if (debug) {
    std::cout << "Length vector: " << std::endl;
    std::copy(length.begin(), length.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    std::cout << "Adjacencies vector: " << std::endl;
    std::copy(adjacencies.begin(), adjacencies.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    std::cout << "Moab_ids vector: " << std::endl;
    std::copy(moab_ids.begin(), moab_ids.end(), std::ostream_iterator<int>(std::cout, ", "));
    std::cout << std::endl;
    std::cout << "Coords vector: " << std::endl;
    std::copy(coords.begin(), coords.end(), std::ostream_iterator<double>(std::cout, ", "));
    std::cout << std::endl;
  }
  return MB_SUCCESS;
}
Example #14
0
void
MetaBlock::postParse() {

    addNamespaces(parent_->namespaces());

    if (!method().empty()) {
        throw std::runtime_error("Method is not allowed in meta");
    }

    if (!params().empty()) {
        throw std::runtime_error("Params is not allowed in meta");
    }

    if (xsltDefined()) {
        throw std::runtime_error("Xslt is not allowed in meta");
    }

    if (lua_block_.get()) {
        if (lua_block_->xsltDefined()) {
            throw std::runtime_error("Xslt is not allowed in meta lua");
        }
        if (lua_block_->metaBlock()) {
            throw std::runtime_error("Meta is not allowed in meta lua");
        }
    }

    if (hasGuard()) {
        throw std::runtime_error("Guard is not allowed in meta");
    }

    if (root_name_.empty()) {
        root_name_.assign("meta");
    }
    else {
        std::string::size_type pos = root_name_.find(':');
        if (std::string::npos != pos) {
            std::string prefix = root_name_.substr(0, pos);
            root_name_.erase(0, pos + 1);

            if (root_name_.empty()) {
                throw std::runtime_error("Empty name in name attribute is not allowed in meta");
            }
            if (!prefix.empty()) {
                const std::map<std::string, std::string> names = namespaces();
                std::map<std::string, std::string>::const_iterator it = names.find(prefix);
                if (names.end() == it) {
                    std::stringstream str;
                    str << "Unknown " << parent_->name() << " block namespace: " << prefix;
                    throw std::runtime_error(str.str());
                }
                root_ns_ = xmlSearchNsByHref(node()->doc, node(), (const xmlChar*)it->second.c_str());
                if (NULL == root_ns_) {
                    std::stringstream str;
                    str << "Cannot find " << parent_->name() << " block namespace: " << prefix;
                    throw std::runtime_error(str.str());
                }
            }
        }
        else {
            root_ns_ = NULL;
        }
    }

    if (before_cache_save_lua_.get()) {
        Range code = getLuaCode(before_cache_save_lua_.get());
        if (!code.empty()) {
            key_.push_back('|');
            key_.append(HashUtils::hexMD5(code.begin(), code.size()));
        }
    }
}
  static PostDataStatus ParseMultipartPost(std::string &completedFile,
                                           struct mg_connection *connection,
                                           const IHttpHandler::Arguments& headers,
                                           const std::string& contentType,
                                           ChunkStore& chunkStore)
  {
    std::string boundary = "--" + contentType.substr(multipartLength);

    std::string postData;
    PostDataStatus status = ReadBody(postData, connection, headers);

    if (status != PostDataStatus_Success)
    {
      return status;
    }

    /*for (IHttpHandler::Arguments::const_iterator i = headers.begin(); i != headers.end(); i++)
      {
      std::cout << "Header [" << i->first << "] = " << i->second << "\n";
      }
      printf("CHUNK\n");*/

    typedef IHttpHandler::Arguments::const_iterator ArgumentIterator;

    ArgumentIterator requestedWith = headers.find("x-requested-with");
    ArgumentIterator fileName = headers.find("x-file-name");
    ArgumentIterator fileSizeStr = headers.find("x-file-size");

    if (requestedWith != headers.end() &&
        requestedWith->second != "XMLHttpRequest")
    {
      return PostDataStatus_Failure; 
    }

    size_t fileSize = 0;
    if (fileSizeStr != headers.end())
    {
      try
      {
        fileSize = boost::lexical_cast<size_t>(fileSizeStr->second);
      }
      catch (boost::bad_lexical_cast)
      {
        return PostDataStatus_Failure;
      }
    }

    typedef boost::find_iterator<std::string::iterator> FindIterator;
    typedef boost::iterator_range<char*> Range;

    //chunkStore.Print();

    try
    {
      FindIterator last;
      for (FindIterator it =
             make_find_iterator(postData, boost::first_finder(boundary));
           it!=FindIterator();
           ++it)
      {
        if (last != FindIterator())
        {
          Range part(&last->back(), &it->front());
          Range content = boost::find_first(part, "\r\n\r\n");
          if (/*content != Range()*/!content.empty())
          {
            Range c(&content.back() + 1, &it->front() - 2);
            size_t chunkSize = c.size();

            if (chunkSize > 0)
            {
              const char* chunkData = &c.front();

              if (fileName == headers.end())
              {
                // This file is stored in a single chunk
                completedFile.resize(chunkSize);
                if (chunkSize > 0)
                {
                  memcpy(&completedFile[0], chunkData, chunkSize);
                }
                return PostDataStatus_Success;
              }
              else
              {
                return chunkStore.Store(completedFile, chunkData, chunkSize, fileName->second, fileSize);
              }
            }
          }
        }

        last = it;
      }
    }
    catch (std::length_error)
    {
      return PostDataStatus_Failure;
    }

    return PostDataStatus_Pending;
  }
Example #16
0
 bool empty() const { return first.empty() && second.empty(); }
Example #17
0
cloth::SwFabric::SwFabric( SwFactory& factory, uint32_t numParticles, 
	Range<const uint32_t> phases, Range<const uint32_t> sets, 
	Range<const float> restvalues, Range<const uint32_t> indices, 
	Range<const uint32_t> anchors, Range<const float> tetherLengths, uint32_t id) 
: mFactory(factory),
  mNumParticles(numParticles),
  mTetherLengthScale(1.0f),
  mId(id)
{
	// should no longer be prefixed with 0
	PX_ASSERT(sets.front() != 0);

#if defined(PX_WINDOWS)
	const uint32_t kSimdWidth = 8; // avx
#elif defined(PX_X360) || defined(PX_PS3)
	const uint32_t kSimdWidth = 8; // unrolled loop
#else
	const uint32_t kSimdWidth = 4;
#endif

	// consistency check
	PX_ASSERT(sets.back() == restvalues.size());
	PX_ASSERT(restvalues.size()*2 == indices.size());
	PX_ASSERT(mNumParticles > *maxElement(indices.begin(), indices.end()));
	PX_ASSERT(mNumParticles + kSimdWidth-1 <= USHRT_MAX);

	mPhases.assign(phases.begin(), phases.end());
	mSets.reserve(sets.size() + 1);
	mSets.pushBack(0); // prefix with 0

	mOriginalNumRestvalues = uint32_t(restvalues.size());

	// padd indices for SIMD
	const uint32_t* iBegin = indices.begin(), *iIt = iBegin;
	const float* rBegin = restvalues.begin(), *rIt = rBegin;
	const uint32_t* sIt, *sEnd = sets.end();
	for(sIt = sets.begin(); sIt != sEnd; ++sIt)
	{
		const float* rEnd = rBegin + *sIt;
		const uint32_t* iEnd = iBegin + *sIt * 2;
		uint32_t numConstraints = uint32_t(rEnd - rIt);

		for(; rIt != rEnd; ++rIt)
			mRestvalues.pushBack(*rIt);

		for(; iIt != iEnd; ++iIt)
			mIndices.pushBack(uint16_t(*iIt));

		// add dummy indices to make multiple of 4
		for(; numConstraints &= kSimdWidth-1; ++numConstraints)
		{
			mRestvalues.pushBack(-FLT_MAX);
			uint32_t index = mNumParticles + numConstraints - 1;
			mIndices.pushBack(uint16_t(index));
			mIndices.pushBack(uint16_t(index));
		}

		mSets.pushBack(uint32_t(mRestvalues.size()));
	}

	// trim overallocations
	RestvalueContainer(mRestvalues.begin(), mRestvalues.end()).swap(mRestvalues);
	Vector<uint16_t>::Type(mIndices.begin(), mIndices.end()).swap(mIndices);

	// tethers
	PX_ASSERT(anchors.size() == tetherLengths.size());

	// pad to allow for direct 16 byte (unaligned) loads
	mTethers.reserve(anchors.size() + 2);
	for(; !anchors.empty(); anchors.popFront(), tetherLengths.popFront())
		mTethers.pushBack(SwTether(uint16_t(anchors.front()), tetherLengths.front()));

	mFactory.mFabrics.pushBack(this);
}
Example #18
0
 bool firstEmpty() const { return first.empty(); }
Example #19
0
int main( int argc, char* argv[] )
{
  bool geom_owners = false;
  bool mesh_owners = false;
  bool just_list = false;
  bool just_list_basic = false;
  bool tag_count = false;
  std::vector<std::string> file_list;
  set_stats total_stats, file_stats;
  std::vector<TagCounts> total_counts, file_counts;
  ErrorCode rval;
  
  Range range;

  int i;
  std::vector<std::string> read_opts;
  
  int proc_id = 0;
#ifdef USE_MPI
  int initd = 0;
  MPI_Initialized(&initd);
  if (!initd) MPI_Init(&argc,&argv);
  MPI_Comm_rank( MPI_COMM_WORLD, &proc_id );
#endif

    // scan arguments
  bool do_flag = true;
  bool print_times = false;
  bool parallel = false, resolve_shared = false, exchange_ghosts = false;
  bool printed_usage = false;
  for (i = 1; i < argc; i++)
  {
    if (!argv[i][0])
      usage_error(argv[0]);
      
    if (do_flag && argv[i][0] == '-')
    {
      switch ( argv[i][1] )
      {
          // do flag arguments:
        case '-': do_flag = false;       break;
        case 'T': print_times = true;    break;
        case 'h': 
        case 'H': print_usage( argv[0], std::cerr ); printed_usage = true; break;
        case 'f': list_formats( &mb );   break;
        case 'l': 
            if (strlen(argv[i]) == 2)
              just_list_basic = true;
            else if (strlen(argv[i]) == 3 && argv[i][2] == 'l')
              just_list = true;
            break;
#ifdef USE_MPI
        case 'p':
            parallel = true;
            if (argv[i][2] == '1' || argv[i][2] == '2') resolve_shared = true;
            if (argv[i][2] == '2') exchange_ghosts = true;
            break;
#endif
        case 'g': geom_owners = true; break;
        case 'm': mesh_owners = true; break;
        case 't': tag_count = true; break;
        default: 
            ++i;
            switch ( argv[i-1][1] )
            {
              case 'O':  read_opts.push_back(argv[i]); break;
              default: std::cerr << "Invalid option: " << argv[i] << std::endl;
            }
          
      }
    }
      // do file names
    else {
      file_list.push_back( argv[i] );
    }
  }
    
    // construct options string from individual options
  std::string read_options;
  if (parallel) {
    read_opts.push_back("PARALLEL=READ_PART");
    read_opts.push_back("PARTITION=PARALLEL_PARTITION");
  }
  if (resolve_shared) read_opts.push_back("PARALLEL_RESOLVE_SHARED_ENTS");
  if (exchange_ghosts) read_opts.push_back("PARALLEL_GHOSTS=3.0.1");
  
  if (!make_opts_string(  read_opts,  read_options )) 
  {
#ifdef USE_MPI
    MPI_Finalize();
#endif
    return USAGE_ERROR;
  }
  
  if (file_list.empty() && !printed_usage)
    print_usage(argv[0], std::cerr);
  
  for (std::vector<std::string>::iterator f = file_list.begin(); f != file_list.end(); ++f)
  {
    reset_times();
    printf("File %s:\n", f->c_str() );
    if (MB_SUCCESS != mb.load_file( f->c_str(), NULL, read_options.c_str() ))
    {
      fprintf(stderr, "Error reading file: %s\n", f->c_str() );
      return 1;
    }
    
    if (tag_count)
      rval = gather_tag_counts( 0, file_counts );
    else if (!just_list)
      rval = gather_set_stats( 0, file_stats );
    else
      rval = MB_SUCCESS;

    if (MB_SUCCESS != rval)
    {
      fprintf(stderr, "Error processing mesh from file: %s\n", f->c_str());
      return 1;
    }
    
    if (tag_count) {
      add_tag_counts( total_counts, file_counts );
      print_tag_counts( file_counts );
      file_counts.clear();
    }
    else if (just_list) {
      mb.list_entities( 0, -1 );
    }
    else {
      total_stats.add( file_stats );
      print_stats( file_stats );
      file_stats.clear();
    }
    
    if (geom_owners)
    {
      Range entities;
      Tag dim_tag = 0, id_tag = 0;
      rval = mb.tag_get_handle( GEOM_DIMENSION_TAG_NAME, 1, MB_TYPE_INTEGER, dim_tag );
      if (MB_TAG_NOT_FOUND == rval) 
      {
        fprintf( stderr, "No geometry tag defined.\n" );
      }
      else if (MB_SUCCESS != rval)
      {
        fprintf( stderr, "Error retreiving geometry tag.\n");
        return 2;
      }
      
      rval = mb.tag_get_handle( GLOBAL_ID_TAG_NAME, 1, MB_TYPE_INTEGER, id_tag );
      if (MB_TAG_NOT_FOUND == rval) 
      {
        fprintf( stderr, "No ID tag defined.\n" );
      }
      else if (MB_SUCCESS != rval)
      {
        fprintf( stderr, "Error retreiving ID tag.\n");
        return 2;
      }
      
      if (dim_tag && id_tag)
      {
        if (MB_SUCCESS != mb.get_entities_by_type_and_tag( 0, 
                                                        MBENTITYSET, 
                                                        &dim_tag,
                                                        0,
                                                        1,
                                                        entities ))
        {
          fprintf( stderr, "Error retreiving geometry entitities.\n" );
        }
      }
      
      if (entities.empty())
      {
        fprintf( stderr, "No geometry entities defined in file.\n" );
      }
      
      for (Range::iterator rit = entities.begin(); rit != entities.end(); ++rit)
      {
        int id = 0, dim = 0;
        if (MB_SUCCESS != mb.tag_get_data( dim_tag, &*rit, 1, &dim ) ||
            MB_SUCCESS != mb.tag_get_data(  id_tag, &*rit, 1,  &id ))
        {
          fprintf( stderr, "Error retreiving tag data for geometry entity.\n");
          continue;
        }
        
        printf( "%s %d:\n", geom_type_names[dim], id );
        if (tag_count)
          rval = gather_tag_counts( *rit, file_counts );
        else if (!just_list && !just_list_basic)
          rval = gather_set_stats( *rit, file_stats );
        
        if (MB_SUCCESS != rval)
          fprintf(stderr, "Error processing mesh from file: %s\n", f->c_str());
        else if (tag_count)
          print_tag_counts( file_counts );
        else if (just_list)
          mb.list_entities( 0, 1 );
        else if (just_list_basic)
          mb.list_entities( 0, 0 );
        else
          print_stats( file_stats );

        file_stats.clear();
        file_counts.clear();
      }
    }


    if (mesh_owners)
    {
      for (int t = 0; t < 3; ++t)
      {
        Range entities;
        Tag tag = 0;
        rval = mb.tag_get_handle( mesh_type_tags[t], 1, MB_TYPE_INTEGER, tag );
        if (MB_TAG_NOT_FOUND == rval) 
        {
          continue;
        }
        else if (MB_SUCCESS != rval)
        {
          fprintf( stderr, "Error retreiving %s tag.\n", mesh_type_tags[t]);
          return 2;
        }
      
        if (MB_SUCCESS != mb.get_entities_by_type_and_tag( 0, 
                                                        MBENTITYSET, 
                                                        &tag,
                                                        0,
                                                        1,
                                                        entities ))
        {
          fprintf( stderr, "Error retreiving %s entitities.\n", mesh_type_names[t] );
          continue;
        }
      
        for (Range::iterator rit = entities.begin(); rit != entities.end(); ++rit)
        {
          int id = 0;
          if (MB_SUCCESS != mb.tag_get_data( tag, &*rit, 1, &id ))
          {
            fprintf( stderr, "Error retreiving tag data for %s entity.\n", mesh_type_names[t]);
            continue;
          }

          printf( "%s %d:\n", mesh_type_names[t], id );
          if (tag_count) {
            rval = gather_tag_counts( *rit, file_counts );
            if (MB_SUCCESS != rval) 
              fprintf(stderr, "Error processing tags from file: %s\n", f->c_str());
            else
              print_tag_counts( file_counts );
          }
          else if (just_list)
            mb.list_entities( 0, 1 );
          else if (just_list_basic)
            mb.list_entities( 0, 0 );
          else if (!just_list && !just_list_basic) {
            rval = gather_set_stats( *rit, file_stats );

            if (rval != MB_SUCCESS)
              fprintf(stderr, "Error processing mesh from file: %s\n", f->c_str());
            else
              print_stats( file_stats );
          }
          file_stats.clear();
          file_counts.clear();
        }
      }
    }
    
    if (print_times && !proc_id) write_times( std::cout );
    mb.delete_mesh();
  }
  
  if (file_list.size() > 1 && !just_list && !just_list_basic)
  {
    printf("Total for all files:\n");
    if (tag_count)
      print_tag_counts( total_counts );
    else
      print_stats( total_stats );
  }
  
  return 0;
}
Example #20
0
typename RangeTypes<Range>::ElementType front() const { return first.empty() ? second.front() : first.front(); }
 bool empty() const {
 	return initial_range.empty() || mapped_range.empty();
 }
Example #22
0
 void popFront() { if (first.empty()) second.popFront(); else first.popFront(); }
Example #23
0
ErrorCode MetisPartitioner::assemble_taggedents_graph(const int dimension,
                                                          std::vector<double> &coords,
                                                          std::vector<int> &moab_ids,
                                                          std::vector<int> &adjacencies, 
                                                          std::vector<int> &length,
                                                          Range &elems,
					                  const char *aggregating_tag)
{
  Tag partSetTag;
  ErrorCode result = mbImpl->tag_get_handle(aggregating_tag, 1, MB_TYPE_INTEGER, partSetTag);
  if (MB_SUCCESS != result) return result;
 
  Range allSubElems;
  result = mbImpl->get_entities_by_dimension(0, dimension, allSubElems);
  if (MB_SUCCESS != result || allSubElems.empty()) return result;
  int partSet;
  std::map<int, Range> aggloElems;
  for (Range::iterator rit = allSubElems.begin(); rit != allSubElems.end(); rit++) 
  {
    EntityHandle entity = *rit;
    result = mbImpl->tag_get_data(partSetTag,&entity,1,&partSet);
    if (MB_SUCCESS != result) return result;
    if (partSet >= 0)
      aggloElems[partSet].insert(entity);
  }
  // clear aggregating tag data
  TagType type;
  result = mbImpl->tag_get_type(partSetTag, type);
  if (type == MB_TAG_DENSE)
  {
    // clear tag on ents and sets
    result = mbImpl->tag_delete(partSetTag); 
    if (MB_SUCCESS != result) return result;
  }
  if (type == MB_TAG_SPARSE)
  {
    // clear tag on ents
    result = mbImpl->tag_delete_data(partSetTag, allSubElems); 
    if (MB_SUCCESS != result) return result;
    // clear tag on sets
    result = mbImpl->get_entities_by_type_and_tag(0 , MBENTITYSET, &partSetTag, 0, 1, elems);
    if (MB_SUCCESS != result) return result;
    result = mbImpl->tag_delete_data(partSetTag, elems); 
    if (MB_SUCCESS != result) return result;
    elems.clear();
  }
  result = mbImpl->tag_get_handle("PARALLEL_PARTITION", 1, MB_TYPE_INTEGER,
                                  partSetTag, MB_TAG_SPARSE|MB_TAG_CREAT); 
  if (MB_SUCCESS != result) return result;
  
  for (std::map<int, Range>::iterator mit = aggloElems.begin(); mit != aggloElems.end(); mit++) 
  {
    EntityHandle new_set;
    result = mbImpl->create_meshset(MESHSET_SET, new_set);
    if (MB_SUCCESS != result) return result;
    result = mbImpl->add_entities(new_set, mit->second);
    if (MB_SUCCESS != result) return result;
    result = mbImpl->tag_set_data (partSetTag, &new_set, 1, &mit->first);
    if (MB_SUCCESS != result) return result;
  }

  result = assemble_taggedsets_graph(dimension, coords, moab_ids, adjacencies, length, elems, &(*aggregating_tag));
  return MB_SUCCESS;
}
Example #24
0
ErrorCode WriteVtk::gather_mesh(const EntityHandle* set_list,
                                int num_sets,
                                Range& nodes,
                                Range& elems)
{
  ErrorCode rval;
  int e;

  if (!set_list || !num_sets) {
    Range a;
    rval = mbImpl->get_entities_by_handle(0, a);
    if (MB_SUCCESS != rval)
      return rval;

    Range::const_iterator node_i, elem_i, set_i;
    node_i = a.lower_bound(a.begin(), a.end(), CREATE_HANDLE(   MBVERTEX, 0, e));
    elem_i = a.lower_bound(   node_i, a.end(), CREATE_HANDLE(     MBEDGE, 0, e));
    set_i  = a.lower_bound(   elem_i, a.end(), CREATE_HANDLE(MBENTITYSET, 0, e));
    nodes.merge(node_i, elem_i);
    elems.merge(elem_i, set_i);

    // Filter out unsupported element types
    EntityType et = MBEDGE;
    for (et++; et < MBENTITYSET; et++) {
      if (VtkUtil::get_vtk_type(et, CN::VerticesPerEntity(et)))
        continue;
      Range::iterator
        eit = elems.lower_bound(elems.begin(), elems.end(), CREATE_HANDLE(et, 0, e)),
        ep1it = elems.lower_bound(elems.begin(), elems.end(), CREATE_HANDLE(et + 1, 0, e));
      elems.erase(eit, ep1it);
    }
  }
  else {
    std::set<EntityHandle> visited;
    std::vector<EntityHandle> sets;
    sets.reserve(num_sets);
    std::copy(set_list, set_list + num_sets, std::back_inserter(sets));
    while (!sets.empty()) {
      // Get next set
      EntityHandle set = sets.back();
      sets.pop_back();
      // Skip sets we've already done
      if (!visited.insert(set).second)
        continue;

      Range a;
      rval = mbImpl->get_entities_by_handle(set, a);
      if (MB_SUCCESS != rval)
        return rval;

      Range::const_iterator node_i, elem_i, set_i;
      node_i = a.lower_bound(a.begin(), a.end(), CREATE_HANDLE(   MBVERTEX, 0, e));
      elem_i = a.lower_bound(   node_i, a.end(), CREATE_HANDLE(     MBEDGE, 0, e));
      set_i  = a.lower_bound(   elem_i, a.end(), CREATE_HANDLE(MBENTITYSET, 0, e));
      nodes.merge(node_i, elem_i);
      elems.merge(elem_i, set_i);
      std::copy(set_i, a.end(), std::back_inserter(sets));

      a.clear();
      rval = mbImpl->get_child_meshsets(set, a);
      std::copy(a.begin(), a.end(), std::back_inserter(sets));
    }

    for (Range::const_iterator ei = elems.begin(); ei != elems.end(); ++ei) {
      std::vector<EntityHandle> connect;
      rval = mbImpl->get_connectivity(&(*ei), 1, connect);
      if (MB_SUCCESS != rval)
        return rval;

      for (unsigned int i = 0; i < connect.size(); ++i)
        nodes.insert(connect[i]);
    }
  }

  if (nodes.empty()) {
    MB_SET_ERR(MB_ENTITY_NOT_FOUND, "Nothing to write");
  }

  return MB_SUCCESS;
}