示例#1
0
Results List::filter(Query q) const
{
    verify_attached();
    if (m_link_view)
        return Results(m_realm, m_link_view, get_query().and_query(std::move(q)));
    return Results(m_realm, get_query().and_query(std::move(q)));
}
示例#2
0
Results List::sort(SortDescriptor order) const
{
    verify_attached();
    if (m_link_view)
        return Results(m_realm, m_link_view, util::none, std::move(order));

    DescriptorOrdering new_order;
    new_order.append_sort(std::move(order));
    return Results(m_realm, get_query(), std::move(new_order));
}
ValueType Object::get_property_value_impl(ContextType& ctx, const Property &property)
{
    verify_attached();

    size_t column = property.table_column;
    if (is_nullable(property.type) && m_row.is_null(column))
        return ctx.null_value();
    if (is_array(property.type) && property.type != PropertyType::LinkingObjects)
        return ctx.box(List(m_realm, *m_row.get_table(), column, m_row.get_index()));

    switch (property.type & ~PropertyType::Flags) {
        case PropertyType::Bool:   return ctx.box(m_row.get_bool(column));
        case PropertyType::Int:    return ctx.box(m_row.get_int(column));
        case PropertyType::Float:  return ctx.box(m_row.get_float(column));
        case PropertyType::Double: return ctx.box(m_row.get_double(column));
        case PropertyType::String: return ctx.box(m_row.get_string(column));
        case PropertyType::Data:   return ctx.box(m_row.get_binary(column));
        case PropertyType::Date:   return ctx.box(m_row.get_timestamp(column));
        case PropertyType::Any:    return ctx.box(m_row.get_mixed(column));
        case PropertyType::Object: {
            auto linkObjectSchema = m_realm->schema().find(property.object_type);
            TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), property.object_type);
            return ctx.box(Object(m_realm, *linkObjectSchema, table->get(m_row.get_link(column))));
        }
        case PropertyType::LinkingObjects: {
            auto target_object_schema = m_realm->schema().find(property.object_type);
            auto link_property = target_object_schema->property_for_name(property.link_origin_property_name);
            TableRef table = ObjectStore::table_for_object_type(m_realm->read_group(), target_object_schema->name);
            auto tv = m_row.get_table()->get_backlink_view(m_row.get_index(), table.get(), link_property->table_column);
            return ctx.box(Results(m_realm, std::move(tv)));
        }
        default: REALM_UNREACHABLE();
    }
}
示例#4
0
        String GetExecutableDirFromArg(int ArgCount, char** ArgVars)
        {
            if(ArgCount>0) {
                if(String("") == BaseName(ArgVars[0])) { // No command is clearly bogus, must bail
                    return "";
                }

                String Results(DirName(ArgVars[0]));

                // strip ./ ../ .\ ..\ and
                //String::iterator From=Results.begin();
                //for(String::iterator Iter=Results.begin(); Iter!=Results.end();)
                //{}

                if( String("") == Results || String("./") == Results || String(".\\") == Results) {// common cases of exe existing but dir is empty
                    return ".";
                }

                if(String("")!=Results) { // and exe is empty.
                    return Results;
                }
                return String("");
            }else{
                return String("");
            }
        }
ThermalCalibrationHelper::ThermalCalibrationHelper(QObject *parent) :
    QObject(parent)
{
    m_tempdir.reset(new QTemporaryDir());

    m_memento = Memento();
    m_memento.statusSaved = false;

    m_results = Results();
    m_results.accelCalibrated = false;
    m_results.gyroCalibrated  = false;
    m_results.baroCalibrated  = false;

    m_progress        = -1;
    m_progressMax     = -1;

    accelSensor       = AccelSensor::GetInstance(getObjectManager());
    gyroSensor        = GyroSensor::GetInstance(getObjectManager());
    baroSensor        = BaroSensor::GetInstance(getObjectManager());
    magSensor         = MagSensor::GetInstance(getObjectManager());
    accelGyroSettings = AccelGyroSettings::GetInstance(getObjectManager());
    revoSettings      = RevoSettings::GetInstance(getObjectManager());

    ExtensionSystem::PluginManager *pm = ExtensionSystem::PluginManager::instance();
    TelemetryManager *telMngr = pm->getObject<TelemetryManager>();
    connect(telMngr, SIGNAL(disconnected()), this, SLOT(cleanup()));
}
示例#6
0
CVariant CLookupProxy::AddCallReq(const CVariant& Requests)
{
	CVariant Results(CVariant::EList);

	for(uint32 i=0; i<Requests.Count(); i++)
	{
		const CVariant& Request = Requests[i];
		if(!m_CallMap.insert(TCallOpMap::value_type(Request["XID"], SCallOp(Request))).second)
			continue; // we already got this request, ignore it

		if(m_pOperator && m_pOperator->IsValid())
		{
			try
			{
				m_pOperator->AddCallReq(Request["FX"], Request["ARG"], Request["XID"]);
			}
			catch(const CJSException& Exception)
			{
				LogReport(Exception.GetFlag(), Exception.GetLine(), Exception.GetError());

				CKadOperation::SOpStatus &Progress = m_CallMap[Request["XID"]].Status;
				Progress.Done = true; // this one is finished

				CVariant Result;
				Result["XID"] = Request["XID"];
				Result["ERR"] = Exception.GetError();
				Results.Append(Result);
			}
		}
	}

	if(m_pOperator)
		Results.Merge(m_pOperator->GetResponses());
	return Results;
}
示例#7
0
	bool render()
	{
		glm::vec2 WindowSize(this->getWindowSize());
		glViewportIndexedf(0, 0, 0, WindowSize.x, WindowSize.y);
		glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f)[0]);

		glBindProgramPipeline(PipelineName);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, semantics::INPUT, BufferName[semantics::INPUT]);
		glBindBufferBase(GL_SHADER_STORAGE_BUFFER, semantics::OUTPUT, BufferName[semantics::OUTPUT]);
		glDispatchCompute(1, 1, 1);

		glMemoryBarrier(GL_ALL_BARRIER_BITS);

		std::vector<GLuint> Results(DataSize);
		glBindBuffer(GL_COPY_READ_BUFFER, BufferName[semantics::OUTPUT]);
		glm::uint* Pointer = (glm::uint*)glMapBufferRange(GL_COPY_READ_BUFFER, 0, sizeof(glm::uint) * Results.size(), GL_MAP_READ_BIT);
		memcpy(&Results[0], Pointer, Results.size() * sizeof(glm::uint));
		glUnmapBuffer(GL_COPY_READ_BUFFER);

		std::array<glm::uint, 14> const Expect{0u,  2u,  3u,  4u,  6u,  7u,  8u};

		for(std::size_t i = 0, n = Expect.size(); i < n; ++i)
			if(Expect[i] != Results[i])
				return false;
		return true;
	}
示例#8
0
int main(int argc, char **argv) {

   ArgsCheck(argv);
   PipeLoop();
   Results();
   ReportCheck();

   return 0;
}
示例#9
0
 String GetExecutableDir(int ArgCount, char** ArgVars)
 {
     String Results( GetExecutableDirFromArg(ArgCount,ArgVars) );
     if( String(".") == Results || String("") == Results ) { // Means it might have valid exename
         return GetExecutableDirFromSystem();
     }else{
         return Results;
     }
 }
