bool ComplexDomainFlux::process(Ports<InputBuffer*>& inp, Ports<OutputBuffer*>& outp) { assert(inp.size()==1); InputBuffer* in = inp[0].data; assert(outp.size()==1); OutputBuffer* out = outp[0].data; if ((out->tokenno()==0) && (in->tokenno()!=-2)) in->prependZeros(2); if (!in->hasTokens(3)) return false; const int N = in->info().size/2; ArrayXcd inPredPredRotator(N); ArrayXcd inPredRotator(N); rotatorOp<double> op; { Map<ArrayXcd> inPredPredData((complex<double>*) in->token(0),N); inPredPredRotator = inPredPredData.unaryExpr(op); } while (in->hasTokens(3)) { Map<ArrayXcd> inPredData((complex<double>*) in->token(1),N); Map<ArrayXcd> inData((complex<double>*) in->token(2), N); inPredRotator = inPredData.unaryExpr(op); double* output = out->writeToken(); *output++ = (inData - (inPredData * (inPredRotator * inPredPredRotator.conjugate()))).abs().sum(); in->consumeToken(); inPredPredRotator.swap(inPredRotator); } return true; }
bool EvoAlgoTestIndividual::loadGenotypes() { // Removing all old genotypes freeGenotypes(); // Loading all genotypes QFile inData(m_filename); if (inData.open(QFile::ReadOnly)) { QTextStream in(&inData); while (!in.atEnd()) { std::unique_ptr<Genotype> g(getPrototype()->clone()); bool loaded = g->loadGen(in); if (!loaded) { // This could be not a real error, only notifying the user Logger::warning(QString("Error loading the genotype at index %1 from file %2").arg(m_genotypes.size()).arg(m_filename)); break; } m_genotypes.append(g.release()); } inData.close(); } else { Logger::error(QString("Cannot open file %1 to read genotypes").arg(m_filename)); return false; } return true; }
void FFT::processToken(double* inPtr, const int N, double* out, const int outSize) { #ifdef WITH_FFTW3 double* inFFT = (double*) fftw_malloc(m_nfft*sizeof(double)); complex<double>* outFFT = (complex<double>*) fftw_malloc((m_nfft/2+1)*sizeof(complex<double>)); Map<VectorXd> infft(inFFT,m_nfft); #else VectorXd infft(m_nfft); #endif Map<VectorXd> inData(inPtr,N); if (m_window.size()>0) infft.segment(0,N) = m_window.array() * inData.array(); else infft.segment(0,N) = inData; if (N<m_nfft) infft.segment(N,m_nfft-N).setZero(); #ifdef WITH_FFTW3 fftw_execute_dft_r2c(m_plan,inFFT,(fftw_complex*)outFFT); memcpy(out,outFFT,outSize*sizeof(double)); fftw_free(inFFT); fftw_free(outFFT); #else m_plan.fwd((std::complex<double>*) out,infft.data(),m_nfft); #endif }
void wxPdfParser::GetStreamBytesRaw(wxPdfStream* stream) { wxPdfNumber* streamLength = (wxPdfNumber*) ResolveObject(stream->Get(_T("/Length"))); size_t size = streamLength->GetInt(); m_tokens->Seek(stream->GetOffset()); wxMemoryOutputStream* memoryBuffer = NULL; wxMemoryOutputStream* streamBuffer = m_tokens->ReadBuffer(size); if (m_encrypted && size > 0) { wxMemoryInputStream inData(*streamBuffer); delete streamBuffer; memoryBuffer = new wxMemoryOutputStream(); unsigned char* buffer = new unsigned char[size]; inData.Read(buffer, size); if (inData.LastRead() == size) { m_decryptor->Encrypt(m_objNum, m_objGen, buffer, size); memoryBuffer->Write(buffer, size); } delete [] buffer; memoryBuffer->Close(); } else { memoryBuffer = streamBuffer; } stream->SetBuffer(memoryBuffer); if (streamLength->IsIndirect()) { delete streamLength; } }
ReflectorSession* SetupProxySession(QTSS_StandardRTSP_Params* inParams, RTSPRelaySession* session) { if(session == NULL) return NULL; UInt32 sdpLen = 0; char* relaySDP = NULL; relaySDP = session->GetSDPInfo()->GetLocalSDP(&sdpLen); if(relaySDP == NULL) return NULL; StrPtrLen inData(relaySDP); return FindOrCreateProxySession(session->GetRef()->GetString(), inParams, &inData,0); }
//void DebugStatsModule::SendRandomNetworkInPacket() Console::CommandResult DebugStatsModule::SendRandomNetworkInPacket(const StringVector ¶ms) { if (params.size() == 0) return Console::ResultSuccess(); int numMessages = atoi(params[0].c_str()); for(int i = 0; i < numMessages; ++i) { std::vector<char> data; int dataLen = rand() % 1600 + 1; for(int i = 0; i < dataLen; ++i) data.push_back(rand() % 256); int msgID = rand(); ProtocolUtilities::NetMessageManager *messageManager = current_world_stream_->GetCurrentProtocolModule()->GetNetworkMessageManager(); if (!messageManager) return Console::ResultSuccess(); try { ProtocolUtilities::NetInMessage msg(msgID, (boost::uint8_t *)&data[0], dataLen, false); #ifdef _DEBUG msg.SetMessageID(msgID); #endif ProtocolUtilities::NetMsgID id = msgID; ProtocolUtilities::NetworkEventInboundData inData(id , &msg); const ProtocolUtilities::NetMessageInfo *messageInfo = messageManager->GetMessageInfoByID(msgID); if (!messageInfo) continue; msg.SetMessageInfo(messageInfo); framework_->GetEventManager()->SendEvent(networkEventCategory_, id, &inData); } catch(const Exception &e) { LogInfo(std::string("Exception thrown: ") + e.what()); } catch(const std::exception &e) { LogInfo(std::string("std::exception thrown: ") + e.what()); } catch(...) { LogInfo("Unknown exception thrown."); } } return Console::ResultSuccess(); }
bool MPEGDecoder::init( bool decodeOnly ) { onlyDecode = decodeOnly; QFile file( testFile ); if ( !file.open(QIODevice::ReadOnly) ) { fprintf( stderr, "%s", QString("MPEGDecoder: FATAL: Can't open %1 !!\n").arg(testFile).toLatin1().data() ); return false; } QDataStream inData( &file ); inData.readRawData( (char*)&width, 4 ); inData.readRawData( (char*)&height, 4 ); inData.readRawData( (char*)&ratio, 8 ); inData.readRawData( (char*)&profile, 4 ); int i; for ( i=0; i<FRAMESINSAMPLE; ++i ) { MPEGFrame *frame = new MPEGFrame(); inData.readRawData( (char*)&frame->info, sizeof(frame->info) ); inData.readRawData( (char*)&frame->dataLength, 4 ); frame->data = new uint8_t[frame->dataLength]; inData.readRawData( (char*)frame->data, frame->dataLength ); frames.append( frame ); } VdpStatus st = vc->vdp_decoder_create( vc->vdpDevice, profile, width, height, 2, &decoder ); if ( st != VDP_STATUS_OK ) { fprintf( stderr, "MPEGDecoder: FATAL: Can't create decoder!!\n" ); return false; } for ( i=0; i<NUMSURFACES; ++i ) { surfaces[ i ] = VDP_INVALID_HANDLE; if ( onlyDecode && i>2 ) continue; st = vc->vdp_video_surface_create( vc->vdpDevice, VDP_CHROMA_TYPE_420, width, height, &surfaces[i] ); if ( st != VDP_STATUS_OK ) { fprintf( stderr, "MPEGDecoder: FATAL: Can't create required surfaces!!\n" ); return false; } } forwardRef = backwardRef = VDP_INVALID_HANDLE; currentSurface = surfaces[0]; currentFrame = 0; //fprintf( stderr, "MPEGDecoder: profile = %d\n", profile ); return true; }
bool Cepstrum::process(Ports<InputBuffer*>& inp, Ports<OutputBuffer*>& outp) { assert(inp.size()==1); InputBuffer* in = inp[0].data; if (in->empty()) return false; assert(outp.size()==1); OutputBuffer* out = outp[0].data; safeLogOp<double> slop; VectorXd outDct; while (!in->empty()) { Map<VectorXd> inData(in->readToken(),in->info().size); outDct.noalias() = m_dctPlan * inData.unaryExpr(slop); memcpy(out->writeToken(),outDct.data() + m_ignoreFirst, out->info().size*sizeof(double)); in->consumeToken(); } return true; }
bool SpecificLoudness::process(Ports<InputBuffer*>& inp, Ports<OutputBuffer*>& outp) { assert(inp.size()==1); InputBuffer* in = inp[0].data; if (in->empty()) return false; assert(outp.size()==1); OutputBuffer* out = outp[0].data; const int N = in->info().size; const int M = out->info().size; while (!in->empty()) { Map<VectorXd> inData(in->readToken(),N); double* outData = out->writeToken(); for (int i=0;i<NB_BARK_BANDS;i++) outData[i] = pow(inData.segment(m_bkBdLimits[i],m_bkBdLimits[i+1]-m_bkBdLimits[i]).sum(),0.23); in->consumeToken(); } return true; }
bool MelFilterBank::process(Ports<InputBuffer*>& inp, Ports<OutputBuffer*>& outp) { assert(inp.size()==1); InputBuffer* in = inp[0].data; if (in->empty()) return false; assert(outp.size()==1); OutputBuffer* out = outp[0].data; while (!in->empty()) { Map<VectorXd> inData(in->readToken(),in->info().size); double* outData = out->writeToken(); for (int f=0;f<m_filters.size();f++) { RowVectorXd& filter = m_filters[f]; outData[f] = filter * inData.segment(m_filterStart[f],filter.size()); } in->consumeToken(); } return true; }
//-------------------------------------------------------------------------------------- // Name: TerrainClass::LoadTerrainFromFile() // Desc: 加载地形高度信息以及纹理 //-------------------------------------------------------------------------------------- BOOL TerrainClass::LoadTerrainFromFile(wchar_t *pRawFileName, wchar_t *pTextureFile) { // 从文件中读取高度信息 std::ifstream inFile; inFile.open(pRawFileName, std::ios::binary); //用二进制的方式打开文件 inFile.seekg(0,std::ios::end); //把文件指针移动到文件末尾 std::vector<BYTE> inData(inFile.tellg()); //用模板定义一个vector<BYTE>类型的变量inData并初始化,其值为缓冲区当前位置,即缓冲区大小 inFile.seekg(std::ios::beg); //将文件指针移动到文件的开头,准备读取高度信息 inFile.read((char*)&inData[0], inData.size()); //关键的一步,读取整个高度信息 inFile.close(); //操作结束,可以关闭文件了 m_vHeightInfo.resize(inData.size()); //将m_vHeightInfo尺寸取为缓冲区的尺寸 //遍历整个缓冲区,将inData中的值赋给m_vHeightInfo for (unsigned int i=0; i<inData.size(); i++) m_vHeightInfo[i] = inData[i]; // 加载地形纹理 if (FAILED(D3DXCreateTextureFromFile(m_pd3dDevice, pTextureFile, &m_pTexture))) return FALSE; return TRUE; }
/** create a SlaterDeterminant * @param cur xmlnode containing \<slaterdeterminant\> * @return a SlaterDeterminant * * @warning MultiSlaterDeterminant is not working yet. */ SPOSetBase* SplineSetBuilder::createSPOSet(xmlNodePtr cur) { string hrefname("NONE"); int norb(0); int degeneracy(1); OhmmsAttributeSet aAttrib; aAttrib.add(norb,"orbitals"); aAttrib.add(degeneracy,"degeneracy"); aAttrib.add(hrefname,"href"); aAttrib.put(cur); if(norb ==0) { app_error() << "SplineSetBuilder::createSPOSet failed. Check the attribte orbitals." << endl; return 0; } app_log() << " Degeneracy = " << degeneracy << endl; std::vector<int> npts(3); npts[0]=GridXYZ->nX; npts[1]=GridXYZ->nY; npts[2]=GridXYZ->nZ; std::vector<RealType> inData(npts[0]*npts[1]*npts[2]); SPOSetType* psi= new SPOSetType(norb); vector<int> occSet(norb); for(int i=0; i<norb; i++) occSet[i]=i; cur=cur->children; while(cur != NULL) { string cname((const char*)(cur->name)); if(cname == "occupation") { string occ_mode("ground"); const xmlChar* o=xmlGetProp(cur,(const xmlChar*)"mode"); if(o!= NULL) occ_mode = (const char*)o; //Do nothing if mode == ground if(occ_mode == "excited") { vector<int> occ_in, occRemoved; putContent(occ_in,cur); for(int k=0; k<occ_in.size(); k++) { if(occ_in[k]<0) occRemoved.push_back(-occ_in[k]-1); } int kpopd=0; for(int k=0; k<occ_in.size(); k++) { if(occ_in[k]>0) occSet[occRemoved[kpopd++]]=occ_in[k]-1; } } hid_t h_file = H5Fopen(hrefname.c_str(),H5F_ACC_RDWR,H5P_DEFAULT); const xmlChar* h5path = xmlGetProp(cur,(const xmlChar*)"h5path"); string hroot("/eigenstates_3/twist_0"); if(h5path != NULL) hroot=(const char*)h5path; char wfname[128],wfshortname[16]; for(int iorb=0; iorb<norb; iorb++) { sprintf(wfname,"%s/band_%d/eigenvector",hroot.c_str(),occSet[iorb]/degeneracy); sprintf(wfshortname,"b%d",occSet[iorb]/degeneracy); SPOType* neworb=0; map<string,SPOType*>::iterator it(NumericalOrbitals.find(wfshortname)); if(it == NumericalOrbitals.end()) { neworb=new SPOType(GridXYZ); HDFAttribIO<std::vector<RealType> > dummy(inData,npts); dummy.read(h_file,wfname); //neworb->reset(inData.begin(), inData.end(), targetPtcl.Lattice.BoxBConds[0]); neworb->reset(inData.begin(), inData.end(), targetPtcl.Lattice.SuperCellEnum); NumericalOrbitals[wfshortname]=neworb; app_log() << " Reading spline function " << wfname << endl; } else { neworb = (*it).second; app_log() << " Reusing spline function " << wfname << endl; } psi->add(neworb); } H5Fclose(h_file); } cur=cur->next; } SPOType* aorb=(*NumericalOrbitals.begin()).second; string fname("spline3d.vti"); std::ofstream dfile(fname.c_str()); dfile.setf(ios::scientific, ios::floatfield); dfile.setf(ios::left,ios::adjustfield); dfile.precision(10); dfile << "<?xml version=\"1.0\"?>" << endl; dfile << "<VTKFile type=\"ImageData\" version=\"0.1\">" << endl; dfile << " <ImageData WholeExtent=\"0 " << npts[0]-2 << " 0 " << npts[1]-2 << " 0 " << npts[2]-2 << "\" Origin=\"0 0 0\" Spacing=\"1 1 1\">"<< endl; dfile << " <Piece Extent=\"0 " << npts[0]-2 << " 0 " << npts[1]-2 << " 0 " << npts[2]-2 << "\">" << endl; dfile << " <PointData Scalars=\"wfs\">" << endl; dfile << " <DataArray type=\"Float32\" Name=\"wfs\">" << endl; int ng=0; GradType grad; ValueType lap; for(int ix=0; ix<npts[0]-1; ix++) { double x(GridXYZ->gridX->operator()(ix)); for(int iy=0; iy<npts[1]-1; iy++) { double y(GridXYZ->gridY->operator()(iy)); for(int iz=0; iz<npts[2]-1; iz++, ng++) { PosType p(x,y,GridXYZ->gridZ->operator()(iz)); //aorb.setgrid(p); //Timing with the ofstream is not correct. //Uncomment the line below and comment out the next two line. //double t=aorb.evaluate(p,grad,lap); dfile << setw(20) << aorb->evaluate(p,grad,lap); if(ng%5 == 4) dfile << endl; } } } dfile << " </DataArray>" << endl; dfile << " </PointData>" << endl; dfile << " </Piece>" << endl; dfile << " </ImageData>" << endl; dfile << "</VTKFile>" << endl; abort(); return psi; }
void XnesAlgo::runEvolution() { Eigen::MatrixXf expCovMat(m_numGenes,m_numGenes); int startGeneration = 0; char statfile[64]; char inFilename[128]; char outFilename[128]; char bestOutFilename[128]; int bestGeneration = -1; int bestFitness = -1; // Set the seed setSeed(m_rngSeed); // Initialise the individual and the covariance matrix initialise(); // Check whether to recover a previous evolution sprintf(statfile,"S%d.fit", seed()); // Check if the file exists DataChunk statTest(QString("stattest"),Qt::blue,2000,false); if (statTest.loadRawData(QString(statfile),0)) { startGeneration = statTest.getIndex(); sprintf(inFilename, "S%dG%d.gen", (seed()), startGeneration); Logger::info("Recovering from startGeneration: " + QString::number(startGeneration)); Logger::info(QString("Loading file: ") + inFilename); QFile inData(inFilename); if (inData.open(QFile::ReadOnly)) { QTextStream in(&inData); bool loaded = m_individual->loadGen(in); // Check possible errors during the loading operation if (!loaded) { Logger::error("Error in the loading of the genotype"); } // Check the consistency of the genotype (i.e., the number of genes) if (m_individual->getLength() != m_numGenes) { Logger::error("Wrong genotype length!"); } // Load the covariance matrix char covMatFilename[64]; sprintf(covMatFilename, "S%dG%d.cvm", (seed()), startGeneration); QFile covMatData(covMatFilename); if (covMatData.open(QFile::ReadOnly)) { QTextStream covMatInput(&covMatData); for (int i = 0; i < m_numGenes; i++) { for (int j = 0; j < m_numGenes; j++) { QString str; covMatInput >> str; bool ok = false; float elem = str.toFloat(&ok); if (!ok || (covMatInput.status() != QTextStream::Ok)) { Logger::error("Error in the loading of the covariance matrix"); } m_covMat(i,j) = elem; expCovMat(i,j) = 0.0; } } covMatData.close(); }
int main(){ int gender; int wealthpercentile; int i,j,l; int deductgrid; int wealth; int wx; int grid; int temp_test; int Sstart; double alpha; int offset; char filename[11]={"table.txt"}; task_group tasks; time_t time_began,time_end; /* output variable */ //memset(&CalcStruct[0],0,sizeof(CALCSTRUCT)); gender=1; //0 is female 1 is male deductgrid=DEDUCTGRID; //wealthpercentile=3; //0-9 different wealth distribution /* calculating declaration: this time run for gird*4 total size from 4-8 so the program make some adjustment */ cout<<"calculating declaration: this time run for gird*4 total size from 4-8 \n so the program make some adjustment"<<endl; cur_time(); offset =0; Sstart=START; Parallel_LTCI *LTCI[10]; { for(gender=1;gender<2;gender++){ // initilize the class of LTCI for(wealthpercentile=Sstart;wealthpercentile<10-offset;wealthpercentile ++) { switch (wealthpercentile){ case 0: wealth=40000; alpha=0.98; wx=0; grid=20; break; case 1: wealth=58450; alpha=0.98; wx=0; grid=20; break; case 2: wealth=93415; alpha=0.91; wx=20000; grid=40; break; case 3: wealth=126875; alpha=0.82; wx=30000; grid=75; break; case 4: wealth=169905; alpha=0.70; wx=10000; grid=100; break; case 5: wealth=222570; alpha=0.60; wx=50000; grid=130; break; case 6: wealth=292780; alpha=0.52; wx=20000; grid=175; break; case 7: wealth=385460; alpha=0.41; wx=40000; grid=225; break; case 8: wealth=525955; alpha=0.35; wx=40000; grid=300; break; case 9: wealth=789475; alpha=0.26; wx=75000; grid=450; break; } //wealth =wealth*224.937/172.192; LTCI[int(wealthpercentile)-Sstart]=new Parallel_LTCI(wealthpercentile,gender,deductgrid,wealth,wx,grid,alpha); } calcSetup(); inputData(gender); for(i=0;i<10-Sstart-offset;i++){ Setup(LTCI[i]); inData(gender,LTCI[i]); } cout<<"calculating for 0:female 1: male ------"<<gender<<endl; cout<<"deductile period is : \t"<<deductgrid<<endl; cout<<"**********************************************"<<endl; cout<<"**********************************************"<<endl; /*task for 1 to 4*/ tasks.run([&gender,<CI,&offset,&Sstart](){ // int wealthpercentile; for(int wealthpercentile=Sstart;wealthpercentile<5-offset;wealthpercentile++) LTCI[wealthpercentile-Sstart]->comput(); }); //// /*task for 4*/ //tasks.run([&gender,<CI,&Sstart](){ // int wealthpercentile=4-Sstart; // LTCI[wealthpercentile]->comput(); //}); // /*task for 5*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=5-Sstart; LTCI[wealthpercentile]->comput(); }); /*task for 6*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=6-Sstart; LTCI[wealthpercentile]->comput(); }); // /*task for 7*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=7-Sstart; LTCI[wealthpercentile]->comput(); }); /*task for 8*/ tasks.run([&gender,<CI,&Sstart](){ int wealthpercentile=8-Sstart; LTCI[wealthpercentile]->comput(); }); /*task for 9*/ tasks.run_and_wait([&gender,<CI,&Sstart](){ int wealthpercentile=9-Sstart; LTCI[wealthpercentile]->comput(); }); } // output some variables if(para.MWcount==0){if (gender==0) para.MW=1.058; else para.MW=0.5;} else if(para.MWcount==1){if (gender==0) para.MW=0.6; else para.MW=0.3;} else if(para.MWcount==2){if (gender==0) para.MW=1.358127; else para.MW=0.6418727;} else if(para.MWcount==3){if (gender==0) para.MW=1.358127; else para.MW=0.6418727;} else if(para.MWcount==4){if (gender==0) para.MW=1; else para.MW=1;} ofstream out(filename, ios::app); if (out.is_open()) { // out<<"*********************************************************************"<<endl; out<<"deductile grid is :"<<deductgrid<<endl; for(i=0;i<10-offset-Sstart;i++) record_result(i,LTCI[i]); // out<<"table "<<endl; // for(i=0;i<10-offset-Sstart;i++){ // out<<i+Sstart<<"0th : \t 1 \t 2 \t 3 \t 4"<<endl; // out<<record.MUstar[i]/record.EPDVMedical[i]<<'\t'; // out<<record.Mstar[i]/record.EPDVMedical[i]<<"\t"; // out<<(record.MUstar[i] - record.Mstar[i])/record.Istarown[i]<<"\t"; // out<<(1-(record.Istarown[i]-(record.MUstar[i]-record.Mstar[i]))/(record.Istarown[i]/para.MW))<<"\t"; // out<<record.wequiv[i]<<"\t"; // out<<endl; // } out<<"*********************************************************************"<<endl; out<<"----------------------------------------------------------------------"<<endl; out<<"---------------------------------raw data---------------------------- "<<endl; out<<"----------------------------------------------------------------------"<<endl; out<<"index for the data: S_Madicaid \t S_Insurance \t S_Madicaid_NI \t S_Medcost \t S_wequiv \t S_medicare \t S_med_joint_NI \t S_med_joint \t S_OOP \t S_OOP_NI"<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Madicaid[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Insurance[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Madicaid_NI[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_Medcost[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_wequiv[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_medicare[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_med_joint_NI[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_med_joint[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_OOP[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.S_OOP_NI[i]<<"\t"; out<<endl; out<<"EPDVMedical wequive Mstar Istar MUstar Istarnon "<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.EPDVMedical[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.wequiv[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.Mstar[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.Istarown[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.MUstar[i]<<"\t"; out<<endl; for(i=0;i<10-offset-Sstart;i++) out<<record.Istarnone[i]<<"\t"; out<<endl; out.close(); } for(i=0;i<10-offset-START;i++) delete LTCI[i]; } system("pause"); return 0; }
int main(int argc, char** argv) { double ri = 0.0; double rf = 1.0; std::vector<int> npts(3); npts[0]=51;npts[1]=51;npts[2]=51; double xcut=0.23; double ycut=0.67; const int nk0=1; const int nk1=1; const int nk2=1; //Create one-dimensional grids for three orthogonal directions typedef LinearGrid<double> GridType; GridType gridX, gridY, gridZ; gridX.set(ri,rf,npts[0]); gridY.set(ri,rf,npts[1]); gridZ.set(ri,rf,npts[2]); //Create an analytic function for assignment ComboFunc infunc; infunc.push_back(0.5,new TestFunc(1,1,1)); //infunc.push_back(0.3,new TestFunc(1,1,2)); //infunc.push_back(0.1,new TestFunc(1,2,1)); //infunc.push_back(0.01,new TestFunc(2,1,1)); //infunc.push_back(0.01,new TestFunc(2,2,1)); //infunc.push_back(0.001,new TestFunc(2,1,2)); //infunc.push_back(0.001,new TestFunc(2,2,2)); //infunc.push_back(0.001,new TestFunc(5,5,5)); //infunc.push_back(-0.3,new TestFunc(7,2,3)); //infunc.push_back(0.01,new TestFunc(7,7,7)); //infunc.push_back(0.001,new TestFunc(5,5,5)); //Write to an array std::vector<double> inData(npts[0]*npts[1]*npts[2]); std::vector<double>::iterator it(inData.begin()); Pooma::Clock timer; timer.start(); //Assign the values for(int ix=0; ix<npts[0]; ix++) { double x(gridX(ix)); for(int iy=0; iy<npts[1]; iy++) { double y(gridY(iy)); for(int iz=0; iz<npts[2]; iz++) { (*it)=infunc.f(x,y,gridZ(iz));++it; } } } timer.stop(); cout << "Time to evaluate " << timer.cpu_time() << endl; //Test TriCubicSplineT function //Create XYZCubicGrid XYZCubicGrid<double> grid3(&gridX,&gridY,&gridZ); //Create a TriCubicSpline with PBC: have to think more about fixed-boundary conditions TriCubicSplineT<double> aorb(&grid3); //Reset the coefficients aorb.reset(inData.begin(), inData.end()); double lap,val; TinyVector<double,3> grad; //aorb.reset(); //Write for vtk ImageData string fname("spline3d.vti"); std::ofstream dfile(fname.c_str()); dfile.setf(ios::scientific, ios::floatfield); dfile.setf(ios::left,ios::adjustfield); dfile.precision(10); dfile << "<?xml version=\"1.0\"?>" << endl; dfile << "<VTKFile type=\"ImageData\" version=\"0.1\">" << endl; dfile << " <ImageData WholeExtent=\"0 " << npts[0]-2 << " 0 " << npts[1]-2 << " 0 " << npts[2]-2 << "\" Origin=\"0 0 0\" Spacing=\"1 1 1\">"<< endl; dfile << " <Piece Extent=\"0 " << npts[0]-2 << " 0 " << npts[1]-2 << " 0 " << npts[2]-2 << "\">" << endl; dfile << " <PointData Scalars=\"wfs\">" << endl; dfile << " <DataArray type=\"Float32\" Name=\"wfs\">" << endl; timer.start(); int ng=0; for(int ix=0; ix<npts[0]-1; ix++) { double x(gridX(ix)); for(int iy=0; iy<npts[1]-1; iy++) { double y(gridY(iy)); for(int iz=0; iz<npts[2]-1; iz++, ng++) { TinyVector<double,3> p(x,y,gridZ(iz)); //aorb.setgrid(p); //Timing with the ofstream is not correct. //Uncomment the line below and comment out the next two line. //double t=aorb.evaluate(p,grad,lap); dfile << setw(20) << aorb.evaluate(p,grad,lap); if(ng%5 == 4) dfile << endl; } } } timer.stop(); cout << "Time to evaluate with spline " << timer.cpu_time() << endl; dfile << " </DataArray>" << endl; dfile << " </PointData>" << endl; dfile << " </Piece>" << endl; dfile << " </ImageData>" << endl; dfile << "</VTKFile>" << endl; hid_t h_file = H5Fcreate("spline3d.h5",H5F_ACC_TRUNC,H5P_DEFAULT,H5P_DEFAULT); HDFAttribIO<std::vector<double> > dump(inData,npts); dump.write(h_file,"orb0000"); HDFAttribIO<TriCubicSplineT<double> > dump1(aorb); dump1.write(h_file,"spline0000"); H5Fclose(h_file); //double lap; //TinyVector<double,3> grad; //for(int k=0; k<nptY-1; k++) { // //TinyVector<double,3> p(xcut,ycut,gridZ(k)+0.11*gridZ.dr(k)); // TinyVector<double,3> p(xcut,gridY(k)+0.11*gridY.dr(k),ycut); // aorb.setgrid(p); // double y=aorb.evaluate(p,grad,lap); // dfile << setw(30) << p[1] << setw(30) << infunc.f(p) << setw(30) << y << setw(30) << infunc.d2f(p) << setw(30) << lap << endl; //} return 0; }
void PWOrbitalBuilder::transform2GridData(PWBasis::GIndex_t& nG, int spinIndex, PWOrbitalSet& pwFunc) { ostringstream splineTag; splineTag << "eigenstates_"<<nG[0]<<"_"<<nG[1]<<"_"<<nG[2]; herr_t status = H5Eset_auto(NULL, NULL); app_log() << " splineTag " << splineTag.str() << endl; hid_t es_grp_id; status = H5Gget_objinfo (hfileID, splineTag.str().c_str(), 0, NULL); if(status) { es_grp_id = H5Gcreate(hfileID,splineTag.str().c_str(),0); HDFAttribIO<PWBasis::GIndex_t> t(nG); t.write(es_grp_id,"grid"); } else { es_grp_id = H5Gopen(hfileID,splineTag.str().c_str()); } string tname=myParam->getTwistName(); hid_t twist_grp_id; status = H5Gget_objinfo (es_grp_id, tname.c_str(), 0, NULL); if(status) twist_grp_id = H5Gcreate(es_grp_id,tname.c_str(),0); else twist_grp_id = H5Gopen(es_grp_id,tname.c_str()); HDFAttribIO<PosType> hdfobj_twist(TwistAngle); hdfobj_twist.write(twist_grp_id,"twist_angle"); ParticleSet::ParticleLayout_t& lattice(targetPtcl.Lattice); RealType dx=1.0/static_cast<RealType>(nG[0]-1); RealType dy=1.0/static_cast<RealType>(nG[1]-1); RealType dz=1.0/static_cast<RealType>(nG[2]-1); #if defined(VERYTINYMEMORY) typedef Array<ValueType,3> StorageType; StorageType inData(nG[0],nG[1],nG[2]); int ib=0; while(ib<myParam->numBands) { string bname(myParam->getBandName(ib)); status = H5Gget_objinfo (twist_grp_id, bname.c_str(), 0, NULL); hid_t band_grp_id, spin_grp_id=-1; if(status) { band_grp_id = H5Gcreate(twist_grp_id,bname.c_str(),0); } else { band_grp_id = H5Gopen(twist_grp_id,bname.c_str()); } hid_t parent_id=band_grp_id; if(myParam->hasSpin) { bname=myParam->getSpinName(spinIndex); status = H5Gget_objinfo (band_grp_id, bname.c_str(), 0, NULL); if(status) { spin_grp_id = H5Gcreate(band_grp_id,bname.c_str(),0); } else { spin_grp_id = H5Gopen(band_grp_id,bname.c_str()); } parent_id=spin_grp_id; } for(int ig=0; ig<nG[0]; ig++) { RealType x=ig*dx; for(int jg=0; jg<nG[1]; jg++) { RealType y=jg*dy; for(int kg=0; kg<nG[2]; kg++) { inData(ig,jg,kg)= pwFunc.evaluate(ib,lattice.toCart(PosType(x,y,kg*dz))); } } } app_log() << " Add spline data " << ib << " h5path=" << tname << "/eigvector" << endl; HDFAttribIO<StorageType> t(inData); t.write(parent_id,myParam->eigvecTag.c_str()); if(spin_grp_id>=0) H5Gclose(spin_grp_id); H5Gclose(band_grp_id); ++ib; } #else typedef Array<ValueType,3> StorageType; vector<StorageType*> inData; int nb=myParam->numBands; for(int ib=0; ib<nb; ib++) inData.push_back(new StorageType(nG[0],nG[1],nG[2])); PosType tAngle=targetPtcl.Lattice.k_cart(TwistAngle); PWOrbitalSet::ValueVector_t phi(nb); for(int ig=0; ig<nG[0]; ig++) { RealType x=ig*dx; for(int jg=0; jg<nG[1]; jg++) { RealType y=jg*dy; for(int kg=0; kg<nG[2]; kg++) { targetPtcl.R[0]=lattice.toCart(PosType(x,y,kg*dz)); pwFunc.evaluate(targetPtcl,0,phi); RealType x(dot(targetPtcl.R[0],tAngle)); ValueType phase(std::cos(x),-std::sin(x)); for(int ib=0; ib<nb; ib++) (*inData[ib])(ig,jg,kg)=phase*phi[ib]; } } } for(int ib=0; ib<nb; ib++) { string bname(myParam->getBandName(ib)); status = H5Gget_objinfo (twist_grp_id, bname.c_str(), 0, NULL); hid_t band_grp_id, spin_grp_id=-1; if(status) { band_grp_id = H5Gcreate(twist_grp_id,bname.c_str(),0); } else { band_grp_id = H5Gopen(twist_grp_id,bname.c_str()); } hid_t parent_id=band_grp_id; if(myParam->hasSpin) { bname=myParam->getSpinName(spinIndex); status = H5Gget_objinfo (band_grp_id, bname.c_str(), 0, NULL); if(status) { spin_grp_id = H5Gcreate(band_grp_id,bname.c_str(),0); } else { spin_grp_id = H5Gopen(band_grp_id,bname.c_str()); } parent_id=spin_grp_id; } app_log() << " Add spline data " << ib << " h5path=" << tname << "/eigvector" << endl; HDFAttribIO<StorageType> t(*(inData[ib])); t.write(parent_id,myParam->eigvecTag.c_str()); if(spin_grp_id>=0) H5Gclose(spin_grp_id); H5Gclose(band_grp_id); } for(int ib=0; ib<nb; ib++) delete inData[ib]; #endif H5Gclose(twist_grp_id); H5Gclose(es_grp_id); }
void TrainModelNN (_String* model, _String* matrix) { _String errMsg; long modelIdx = modelNames.Find(model); _Parameter verbI; checkParameter (VerbosityLevelString, verbI, 0.0); char buffer [128]; if (modelIdx < 0) { errMsg = *model & " did not refer to an existring model"; } else { _Variable* boundsMatrix = FetchVar (LocateVarByName (*matrix)); if (boundsMatrix && (boundsMatrix->ObjectClass() == MATRIX)) { _Matrix * bmatrix = (_Matrix*) boundsMatrix->GetValue (); if (bmatrix->IsAStringMatrix() && (bmatrix->GetVDim () == 3)) { _Variable* modelMatrix = LocateVar (modelMatrixIndices.lData[modelIdx]); _SimpleList modelVariableList; { _AVLList mvla (&modelVariableList); modelMatrix->ScanForVariables (mvla, true); mvla.ReorderList(); } if (bmatrix->GetHDim () == modelVariableList.lLength) { // now map model variables to bounds matrix _SimpleList variableMap; _String *myName; for (long k = 0; k < modelVariableList.lLength; k++) { myName = ((_FString*)bmatrix->GetFormula(k,0)->Compute())->theString; long vID = LocateVarByName (*myName); if (vID < 0) { break; } vID = variableNames.GetXtra (vID); vID = modelVariableList.Find(vID); if (vID < 0) { break; } variableMap << vID; } if (variableMap.lLength == modelVariableList.lLength) { _Matrix vBounds (variableMap.lLength,2, false, true); long k2 = 0; for (; k2 < variableMap.lLength; k2++) { _Parameter lb = ((_FString*)bmatrix->GetFormula(k2,1)->Compute())->theString->toNum(), ub = ((_FString*)bmatrix->GetFormula(k2,2)->Compute())->theString->toNum(); if ( ub>lb || k2) { vBounds.Store (k2,0,lb); vBounds.Store (k2,1,ub); if (ub<=lb && vBounds (k2-1,0) <= vBounds (k2-1,1) && (!CheckEqual(vBounds (k2-1,0),0.0) || !CheckEqual(vBounds (k2-1,1),1.0))) { break; } } } if (k2 == modelVariableList.lLength) { // set up the sampling now _String fName = ProcessLiteralArgument (&ModelNNFile,nil); FILE* nnFile = doFileOpen (fName.getStr(), "w"); if (nnFile) { _Matrix* modelMatrix = (_Matrix*) LocateVar(modelMatrixIndices.lData[modelIdx])->GetValue(); _Parameter mainSteps, checkSteps, errorTerm, loopMax, hiddenNodes, absError, nn1, nn2; long fullDimension = modelMatrix->GetHDim() * modelMatrix->GetVDim(); checkParameter (ModelNNTrainingSteps, mainSteps, 10000.0); checkParameter (ModelNNVerificationSample, checkSteps, 500.0); checkParameter (ModelNNPrecision, errorTerm, 0.01); checkParameter (ModelNNTrainingSteps, loopMax, 10); checkParameter (ModelNNHiddenNodes, hiddenNodes, 5); checkParameter (ModelNNLearningRate, nn1, .3); checkParameter (ModelNNPersistenceRate, nn2, .1); Net** matrixNet = new Net* [fullDimension] ; for (long i = 0; i < fullDimension; i++) { checkPointer (matrixNet [i] = new Net (variableMap.lLength,(long)hiddenNodes,1,errorTerm,nn1,nn2,100,200,true)); //matrixNet[i]->verbose = true; } checkPointer (matrixNet); _List tIn, tOut; FILE* varSamples = doFileOpen ("variableSamples.out", "w"); fprintf (varSamples, "%s" ,LocateVar(modelVariableList.lData[0])->GetName()->getStr()); for (long vc = 1; vc < modelVariableList.lLength; vc++) { fprintf (varSamples, ",%s" ,LocateVar(modelVariableList.lData[variableMap.lData[vc]])->GetName()->getStr()); } fprintf (varSamples, "\n"); for (long itCount = 0; itCount < loopMax; itCount ++) { if (verbI > 5) { snprintf (buffer, sizeof(buffer), "\nNeural Network Pass %ld. Building a training set...\n", itCount); BufferToConsole (buffer); } while (tIn.countitems() < mainSteps) { NNMatrixSampler (0, vBounds, modelVariableList, variableMap, modelMatrix, tIn, tOut); } _Matrix inData (mainSteps, variableMap.lLength, false, true); _Parameter *md = inData.theData; for (long matrixC = 0; matrixC < mainSteps; matrixC++) { _Parameter * ed = ((_Matrix*)tIn (matrixC))->theData; fprintf (varSamples, "\n%g",*ed); *md = *ed; ed++; md++; for (long entryC = 1; entryC < variableMap.lLength; entryC++, ed++, md++) { *md = *ed; fprintf (varSamples, ",%g", *md); } } tIn.Clear(); if (verbI > 5) { BufferToConsole ( "Done Building Training Set. Training...\n"); } long lastDone = 0; for (long cellCount = 0; cellCount < fullDimension; cellCount++) { Net* thisCell = matrixNet[cellCount]; _Matrix outVector (mainSteps, 1, false, true); for (long oc = 0; oc < mainSteps; oc++) { outVector.theData[oc] = ((_Matrix*)tOut(oc))->theData[cellCount]; } thisCell->studyAll (inData.theData, outVector.theData, mainSteps); long nowDone = (cellCount+1)*100./fullDimension; if (nowDone > lastDone) { snprintf (buffer, sizeof(buffer),"%ld%% done\n", lastDone = nowDone); BufferToConsole (buffer); } } tOut.Clear(); if (verbI > 5) { BufferToConsole ( "Done Training. Resampling...\n"); } _PMathObj tObj = _Constant(0).Time(); _Parameter time1 = tObj->Value(), time2; while (tIn.countitems() < checkSteps) { NNMatrixSampler (0, vBounds, modelVariableList, variableMap, modelMatrix, tIn, tOut); } absError = 0.0; DeleteObject (tObj); tObj = _Constant(0).Time(); time2 = tObj->Value(); if (verbI > 5) { snprintf (buffer, sizeof(buffer),"Done Resampling in %g seconds. Computing Error...\n", time2-time1); BufferToConsole (buffer); } _Parameter maxValT, maxValE; for (long verCount = 0; verCount < checkSteps; verCount++) { _Parameter* inData = ((_Matrix*)tIn(verCount))->theData, * outData = ((_Matrix*)tOut(verCount))->theData; for (long cellCount = 0; cellCount < fullDimension; cellCount++) { Net *thisCell = matrixNet[cellCount]; _Parameter estVal = thisCell->eval(inData)[0], trueVal = outData[cellCount], localError; localError = estVal-trueVal; if (localError < 0) { localError = -localError; } if (absError < localError) { maxValT = trueVal; maxValE = estVal; absError = localError; } } } DeleteObject (tObj); tObj = _Constant(0).Time(); time1 = tObj->Value(); DeleteObject (tObj); if (verbI > 5) { snprintf (buffer, sizeof(buffer), "Done Error Checking in %g seconds. Got max abs error %g on the pair %g %g\n", time1-time2, absError, maxValT, maxValE); BufferToConsole (buffer); } if (absError <= errorTerm) { break; } } if (absError > errorTerm) { ReportWarning (_String("Couldn't achive desired precision in TrainModelNN. Achieved error of ") & absError); } fclose (varSamples); fprintf (nnFile,"{{\n\"%s\"", LocateVar(modelVariableList.lData[0])->GetName()->getStr()); _Matrix newBounds (modelVariableList.lLength, 2, false, true); if (vBounds(0,0)>vBounds(0,1)) { newBounds.Store (variableMap.lData[0],0,0.); newBounds.Store (variableMap.lData[0],1,1.); } else { newBounds.Store (variableMap.lData[0],0,vBounds(0,0)); newBounds.Store (variableMap.lData[0],1,vBounds(0,1)); } for (long varCounter = 1; varCounter < modelVariableList.lLength; varCounter ++) { fprintf (nnFile,",\n\"%s\"", LocateVar(modelVariableList.lData[varCounter])->GetName()->getStr()); if (vBounds(varCounter,0)>vBounds(varCounter,1)) { newBounds.Store (variableMap.lData[varCounter],0,0.); newBounds.Store (variableMap.lData[varCounter],1,1.); } else { newBounds.Store (variableMap.lData[varCounter],0,vBounds(varCounter,0)); newBounds.Store (variableMap.lData[varCounter],1,vBounds(varCounter,1)); } } fprintf (nnFile,"\n}}\n"); newBounds.toFileStr (nnFile); for (long i2 = 0; i2 < fullDimension; i2++) { matrixNet[i2]->save(nnFile); delete matrixNet [i2]; } fclose (nnFile); delete matrixNet; } else { errMsg = _String ("Failed to open ") & fName & " for writing"; } } else { errMsg = _String ("Invalid variable bounds in row ") & (k2+1) & " of the bounds matrix"; } } else { errMsg = *myName & " was not one of the model parameters"; } } else { errMsg = *matrix & " must be a have the same number of rows as the number of model parameters"; } } else { errMsg = *matrix & " must be a string matrix with 3 columns"; } } else { errMsg = *matrix & " was not the identifier of a valid matrix variable"; } } if (errMsg.sLength) { errMsg = errMsg & _String(" in call to TrainModelNN."); WarnError (errMsg); } }
void SteadyStateAlgo::runEvolution() { int startGeneration = 0; char statfile[64]; char inFilename[128]; char outFilename[128]; char bestOutFilename[128]; int bestGeneration = -1; float bestFitness = -1.0; // Define the final mutation rate (i.e., the lower bound for the mutation rate) const double finalMutRate = m_mutRate; // Initialise the mutation rate m_mutRate = m_initMutRate; // initially mutation (default 50%) // Set the seed setSeed(m_rngSeed); // Initialise the population randomisePopulation(); // Check whether to recover a previous evolution sprintf(statfile, "S%d.fit", seed()); // Check if the file exists DataChunk statTest(QString("stattest"), Qt::blue, 2000, false); if (statTest.loadRawData(QString(statfile), 0)) { startGeneration = statTest.getIndex(); sprintf(inFilename, "S%dG%d.gen", (seed()), startGeneration); Logger::info("Recovering from startGeneration: " + QString::number(startGeneration)); Logger::info(QString("Loading file: ") + inFilename); QFile inData(inFilename); if (inData.open(QFile::ReadOnly)) { QTextStream in(&inData); for (int i = 0; i < m_popSize; i++) { bool loaded = m_population[i]->loadGen(in); // Check possible errors during the loading operation if (!loaded) { Logger::error("Error in the loading of the genotype"); } // Check the consistency of the genotype (i.e., the number of genes) if (m_population[i]->getLength() != m_numGenes) { Logger::error("Wrong genotype length!"); } } inData.close(); } } // Flow control pauseFlow(); if (stopFlow()) { // Cleanup return; } // Do all generations for (int gn = startGeneration; gn < m_numGenerations; gn++) { // Define a fitness array for all the individuals to be tested QVector<float> fit(m_popSize * 2); m_gae->setIndividualCounter(); m_gae->initGeneration(gn); // Evaluate all the individuals for (int i = 0; i < m_popSize; i++) { // Set the genotype to be tested m_gt->setGenotype(m_population[i]); // Evaluate the genotype m_gae->evaluate(); // Get the fitness fit[i] = m_gae->getFitness(); // Set the fitness of the current genotype m_population[i]->setFitness(fit[i]); // Use subclasses for modifying and/or getting elements (i.e., genes) GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]); GenotypeInt* off = dynamic_cast<GenotypeInt*>(m_population[i + m_popSize]); // Now generate an offspring and evaluate it for (int g = 0; g < m_numGenes; g++) { int val = ind->getGene(g); // Mutate the value int newVal = mutate(val, m_mutRate); off->setGene(g, newVal); } m_gt->setGenotype(m_population[i + m_popSize]); // Evaluate the genotype m_gae->evaluate(); // Get the fitness fit[i + m_popSize] = m_gae->getFitness(); // Flow control pauseFlow(); if (stopFlow()) { return; } } m_gae->resetIndividualCounter(); // Select the best <popSize> individuals QVector<int> indices = sortFit(fit); // Define a temporary array for storing // the best <popSize> individuals QVector<float*> tmpPop(m_popSize); // Define a temporary array for storing // the fitnesses of the best individuals QVector<float> tmpFit(m_popSize); for (int i = 0; i < m_popSize; i++) { tmpPop[i] = new float[m_numGenes]; int idx = indices[i]; GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[idx]); for (int g = 0; g < m_numGenes; g++) { tmpPop[i][g] = ind->getGene(g); } tmpFit[i] = fit[idx]; } // Swap individuals for (int i = 0; i < m_popSize; i++) { GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]); for (int g = 0; g < m_numGenes; g++) { ind->setGene(g, tmpPop[i][g]); ind->setFitness(tmpFit[i]); } } // Flow control pauseFlow(); if (stopFlow()) { break; } // Save fitness statistics char fitStatFilename[64]; sprintf(fitStatFilename, "S%d.fit", seed()); QFile fitStatData(fitStatFilename); bool openOk = false; if (gn == 0) { openOk = fitStatData.open(QIODevice::WriteOnly); } else { openOk = fitStatData.open(QIODevice::Append); } if (openOk) { QTextStream fitStat(&fitStatData); // Compute maximum, minimum and average fitness and store them in a vector QVector<float> fitArray(3); // Max float maxFit = fit[indices[0]]; fitArray[0] = maxFit; // Average float avgFit = 0.0; for (int i = 0; i < m_popSize; i++) { avgFit += fit[indices[i]]; } avgFit /= m_popSize; fitArray[1] = avgFit; // Min float minFit = fit[indices[m_popSize - 1]]; fitArray[2] = minFit; saveFitStats(fitArray, fitStat); fitStatData.close(); } // Save all fitness statistics if <saveFitnessAllIndividuals> flag is set to true if (m_saveFitnessAllIndividuals) { char allFitStatFilename[64]; sprintf(allFitStatFilename, "S%dall.fit", seed()); QFile allFitStatData(allFitStatFilename); openOk = false; if (gn == 0) { openOk = allFitStatData.open(QIODevice::WriteOnly); } else { openOk = allFitStatData.open(QIODevice::Append); } if (openOk) { QTextStream allFitStat(&allFitStatData); saveFitStats(fit, allFitStat); allFitStatData.close(); } } // Save the best genotype sprintf(bestOutFilename, "S%dB%d.gen", seed(), 0); QFile bestOutData(bestOutFilename); bool operation = false; if (gn == 0) { // Open the QFile in write mode operation = bestOutData.open(QIODevice::WriteOnly); } else { // Open the QFile in append mode operation = bestOutData.open(QFile::Append); } if (operation) { QTextStream bestOut(&bestOutData); GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[0]); ind->saveGen(bestOut); bestOutData.close(); } // Save all the genotypes sprintf(outFilename, "S%dG%d.gen", seed(), (gn + 1)); QFile outData(outFilename); if (outData.open(QIODevice::WriteOnly)) { QTextStream out(&outData); // Save the population for (int i = 0; i < m_popSize; i++) { GenotypeInt* ind = dynamic_cast<GenotypeInt*>(m_population[i]); ind->saveGen(out); } outData.close(); } // Decrease the mutation rate (until it becomes equal to the lower bound) if (m_mutRate > finalMutRate) { m_mutRate -= m_mutDecay; } else { m_mutRate = finalMutRate; } // Check the best generation if (fit[indices[0]] > bestFitness) { bestFitness = fit[indices[0]]; bestGeneration = gn; } m_gae->endGeneration(gn); } // Save the information about the best generation char bestGenFileName[64]; sprintf(bestGenFileName, "S%dbest.fit", seed()); QFile bestGenData(bestGenFileName); // Open the QFile in write mode if (bestGenData.open(QIODevice::WriteOnly)) { QTextStream bestGenOut(&bestGenData); QString outStr; //! Write the best generation index outStr = QString::number(bestGeneration); bestGenOut << outStr; //! Write the fitness of the best generation outStr = QString::number(bestFitness); bestGenOut << " " << outStr; bestGenOut << endl; bestGenData.close(); } }