Esempio n. 1
0
std::string toString(const Fields& fields) {
    std::vector<Point> fluxes;
    std::stringstream ss;
    ss << fields.size() << "\n";
    ss << fields[0].size() << "\n";
    for (size_t y = 0; y < fields[0].size(); ++y) {
        for (size_t x = 0; x < fields.size(); ++x) {
            ss << fields[x][y];
            if (fields[x][y].is<FluxCapatitor>()) {
                fluxes.push_back(Point(x, y));
            }
        }
        ss << '\n';
    }
    for (size_t y = 0; y < fields[0].size(); ++y) {
        for (size_t x = 0; x < fields.size(); ++x) {
            if (fields[x][y].is<Chest>()) {
                ss << fields[x][y].as<Chest>().survive_timetravels << " ";
            }
            else
                ss << 0 << " ";
        }
        ss << '\n';
    }
    for (const Point& p : fluxes) {
        ss << "Flux at " << p << ": "
            << fields[p.x][p.y].as<FluxCapatitor>() << '\n';
    }
    return ss.str();
}
Esempio n. 2
0
GetOptions::Fields GetOptions::getFileNameFields(const char* fname) {
	string tmp = string(fname);
	// Get extension (if any)
	string pathAndName, ext;
	size_t dotPos = tmp.find_last_of('.');
	if(dotPos != string::npos) {
		pathAndName = tmp.substr(0, dotPos);
		ext = tmp.substr(dotPos+1);
	} else {
		pathAndName = tmp;
		ext.clear();
	}
	// Get path and name (if any)
	string path, name;
	size_t slashPos = pathAndName.find_last_of('/');
	if(slashPos != string::npos) {
		path = pathAndName.substr(0, slashPos);
		name = pathAndName.substr(slashPos+1);
	} else {
		path.clear();
		name = pathAndName;
	}
	Fields fields;
	fields.push_back(path);
	fields.push_back(name);
	fields.push_back(ext);
	return fields;
}
Esempio n. 3
0
RecordInfo::Fields* RecordInfo::CollectFields() {
  // Compute the collection locally to avoid inconsistent states.
  Fields* fields = new Fields;
  if (!record_->hasDefinition())
    return fields;
  TracingStatus fields_status = TracingStatus::Unneeded();
  for (RecordDecl::field_iterator it = record_->field_begin();
       it != record_->field_end();
       ++it) {
    FieldDecl* field = *it;
    // Ignore fields annotated with the GC_PLUGIN_IGNORE macro.
    if (Config::IsIgnoreAnnotated(field))
      continue;
    // Check if the unexpanded type should be recorded; needed
    // to track iterator aliases only
    const Type* unexpandedType = field->getType().getSplitUnqualifiedType().Ty;
    Edge* edge = CreateEdgeFromOriginalType(unexpandedType);
    if (!edge)
      edge = CreateEdge(field->getType().getTypePtrOrNull());
    if (edge) {
      fields_status = fields_status.LUB(edge->NeedsTracing(Edge::kRecursive));
      fields->insert(std::make_pair(field, FieldPoint(field, edge)));
    }
  }
  fields_need_tracing_ = fields_status;
  return fields;
}
TEST_F( FieldsTest, FieldsMethodInAssignment ) {
  Fields abc = fields
               ( "a", ActiveRecord::integer )
               ( "b", ActiveRecord::text )
               ( "c", ActiveRecord::floating_point )
               ( "d", ActiveRecord::date );

  ASSERT_EQ( 4, abc.size() );
}
Esempio n. 5
0
bool check(const std::string & s)
{
	Fields f;
	parse(f, s);
	if (f.size() < 2)
		return false;
	char buf[4];
	sprintf(buf, "%02X", checksum(s));
	return f.back() == buf;
}
Esempio n. 6
0
Fields Project::withoutFixed(Fields fields, const Lisp<Fixed> fixed)
	{
	if (! hasFixed(fields, fixed))
		return fields;
	Fields fldswof;
	for (; ! nil(fields); ++fields)
		if (! isfixed(fixed, *fields))
			fldswof.push(*fields);
	return fldswof.reverse();
	}