//--------------------------------------------------------------
string ofxLanguageDetector::detect(const string& input) {
    Settings settings = Settings();
    Results  results  = Results();
    
    string lang = detect(input,settings,results);
    
    if(!results.isReliable) {
        ofLog(OF_LOG_WARNING,"ofxLanguageDetector::detect results not reliable.");
    }
    
    return lang;
}
示例#11
0
CVariant CKadScript::Execute(const map<CVariant, CKadOperator::SKadRequest>& Requests, const CUInt128& TargetID, CReportLogger* pLogger)
{
	KeepAlive();

	m_pLogger = CPointer<CReportLogger>(pLogger, true); // this is a week pointer and it gets cleared when the caller exits

	CVariant Results(CVariant::EList);
	for(map<CVariant, CKadOperator::SKadRequest>::const_iterator I = Requests.begin(); I != Requests.end(); I++)
	{
		CKadRequest* pRequest = I->second.pRequest;
		Results.Append(Call(pRequest->GetName(), pRequest->GetArguments(), TargetID, pRequest->GetXID()));
	}
	return Results;
}
示例#12
0
CVariant CKadScript::Execute(const CVariant& Requests, const CUInt128& TargetID, CReportLogger* pLogger)
{
	KeepAlive();

	m_pLogger = CPointer<CReportLogger>(pLogger, true); // this is a week pointer and it gets cleared when the caller exits

	CVariant Results(CVariant::EList);
	for(uint32 i=0; i < Requests.Count(); i++)
	{
		const CVariant& Request = Requests.At(i);
		Results.Append(Call(Request["FX"], Request["ARG"], TargetID, Request["XID"]));
	}
	return Results;
}
示例#13
0
void Organizer::MakeSchedule(list<Team>& teams)
{
	int N;
	int count = teams.size();
	for (int i = 0; i < count ; i++)
	{
		N = rand() % teams.size();
		list<Team>::iterator it;
		it = next(teams.begin(), N);
		matches.push(*it);
		teams.erase(it);
		it = teams.begin();
	}
	TeamSchedulerDisplayer(*this);
	Results(*this);


}
示例#14
0
int GetUserpassInput(prompts_t * p, const uint8_t * /*in*/, int /*inlen*/)
{
  assert(p != nullptr);
  TSecureShell * SecureShell = NB_STATIC_DOWNCAST(TSecureShell, p->frontend);
  assert(SecureShell != nullptr);

  int Result;
  std::unique_ptr<TStrings> Prompts(new TStringList());
  std::unique_ptr<TStrings> Results(new TStringList());
  {
    for (size_t Index = 0; Index < p->n_prompts; ++Index)
    {
      prompt_t * Prompt = p->prompts[Index];
      Prompts->AddObject(Prompt->prompt, reinterpret_cast<TObject *>(static_cast<size_t>(FLAGMASK(Prompt->echo, pupEcho))));
      // this fails, when new passwords do not match on change password prompt,
      // and putty retries the prompt
      assert(Prompt->resultsize == 0);
      Results->Add(L"");
    }

    if (SecureShell->PromptUser(p->to_server != 0, p->name, p->name_reqd != 0,
          UnicodeString(p->instruction), p->instr_reqd != 0, Prompts.get(), Results.get()))
    {
      for (size_t Index = 0; Index < p->n_prompts; ++Index)
      {
        prompt_t * Prompt = p->prompts[Index];
        prompt_set_result(Prompt, AnsiString(Results->GetString(Index).c_str()).c_str());
      }
      Result = 1;
    }
    else
    {
      Result = 0;
    }
  }

  return Result;
}
示例#15
0
RaceAnalyzer::Results  RaceAnalyzer::riderResults(unsigned       stage,
	const string  &team,
	const string  &country)  const
{
	return Results();
}
// Action_AtomicFluct::Print()
void Action_AtomicFluct::Print() {
    mprintf("    ATOMICFLUCT: Calculating fluctuations for %i sets.\n",sets_);

    double Nsets = (double)sets_;
    // SumCoords will hold the average: <R>
    SumCoords_.Divide(Nsets);
    // SumCoords2 will hold the variance: <R^2> - <R>^2
    SumCoords2_.Divide(Nsets);
    SumCoords2_ = SumCoords2_ - (SumCoords_ * SumCoords_);
    // Cross terms: XY, XZ, YZ
    if (calc_adp_)
        Cross_.Divide(Nsets);

    // Hold fluctuation results - initialize to 0
    std::vector<double> Results( SumCoords2_.Natom(), 0 );
    std::vector<double>::iterator result = Results.begin();

    if (bfactor_) {
        // Set up b factor normalization
        // B-factors are (8/3)*PI*PI * <r>**2 hence we do not sqrt the fluctuations
        double bfac = (8.0/3.0)*Constants::PI*Constants::PI;
        for (int i = 0; i < SumCoords2_.size(); i+=3) {
            double fluct = SumCoords2_[i] + SumCoords2_[i+1] + SumCoords2_[i+2];
            if (fluct > 0)
                *result = bfac * fluct;
            ++result;
            if (calc_adp_) {
                int atom = (i/3);
                if (Mask_.AtomInCharMask(atom)) {
                    int resnum = (*fluctParm_)[atom].ResNum();
                    int u11 = (int)(SumCoords2_[i  ] * 10000);
                    int u22 = (int)(SumCoords2_[i+1] * 10000);
                    int u33 = (int)(SumCoords2_[i+2] * 10000);
                    // Calculate covariance: <XY> - <X><Y> etc.
                    int u12 = (int)((Cross_[i  ] - SumCoords_[i  ] * SumCoords_[i+1]) * 10000);
                    int u13 = (int)((Cross_[i+1] - SumCoords_[i  ] * SumCoords_[i+2]) * 10000);
                    int u23 = (int)((Cross_[i+2] - SumCoords_[i+1] * SumCoords_[i+2]) * 10000);
                    PDBfile& adpout = static_cast<PDBfile&>( *adpoutfile_ );
                    adpout.WriteANISOU(
                        atom+1, (*fluctParm_)[atom].c_str(), fluctParm_->Res(resnum).c_str(),
                        fluctParm_->Res(resnum).ChainID(), fluctParm_->Res(resnum).OriginalResNum(),
                        u11, u22, u33, u12, u13, u23, (*fluctParm_)[atom].ElementName(), 0 );
                }
            }
        }
    } else {
        // Atomic fluctuations
        for (int i = 0; i < SumCoords2_.size(); i+=3) {
            double fluct = SumCoords2_[i] + SumCoords2_[i+1] + SumCoords2_[i+2];
            if (fluct > 0)
                *result = sqrt(fluct);
            ++result;
        }
    }

    DataSet_Mesh& dset = static_cast<DataSet_Mesh&>( *dataout_ );
    if (outtype_ == BYATOM) {
        // By atom output
        dset.Dim(Dimension::X).SetLabel("Atom");
        for (int atom = 0; atom < (int)Results.size(); atom++ ) {
            if (Mask_.AtomInCharMask(atom))
                dset.AddXY( atom+1, Results[atom] );
        }
    } else if (outtype_ == BYRES) {
        // By residue output
        dset.Dim(Dimension::X).SetLabel("Res");
        for (Topology::res_iterator residue = fluctParm_->ResStart();
                residue != fluctParm_->ResEnd(); ++residue) {
            double xi = 0.0;
            double fluct = 0.0;
            for (int atom = (*residue).FirstAtom(); atom < (*residue).LastAtom(); atom++) {
                if ( Mask_.AtomInCharMask(atom) ) {
                    double mass = (*fluctParm_)[atom].Mass();
                    xi += mass;
                    fluct += Results[atom] * mass;
                }
            }
            if (xi > Constants::SMALL)
                dset.AddXY( residue - fluctParm_->ResStart() + 1, fluct / xi );
        }
    } else if (outtype_ == BYMASK) {
        // By mask output
        dset.Dim(Dimension::X).SetLabel( Mask_.MaskExpression() );
        double xi = 0.0;
        double fluct = 0.0;
        for (int atom = 0; atom < (int)Results.size(); atom++) {
            if (Mask_.AtomInCharMask(atom)) {
                double mass = (*fluctParm_)[atom].Mass();
                xi += mass;
                fluct += Results[atom] * mass;
            }
        }
        if (xi > Constants::SMALL)
            dset.AddXY( 1, fluct / xi );
    }
}
示例#17
0
Results List::as_results() const
{
    verify_attached();
    return m_link_view ? Results(m_realm, m_link_view) : Results(m_realm, *m_table);
}
示例#18
0
文件: PuttyIntf.cpp 项目: elfmz/far2l
int GetUserpassInput(prompts_t * p, const uint8_t * /*in*/, int /*inlen*/)
{
  DebugAssert(p != nullptr);
  TSecureShell * SecureShell = NB_STATIC_DOWNCAST(TSecureShell, p->frontend);
  DebugAssert(SecureShell != nullptr);

  int Result;
  std::unique_ptr<TStrings> Prompts(new TStringList());
  std::unique_ptr<TStrings> Results(new TStringList());
  {
    UnicodeString Name = UTF8ToString(p->name);
    UnicodeString AName = Name;
    TPromptKind PromptKind = SecureShell->IdentifyPromptKind(AName);
    bool UTF8Prompt = (PromptKind != pkPassphrase);

    for (size_t Index = 0; Index < p->n_prompts; ++Index)
    {
      prompt_t * Prompt = p->prompts[Index];
      UnicodeString S;
      if (UTF8Prompt)
      {
        S = UTF8ToString(Prompt->prompt);
      }
      else
      {
        S = UnicodeString(AnsiString(Prompt->prompt));
      }
      Prompts->AddObject(S, reinterpret_cast<TObject *>(static_cast<size_t>(FLAGMASK(Prompt->echo, pupEcho))));
      // this fails, when new passwords do not match on change password prompt,
      // and putty retries the prompt
      DebugAssert(Prompt->resultsize == 0);
      Results->Add(L"");
    }

    UnicodeString Instructions = UTF8ToString(p->instruction);
    if (SecureShell->PromptUser(p->to_server != 0, Name, p->name_reqd != 0,
          Instructions, p->instr_reqd != 0, Prompts.get(), Results.get()))
    {
      for (size_t Index = 0; Index < p->n_prompts; ++Index)
      {
        prompt_t * Prompt = p->prompts[Index];
        RawByteString S;
        if (UTF8Prompt)
        {
          S = RawByteString(UTF8String(Results->GetString(Index)));
        }
        else
        {
          S = RawByteString(AnsiString(Results->GetString(Index)));
        }
        prompt_set_result(Prompt, S.c_str());
      }
      Result = 1;
    }
    else
    {
      Result = 0;
    }
  }
  __finally
  {
//    delete Prompts;
//    delete Results;
  };

  return Result;
}
/// static function that reads the results file
/// @param[in] node FileNode to read from
/// @param[out] Results result to be saved from FileNode
/// @param[in] default_value value by default if FileNode is empty
static void read(const FileNode& node, Results& result,const Results& default_value = Results())
{
	if (node.empty())
	{
		result = default_value;
	} else
	{
		result.read(node);
	}
}
示例#20
0
//M+	
void mp(
	int MinCoreSize,
	int MaxCoreSize,
	int SamplingFreq,
	int NumReplicates,
	char* OutFilePath,
	std::string Kernel,
	vector<int> KernelAccessionIndex,
	vector<int> AccessionNameList,
	vector<vector<vector<std::string> > > ActiveAlleleByPopList,
	vector<vector<vector<std::string> > > TargetAlleleByPopList,
	vector<int> ActiveMaxAllelesList,
	vector<int> TargetMaxAllelesList,
	vector<std::string> FullAccessionNameList,
	int parallelism_enabled,
	int ncpu
	)	
{
	
	//make recovery files (0) or not (1)
	int MakeRecovery=1;
	
	//set up variables for monitoring progress
	int percent; //percent of analysis completed
	int progindex = 0;  //index to monitor progress, percent = 100*(progindex/l)
	//below is a stupid way to calculate the number of rows in the output file, value l (which = V1) 
	//used to monitor progress and as the maximum vector index for shared output vectors
	int l=0;
	for (int i=MinCoreSize;i<MaxCoreSize+1;i=i+SamplingFreq)
	{
	for (int j=0;j<NumReplicates;j++)
		{
			l++;
		}
	}
	
	//set up vectors to fill with results
	unsigned long long V1 = l; //(MaxCoreSize - MinCoreSize + 1)*NumReplicates; //number of rows in output vectors
	vector<vector<double> > Results(V1, vector<double>(9)); //will contain numerical results
	vector<vector<string> > Members(V1); //will contain core set members
	

	#pragma omp parallel if(parallelism_enabled) num_threads(ncpu)
	{		
		unsigned int r; //r = core size, 
		int nr, RandAcc, b, row, bsc, plateau; //nr = controller to repeat NumReplicates times
								//row = result vector row number, bsc = holds best sub core member, and other indexed accessions
									//plateau = index of the number of reps in optimization loop with same diversity value
								
		double RandomActiveDiversity;
		double AltRandomActiveDiversity;
		double StartingRandomActiveDiversity;
		double StartingAltRandomActiveDiversity;
		double RandomTargetDiversity;
		double AltRandomTargetDiversity;
		double StartingDiversity;
		double TempAltOptimizedActiveDiversity;
		double AltOptimizedActiveDiversity;
		double OptimizedTargetDiversity;
		double AltOptimizedTargetDiversity;
		double best;
		double nnew;
		vector<vector<vector<std::string> > > AlleleList;
		vector<vector<vector<std::string> > > CoreAlleles;
		vector<vector<vector<std::string> > > TdTempList;
		vector<vector<vector<std::string> > > BestSubCoreAlleles;
		std::string Standardize = "yes";  //a run that mimics the MSTRAT approach can be accomplished by setting Standardize="no", and setting up the var file so that each column in the .dat file is treated as a single locus, rather than two (or more) adjacent columns being treated as a single codominant locus.
		vector<int> AccessionsInCore;
		vector<int> AccessionsInSubCore;
		vector<int> BestSubCore;
		vector<int> BestSubCoreRevSorted;
		vector<int> TempList;
		vector<int> TempList2;
		vector<int> bestcore;
		vector<std::string> TempListStr;
	
		//seed the random number generator for each thread
		int tt;
		tt = (time(NULL));
		srand ( tt ^ omp_get_thread_num() ); //initialize
	
		//set up a recovery file for each thread that saves progress as program runs
		const char* RecoveryFilePath;
		if ( MakeRecovery == 0 ) // only write the recovery file to disk when option = 0
		{
			stringstream ss;
			ss << OutFilePath << ".t" << omp_get_thread_num() << ".tmp"; 
			string rfp = ss.str();
			RecoveryFilePath = rfp.c_str();
			ofstream RecoveryFile; 
			RecoveryFile.open(RecoveryFilePath);
			RecoveryFile.close(); //quick open close done to clear any existing file each time program is run
			RecoveryFile.open(RecoveryFilePath, ios::out | ios::app); //open file in append mode
			RecoveryFile << "core size	random reference diversity	optimized reference diversity	random target diversity	optimized target diversity	alt random reference diversity	alt optimized reference diversity	alt random target diversity	alt optimized target diversity	core members" << "\n";
			RecoveryFile.close();
		}
		
		//do parallelization so that each rep by core size combo can be
		//handled by a distinct thread.  this involves figuring out the total
		//number of reps*coresizes taking into account the SamplingFreq

		int rsteps = 1 + (int)floor( (MaxCoreSize - MinCoreSize) / SamplingFreq ); //number of steps from MinCoreSize to MaxCoreSize

		#pragma omp for
			for (int rnr = 0; rnr<rsteps*NumReplicates;++rnr)
			{
				r = MinCoreSize + ((rnr / NumReplicates) * SamplingFreq); //int rounds to floor
				nr = rnr % NumReplicates; // modulo
				//develop random starting core set
				//clear AccessionsInCore and set size
				AccessionsInCore.clear();
				AccessionsInCore.resize(r);
				
				//add kernel accessions to core, if necessary
				if (Kernel == "yes")
				{
					for (unsigned int i=0;i<KernelAccessionIndex.size();i++)
					{
						AccessionsInCore[i] = KernelAccessionIndex[i];
					}
				}

				//clear TempList and set size					
				TempList.clear();
				TempList.resize( AccessionNameList.size() );
				
				//set list of available accessions in TempList, by erasing those already in the core
				TempList = AccessionNameList;
				//expunge the kernel accessions, so they are not available for random addition below
				//KernelAccessionIndex has been reverse sorted so you don't go outside range after automatic resize by .erase
				for (unsigned int i=0;i<KernelAccessionIndex.size();i++)
				{
					b = KernelAccessionIndex[i];
					TempList.erase(TempList.begin()+b);
				}
			
				//randomly add accessions until r accessions are in the core. if there is a kernel, include those (done above)
				//plus additional, randomly selected accessions, until you get r accessions
				//for (int i=0;i<r;i++)
				for (unsigned int i=KernelAccessionIndex.size();i<r;i++)
				{
					//choose an accession randomly from those available
					RandAcc = rand() % TempList.size();
					//add it to the list
					AccessionsInCore[i] = TempList[RandAcc];
				
					//remove it from the list of available accessions
					TempList.erase(TempList.begin()+RandAcc);
				}
		
				//assemble genotypes for random core and calculate diversity
				//1. put together initial list of active alleles
				CoreAlleles.clear();
				CoreAlleles.resize( AccessionsInCore.size() );
				for (unsigned int i=0;i<AccessionsInCore.size();i++)
				{
					b = AccessionsInCore[i];
					CoreAlleles[i] = ActiveAlleleByPopList[b];
				}

				//2. calculate diversity from random selection at active loci
				//vector<vector<vector<std::string> > >().swap(AlleleList); //clear AlleleList
				AlleleList.clear();
				AlleleList = CoreAlleles;
		
				MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
				//in MyCalculateDiversity, latter two variables are updated as references
				//save them away in non-updated variables
				StartingRandomActiveDiversity = RandomActiveDiversity;
				StartingAltRandomActiveDiversity = AltRandomActiveDiversity;

				//3. calculate diversity from random selection at target loci
				AlleleList.clear();
				AlleleList.resize( AccessionsInCore.size() );
				for (unsigned int j=0;j<AccessionsInCore.size();j++)
				{
					b = AccessionsInCore[j];
					AlleleList[j] = TargetAlleleByPopList[b];
				}
				MyCalculateDiversity(AlleleList, TargetMaxAllelesList, Standardize, RandomTargetDiversity, AltRandomTargetDiversity);

	
				//BEGIN OPTIMIZATION
				StartingDiversity = 0; //this is the diversity recovered during the prior iteration.
				plateau = 0; //count of the number of times you have found the best value, evaluates when you are
							 //stuck on a plateau, assuming acceptance criterion allows downhill steps
				//this is the iterations step, now an indefinite loop that is broken when 
				//no improvement is made during the course of the optimization algorithm
				//If r = kernel size = MinCoreSize then do no optimization but still calculate all variables.
				if (KernelAccessionIndex.size() == r)
				{
					//assemble genotypes for core
					//1. put together initial list
					CoreAlleles.clear();
					CoreAlleles.resize(r);
					for (unsigned int i=0;i<r;i++)
					{
						b = AccessionsInCore[i];
						CoreAlleles[i] = ActiveAlleleByPopList[b];
					}
					
					AlleleList = CoreAlleles;
					
					MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
					best = RandomActiveDiversity; //best is equivalent to OptimizedActiveDiversity
					AltOptimizedActiveDiversity = AltRandomActiveDiversity;
				}
				else
				{
					//do optimization
					while ( true )
					{
						//assemble genotypes for core
						//1. put together initial list
						CoreAlleles.clear();
						CoreAlleles.resize(r);
						for (unsigned int i=0;i<r;i++)
						{
							b = AccessionsInCore[i];
							CoreAlleles[i] = ActiveAlleleByPopList[b];
						}
			
						//2. go through all possible subsets of size r-1, one at a time, noting which is best.
						//If there is a kernel, do not swap out any of those accessions (they are retained as the
						//first KernelAccessionIndex.size() items in CoreAlleles).  Accomplished by starting for loop
						//at KernelAccessionIndex.size().
						best=0;
						for (unsigned int i=KernelAccessionIndex.size();i<CoreAlleles.size();i++)
						{
							//remove each item consecutively from the list of all populations in the core
							AlleleList.clear();
							TdTempList.clear();
					
							TdTempList = CoreAlleles; //swap to temporary vector
							TdTempList.erase( TdTempList.begin() + i);
							AlleleList = TdTempList;
				
							TempList2.clear();
							TempList2 = AccessionsInCore;
							TempList2.erase(TempList2.begin() + i);
							AccessionsInSubCore = TempList2;

							/*Data structure for SubCoreAlleles:
							SubCore 1..r
								Population 1..(r-1)
									AlleleArray 1..NumLoci		
				
							--3. fuse alleles from the same locus into a single array, for all accessions, for the current subcore
							--4. assemble a list of diversity (M) for each locus separately
							--5. standardize the M values to the maximum possible number of alleles at that locus, and add them up to get final estimate of standardized allelic diversity in the core.  then divide by the number of loci to get a number that is comparable across data sets.
							--5.5. simultaneous to the calculation, keep track of which subcore is best
							*/
				
							MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
							nnew = RandomActiveDiversity;
	
							if (nnew >= best) // >= allows sideways movement during hill climbing
							{
								best = nnew;

								BestSubCore.clear();
								BestSubCore = AccessionsInSubCore;
								BestSubCoreAlleles.clear();
								BestSubCoreAlleles = AlleleList;
							}
						}  //for loop cycles thru all subcores

						//reverse sort BestSubCore to support easy assembly of pared TempList below
						BestSubCoreRevSorted = BestSubCore;
						std::sort(BestSubCoreRevSorted.begin(), BestSubCoreRevSorted.end(), std::greater<int>());
		
						/*
						6. take the subcore with greatest diversity and consecutively add each 
						possible additional accession from the base collection.  find the core of size r 
						(not r-1 subcore) that has the greatest diversity.

						suppress the IDs of those accessions found in the BestSubCore from the 
						list of all accessions to get a list of remaining accessions.*/
						TempList = AccessionNameList;
						for (unsigned int k=0;k<BestSubCoreRevSorted.size();k++)
						{
							bsc = BestSubCoreRevSorted[k];
							TempList.erase( TempList.begin() + bsc );
						}
				
						//shuffle the list of remaining accessions, so addition order is not predictable
						std::random_shuffle (TempList.begin(), TempList.end());
					
						//add each remaining accession consecutively, calculate diversity, test 
						//whether it is better than the prior one
						best = 0;
						for (unsigned int k=0;k<TempList.size();k++)
						{
							bsc = TempList[k];
				
							//define the core
							TempList2 = BestSubCore;
							TempList2.resize( TempList2.size() + 1 );
							//TempList2.push_back(i);
							TempList2[TempList2.size()-1] = bsc; //add new accession to last vector element
							AccessionsInCore = TempList2;
				
							//assemble the allelelist for the core
							TdTempList = BestSubCoreAlleles;
							TdTempList.resize( TdTempList.size() + 1 );
							//TdTempList.push_back( ActiveAlleleByPopList[i] );
							TdTempList[TdTempList.size()-1] = ActiveAlleleByPopList[bsc];
							AlleleList = TdTempList;
				
							//calculate diversity
							MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, nnew, TempAltOptimizedActiveDiversity); 
			
							//test whether current diversity is higher than the best diversity found so far
							if (nnew >= best) // >= allows sideways movement during hill climbing
							{
								best = nnew;
								bestcore = AccessionsInCore;
								//save the alternative diversity value for the best core
								AltOptimizedActiveDiversity = TempAltOptimizedActiveDiversity;
							}
						}

						AccessionsInCore = bestcore; //define starting variable for next MSTRAT iteration
			
						//if there has been no improvement from the prior iteration, you have reached
						// the plateau and should exit the repeat
						if (best == StartingDiversity) 
						{
							plateau++;
							if (plateau > 0) break;
						}
						//update starting value and repeat
						else if (best > StartingDiversity) StartingDiversity = best;
					
					} //while(true) endless loop
				}
	
				//7. Calculate diversity at target loci
				//assemble the target loci allelelist for the accessions in the best core
				AlleleList.clear();
				AlleleList.resize( AccessionsInCore.size() );
				for (unsigned int j=0;j<AccessionsInCore.size();j++)
				{
					b = AccessionsInCore[j];
					AlleleList[j] = TargetAlleleByPopList[b];
				}
		
		
				//calculate diversity at target loci based upon the optimized core selection
				MyCalculateDiversity(AlleleList, TargetMaxAllelesList, Standardize, OptimizedTargetDiversity, AltOptimizedTargetDiversity);

		
				//8. Assemble stats for optimized core and add to output vectors
				//create a list of accession names from the list of accession ID's in AccessionsInCore
				sort( AccessionsInCore.begin(), AccessionsInCore.end() );
				
				TempListStr.clear();
				TempListStr.resize(r);
				for (unsigned int i=0;i<AccessionsInCore.size();i++)
				{
					b = AccessionsInCore[i];
					TempListStr[i] = FullAccessionNameList[b];
				}

				//load the variables onto the results vectors
				//numerical results
				row = ((r - MinCoreSize)*NumReplicates) + nr - ( (NumReplicates*(SamplingFreq-1))*( (r-MinCoreSize)/SamplingFreq ) );
				// (r - MinCoreSize)*NumReplicates) + nr specifies row number if SamplingFreq=1
				// (NumReplicates*(SamplingFreq-1)) specifies a step value to correct when SamplingFreq>1
				// ( (r-MinCoreSize)/SamplingFreq ) specifies the replicate on core size, accounting for SamplingFreq
				// see file Calculation of row value.xlsx for development of the 'row' index
				Results[row][0] = r;
				Results[row][1] = StartingRandomActiveDiversity;//RandomActiveDiversity;
				Results[row][2] = best; //equivalent to OptimizedActiveDiversity
				Results[row][3] = RandomTargetDiversity;
				Results[row][4] = OptimizedTargetDiversity;
				Results[row][5] = StartingAltRandomActiveDiversity;//AltRandomActiveDiversity;
				Results[row][6] = AltOptimizedActiveDiversity;
				Results[row][7] = AltRandomTargetDiversity;
				Results[row][8] = AltOptimizedTargetDiversity;
		
				//core set members
				Members[row] = TempListStr; 
		
				//write the results onto the recovery files
				if ( MakeRecovery == 0) 
				{
					WriteRecoveryFile(RecoveryFilePath, r, StartingRandomActiveDiversity, best, RandomTargetDiversity, OptimizedTargetDiversity, StartingAltRandomActiveDiversity, AltOptimizedActiveDiversity, AltRandomTargetDiversity, AltOptimizedTargetDiversity, TempListStr);
				}
				
				//display progress
				progindex = progindex + 1;
				percent = 100*(progindex/(double)V1);
				printProgBar(percent); 
			} //end #pragma omp for loop
	} //end #pragma omp parallel	
	
	//set up file stream for output file
	ofstream output; 
	output.open(OutFilePath);
	output.close(); //quick open close done to clear any existing file each time program is run
	output.open(OutFilePath, ios::out | ios::app); //open file in append mode
	output << "core size	random reference diversity	optimized reference diversity	random target diversity	optimized target diversity	alt random reference diversity	alt optimized reference diversity	alt random target diversity	alt optimized target diversity	core members" << "\n";
		
	//write out results row by row
	for (unsigned int i=0;i<V1;i++)
	{
		//write variables
		output 	<< Results[i][0] 
				<< "	" << Results[i][1] 
				<< "	" << Results[i][2] 
				<< "	" << Results[i][3] 
				<< "	" << Results[i][4] 
				<< "	" << Results[i][5] 
				<< "	" << Results[i][6] 
				<< "	" << Results[i][7] 
				<< "	" << Results[i][8] 
				<< "	" << "(";
		//write Accessions retained
		for (unsigned int j=0;j<Members[i].size();j++)
		{
			if ( j==(Members[i].size() - 1) )
			{
				//add trailing parentheses and move to next row
				output << Members[i][j] << ")\n";
			}
			else
			{
				output << Members[i][j] << ",";
			}
		}
	}
	
	//wrap up write step
	output.close();

	//delete all recovery files
	if ( MakeRecovery == 0 )
	{
		cout << "\n\nDeleting recovery files...\n";
		#pragma omp parallel if(parallelism_enabled) num_threads(ncpu) 
		{		
			stringstream ss;
			ss << OutFilePath << ".t" << omp_get_thread_num() << ".tmp"; 
			string rfp = ss.str();
			const char* RecoveryFilePath = rfp.c_str();
		
			if (remove(RecoveryFilePath))
				cout << "Failed to delete " << RecoveryFilePath << ": " << strerror(errno) << "\n";
			//else cout << RecoveryFilePath << " successfully deleted.\n";
		}
	}
}
示例#21
0
int main() {
Data();
Simplex();
Results();
}
示例#22
0
文件: game.c 项目: mtl23/2DFINAL
/*notice the default arguments for main.  SDL expects main to look like that, so don't change it*/
int main(int argc, char *argv[])
{

 // SDL_Surface *temp = NULL;

  
  int done;// the player
  const Uint8 *keys;// the player

  /* This section starts by loading the BG as a surface and converting it to a texture This will have to change 
  if I can manage to scroll the trexture arond the player*/
 
SDL_CreateWindowAndRenderer(800, 600, SDL_WINDOW_RESIZABLE, &mainWindow, &renderer);
SDL_SetWindowTitle(mainWindow, "Nitro Hotness");
 if( TTF_Init() == -1 )
    {
        return false;    
    }

  if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
    {
        return false;    
    }

InitSpriteSystem();
InitEntitySystem(entityMax);


map mymap = setWorld();
ObstacleList ol = newObstacleList();
mew = newPlayer();
Obstacle Doh = newObstacle(0);
Road_M Path = initRoad();
AI rival = new_AI();
GUI HUD = InitGUI();
mew.position=0;
done = 0;

//The music that will be played
   Mix_Music *music = NULL;


   Mix_Chunk *buzz = NULL;
    buzz = Mix_LoadWAV( "sfx/buzz.wav" );
	readSave(&mew);
	showTitle();
	showMain();
  oldTime = 0;
  currentTime = 0;
  mytime = 0;

do
 	{
		
  oldTime = 0;
  currentTime = 0;
  mytime = 0;
	  if( Mix_PlayingMusic() == 0 )
                    {
                        //Play the music
                        if( Mix_PlayMusic( level_music, -1 ) == -1 )
                        {
                            return 1;
                        } 
					}
	 SDL_Event e;
	 SDL_PollEvent( &e ); 
		if(&e)
					{
					//User requests quit
					if( e.type == SDL_QUIT )
					{
						done = 1;
					}
					//user presses enter to go to next menu
					
					//User presses a key
					else if( e.type == SDL_KEYDOWN )
					{
						//Select surfaces based on key press
						switch( e.key.keysym.sym )
						{
						
						case SDLK_LEFT:
				//		slog("left is down");	
						mew.playerX += 3;
						mew.accel = (mew.accel - .000001);
						break;

						case SDLK_RIGHT:
					//	slog("right is down");
						mew.playerX -= 3;
						mew.accel = (mew.accel - .000001);
						break;

						case SDLK_UP:
					//	slog("up is down");
						 mew.accel = (mew.accel + .00007);
						 Mix_PlayChannel( 1, buzz, 0 );
						 break;
						
						case SDLK_DOWN:
					//	slog("down is down");
						mew.accel = (mew.accel - .00008);
						break;
						}
					}

					else if( e.type == SDL_KEYUP )
					{
						//Select surfaces based on key press
						switch( e.key.keysym.sym )
						{	
						
						case SDLK_RETURN :
						if(mew.done ==1)
						{
							Mix_HaltMusic();
							if(GP == 1)
							{
							mew.done=0;
							lvl++;
							//slog("new level is %i",lvl);
							mew.position = 0;
							rival.position =0;
							setWorld();
							Results(mew.rank,lvl);
							}
						else if (GP == 0)
							{
							mew.done=0;
							mew.position = 0;
							rival.position =0;
							levelSelect();
							}
						
						}
						else
						{
						slog("too soon");
						}
						
						case SDLK_LEFT:
					//	slog("left is up");	
						e.type = SDLK_CLEAR;
						break;

						case SDLK_RIGHT:
					//	slog("right is up");
						e.type = SDLK_CLEAR;
						break;

						case SDLK_UP:
					//	slog("up is up");
						mew.accel = (mew.accel - .001);
						Mix_HaltChannel(1);
						e.type = SDLK_CLEAR;
						break;

						case SDLK_DOWN:
					//	slog("down is up");
						mew.accel = 0;
						e.type = SDLK_CLEAR;
						break;

						default:
					//slog("simple decel");	
						mew.accel = (mew.accel-0.00001);
						break;

						}
					}

		if(mew.position > rival.position)
		{
			mew.rank = 1 ;
		}
		else if( rival.position > mew.position )
		{
			mew.rank = 2 ;
		}
		SDL_RenderClear(renderer);
		DrawBG(BG1,BG2);
		roadUpdate(Path,mymap,mew);
		roadDraw(Path,mymap,&mew);
		roadFetch(Path,mymap,&mew);
		checkForObstacles(ol , &mew, Doh);
		update_AI(&rival, &mew);
		UpdatePlayer(&mew);
		DrawGui(HUD,mew);
		NextFrame();
		keys = SDL_GetKeyboardState(NULL);

	if(keys[SDL_SCANCODE_ESCAPE])
    {
        done = 1;
    }
	
}
  }while(!done);
      //Free the sound effects
   //Free the music
  Mix_FreeMusic( music );
  CloseEntitySystem();
  CloseSpriteSystem();
  exit(0);		/*technically this will end the program, but the compiler likes all functions that can return a value TO return a value*/ 
 return 0;
}
示例#23
0
//M+	
void mp(
	int MinCoreSize,
	int MaxCoreSize,
	int SamplingFreq,
	int NumReplicates,
	char* OutFilePath,
	std::string Kernel,
	vector<int> KernelAccessionIndex,
	vector<int> AccessionNameList,
	vector<vector<vector<int> > > ActiveAlleleByPopList,
	vector<vector<vector<int> > > TargetAlleleByPopList,
	vector<int> ActiveMaxAllelesList,
	vector<int> TargetMaxAllelesList,
	vector<std::string> FullAccessionNameList
	)	
{

	//PERFORM INITIAL MPI STUFF
	MPI_Status status; //this struct contains three fields which will contain info about the sender of a received message
						 // MPI_SOURCE, MPI_TAG, MPI_ERROR
	
	//MPI::Init ();  //Initialize MPI.
	int nproc = MPI::COMM_WORLD.Get_size ( );  //Get the number of processes.
	int procid = MPI::COMM_WORLD.Get_rank ( );  //Get the individual process ID.
	

	//set up vectors to fill with results
	//below is a stupid way to calculate the number of rows in the output file, value l (which = V1) 
	//used to monitor progress and as the maximum vector index for shared output vectors
	int l=0;
	for (int i=MinCoreSize;i<MaxCoreSize+1;i=i+SamplingFreq)
	{
		for (int j=0;j<NumReplicates;j++)
		{
			l++;
		}
	}
	
	double V1 = (double)l; //(MaxCoreSize - MinCoreSize + 1)*NumReplicates; //number of rows in output vectors
	vector<vector<double> > Results(V1, vector<double>(9)); //will contain numerical results
	vector<vector<string> > Members(V1); //will contain core set members
	
	//***MPI:  RECEIVE RESULTS AT MASTER 0
	//receive values from any slave, in any order, exiting when the number of 'receives' = the top vector size
	if ( procid == 0 ) 
	{
		//set up variables for monitoring progress
		int percent; //percent of analysis completed
		int progindex = 0;  //index to monitor progress, percent = 100*(progindex/l)

		//receive and process results from slave processors
		unsigned int i = 0;
		while (i<2*(Results.size())) //two receives per row
		{
			//probe the incoming message to determine its tag
			int nchar; //will contain the length of the char array passed with tag=1
			int vchar; //will contain the length of the vector passed with tag=0
			int tag; //tag of message from sender
			int source; //procid of sender
			
			MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
			//MPI_Get_count(&status, MPI_CHAR, &nchar); //probes the length of the message, saves it in nchar
			tag = status.MPI_TAG; //the tag defines which kind of comm it is, a vector of stats (0=resvec()) 
			                      //or a char array describing the members of the core (1=cc)
			source = status.MPI_SOURCE; //determine the source of the message so that you can define which sender to Recv from.  This will avoid an intervening message coming in after the MPI_Probe with a different length, causing a message truncated error.
			
			if (tag == 0)
			{
				//determine the length of the message tagged 0
				MPI_Get_count(&status, MPI_DOUBLE, &vchar);

				//cout <<" vchar="<<vchar<<" tag="<<tag<<" MPI_SOURCE="<<status.MPI_SOURCE<<" MPI_ERROR="<<status.MPI_ERROR<<"\n";

				//receive the vector of results, tagged 0, from:
				//MPI_Send(&resvec[0], resvec.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
				vector<double> t(10);
				MPI_Recv(&t[0], vchar, MPI_DOUBLE, source, 0, MPI_COMM_WORLD, &status);
			
				//load data from vector received onto Results, row number is last item t[9]
				for (int j=0;j<9;++j)
				{
					Results[ t[9] ][j] = t[j];
				}
				t.clear();
			}

			else if (tag == 1)
			{
				//determine the length of the message tagged 1
				MPI_Get_count(&status, MPI_CHAR, &nchar); //probes the length of the message, saves it in nchar

				//cout <<" nchar="<<nchar<<" tag="<<tag<<" MPI_SOURCE="<<status.MPI_SOURCE<<" MPI_ERROR="<<status.MPI_ERROR<<"\n";
				
				//receive the vector<string> of the core set, tagged 1, from:
				//MPI_Send(&m[0], nchar, MPI_CHAR, 0, 1, MPI_COMM_WORLD);
				//vector<string> m(nchar);
				char m[nchar];
				MPI_Recv(&m[0], nchar, MPI_CHAR, source, 1, MPI_COMM_WORLD, &status);
			
				//load core set onto Members
				//1. convert char array into a string
				string mstr(m);
			
				//2. split string on delimiter ',<!>,'
				string delim = ",<!>,";
				vector<string> mvec( countSubstring(mstr, delim) );
				unsigned int st = 0;
				std::size_t en = mstr.find(delim);
				int k = 0;
				while (en != std::string::npos)
				{
					mvec[k] = mstr.substr(st, en-st);
					st = en + delim.length();
					en = mstr.find(delim,st);
					++k;
				}
				string z = mstr.substr(st); //get row number as last item in mstr
				int zz = atoi(z.c_str()); //convert string to c-string then to int
			
				//3. load onto Members
				Members[zz] = mvec;
				
				//4. clean up
				memset(m, 0, nchar);; mstr=""; mvec.clear();
				

			}


			++i;
			
			//display progress
			progindex = progindex + 1;
			percent = 100*( progindex/(V1*2) ); //number of rows X 2 repeats needed to complete search
			printProgBar(percent); 
		}
	}//***MPI: END MASTER RECEIVE***/

	
	/***MPI:  SEND RESULTS FROM SLAVE PROCESSES***/
	else if ( procid != 0 )
	{
		unsigned int r; //r = core size, 
		//int nr, RandAcc, b, bsc, plateau; //nr = controller to repeat NumReplicates times
		int RandAcc, b, bsc, plateau; //nr = controller to repeat NumReplicates times
								//row = result vector row number, bsc = holds best sub core member, and other indexed accessions
									//plateau = index of the number of reps in optimization loop with same diversity value
		double RandomActiveDiversity;
		double AltRandomActiveDiversity;
		double StartingRandomActiveDiversity;
		double StartingAltRandomActiveDiversity;
		double RandomTargetDiversity;
		double AltRandomTargetDiversity;
		double StartingDiversity;
		double TempAltOptimizedActiveDiversity;
		double AltOptimizedActiveDiversity;
		double OptimizedTargetDiversity;
		double AltOptimizedTargetDiversity;
		double best;
		double nnew;
		vector<vector<vector<int> > > AlleleList;
		vector<vector<vector<int> > > CoreAlleles;
		vector<vector<vector<int> > > TdTempList;
		vector<vector<vector<int> > > BestSubCoreAlleles;
		std::string Standardize = "yes";  //a run that mimics the MSTRAT approach can be accomplished by setting Standardize="no", and setting up the var file so that each column in the .dat file is treated as a single locus, rather than two (or more) adjacent columns being treated as a single codominant locus.
		vector<int> AccessionsInCore;
		vector<int> AccessionsInSubCore;
		vector<int> BestSubCore;
		vector<int> BestSubCoreRevSorted;
		vector<int> TempList;
		vector<int> TempList2;
		vector<int> bestcore;
		vector<std::string> TempListStr;
	
		//seed the random number generator for each processor
		int tt;
		tt = (time(NULL));
		srand ( abs(((tt*181)*((procid-83)*359))%104729) );
			
		//do parallelization so that each rep by core size combo can be
		//handled by a distinct thread.  this involves figuring out the total
		//number of reps*coresizes taking into account the SamplingFreq
		int rsteps = 1 + floor( (MaxCoreSize - MinCoreSize) / SamplingFreq ); //number of steps from MinCoreSize to MaxCoreSize

		//***MPI: figure out where to start and stop loop for each processor
		int nreps = rsteps*NumReplicates;
		int count = nreps/(nproc-1); //p-1 assumes a master, i.e. one less processor than total
		int start = (procid-1) * count; //procid-1 makes you start at 0, assumes master is p0
		int stop;
		
		if (nreps % (nproc-1) > (procid-1))
		{
			start += procid - 1;
			stop = start + (count + 1); 
		}
		else
		{
			start += nreps % (nproc-1);
			stop = start + count;
		}
		
		//iterate thru the relevant rows
		for (int rnr=start;rnr<stop;++rnr)
		{
			r = MinCoreSize + ((rnr / NumReplicates) * SamplingFreq); //int rounds to floor
			
			//develop random starting core set
			//clear AccessionsInCore and set size
			AccessionsInCore.clear();
			AccessionsInCore.resize(r);
			
			//add kernel accessions to core, if necessary
			if (Kernel == "yes")
			{
				for (unsigned int i=0;i<KernelAccessionIndex.size();i++)
				{
					AccessionsInCore[i] = KernelAccessionIndex[i];
				}
			}

			//clear TempList and set size					
			TempList.clear();
			TempList.resize( AccessionNameList.size() );
			
			//set list of available accessions in TempList, by erasing those already in the core
			TempList = AccessionNameList;
			//expunge the kernel accessions, so they are not available for random addition below
			//KernelAccessionIndex has been reverse sorted so you don't go outside range after automatic resize by .erase
			for (unsigned int i=0;i<KernelAccessionIndex.size();i++)
			{
				b = KernelAccessionIndex[i];
				TempList.erase(TempList.begin()+b);
			}
		
			//randomly add accessions until r accessions are in the core. if there is a kernel, include those (done above)
			//plus additional, randomly selected accessions, until you get r accessions
			for (unsigned int i=KernelAccessionIndex.size();i<r;i++)
			{
				//choose an accession randomly from those available
				RandAcc = rand() % TempList.size();
				//add it to the list
				AccessionsInCore[i] = TempList[RandAcc];
			
				//remove it from the list of available accessions
				TempList.erase(TempList.begin()+RandAcc);
			}
	
			//assemble genotypes for random core and calculate diversity
			//1. put together initial list of active alleles
			CoreAlleles.clear();
			CoreAlleles.resize( AccessionsInCore.size() );
			for (unsigned int i=0;i<AccessionsInCore.size();i++)
			{
				b = AccessionsInCore[i];
				CoreAlleles[i] = ActiveAlleleByPopList[b];
			}

			//2. calculate diversity from random selection at active loci
			AlleleList.clear();
			AlleleList = CoreAlleles;
	
			MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
			//in MyCalculateDiversity, latter two variables are updated as references
			//save them away in non-updated variables
			StartingRandomActiveDiversity = RandomActiveDiversity;
			StartingAltRandomActiveDiversity = AltRandomActiveDiversity;

			//3. calculate diversity from random selection at target loci
			AlleleList.clear();
			AlleleList.resize( AccessionsInCore.size() );
			for (unsigned int j=0;j<AccessionsInCore.size();j++)
			{
				b = AccessionsInCore[j];
				AlleleList[j] = TargetAlleleByPopList[b];
			}
			MyCalculateDiversity(AlleleList, TargetMaxAllelesList, Standardize, RandomTargetDiversity, AltRandomTargetDiversity);


			//BEGIN OPTIMIZATION
			StartingDiversity = 0; //this is the diversity recovered during the prior iteration.
			plateau = 0; //count of the number of times you have found the best value, evaluates when you are
						 //stuck on a plateau, assuming acceptance criterion allows downhill steps
			//this is the iterations step, now an indefinite loop that is broken when 
			//no improvement is made during the course of the optimization algorithm
			//If r = kernel size = MinCoreSize then do no optimization but still calculate all variables.
			if (KernelAccessionIndex.size() == r)
			{
				//assemble genotypes for core
				//1. put together initial list
				CoreAlleles.clear();
				CoreAlleles.resize(r);
				for (unsigned int i=0;i<r;i++)
				{
					b = AccessionsInCore[i];
					CoreAlleles[i] = ActiveAlleleByPopList[b];
				}
				
				AlleleList = CoreAlleles;
				
				MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
				best = RandomActiveDiversity; //best is equivalent to OptimizedActiveDiversity
				AltOptimizedActiveDiversity = AltRandomActiveDiversity;
			}
			else
			{
				//do optimization
				while ( true )
				{
					//assemble genotypes for core
					//1. put together initial list
					CoreAlleles.clear();
					CoreAlleles.resize(r);
					for (unsigned int i=0;i<r;i++)
					{
						b = AccessionsInCore[i];
						CoreAlleles[i] = ActiveAlleleByPopList[b];
					}
		
					//2. go through all possible subsets of size r-1, one at a time, noting which is best.
					//If there is a kernel, do not swap out any of those accessions (they are retained as the
					//first KernelAccessionIndex.size() items in CoreAlleles).  Accomplished by starting for loop
					//at KernelAccessionIndex.size().
					best=0;
					for (unsigned int i=KernelAccessionIndex.size();i<CoreAlleles.size();i++)
					{
						//remove each item consecutively from the list of all populations in the core
						AlleleList.clear();
						TdTempList.clear();
				
						TdTempList = CoreAlleles; //swap to temporary vector
						TdTempList.erase( TdTempList.begin() + i);
						AlleleList = TdTempList;
			
						TempList2.clear();
						TempList2 = AccessionsInCore;
						TempList2.erase(TempList2.begin() + i);
						AccessionsInSubCore = TempList2;

						/*Data structure for SubCoreAlleles:
						SubCore 1..r
							Population 1..(r-1)
								AlleleArray 1..NumLoci		
			
						--3. fuse alleles from the same locus into a single array, for all accessions, for the current subcore
						--4. assemble a list of diversity (M) for each locus separately
						--5. standardize the M values to the maximum possible number of alleles at that locus, and add them up to get final estimate of standardized allelic diversity in the core.  then divide by the number of loci to get a number that is comparable across data sets.
						--5.5. simultaneous to the calculation, keep track of which subcore is best
						*/
			
						MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, RandomActiveDiversity, AltRandomActiveDiversity);
						nnew = RandomActiveDiversity;

						if (nnew >= best) // >= allows sideways movement during hill climbing
						{
							best = nnew;

							BestSubCore.clear();
							BestSubCore = AccessionsInSubCore;
							BestSubCoreAlleles.clear();
							BestSubCoreAlleles = AlleleList;
						}
					}  //for loop cycles thru all subcores

					//reverse sort BestSubCore to support easy assembly of pared TempList below
					BestSubCoreRevSorted = BestSubCore;
					std::sort(BestSubCoreRevSorted.begin(), BestSubCoreRevSorted.end(), std::greater<int>());
	
					/*
					6. take the subcore with greatest diversity and consecutively add each 
					possible additional accession from the base collection.  find the core of size r 
					(not r-1 subcore) that has the greatest diversity.

					suppress the IDs of those accessions found in the BestSubCore from the 
					list of all accessions to get a list of remaining accessions.*/
					TempList = AccessionNameList;
					for (unsigned int k=0;k<BestSubCoreRevSorted.size();k++)
					{
						bsc = BestSubCoreRevSorted[k];
						TempList.erase( TempList.begin() + bsc );
					}
			
					//shuffle the list of remaining accessions, so addition order is not predictable
					std::random_shuffle (TempList.begin(), TempList.end());
				
					//add each remaining accession consecutively, calculate diversity, test 
					//whether it is better than the prior one
					best = 0;
					for (unsigned int k=0;k<TempList.size();k++)
					{
						bsc = TempList[k];
			
						//define the core
						TempList2 = BestSubCore;
						TempList2.resize( TempList2.size() + 1 );
						//TempList2.push_back(i);
						TempList2[TempList2.size()-1] = bsc; //add new accession to last vector element
						AccessionsInCore = TempList2;
			
						//assemble the allelelist for the core
						TdTempList = BestSubCoreAlleles;
						TdTempList.resize( TdTempList.size() + 1 );
						//TdTempList.push_back( ActiveAlleleByPopList[i] );
						TdTempList[TdTempList.size()-1] = ActiveAlleleByPopList[bsc];
						AlleleList = TdTempList;
			
						//calculate diversity
						MyCalculateDiversity(AlleleList, ActiveMaxAllelesList, Standardize, nnew, TempAltOptimizedActiveDiversity); 
		
						//test whether current diversity is higher than the best diversity found so far
						if (nnew >= best) // >= allows sideways movement during hill climbing
						{
							best = nnew;
							bestcore = AccessionsInCore;
							//save the alternative diversity value for the best core
							AltOptimizedActiveDiversity = TempAltOptimizedActiveDiversity;
						}
					}

					AccessionsInCore = bestcore; //define starting variable for next MSTRAT iteration
		
					//if there has been no improvement from the prior iteration, you have reached
					// the plateau and should exit the repeat
					if (best == StartingDiversity) 
					{
						plateau++;
						if (plateau > 0) break;
					}
					//update starting value and repeat
					else if (best > StartingDiversity) StartingDiversity = best;
				
				} //while(true) endless loop
			}

			//7. Calculate diversity at target loci
			//assemble the target loci allelelist for the accessions in the best core
			AlleleList.clear();
			AlleleList.resize( AccessionsInCore.size() );
			for (unsigned int j=0;j<AccessionsInCore.size();j++)
			{
				b = AccessionsInCore[j];
				AlleleList[j] = TargetAlleleByPopList[b];
			}
	
			//calculate diversity at target loci based upon the optimized core selection
			MyCalculateDiversity(AlleleList, TargetMaxAllelesList, Standardize, OptimizedTargetDiversity, AltOptimizedTargetDiversity);

			//8. Assemble stats for optimized core and add to output vectors
			//create a list of accession names from the list of accession ID's in AccessionsInCore
			sort( AccessionsInCore.begin(), AccessionsInCore.end() );
			
			TempListStr.clear();
			TempListStr.resize(r);
			for (unsigned int i=0;i<AccessionsInCore.size();i++)
			{
				b = AccessionsInCore[i];
				TempListStr[i] = FullAccessionNameList[b];
			}

			/***MPI: BUILD & SEND RESULTS VECTOR***/
			//load the variables onto the results vectors
			
			//no need to calculate row number, it is the same as rnr, formula saved because it might be useful later
			//row = ((r - MinCoreSize)*NumReplicates) + nr - ( (NumReplicates*(SamplingFreq-1))*( (r-MinCoreSize)/SamplingFreq ) );
			// (r - MinCoreSize)*NumReplicates) + nr specifies row number if SamplingFreq=1
			// (NumReplicates*(SamplingFreq-1)) specifies a step value to correct when SamplingFreq>1
			// ( (r-MinCoreSize)/SamplingFreq ) specifies the replicate on core size, accounting for SamplingFreq
			// see file Calculation of row value.xlsx for development of the 'row' index
			
			//put results 0-8 into a vector, resvec, return row as last item
			vector<double> resvec(10);

			resvec[0] = double(r);
			resvec[1] = StartingRandomActiveDiversity;//RandomActiveDiversity;
			resvec[2] = best; //equivalent to OptimizedActiveDiversity
			resvec[3] = RandomTargetDiversity;
			resvec[4] = OptimizedTargetDiversity;
			resvec[5] = StartingAltRandomActiveDiversity;//AltRandomActiveDiversity;
			resvec[6] = AltOptimizedActiveDiversity;
			resvec[7] = AltRandomTargetDiversity;
			resvec[8] = AltOptimizedTargetDiversity;
			resvec[9] = double(rnr);
			
			
			//cout<<"MPI_Rank="<<MPI_Rank<<" 
			
			
			//send result vector to master 0, send row number, rnr, as last element.
			//message is tagged as 0
			//here you are pointing to the first element, then returning resvec.size() doubles-
			//worth of memory from that starting location.
			MPI_Send(&resvec[0], resvec.size(), MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
			/***MPI: END BUILD & SEND RESULTS VECTOR***/


			/***MPI: BUILD & SEND MEMBERS VECTOR***/
			//add row number as last item in TempListStr
			TempListStr.resize(TempListStr.size()+1);
			stringstream ss;
			ss << rnr;	//convert int to stringstream to string			
			TempListStr[ TempListStr.size() - 1 ] = ss.str();
		
			//convert vector<string> to a single, ',<!>,' delimited, string
			string concat;
			for (unsigned int i=0;i<TempListStr.size();++i)
			{
				concat += TempListStr[i]; //add vector element
				if (i<TempListStr.size()-1) concat += ",<!>,"; //add delimiter, except for last item
			}
			//convert the string to a char array
			char cc[concat.size()+1];
			strcpy(cc, concat.c_str());
			
			//send the char array to master0 tagged as 1
			//tagged as 1 to distinguish from result vector send
			MPI_Send(&cc, sizeof(cc), MPI_CHAR, 0, 1, MPI_COMM_WORLD);

		} //end for loop over rows
	} //***MPI:  END SEND
	

	/*MPI: MASTER 0 WRITES OUTPUT*/
	if ( procid == 0 )
	{
		//set up file stream for output file
		ofstream output; 
		output.open(OutFilePath);
		output.close(); //quick open close done to clear any existing file each time program is run
		output.open(OutFilePath, ios::out | ios::app); //open file in append mode
		output << "core size	random reference diversity	optimized reference diversity	random target diversity	optimized target diversity	alt random reference diversity	alt optimized reference diversity	alt random target diversity	alt optimized target diversity	core members" << "\n";
		
		//write out results row by row
		for (int i=0;i<V1;i++)
		{
			//write variables
			output 	<< Results[i][0] 
					<< "	" << Results[i][1] 
					<< "	" << Results[i][2] 
					<< "	" << Results[i][3] 
					<< "	" << Results[i][4] 
					<< "	" << Results[i][5] 
					<< "	" << Results[i][6] 
					<< "	" << Results[i][7] 
					<< "	" << Results[i][8] 
					<< "	" << "(";
			//write Accessions retained
			for (unsigned int j=0;j<Members[i].size();j++)
			{
				if ( j==(Members[i].size() - 1) )
				{
					//add trailing parentheses and move to next row
					output << Members[i][j] << ")\n";
				}
				else
				{
					output << Members[i][j] << ",";
				}
			}
		}
	
		//wrap up write step
		output.close();
	} /***MPI: END MASTER WRITE***/
	
	//Terminate MPI.
	//MPI::Finalize ( );

}