void AIVabCheck(char plr, char mis, char prog) { VASqty = 0; //prog=1; 0=UnM : 1=1Mn ... GetMisType(mis); whe[0] = whe[1] = -1; if (prog == 5) { if (Mis.Jt == 0 && Mis.LM == 0 && Mis.Doc == 0) { BuildVAB(plr, mis, 1, 0, prog - 1); CalcSaf(plr, VASqty); whe[0] = Best(); if (Mew[whe[0]].i < 60) { whe[0] = 0; // Weed out low safety's } } } else if (prog >= Mis.mEq && (prog != 0)) { // && (Mis.mVab[0]&0x80 || Mis.mVab[1]&0x80)) ) if (Mis.Jt == 1) { // Joint mission BuildVAB(plr, mis, 1, 0, prog - 1); // first launch CalcSaf(plr, VASqty); whe[0] = Best(); if (Mew[whe[0]].i < 60) { whe[0] = 0; } BuildVAB(plr, mis, 1, 1, prog - 1); CalcSaf(plr, VASqty); whe[1] = Best(); if (Mew[whe[1]].i < 60) { whe[1] = 0; // Weed out low safety's } } else { // RectFill(100,100,200,190,5); // PrintAt(110,110,"MIS ");DispNum(0,0,mis); // PrintAt(110,120,"PRG ");DispNum(0,0,prog); // PauseMouse(); BuildVAB(plr, mis, 1, 0, prog - 1); // PrintAt(110,130,"VAS ");DispNum(0,0,VASQTY); CalcSaf(plr, VASqty); whe[0] = Best(); if (Mew[whe[0]].i < 60) { whe[0] = 0; } } } else if (prog == 0 && prog == Mis.mEq) { // Unmanned Vechicle BuildVAB(plr, mis, 1, 0, prog); // plr,mcode,ty=1,part,prog CalcSaf(plr, VASqty); whe[0] = Best(); // if (Mew[whe[0]].i<30) whe[0]=0; // ShowVA(whe[0]); } return; }
Outcome minimax( int player, Game game, vector<int> alphaBeta,int currLevel ) // notice that this is a call by value, so array gets copied!!!! { //char c = 13; //if ( ! (minimaxCalls % 1000000 ) ) // cout << "minimax Calls = " << minimaxCalls/1000000 << " 000000" << c; // minimaxCalls++; int index = 1 - ((player*2)+2)/4; Move move = firstMove( game,player ); Outcome Best( tryMove( player, move, game, alphaBeta,currLevel ), move ); // get a starting value on the first branch for ( move = nextMove( game, move ,player); move != noMovesLeft; move=nextMove( game, move ,player) ) { // If I am a max, being simulated by a min, who can already get // a score of beta, and the outcome from above is worse (for my parent), I might as well quit at this point. // Why? The grandparent will be totally uninterested in anything this node has to offer because it can pick // the previous node. alphaBeta[index] = player*__max( player*alphaBeta[index], player*Best.first ); if ( alphaBeta[0] > alphaBeta[1] ) { Best.first = alphaBeta[index]; break; } //add a check but ensure that we track the levels int currentScore = tryMove( player, move, game, alphaBeta ,currLevel+1); if ( currentScore * player > Best.first * player ) { Best = Outcome(currentScore, move); } } return Best; }
//======================================================Programa Principal=====================================================================// int main(){ int ciclo, i, j, n, aux, exp, selecao, inicio, comp, fim, MT, melhor, melhor1, corrida,melhorCiclo; double Populacao[TAMPOP][TAMCADEIA], ProxGer[TAMPOP][TAMCADEIA], PopReal[TAMPOP][QTDVAR]; double min[QTDVAR], max[QTDVAR], Apt[TAMPOP], f1[TAMCADEIA], f2[TAMCADEIA], solucao[TAMCADEIA]; double soma, aleatorio, x1, x2,fit; /*Atribuindo valores passados ao programa para as variáveis*/ //Gerando números aleatórios //Utiliza o relógio do computador // srand((unsigned)time(NULL)); //Especifica qual semente será utilizada para gerar os números aleatórios unsigned semente = 1; srand(semente); //Permite ao usiário digitar uma semente para gerar os números aleatórios // unsigned semente; // printf("Entre com a semente: "); // scanf ("%u", &semente); // srand(semente); //--------------------------------------------------------Intervalo de busca das funções-------------------------------------------------------// min[0] = -5.12; //Valor minimo do intervalo de busca de x1. max[0] = 5.12; //Valor maximo do intervalo de busca de x1. min[1] = -5.12; //Valor minimo do intervalo de busca de x2. max[1] = 5.12; //Valor maximo do intervalo de busca de x1. //---------------------------------------------------------------------Fim---------------------------------------------------------------------// FILE *arquivo,*arq; arquivo=fopen("GA.txt","w"); //Abrindo o arquivo para gravar os resultados arq=fopen("GAresult.txt","a"); printf("*\n"); clock_t tInicio, tFim, tDecorrido; //Calculando o tempo de execução do programa tInicio=clock(); fit=0.0; //pega o valor da função objetivo inicial para fins de comparação for(corrida = 1; corrida <= TOTCOR; corrida++){ //Numero de corridas realizadas pelo programa //---------------------------------------------------------Gerando a populacao inicial---------------------------------------------------------// // printf("Populacao Inicial:\n"); for(i = 0; i < TAMPOP; i++){ //Gerando os elementos da matriz de cromossomos. for(j = 0; j < TAMCADEIA; j++){ Populacao[i][j] = (double)(0 + rand() % 2); //Números aleatórios entre [0, 1] // printf("%.f ", Populacao[i][j]); } // printf("\n"); } //Fim (Gerando os elementos da matriz de cromossomos). //--------------------------------------------------------------------Fim----------------------------------------------------------------------// //----------------------------------------------------Transformando a populacao binaria em real------------------------------------------------// PopulacaoReal(Populacao, PopReal, min, max); //Gerando a nova matriz com numeros reais. //Imprimindo a populacao na base decimal. // printf("\nPopulacao Real:\n"); // for(i = 0; i < TAMPOP; i++){ // for(j = 0; j < QTDVAR; j++){ // printf("%7.4f ", PopReal[i][j]); // } // printf("\n"); // } //Fim (Gerando os elementos da matriz de cromossomos). //--------------------------------------------------------------------Fim----------------------------------------------------------------------// //----------------------------------------------Calculando a aptidao de cada cadeia de cromossomo----------------------------------------------// for(i = 0; i < TAMPOP; i++){ //Calcula a aptidao de cada cadeia de cromossomos. Apt[i] = Fitness(PopReal[i][0], PopReal[i][1]); } AptAdm(Apt); //Admencionaliza as Aptidoes. //----------------------------------------------------------------Fim--------------------------------------------------------------------------// //-----------------------------------------------------Calculando o melhor cromossomo----------------------------------------------------------// melhor = Best(Apt); melhor1 = melhor; for(i = 0; i < TAMCADEIA; i++){ solucao[i]=Populacao[melhor1][i]; //Solução na forma binária. } x1 = PopReal[melhor1][0]; //Guarda a melhor solução do primeiro cromossomo em formato real. x2 = PopReal[melhor1][1]; //Guarda a melhor solução do segundo cromossomo em formato real. /*MEU COMENTÁRIO NAS DUAS LINHAS SEGUINTES fprintf(arquivo,"Melhor da Populacao Inicial:\n"); fprintf(arquivo,"%10.6f %10.6f %10.6f\n", x1, x2, Fitness(x1, x2)); //Imprime a melhor solução até o momento. // printf("\nMelhor solucao da Populacao Inicial:\n");*/ // printf("%7.4f %7.4f %7.4f\n", x1, x2, Fitness(x1, x2)); //Imprime a melhor solução até o momento. //----------------------------------------------------------------Fim--------------------------------------------------------------------------// //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Evolucoes+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Ciclo de evolução da técnica: evolução, crossover e mutação /* COMENTEI fprintf(arquivo,"\nEvolucoes:\n"); */ // printf("\nCromossomos selecionados:\n"); ciclo = 1; while(ciclo <= NUMEVOL){ for(j = 0; j < TAMCADEIA; j++){ ProxGer[0][j] = solucao[j]; //Pego minha melhor solução da População } for(i = 1; i < TAMPOP; i++){ selecao = Roleta(Apt); for(j = 0; j < TAMCADEIA; j++){ ProxGer[i][j] = Populacao[selecao][j]; //Cromossomo selecionado na População. } } //----------------------------------------------------------------Reproduzir-------------------------------------------------------------------// for(i = 0; i < TAMPOP; i += 2){ //Realiza o crossover (crusamento) dos cromossomos selecionados 2 a 2. aleatorio = ((double)rand() / (double)RAND_MAX); //Numero aleatorio entre [0, 1]. if(aleatorio <= TXCO){ //Inicio do crossover. inicio = rand() % (TAMCADEIA - 1); //Ponto de inicio do crossover. comp = ((TAMCADEIA - 1) - inicio); //Comprimento do crossover. fim = (rand() % (comp)) + inicio; //Ponto de termino do crossover. for(j = 0; j < TAMCADEIA; j++){ //Inicializando os vetores dos cromossomos filhos. f1[j] = -1.0; //Filho 1. f2[j] = -1.0; //Filho 2. } //Fim (Inicializando os vetores dos cromossomos filhos). for(j = inicio; j <= fim; j++){ //Gerando da parte interna dos cromossomos filhos. f1[j] = ProxGer[i][j]; //Filho 1 recebe os genes do Pai 1. f2[j] = ProxGer[i + 1][j]; //Filho 2 recebe os genes do Pai 2. } //Fim (Gerando da parte interna dos cromossomos filhos). for(j = 0; j < TAMCADEIA; j++){ //Gerando os extremos dos cromossomos filhos. if((f1[j] == -1) && (f2[j] == -1)){ f1[j] = ProxGer[i + 1][j]; //Filho 1 recebe os genes do Pai 2. f2[j] = ProxGer[i][j]; //Filho 2 recebe os genes do Pai 1. } } //Fim (Gerando os extremos dos cromossomos filhos). MT = rand() % (TAMCADEIA); //Definindo o elemento do cromossomo f1 a sofrer mutacao. f1[MT] = Mutacao(f1[MT]); //Realizando a mutacao no filho 1. MT = rand() % (TAMCADEIA); //Definindo o elemento do cromossomo f1 a sofrer mutacao. f2[MT] = Mutacao(f2[MT]); //Realizando a mutacao no filho 2. for(j = 0; j < TAMCADEIA; j++){ Populacao[i][j] = f1[j]; //A nova populacao recebe o filho 1. Populacao[i + 1][j] = f2[j]; //A nova populacao recebe o filho 2. } } //Fim (Inicio do crossover). else{ //Definindo a nova Populacao de cromossomos caso nao ocorra o crossover. for(j = 0; j < TAMCADEIA; j++){ //A matriz Populacao recebe a matriz ProxGeracao. Populacao[i][j] = ProxGer[i][j]; Populacao[i + 1][j] = ProxGer[i + 1][j]; } //Fim (A matriz Populacao recebe a matriz ProxGeracao). } //Fim (Definindo a nova Populacao de cromossomos caso nao ocorra o crossover). } //Fim (Realiza o crossover dos cromossomos selecionados 2 a 2). //-------------------------------------------------------------Fim da reproducao---------------------------------------------------------------// //---------------------------------------------------Transformando a populacao binaria em real-------------------------------------------------// PopulacaoReal(Populacao, PopReal, min, max); //Gerando a nova matriz com numeros reais. //-------------------------------------------------------------------Fim-----------------------------------------------------------------------// //-----------------------------------------------------------Calculando a aptidao--------------------------------------------------------------// for(i = 0; i < TAMPOP; i++){ //Calcula a aptidao de cada cadeia de cromossomos. Apt[i] = Fitness(PopReal[i][0], PopReal[i][1]); } AptAdm(Apt); //Admencionaliza as Aptidoes. //-------------------------------------------------------------------Fim-----------------------------------------------------------------------// //---------------------------------------------------------Calculando o melhor cromossomo------------------------------------------------------// melhor = Best(Apt); if(Fitness(PopReal[melhor][0], PopReal[melhor][1]) < Fitness(x1, x2)){ //Avalia se a melhor solução da geração é melhor melhor1 = melhor; //que a guardadae a atualiza caso isso ocorra. for(i = 0; i < TAMCADEIA; i++){ solucao[i] = Populacao[melhor1][i]; } x1 = PopReal[melhor1][0]; x2 = PopReal[melhor1][1]; } fprintf(arquivo,"%10.6f %10.6f %10.6f\n", x1, x2, Fitness(x1, x2)); //Imprime a melhor solução até o momento. /*Guardar a última iteração em que ocorreu mudança em x1 ou x2*/ if (fit!=Fitness(x1,x2)){ //printf("%.6f\t%6f\n",fit,Fitness(x1,x2)); fit=Fitness(x1,x2); melhorCiclo=ciclo; tFim = clock(); //Finalizando e imprimindo o tempo de gasto para executar o programa } //fprintf(arquivo,"%10.6f\n", Fitness(x1, x2)); //Imprime a melhor solução até o momento. //-------------------------------------------------------------------Fim-----------------------------------------------------------------------// ciclo++; } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++Fim das Evolucoes++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++// //Imprimindo o resultado final. //fprintf(arquivo,"\nResultado Final:\n"); /*MEU COMENTÁRIO NA PRÓXIMA LINHA fprintf(arquivo,"%10.6f %10.6f %10.6f %5d\n", x1, x2, Fitness(x1, x2),melhorCiclo); */ }//-----------------------------------------------------Fim do Numero de corridas--------------------------------------------------------------// //tFim = clock(); //Finalizando e imprimindo o tempo de gasto para executar o programa /*imprimir para padrao do relatório TAMPOP TAM_CROMOSSOMO TAM_CADEIA N_EVOLUÇAO TAXA_CROSS TAXA_MUT X1 X2 FUNCAO TEMPO*/ fprintf(arq,"%2d %4d %4d %8d %2.3f %2.3f %10.6f %10.6f %10.6f %ld\n", TAMPOP,TAMCROM,TAMCADEIA, melhorCiclo,TXCO,TXMT,x1, x2, fit,tDecorrido = ((tFim - tInicio) / (CLOCKS_PER_SEC/1000))); //fprintf(arquivo,"\nTempo de execucao: %ld milisegundos.\n",tDecorrido = ((tFim - tInicio) / (CLOCKS_PER_SEC/1000))); fclose(arquivo); //Fechando o arquivo onde os dados foram gravados fclose(arq); //getchar(); return (0); }
bool DlgMain::OnClickSearch() { double maxCloud = QBeforeLast(m_ComboBox_MaxCloud->currentText(), '%').toDouble(); vector<MTLParser> selectedMTLParsers; QStringList selectedMTLFiles; QString inputPath = m_Edit_InputPath->text(); m_StartDate = m_DateEdit_StartDate->date(); m_EndDate = m_DateEdit_EndDate->date(); QStringList filter; QStringList MTLFiles; filter<<"*MTL.txt"; FindFile(inputPath, filter, MTLFiles); int nFiles = (int)MTLFiles.size(); if (nFiles < 1) { #ifdef debug cout<<"no MTL files are found!"<<endl; #endif return false; } vector<MTLParser> MTLParserList; for (int i = 0;i < nFiles;++i) { MTLParser psr; psr.parse(MTLFiles[i]); if (psr.DATE_ACQUIRED > m_StartDate && psr.DATE_ACQUIRED < m_EndDate) { MTLParserList.push_back(psr); } } nFiles = (int)MTLParserList.size(); if (nFiles < 1) { #ifdef debug cout<<"no MTL files are found!"<<endl; #endif return false; } // 按Path Row排序 std::sort(MTLParserList.begin(), MTLParserList.end(), comparePathRow); vector<MTLParser> MTLParserListTemp; MTLParserListTemp.push_back(MTLParserList[0]); QString currentPathRow = MTLParserList[0].m_strPathRow; for (int i = 1;i < nFiles;++i) { if (0 == MTLParserList[i].m_strPathRow.compare(currentPathRow)) { MTLParserListTemp.push_back(MTLParserList[i]); } else { MTLParser bestMTL = Best(MTLParserListTemp, m_StartDate, m_EndDate); if (bestMTL.CLOUD_COVER <= maxCloud) { selectedMTLParsers.push_back(bestMTL); selectedMTLFiles.push_back(bestMTL.m_PathMTL); } MTLParserListTemp.clear(); MTLParserListTemp.push_back(MTLParserList[i]); } currentPathRow = MTLParserListTemp.back().m_strPathRow; } MTLParser bestMTL = Best(MTLParserListTemp, m_StartDate, m_EndDate); if (bestMTL.CLOUD_COVER <= maxCloud) { selectedMTLParsers.push_back(bestMTL); selectedMTLFiles.push_back(bestMTL.m_PathMTL); } // 将挑选的数据写入日志文件 QString outLogFile = QDir::toNativeSeparators(m_Edit_OutputPath->text() + QDir::separator() + logFile); FILE* pf; QString dateFormat("yyyy.MM.dd"); fopen_s(&pf, outLogFile.toUtf8(), "w+"); int nSelected = (int)selectedMTLParsers.size(); fprintf(pf, "起始时间:%s\n", m_StartDate.toString(dateFormat).toUtf8().data()); fprintf(pf, "截止时间:%s\n", m_EndDate.toString(dateFormat).toUtf8().data()); fprintf(pf, "共挑选 %d 景\n", nSelected); for (int i = 0;i < nSelected;++i) { // 轨道号 日期 云量 路径 fprintf(pf, "%s\t%s\t%lf\t%s\n", selectedMTLParsers[i].m_strPathRow.toUtf8().data(), selectedMTLParsers[i].DATE_ACQUIRED.toString(dateFormat).toUtf8().data(), selectedMTLParsers[i].CLOUD_COVER, selectedMTLParsers[i].m_PathMTL.toUtf8().data()); } fclose(pf); ////////////////////////////////////////////////////////////////////////// // 开始复制数据 FileCopyProcessThread *fileCopyProcess = new FileCopyProcessThread; //m_progressListener = new DemConvertListener; //connect(m_progressListener,SIGNAL(updateProgress(double)),this,SLOT(OnUpdateProgress(double))); //connect(fileCopyProcess, SIGNAL(addLog(QString)),this,SLOT(OnAddLog(QString))); connect(fileCopyProcess, SIGNAL(taskProgress(double)),this,SLOT(OnTaskProgress(double))); //connect(fileCopyProcess, SIGNAL(newProgressListener()),this,SLOT(OnNewProgressListener())); //connect(fileCopyProcess, SIGNAL(releaseProgressListener()),this,SLOT(OnReleaseProgressListener())); connect(fileCopyProcess, SIGNAL(beginUI()),this,SLOT(lockUI())); connect(fileCopyProcess, SIGNAL(endUI()),this,SLOT(unlockUI())); //demListener->start(); //demListener->demListener(demProcess->m_progressListener);//监视进度线程 //demProcess->m_pDEMListenerThread = demListener; //double could = m_ComboBox_MaxCloud->currentText().toDouble(); bool bOverWrite = false; if (Qt::CheckState::Checked == m_CheckBox_OverWrite->checkState()) { bOverWrite = true; } fileCopyProcess->Process(selectedMTLFiles, m_Edit_OutputPath->text(), bOverWrite); //数据处理线程 return true; }