Esempio n. 7
0
STDMETHODIMP CADOTier::get_FieldCount(long * newVal)
{
	Fields* fields = 0;
	HRESULT hr = m_recordset->get_Fields(&fields);
	if (SUCCEEDED(hr))
		hr = fields->get_Count(newVal);
	if (SUCCEEDED(hr))
		fields->Release();
	return hr;
}
Esempio n. 8
0
void GetOptions::processOptions() {
    
    /*
     * Wavelet type
     */
    
    if (waveletType.empty())
        waveletType = "log";
    
    /* 
     * Wavelet scales
     */
    
    // Wavelet scales
	Fields fields = getFields(scalesPar.c_str());
	if(fields.empty() | fields.size() != 4) {
		printf("ERROR : parsing scales parameters\n");
        isValidFlag = false;
		return;
	}
	
    scalesType  = fields[0].c_str();
    scalesSz    = atoi(fields[1].c_str());
	scalesMin   = atof(fields[2].c_str());
	scalesMax   = atof(fields[3].c_str());

    /*
     * Input file
     */
    
    if (inFileName.empty()) {
        printf("ERROR : missing input file\n");
        isValidFlag = false;
        return;
    }
    
    fields = getFileNameFields(inFileName.c_str());
    inFileType = fields[2].c_str();
    
    /*
     * Output file
     */
    
    if (outFileName.empty()) {
        printf("ERROR : missing output file\n");
        isValidFlag = false;
        return;
    }
    
    fields = getFileNameFields(outFileName.c_str());
    outFileType = fields[2].c_str();
    
}
Esempio n. 9
0
void CmyWord::UpdateField(CString strBMark)
{
	COleVariant varBMark_del(strBMark);		//设置变量
	Bookmarks  bookmarks = m_wdDoc.GetBookmarks();
	if(!bookmarks.Exists((LPCTSTR)strBMark))
	{
		return;
	}
	m_wdSel.GoTo(COleVariant(short(1),VT_BOOL),COleVariant((short)0),COleVariant((short)0),varBMark_del);
	Fields fields = Fields(m_wdSel.GetFields());
	fields.Update();
	bookmarks.ReleaseDispatch();
}
Esempio n. 10
0
STDMETHODIMP CADOTier::put_Field(VARIANT idx, VARIANT newVal)
{
	Fields* fields = 0;
	HRESULT hr = m_recordset->get_Fields(&fields);
	Field* field = 0;
	if (SUCCEEDED(hr))
		hr = fields->get_Item(idx, &field);
	if (SUCCEEDED(hr))
		hr = field->put_Value(newVal);

	if (SUCCEEDED(hr))
	{
		fields->Release();
		field->Release();
	}
	return hr;
}
Esempio n. 11
0
	virtual void readable() override {
		doc.reset();
		
		this->read(doc);
		
		f.parse(doc);
		timeout();
	}
Esempio n. 12
0
void Project::includeDeps(const Fields& columns)
	{
	for (Fields f = flds; ! nil(f); ++f)
		{
		gcstring deps(*f + "_deps");
		if (columns.member(deps) && ! flds.member(deps))
			flds.append(deps);
		}
	}
Esempio n. 13
0
GetOptions::Fields GetOptions::getFields(const char *str, char sep) {
	string tmp = string(str);
	Fields fields;
	while(true) {
		size_t pos = tmp.find_first_of(sep);		
		if(pos == string::npos && tmp.size() != 0) {	// One field without sep char
			fields.push_back(tmp);						// Save string
			break;										// End loop
		} else {										// Field found
			if(pos != 0)
				fields.push_back(tmp.substr(0, pos));	// Save string
			tmp = tmp.substr(pos+1);					// Get remaining fields
			if(tmp.size() == 0)							// No more fields
				break;									// End loop
		}
	}
	return fields;
}
Esempio n. 14
0
TEST(TestDatabaseUtils, GetSelectFields)
{
  Fields fields;
  FieldList fieldlist;

  EXPECT_FALSE(DatabaseUtils::GetSelectFields(fields, MediaTypeAlbum,
                                              fieldlist));

  fields.insert(FieldId);
  fields.insert(FieldGenre);
  fields.insert(FieldAlbum);
  fields.insert(FieldArtist);
  fields.insert(FieldTitle);
  EXPECT_FALSE(DatabaseUtils::GetSelectFields(fields, MediaTypeNone,
                                              fieldlist));
  EXPECT_TRUE(DatabaseUtils::GetSelectFields(fields, MediaTypeAlbum,
                                             fieldlist));
  EXPECT_FALSE(fieldlist.empty());
}
Esempio n. 15
0
void parse(Fields & v, const std::string & s)
{
	using std::string;
	string::size_type i = 0;
	string f;
	while (parse(f, s, i)) {
		i += f.size() + 1;
		v.push_back(f);
	}
}
Esempio n. 16
0
RecordInfo::Fields* RecordInfo::CollectFields() {
  // Compute the collection locally to avoid inconsistent states.
  Fields* fields = new Fields;
  if (!record_->hasDefinition())
    return fields;
  TracingStatus fields_status = TracingStatus::Unneeded();
  for (RecordDecl::field_iterator it = record_->field_begin();
       it != record_->field_end();
       ++it) {
    FieldDecl* field = *it;
    // Ignore fields annotated with the GC_PLUGIN_IGNORE macro.
    if (Config::IsIgnoreAnnotated(field))
      continue;
    if (Edge* edge = CreateEdge(field->getType().getTypePtrOrNull())) {
      fields_status = fields_status.LUB(edge->NeedsTracing(Edge::kRecursive));
      fields->insert(std::make_pair(field, FieldPoint(field, edge)));
    }
  }
  fields_need_tracing_ = fields_status;
  return fields;
}
Esempio n. 17
0
bool DatabaseUtils::GetSelectFields(const Fields &fields, const MediaType &mediaType, FieldList &selectFields)
{
  if (mediaType == MediaTypeNone || fields.empty())
    return false;

  Fields sortFields = fields;

  // add necessary fields to create the label
  if (mediaType == MediaTypeSong || mediaType == MediaTypeVideo || mediaType == MediaTypeVideoCollection ||
      mediaType == MediaTypeMusicVideo || mediaType == MediaTypeMovie || mediaType == MediaTypeTvShow || mediaType == MediaTypeEpisode)
    sortFields.insert(FieldTitle);
  if (mediaType == MediaTypeEpisode)
  {
    sortFields.insert(FieldSeason);
    sortFields.insert(FieldEpisodeNumber);
  }
  else if (mediaType == MediaTypeAlbum)
    sortFields.insert(FieldAlbum);
  else if (mediaType == MediaTypeSong)
    sortFields.insert(FieldTrackNumber);
  else if (mediaType == MediaTypeArtist)
    sortFields.insert(FieldArtist);

  selectFields.clear();
  for (Fields::const_iterator it = sortFields.begin(); it != sortFields.end(); ++it)
  {
    // ignore FieldLabel because it needs special handling (see further up)
    if (*it == FieldLabel)
      continue;

    if (GetField(*it, mediaType, DatabaseQueryPartSelect).empty())
    {
      CLog::Log(LOGDEBUG, "DatabaseUtils::GetSortFieldList: unknown field %d", *it);
      continue;
    }
    selectFields.push_back(*it);
  }

  return !selectFields.empty();
}
Esempio n. 18
0
void SortUtils::Sort(SortBy sortBy, SortOrder sortOrder, SortAttribute attributes, SortItems& items, int limitEnd /* = -1 */, int limitStart /* = 0 */)
{
  if (sortBy != SortByNone)
  {
    // get the matching SortPreparator
    SortPreparator preparator = getPreparator(sortBy);
    if (preparator != NULL)
    {
      Fields sortingFields = GetFieldsForSorting(sortBy);

      // Prepare the string used for sorting and store it under FieldSort
      for (SortItems::iterator item = items.begin(); item != items.end(); ++item)
      {
        // add all fields to the item that are required for sorting if they are currently missing
        for (Fields::const_iterator field = sortingFields.begin(); field != sortingFields.end(); ++field)
        {
          if ((*item)->find(*field) == (*item)->end())
            (*item)->insert(std::pair<Field, CVariant>(*field, CVariant::ConstNullVariant));
        }

        std::wstring sortLabel;
        g_charsetConverter.utf8ToW(preparator(attributes, **item), sortLabel, false);
        (*item)->insert(std::pair<Field, CVariant>(FieldSort, CVariant(sortLabel)));
      }

      // Do the sorting
      std::stable_sort(items.begin(), items.end(), getSorterIndirect(sortOrder, attributes));
    }
  }

  if (limitStart > 0 && (size_t)limitStart < items.size())
  {
    items.erase(items.begin(), items.begin() + limitStart);
    limitEnd -= limitStart;
  }
  if (limitEnd > 0 && (size_t)limitEnd < items.size())
    items.erase(items.begin() + limitEnd, items.end());
}
Esempio n. 19
0
void TableSet::update_table( Table &required ) {
  log( "TableSet::update_table" );
  log( required.table_name() );
  Table existing = table_data( required.connection(), required.table_name() );
  Fields missing = required.fields() - existing.fields();
  Fields remove  = existing.fields() - required.fields();
  for( Fields::iterator it = missing.begin(); it != missing.end(); ++it )
    existing.add_field( *it );
  for( Fields::iterator it = remove.begin(); it != remove.end(); ++it ) {
    throw ActiveRecordException( "Table::remove_field not yet implemented", __FILE__, __LINE__ );
    //existing.remove_field( *it );
  }
}
Esempio n. 20
0
T fieldValue(const Fields& fields, const std::string& name, const T& defaultVal)
{
   Fields::const_iterator pos = findField(fields, name);
   if (pos != fields.end())
   {
      try
      {
         return boost::lexical_cast<T>(pos->second);
      }
      catch(boost::bad_lexical_cast&)
      {
         return defaultVal;
      }
   }
   else // not found, return default
   {
      return defaultVal;
   }
}
Esempio n. 21
0
bool RMC::set(RMC & d, const Fields & f)
{
	if (type(f) != TYPE_RMC)
		return false;
	if (f.size() != 14)
		return false;
	field(d.time, f[1]);
	field(d.status, f[2]);
	field(d.lat, f[3]);
	field(d.lat_h, f[4]);
	field(d.lon, f[5]);
	field(d.lon_h, f[6]);
	field(d.v, f[7]);
	field(d.heading, f[8]);
	field(d.date, f[9]);
	field(d.m, f[10]);
	field(d.m_h, f[11]);
	field(d.mode, f[12]);
	return true;
}
Esempio n. 22
0
TEST(TestSortUtils, GetFieldsForSorting)
{
  Fields fields;

  fields = SortUtils::GetFieldsForSorting(SortByArtist);
  Fields::iterator it;
  it = fields.find(FieldAlbum);
  EXPECT_EQ(FieldAlbum, *it);
  it = fields.find(FieldArtist);
  EXPECT_EQ(FieldArtist, *it);
  it = fields.find(FieldYear);
  EXPECT_EQ(FieldYear, *it);
  it = fields.find(FieldTrackNumber);
  EXPECT_EQ(FieldTrackNumber, *it);
  EXPECT_EQ((unsigned int)4, fields.size());
}
Esempio n. 23
0
bool fieldsToBufString(IErrorHandler* err, char*& buf, size_t& bufSize, const Fields& fields, uint32_t fieldMask) {
    if (!bufStringSet(err, buf, bufSize, "{", 1))
        return false;

    char* fieldAsString = nullptr;
    size_t fieldAsStringSize = 0;

    AllocGuard guard(fieldAsString);
    bool first = true;

    for (size_t i = 0; i < fields.count(); i++) {
        const auto& field = fields[i];

        if (!(field.systemFlags & fieldMask))
            continue;

        if (!first) {
            if (!bufStringAppend(err, buf, bufSize, ", ", 2))
                return false;
        }
        else
            first = false;

        if (!field.toString(err, fieldAsString, fieldAsStringSize))
            return false;

        if (!bufStringAppend(err, buf, bufSize, field.name, strlen(field.name))
                || !bufStringAppend(err, buf, bufSize, "=\"", 2)
                || !bufStringAppend(err, buf, bufSize, fieldAsString, strlen(fieldAsString))
                || !bufStringAppend(err, buf, bufSize, "\"", 1))
            return false;

    }

    if (!bufStringAppend(err, buf, bufSize, "}", 1))
        return false;

    return true;
}
TEST_F( FieldsTest, DoesNotSubtractAccordingToType ) {
  Field i( "a", ActiveRecord::integer );
  Field t( "a", ActiveRecord::text );
  Field f( "a", ActiveRecord::floating_point );

  Fields it;
  it.push_back( i );
  it.push_back( t );

  Fields tf;
  tf.push_back( t );
  tf.push_back( f );

  Fields result = it - tf;

  ASSERT_EQ( 0, result.size() );
}
TEST_F( FieldTest, SubtractsAccordingToName ) {
  Field a( "a", ActiveRecord::integer );
  Field b( "b", ActiveRecord::integer );
  Field c( "c", ActiveRecord::integer );
  Field d( "d", ActiveRecord::integer );

  Fields abc;
  abc.push_back( a );
  abc.push_back( b );
  abc.push_back( c );

  Fields cd;
  cd.push_back( c );
  cd.push_back( d );

  Fields ab = abc - cd;

  ASSERT_EQ( 2, ab.size() );
  ASSERT_STREQ( "a", ab[ 0 ].name().c_str() );
  ASSERT_STREQ( "b", ab[ 1 ].name().c_str() );
}
Esempio n. 26
0
bool fieldValue(const Fields& fields, 
                const std::string& name, 
                const Predicate& validator,
                T* pValue)
{
   Fields::const_iterator pos = findField(fields, name);
   if (pos != fields.end())
   {
      try
      {
         *pValue = boost::lexical_cast<T>(pos->second);
         return validator(*pValue);
      }
      catch(boost::bad_lexical_cast&)
      {
         return false;
      }
   }
   else 
   {
      return false;
   }
}
Esempio n. 27
0
	virtual void timeout() {
		this->write(f.moves(millisecToNext));
	}
Esempio n. 28
0
Type type(const Fields & v)
{
	if (!v.empty())
		return type(v[0]);
	return TYPE_UNKNOWN;
}
Esempio n. 29
0
SpatialRegion* SpatialRegionGroup::CreateCounterPart()
  throw(Oops){
  if (CP.getFrandseed())
    frandseed = CP.getFrandseed();
  GP.checkRules();
  GP.showRuleMessages();
  CP.checkRules();
  CP.showRuleMessages();
  Grid *G;
#ifdef MPI_VERSION
  int MPI_MAX_RANK;
  MPI_Comm_size(XOOPIC_COMM,&MPI_MAX_RANK);
  if (MPI_MAX_RANK > 1) {  //  if we have more than one region.
#ifdef MPI_DEBUG
    printf("\n%d: Creating grid with %d partitions.",MPI_RANK,MPI_MAX_RANK);
#endif
    G = GP.CreateCounterPart(CP.getMPIpartition());
  }
  else
#endif /* MPI_VERSION */
    G = GP.CreateCounterPart();
  
  oopicList<Boundary> *BList = new BoundaryList;
  
  //put the periodic boundary on the boundary list MUST BE FIRST HERE SO THAT IT IS LAST IN PHYSICS
  if ((GP.getPeriodicFlagX1())||(GP.getPeriodicFlagX2())){
    oopicList<LineSegment> *LineSegmentList = new oopicList<LineSegment>;
    LineSegment *newSeg = new LineSegment(Vector2(0,0),Vector2(GP.getJ(),GP.getK()),1);
    LineSegmentList->add(newSeg);
    Boundary* B = 
      new Periodic(LineSegmentList, GP.getPeriodicFlagX1(), GP.getPeriodicFlagX2());
    BList->add(B);
  }
  
  oopicListIter<BoundaryParams> nB(Boundaries);
  for (nB.restart(); !nB.Done(); nB++)
    {
      BoundaryParams *bParam=nB.current();
      try{
        bParam->toGrid(G);  //cause the boundary to 'snap to' j,k's if given MKS
      // moved toGrid to checkRules because some of the rules are for j1,j2,k1,k2.
      // moved back to CreateCounter Part and removed checkRules
      }
      catch(Oops& oops){
        oops.prepend("SpatialRegionGroup::CreateCounterPart: Error:\n"); //AdvisorManager::createDevice
        throw oops;
      }

#ifdef MPI_VERSION
      if(! (bParam->j1.getValue()==-1 && bParam->A1.getValue()==-1)) {
        // we don't want to create boundaries which are out-of-bounds!
#endif /* MPI_VERSION */
        bParam->checkRules();
        bParam->showRuleMessages();
        Boundary* bPtr = 0;
        try{
          bPtr = bParam->CreateCounterPart();
        }
        catch(Oops& oops2){
          oops2.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");//done
          throw oops2;
        }
        bParam->setBoundaryParams(bPtr);  //should probably cascade CreateCounterPart()
        BList->add(bPtr);
#ifdef MPI_VERSION
      }
#endif /*MPI_VERSION */
    }
  
  // Move this call here.  It saves trouble with deciding where to put any SRB's.
  G->setBoundaryMask(*BList);
#ifdef MPI_VERSION
  /*  At this point, we should add all the necessary SRB's to our region.  */
  try{
    addNeededSRBstoRegion(BList,G);
  }
  catch(Oops& oops3){
    oops3.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");
    throw oops3;
  }

#endif /*MPI_VERSION*/

  SpeciesParamsList* speciesParamsList = advisorp->get_speciesParamsList();
  int tmpDim = speciesParamsList->nItems();
  ParticleGroupList** pgListArray = new ParticleGroupList*[tmpDim];
  for (int i=0; i<tmpDim; i++)
    pgListArray[i] = new ParticleGroupList;
  
  SpeciesList* speciesList = advisorp->get_speciesList();
  
  Scalar epsilonR = 1.0;
  Fields *F = new Fields(G, BList, speciesList, epsilonR, 
                         CP.getElectrostaticFlag(),CP.get_presidue(),
                         CP.getBoltzmannFlag(),CP.getSynchRadiationFlag());
  
  F->set_bSpecies(get_speciesPtr(CP.getBoltzSpecies()));
  if (!F->setBNodeStatic(Vector3(CP.getB01(),CP.getB02(),CP.getB03()),
                         CP.getbetwig(), CP.getzoff(),CP.getBf().c_str(),
                         CP.getB01analytic(),CP.getB02analytic(),
			 CP.getB03analytic()))
    abort();;
  
  
  F->setBeamDump(CP.get_j1BeamDump(), CP.get_j2BeamDump());
  
  F->setMarderIter(CP.getMarderIter());
  F->setDivergenceCleanFlag(CP.getDivergenceCleanFlag());
  F->setCurrentWeightingFlag(CP.getCurrentWeighting());
  F->set_freezeFields(CP.get_FreezeFields());
  F->setNonRelativisticFlag(CP.getNonRelativisticFlag());
  F->set_nSmoothing(CP.get_nSmoothing());
  F->setInfiniteBFlag(CP.getInfiniteBFlag());
  F->setFieldSubFlag(CP.getFieldSubFlag());
  F->setMarderParameter(CP.getMarderParameter());
  F->setEMdamping(CP.getEMdamping());
  
  if ( (CP.getElectrostaticFlag()) && (CP.getBoltzmannFlag()) ) {
    Species* species = get_speciesPtr(CP.getBoltzSpecies());
    Boltzmann* boltzmann= new Boltzmann(F,CP.getBoltzmannTemp(), species, CP.getBoltzmannEBFlag());
    F->setBoltzmann(boltzmann);
  }
  MCC*   mcc = 0;
  MCTI* mcti = 0;
  SpatialRegion *region = new SpatialRegion(F,BList, pgListArray, speciesList, 
                                            mcc, mcti, get_dt());
  
  if (MCCParamsList.nItems() > 0) {
    mcc  = new MCC;
    mcti = new MCTI; 
    oopicListIter<MCCParams> mIter(MCCParamsList);
    for (mIter.restart(); !mIter.Done(); mIter++) {
      mIter()->checkRules();
      mIter()->showRuleMessages();
      try{
        mIter()->CreateCounterPart(region, mcc, mcti);
      }
      catch(Oops& oops2){
        oops2.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");//OK
        throw oops2;
      }

      /**
       * note the difference in the call to 
       * CreateCoungerPart(...) in the line of code above
       * from its earlier use:
       * mcc->addPackage(mIter()->CreateCounterPart(region));
       * which was the case when tunneling ionization was not 
       * coded. For the tunneling ionization we have a class
       * MCTI analogous to the MCC class and the pointers to
       * these two classes are now passed to the 
       * CreateCounterPart for proper initialization of the 
       * list objects these clases contain.
       * dad: 12/20/2000.
       */
    }
    region->setMCC(mcc);
    region->setMCTI(mcti);
    region->setNGDListPtrs();
#ifdef MPI_VERSION
    //
    // allocate memory for the buffers in the SpatialRegionBoundary
    // objects for the NGD data
    // 
    oopicListIter<Boundary> nextb(*BList);
    for(nextb.restart(); !nextb.Done(); nextb++)
      nextb.current()->allocMemNGDbuffers();
#endif // MPI_VERSION
  }
  
  region->setParticleLimit( CP.get_particleLimit() );
  region->set_np2cFactor( CP.get_np2cFactor() );
  region->setduplicateParticles( (int)(CP.getduplicateParticles()+0.1) );

  region->set_histmax(CP.get_histmax());
  
#ifdef MPI_VERSION
  char buf[512];
  if(Name.getValue()==ostring("Noname") )
    sprintf(buf,"Region %d",MPI_RANK);
  else
    sprintf(buf,"%s Region %d",Name.getValue().c_str(),MPI_RANK);
  region->setName(buf);
#else  /* MPI_VERSION */
  region->setName(Name.getValue());
#endif  /* MPI_VERSION */
  oopicList<Diag> *DList = new DiagList;
  oopicListIter<DiagParams> nD(Diags);
  for (nD.restart(); !nD.Done(); nD++){
    try{
      nD.current()->toGrid(G);
    }
    catch(Oops& oops){
      oops.prepend("SpatialRegionGroup::CreateCounterPart: Error:\n"); //OK
      throw oops;
    }

#ifdef MPI_VERSION
    if(! (nD.current()->j1.getValue()==-1 && nD.current()->A1.getValue()==-1)) {
      // we don't want to create boundaries which are out-of-bounds!
#endif /* MPI_VERSION */
      Diag* dPtr = 0;
      try{
        dPtr = nD.current()->CreateCounterPart(region);
      }
      catch(Oops& oops2){
        oops2.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");//OK
        throw oops2;
      }
      DList->add(dPtr);
#ifdef MPI_VERSION
    }
#endif
    
  }
  region->setDiagList(DList);

// create a pointer to list of H5Diagnostic parameters

  oopicList<H5DiagParams> *H5DList = new oopicList<H5DiagParams>;
  oopicListIter<H5DiagParams> nDD(H5DiagDumpParams);
  for (nDD.restart(); !nDD.Done(); nDD++){
     H5DList->add(nDD.current());
  }
  region->setH5DiagDumpList(H5DList);
    
  if (WasDumpFileGiven)	{
    try{
      Restore(region);
    }
    catch(Oops& oops2){
      oops2.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");//OK
      throw oops2;
    }
  }
  
  //	else 
  try {
    ApplyToList(CreateCounterPart(region), Loads, LoadParams);
  }
  catch(Oops& oops2){
      oops2.prepend("SpatialRegion::CreateCounterPart: Error: \n");
      throw oops2;
  }
  
  F->compute_rho(region->getParticleGroupListArray(),
                 region->get_nSpecies());
  
#ifdef MPI_VERSION
  linkSRB();
#endif
  try{
    ApplyToList(putCharge_and_Current(region->getTime()),*BList,Boundary);
  }
  catch(Oops& oops2){
      oops2.prepend("SpatialRegion::CreateCounterPart: Error: \n");//done
      throw oops2;
  }
  
  // Need to receive a message sent by putCharge_and_Current
  // in MPI, to set up toNodes applyFields with dt=0 just receives
  // sent fields and sets up the SRB for toNodes
#ifdef MPI_VERSION
  try{
    ApplyToList(applyFields(region->getTime(),0),SpatialRegionBoundaryList, SpatialRegionBoundary);
  }
  catch(Oops& oops3){
    oops3.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");
    throw oops3;
  }

#endif

   // Some boundaries need feedback info from SpatialRegion
   //
   //
   ApplyToList(setRegion(region),*BList,Boundary);
   
   /* this line need to follow compute_rho so that the boundary 
      get rho correct */

   if ((CP.getElectrostaticFlag() || !WasDumpFileGiven) && CP.getInitPoissonSolveFlag()){

#ifndef MPI_VERSION  /* ES field not working in MPI version yet! */
    F->ElectrostaticSolve(region->getTime(),region->get_dt());
#endif /* MPI_VERSION */
    
  }

#ifdef MPI_VERSION /* Since the ES field solve is not working, at least apply BC */
  if( CP.getInitPoissonSolveFlag()) {
    try{
      ApplyToList(applyFields(region->getTime(),region->get_dt()),*BList,Boundary);
    }
    catch(Oops& oops3){
      oops3.prepend("SpatialRegionGroup::CreateCounterPart: Error: \n");
      throw oops3;
    }
  }
#endif
  
  F->setdt(region->get_dt());
  
  //  the next two lines set up initial EM fields
  //  which are added to any previous fields.
  //  since it is additive, we should do it only once.
  if(!WasDumpFileGiven) {
    F->setEinit(CP.getE1init(),CP.getE2init(),CP.getE3init());
    F->setBinit(CP.getB1init(),CP.getB2init(),CP.getB3init());
  }
  
  F->toNodes(region->getTime());
  
  
  // set up the moving window.
  switch(CP.getMovingWindow()){
  case 1:
    region->setShift(Vector2(-1,0));
    break;
  case 2:
    region->setShift(Vector2(1,0));
    break;
  case 3:
    region->setShift(Vector2(-1,0));
    break;
  case 4:
    region->setShift(Vector2(1,0));
    break;
  }

  region->setShiftDelayTime(CP.getShiftDelayTime());
  region->setGasOffTime(CP.getGasOffTime());

  
  return region;
}
Esempio n. 30
0
int main (int argc, char *argv[])
{
  int       rank, size;
  int       *perio;
  int       *dimns;
  int       *coord;
  int       cycle0   = 0;
  int       tsave    = 100;
  int       ncycle   = 200;
  int       ndim     = 3;
  int       reorder  = 1;
  int       nspec    = 2;
  int       ntcx     = 64;
  int       ntcy     = 64;
  int       ntcz     = 64;
  int       ntxn;
  int       ntyn;
  int       ntzn;
  double    Lx       = 10.0;
  double    Ly       = 10.0;
  double    Lz       = 10.0;
  double    L[3];
  MPI_Comm  CART_COMM;
  Fields    EMf;
  H5input   file;
  H5output  outfile;
  H5hutpart *myPart;

  /* -------------------------- */
  /* Initialize MPI environment */
  /* -------------------------- */

  perio = new int[ndim];
  dimns = new int[ndim];
  coord = new int[ndim];

  MPI_Init (&argc, &argv);
  MPI_Comm_size  (MPI_COMM_WORLD, &size);
  if (ndim==3) MPI_Dims_create(size, 3, dimns);
  else         MPI_Dims_create(size, 2, dimns);
  MPI_Cart_create(MPI_COMM_WORLD, ndim, dimns, perio, reorder, &CART_COMM);
  MPI_Comm_rank  (CART_COMM,&rank);
  MPI_Cart_coords(CART_COMM, rank, ndim, coord);

  /* ------------------------- */
  /* Set simulation conditions */
  /* ------------------------- */

  ntxn = ntcx + 1;
  ntyn = ntcy + 1;
  ntzn = ntcz + 1;

  int nxc = (ntcx / dimns[0]) + 2;
  int nyc = (ntcy / dimns[1]) + 2;
  int nzc = (ntcz / dimns[2]) + 2;
  int nxn = nxc + 1;
  int nyn = nyc + 1;
  int nzn = nzc + 1;

  L[0] = Lx;
  L[1] = Ly;
  L[2] = Lz;

  /* ------------------ */
  /* Read the particles */
  /* ------------------ */

  file.SetNameCycle("GEMtest", cycle0);

  myPart = new H5hutpart[nspec];

  file.OpenPartclFile(nspec);
  file.ReadParticles(rank, size, dimns, L, CART_COMM);

  for (int s = 0; s < nspec; s++){
    myPart[s].memalloc(file.GetNp(s));

    file.DumpPartclX(myPart[s].getXref(), s);
    file.DumpPartclY(myPart[s].getYref(), s);
    file.DumpPartclZ(myPart[s].getZref(), s);
    file.DumpPartclU(myPart[s].getUref(), s);
    file.DumpPartclV(myPart[s].getVref(), s);
    file.DumpPartclW(myPart[s].getWref(), s);
    file.DumpPartclQ(myPart[s].getQref(), s);
  }
  file.ClosePartclFile();

  /* --------------- */
  /* Read the fields */
  /* --------------- */

  EMf.Init(nspec, nxc, nyc, nzc);

  file.OpenFieldsFile("Node", nspec, ntxn, ntyn, ntzn, coord, dimns, CART_COMM);
  file.ReadFields(EMf.getEx(), "Ex", nxn, nyn, nzn);
  file.ReadFields(EMf.getEy(), "Ey", nxn, nyn, nzn);
  file.ReadFields(EMf.getEz(), "Ez", nxn, nyn, nzn);
  file.ReadFields(EMf.getBx(), "Bx", nxn, nyn, nzn);
  file.ReadFields(EMf.getBy(), "By", nxn, nyn, nzn);
  file.ReadFields(EMf.getBz(), "Bz", nxn, nyn, nzn);
  file.CloseFieldsFile();

  /* -------------------------------------- */
  /* Empty simulation with multiple outputs */
  /* -------------------------------------- */

  for (int t = cycle0; t <= cycle0+ncycle; t++) {

    std::cout << " Cycle: " << t << std::endl;
    /* here goes the computation */

    if (t%tsave==0) {

      outfile.SetNameCycle("Output", t);

      /* ----------- */
      /* Save fields */
      /* ----------- */

      outfile.OpenFieldsFile("Node", nspec, ntxn, ntyn, ntzn, coord, dimns, CART_COMM);
      outfile.WriteFields(EMf.getEx(), "Ex", nxn, nyn, nzn);
      outfile.WriteFields(EMf.getEy(), "Ey", nxn, nyn, nzn);
      outfile.WriteFields(EMf.getEz(), "Ez", nxn, nyn, nzn);
      outfile.WriteFields(EMf.getBx(), "Bx", nxn, nyn, nzn);
      outfile.WriteFields(EMf.getBy(), "By", nxn, nyn, nzn);
      outfile.WriteFields(EMf.getBz(), "Bz", nxn, nyn, nzn);
      outfile.CloseFieldsFile();

      /* -------------- */
      /* Save particles */
      /* -------------- */

      outfile.OpenPartclFile(nspec, CART_COMM);
      for (int i=0; i<nspec; i++) {
        outfile.WriteParticles(i, myPart[i].getNP(),
                                  myPart[i].getQ(),
                                  myPart[i].getX(),
                                  myPart[i].getY(),
                                  myPart[i].getZ(),
                                  myPart[i].getU(),
                                  myPart[i].getV(),
                                  myPart[i].getW(),
                                  CART_COMM);
      }
      outfile.ClosePartclFile();
    }
  }

  std::cout << rank << " : Freeing memory..." << std::endl;

  delete [] myPart;
  delete [] perio;
  delete [] dimns;
  delete [] coord;

  std::cout << rank << " : Finalizing MPI" << std::endl;

  MPI_Finalize();

  return 0;
}