void InverseOperator::Reshape(const Operator& Op, const string Type, Teuchos::ParameterList& List, Teuchos::ParameterList* pushlist) { ResetTimer(); StackPush(); Op_ = Op; RCPRowMatrix_ = Op.GetRCPRowMatrix(); // FIXME: to add overlap and level-of-fill int NumSweeps = List.get("smoother: sweeps", 1); double Damping = List.get("smoother: damping factor", 0.67); int LOF_ilu = List.get("smoother: ilu fill", 0); double LOF_ict = List.get("smoother: ilut fill", 1.0); double LOF_ilut = List.get("smoother: ict fill", 1.0); string reorder = List.get("schwarz: reordering type","rcm"); Teuchos::ParameterList IFPACKList; // any parameters from the main list List are overwritten by the pushlist IFPACKList.set("relaxation: sweeps", NumSweeps); IFPACKList.set("relaxation: damping factor", Damping); IFPACKList.set("fact: level-of-fill", LOF_ilu); IFPACKList.set("fact: ict level-of-fill", LOF_ict); IFPACKList.set("fact: ilut level-of-fill", LOF_ilut); IFPACKList.set("relaxation: zero starting solution", false); IFPACKList.set("schwarz: reordering type",reorder); IFPACKList.set("fact: relative threshold",1.0); // if present, the pushlist is assumed to be a preconstructed ifpack list // that is copied straight to the ifpack list here // entries in pushlist overwrite previous list entries if (pushlist) IFPACKList.setParameters(*pushlist); bool verbose = false; //(GetMyPID() == 0 && GetPrintLevel() > 5); // the ML smoother RCPMLPrec_ = Teuchos::null; // The Ifpack smoother Ifpack_Preconditioner* Prec = NULL; if (Type == "Jacobi") { if (verbose) { cout << "Damping factor = " << Damping << ", sweeps = " << NumSweeps << endl; cout << endl; } IFPACKList.set("relaxation: type", "Jacobi"); Prec = new Ifpack_PointRelaxation(RowMatrix()); } else if (Type == "Gauss-Seidel") { if (verbose) { cout << "Damping factor = " << Damping << ", sweeps = " << NumSweeps << endl; cout << endl; } IFPACKList.set("relaxation: type", "Gauss-Seidel"); Prec = new Ifpack_PointRelaxation(RowMatrix()); } else if (Type == "symmetric Gauss-Seidel") { if (verbose) { cout << "Damping factor = " << Damping << ", sweeps = " << NumSweeps << endl; cout << endl; } IFPACKList.set("relaxation: type", "symmetric Gauss-Seidel"); Prec = new Ifpack_PointRelaxation(RowMatrix()); } else if (Type == "ILU") { if (verbose) { cout << "ILU factorization, ov = 0, no reordering, LOF = " << LOF_ilu << endl; cout << endl; } // use the Additive Schwarz class because it does reordering Prec = new Ifpack_AdditiveSchwarz<Ifpack_ILU>(RowMatrix()); } else if (Type == "ILUT") { if (verbose) { cout << "ILUT factorization, ov = 0, no reordering, LOF = " << LOF_ilu << endl; cout << endl; } Prec = new Ifpack_ILUT(RowMatrix()); } else if (Type == "IC") { if (verbose) { cout << "IC factorization, ov = 0, no reordering, LOF = " << LOF_ilu << endl; cout << endl; } Prec = new Ifpack_IC(RowMatrix()); } else if (Type == "ICT") { if (verbose) { cout << "ICT factorization, ov = 0, no reordering, LOF = " << LOF_ilu << endl; cout << endl; } Prec = new Ifpack_ICT(RowMatrix()); } else if (Type == "LU") { if (verbose) { cout << "LU factorization, ov = 0, local solver = KLU" << endl; cout << endl; } Prec = new Ifpack_AdditiveSchwarz<Ifpack_Amesos>(RowMatrix()); } else if (Type == "Amesos" || Type == "Amesos-KLU") { if (verbose) { cout << "Amesos-KLU direct solver" << endl; cout << endl; } Prec = new Ifpack_Amesos(RowMatrix()); } else if (Type == "MLS" || Type == "ML MLS" || Type == "ML symmetric Gauss-Seidel" || Type == "ML Gauss-Seidel") { if (verbose) { cout << "ML's MLS smoother" << endl; cout << endl; } Teuchos::ParameterList mlparams; ML_Epetra::SetDefaults("SA",mlparams); int output = List.get("ML output",-47); if (output == -47) output = List.get("output",-1); if (output != -1) mlparams.set("ML output",output); mlparams.set("max levels",1); int sweeps = List.get("smoother: sweeps",1); mlparams.set("coarse: sweeps",sweeps); double damp = List.get("smoother: damping factor",0.67); mlparams.set("coarse: damping factor",damp); mlparams.set("zero starting solution", false); if (Type == "MLS" || Type == "ML MLS") { mlparams.set("coarse: type","MLS"); // MLS symmetric Gauss-Seidel Amesos-KLU int poly = List.get("smoother: MLS polynomial order",3); mlparams.set("coarse: MLS polynomial order",poly); } else if (Type == "ML symmetric Gauss-Seidel") mlparams.set("coarse: type","symmetric Gauss-Seidel"); // MLS symmetric Gauss-Seidel Amesos-KLU else if (Type == "ML Gauss-Seidel") mlparams.set("coarse: type","Gauss-Seidel"); else if (Type == "ML Jacobi") mlparams.set("coarse: type","Jacobi"); else ML_THROW("Requested type (" + Type + ") not recognized", -1); RCPMLPrec_ = Teuchos::rcp(new ML_Epetra::MultiLevelPreconditioner(*RowMatrix(),mlparams,true)); } else ML_THROW("Requested type (" + Type + ") not recognized", -1); if (Prec) { RCPData_ = Teuchos::rcp(Prec); RCPData_->SetParameters(IFPACKList); RCPData_->Initialize(); RCPData_->Compute(); UpdateFlops(RCPData_->InitializeFlops()); UpdateFlops(RCPData_->ComputeFlops()); } else RCPData_ = Teuchos::null; StackPop(); UpdateTime(); }
SolutionSet *MOCHC::execute() { int populationSize; int iterations; int maxEvaluations; int convergenceValue; int minimumDistance; int evaluations; double preservedPopulation; double initialConvergenceCount; bool condition = false; SolutionSet *solutionSet, *offSpringPopulation, *newPopulation; Comparator * crowdingComparator = new CrowdingComparator(); SolutionSet * population; SolutionSet * offspringPopulation; SolutionSet * unionSolution; Operator * cataclysmicMutation; Operator * crossover; Operator * parentSelection; //Read the parameters populationSize = *(int *) getInputParameter("populationSize"); maxEvaluations = *(int *) getInputParameter("maxEvaluations"); convergenceValue = *(int *) getInputParameter("convergenceValue"); initialConvergenceCount = *(double *)getInputParameter("initialConvergenceCount"); preservedPopulation = *(double *)getInputParameter("preservedPopulation"); //Read the operators cataclysmicMutation = operators_["mutation"]; crossover = operators_["crossover"]; parentSelection = operators_["parentSelection"]; iterations = 0; evaluations = 0; // calculating the maximum problem sizes .... Solution * sol = new Solution(problem_); int size = 0; for (int var = 0; var < problem_->getNumberOfVariables(); var++) { Binary *binaryVar; binaryVar = (Binary *)sol->getDecisionVariables()[var]; size += binaryVar->getNumberOfBits(); } minimumDistance = (int) std::floor(initialConvergenceCount*size); // Create the initial solutionSet Solution * newSolution; population = new SolutionSet(populationSize); for (int i = 0; i < populationSize; i++) { newSolution = new Solution(problem_); problem_->evaluate(newSolution); problem_->evaluateConstraints(newSolution); evaluations++; population->add(newSolution); } //for while (!condition) { offSpringPopulation = new SolutionSet(populationSize); Solution **parents = new Solution*[2]; for (int i = 0; i < population->size()/2; i++) { parents[0] = (Solution *) (parentSelection->execute(population)); parents[1] = (Solution *) (parentSelection->execute(population)); if (hammingDistance(*parents[0],*parents[1])>= minimumDistance) { Solution ** offSpring = (Solution **) (crossover->execute(parents)); problem_->evaluate(offSpring[0]); problem_->evaluateConstraints(offSpring[0]); problem_->evaluate(offSpring[1]); problem_->evaluateConstraints(offSpring[1]); evaluations+=2; offSpringPopulation->add(offSpring[0]); offSpringPopulation->add(offSpring[1]); } } SolutionSet *join = population->join(offSpringPopulation); delete offSpringPopulation; newPopulation = rankingAndCrowdingSelection(join,populationSize); delete join; if (equals(*population,*newPopulation)) { minimumDistance--; } if (minimumDistance <= -convergenceValue) { minimumDistance = (int) (1.0/size * (1-1.0/size) * size); int preserve = (int) std::floor(preservedPopulation*populationSize); newPopulation->clear(); //do the new in c++ really hurts me(juanjo) population->sort(crowdingComparator); for (int i = 0; i < preserve; i++) { newPopulation->add(new Solution(population->get(i))); } for (int i = preserve; i < populationSize; i++) { Solution * solution = new Solution(population->get(i)); cataclysmicMutation->execute(solution); problem_->evaluate(solution); problem_->evaluateConstraints(solution); newPopulation->add(solution); } } iterations++; delete population; population = newPopulation; if (evaluations >= maxEvaluations) { condition = true; } } return population; }
Expression* Parser::createAST(vector<Token> tokens) { // Create the needed stacks stack<Operator> operatorStack; stack<Expression*> expressionStack; // Loop through the whole vector of tokens // For simplicity, we use a GOTO label, since breaking or refactoring nested loops isn't so simple in C++ Label_MainLoop: for (int i = 0; i < tokens.size(); i++) { // Assign the current token Token token = tokens[i]; // If the token is a left parenthesis if ( token.isLeftParen() ) { // Push it onto the stack as an operator operatorStack.push( Operator('(', 5, false) ); } // Else if it's a right parenthesis else if ( token.isRightParen() ) { // Loop backwards through the stack Operator popOp; while ( !operatorStack.empty() ) { // Pop off the top operator popOp = operatorStack.top(); operatorStack.pop(); // Check if it's the matching paren if( popOp.getSymbol() == '(' ) { // Continue the outer for loop if it is goto Label_MainLoop; } // Otherwise, add a node from the inner expression and loop again else { addNode(expressionStack, popOp); } } // If we get here, the stack has emptied before we found the matching paren, which is bad. throw runtime_error("Missing a \')\' in the expression"); } // Default case else { // If the token is an operator, decide what to do with it if ( token.isOperator() ) { Operator o1 = token.op; Operator o2; while( !operatorStack.empty() ) // Not needed?? -> && operatorStack.top() != null { // Define o2 as the top of the stack o2 = operatorStack.top(); // If o1 is right assoc and has the same precedence as the last op, or o1 has lower precedence if ((!o1.isRightAssoc() && o1.comparePrecedence(o2) == 0) || o1.comparePrecedence(o2) < 0) { operatorStack.pop(); addNode(expressionStack, o2); } else { break; } } // Push this operator onto the stack operatorStack.push( token.op ); } // Otherwise, if it's a number else if ( token.isNumber() ) { expressionStack.push( new Expression( token.number ) ); } // The token should have been an operator or a number. How'd we get here? Throw an error else { throw runtime_error("Error in building the AST. Invalid Token."); } } // End for loop } // Finish adding nodes while(!operatorStack.empty()) { addNode(expressionStack, operatorStack.top()); operatorStack.pop(); } // Will this work? Only testing will tell return expressionStack.top(); }
/*----------------------------------------------------------------------* | compute the preconditioner (public) m.gee 03/06| *----------------------------------------------------------------------*/ bool MOERTEL::Mortar_ML_Preconditioner::Compute() { iscomputed_ = false; MLAPI::Init(); // get parameters int maxlevels = mlparams_.get("max levels",10); int maxcoarsesize = mlparams_.get("coarse: max size",10); double* nullspace = mlparams_.get("null space: vectors",(double*)NULL); int nsdim = mlparams_.get("null space: dimension",1); int numpde = mlparams_.get("PDE equations",1); double damping = mlparams_.get("aggregation: damping factor",1.33); std::string eigenanalysis = mlparams_.get("eigen-analysis: type", "Anorm"); std::string smoothertype = mlparams_.get("smoother: type","symmetric Gauss-Seidel"); std::string coarsetype = mlparams_.get("coarse: type","Amesos-KLU"); std::string ptype = mlparams_.get("prolongator: type","mod_full"); // create the missing rowmap Arrmap_ Arrmap_ = Teuchos::rcp(MOERTEL::SplitMap(A_->RowMap(),*Annmap_)); Teuchos::RCP<Epetra_Map> map1 = Arrmap_; Teuchos::RCP<Epetra_Map> map2 = Annmap_; // split Atilde // // Atilde11 Atilde12 // Atilde21 Atilde22 // Teuchos::RCP<Epetra_CrsMatrix> Atilde11; Teuchos::RCP<Epetra_CrsMatrix> Atilde12; Teuchos::RCP<Epetra_CrsMatrix> Atilde21; Teuchos::RCP<Epetra_CrsMatrix> Atilde22; MOERTEL::SplitMatrix2x2(Atilde_,map1,map2,Atilde11,Atilde12,Atilde21,Atilde22); // build Atildesplit // // Atilde11 0 // 0 I // Atildesplit_ = Teuchos::rcp(new Epetra_CrsMatrix(Copy,A_->RowMap(),50,false)); MOERTEL::MatrixMatrixAdd(*Atilde11,false,1.0,*Atildesplit_,0.0); Teuchos::RCP<Epetra_CrsMatrix> tmp = Teuchos::rcp(MOERTEL::PaddedMatrix(*map2,1.0,1)); tmp->FillComplete(); MOERTEL::MatrixMatrixAdd(*tmp,false,1.0,*Atildesplit_,1.0); Atildesplit_->FillComplete(); Atildesplit_->OptimizeStorage(); // split A // // A11 A12 // A21 A22 // Teuchos::RCP<Epetra_CrsMatrix> A11; Teuchos::RCP<Epetra_CrsMatrix> A12; Teuchos::RCP<Epetra_CrsMatrix> A21; Teuchos::RCP<Epetra_CrsMatrix> A22; MOERTEL::SplitMatrix2x2(A_,map1,map2,A11,A12,A21,A22); // build Asplit_ // // A11 0 // 0 A22 // Asplit_ = Teuchos::rcp(new Epetra_CrsMatrix(Copy,A_->RowMap(),50,false)); MOERTEL::MatrixMatrixAdd(*A11,false,1.0,*Asplit_,0.0); MOERTEL::MatrixMatrixAdd(*A22,false,1.0,*Asplit_,1.0); Asplit_->FillComplete(); Asplit_->OptimizeStorage(); // build BWT (padded to full size) // // 0 Mr Dinv // 0 I // Teuchos::RCP<Epetra_CrsMatrix> BWT = Teuchos::rcp(MOERTEL::MatMatMult(*B_,false,*WT_,false,10)); tmp = Teuchos::rcp(MOERTEL::PaddedMatrix(BWT->RowMap(),0.0,25)); MOERTEL::MatrixMatrixAdd(*BWT,false,1.0,*tmp,0.0); tmp->FillComplete(BWT->DomainMap(),BWT->RangeMap()); BWT = tmp; tmp = Teuchos::null; // split BWT to obtain M = Mr Dinv Teuchos::RCP<Epetra_CrsMatrix> Zero11; Teuchos::RCP<Epetra_CrsMatrix> M; Teuchos::RCP<Epetra_CrsMatrix> Zero21; Teuchos::RCP<Epetra_CrsMatrix> I22; MOERTEL::SplitMatrix2x2(BWT,map1,map2,Zero11,M,Zero21,I22); // build matrix Ahat11 = Atilde11 - M Atilde22 M^T Teuchos::RCP<Epetra_CrsMatrix> Ahat11 = Teuchos::rcp(new Epetra_CrsMatrix(Copy,*map1,50,false)); MOERTEL::MatrixMatrixAdd(*Atilde11,false,1.0,*Ahat11,0.0); Teuchos::RCP<Epetra_CrsMatrix> tmp1 = Teuchos::rcp(MOERTEL::MatMatMult(*Atilde22,false,*M,true,10)); Teuchos::RCP<Epetra_CrsMatrix> tmp2 = Teuchos::rcp(MOERTEL::MatMatMult(*M,false,*tmp1,false,10)); MOERTEL::MatrixMatrixAdd(*tmp2,false,-1.0,*Ahat11,1.0); Ahat11->FillComplete(); Ahat11->OptimizeStorage(); // build matrix Ahat // // Ahat11 0 = Atilde11 - M Atilde22 M^T 0 // 0 0 0 0 // Ahat_ = Teuchos::rcp(MOERTEL::PaddedMatrix(A_->RowMap(),0.0,25)); MOERTEL::MatrixMatrixAdd(*Ahat11,false,1.0,*Ahat_,0.0); Ahat_->FillComplete(); Ahat_->OptimizeStorage(); // build mlapi objects Space space(A_->RowMatrixRowMap()); Operator mlapiAsplit(space,space,Asplit_.get(),false); Operator mlapiAtildesplit(space,space,Atildesplit_.get(),false); Operator mlapiAhat(space,space,Ahat_.get(),false); Operator mlapiBWT(space,space,BWT.get(),false); Operator mlapiBWTcoarse; Operator ImBWTfine = GetIdentity(space,space) - mlapiBWT; Operator ImBWTcoarse; Operator Ptent; Operator P; Operator Pmod; Operator Rtent; Operator R; Operator Rmod; Operator IminusA; Operator C; InverseOperator S; mlapiAtildesplit_.resize(maxlevels); mlapiAhat_.resize(maxlevels); mlapiImBWT_.resize(maxlevels); mlapiImWBT_.resize(maxlevels); mlapiRmod_.resize(maxlevels); mlapiPmod_.resize(maxlevels); mlapiS_.resize(maxlevels); mlapiAtildesplit_[0] = mlapiAtildesplit; mlapiAhat_[0] = mlapiAhat; mlapiImBWT_[0] = ImBWTfine; mlapiImWBT_[0] = GetTranspose(ImBWTfine); // build nullspace MultiVector NS; MultiVector NextNS; NS.Reshape(mlapiAsplit.GetRangeSpace(),nsdim); if (nullspace) { for (int i=0; i<nsdim; ++i) for (int j=0; j<NS.GetMyLength(); ++j) NS(j,i) = nullspace[i*NS.GetMyLength()+j]; } else { if (numpde==1) NS = 1.0; else { NS = 0.0; for (int i=0; i<NS.GetMyLength(); ++i) for (int j=0; j<numpde; ++j) if ( i % numpde == j) NS(i,j) = 1.0; } } double lambdamax; // construct the hierarchy int level=0; for (level=0; level<maxlevels-1; ++level) { // this level's smoothing operator mlapiAtildesplit = mlapiAtildesplit_[level]; // build smoother if (Comm().MyPID()==0) { ML_print_line("-", 78); std::cout << "MOERTEL/ML : creating smoother level " << level << std::endl; fflush(stdout); } S.Reshape(mlapiAtildesplit,smoothertype,mlparams_); if (level) mlparams_.set("PDE equations", NS.GetNumVectors()); if (Comm().MyPID()==0) { ML_print_line("-", 80); std::cout << "MOERTEL/ML : creating level " << level+1 << std::endl; ML_print_line("-", 80); fflush(stdout); } mlparams_.set("workspace: current level",level); // get tentative prolongator based on decoupled original system GetPtent(mlapiAsplit,mlparams_,NS,Ptent,NextNS); NS = NextNS; // do prolongator smoothing if (damping) { if (eigenanalysis == "Anorm") lambdamax = MaxEigAnorm(mlapiAsplit,true); else if (eigenanalysis == "cg") lambdamax = MaxEigCG(mlapiAsplit,true); else if (eigenanalysis == "power-method") lambdamax = MaxEigPowerMethod(mlapiAsplit,true); else ML_THROW("incorrect parameter (" + eigenanalysis + ")", -1); IminusA = GetJacobiIterationOperator(mlapiAsplit,damping/lambdamax); P = IminusA * Ptent; R = GetTranspose(P); Rtent = GetTranspose(Ptent); } else { P = Ptent; Rtent = GetTranspose(Ptent); R = Rtent; lambdamax = -1.0; } // do variational coarse grid of split original matrix Asplit C = GetRAP(R,mlapiAsplit,P); // compute the mortar projections on coarse grid mlapiBWTcoarse = GetRAP(Rtent,mlapiBWT,Ptent); ImBWTcoarse = GetIdentity(C.GetDomainSpace(),C.GetRangeSpace()); ImBWTcoarse = ImBWTcoarse - mlapiBWTcoarse; // do modified prolongation and restriction if (ptype=="mod_full") Rmod = ImBWTcoarse * ( R * ImBWTfine ) + mlapiBWTcoarse * ( R * mlapiBWT ); else if (ptype=="mod_middle") Rmod = ImBWTcoarse * ( R * ImBWTfine ); else if (ptype=="mod_simple") Rmod = R * ImBWTfine; else if (ptype=="original") Rmod = R; else ML_THROW("incorrect parameter ( " + ptype + " )", -1); Pmod = GetTranspose(Rmod); // store matrix for construction of next level mlapiAsplit = C; // make coarse smoothing operator // make coarse residual operator mlapiAtildesplit_[level+1] = GetRAP(Rmod,mlapiAtildesplit,Pmod); mlapiAhat_[level+1] = GetRAP(Rmod,mlapiAhat_[level],Pmod); mlapiImBWT_[level] = ImBWTfine; mlapiImBWT_[level+1] = ImBWTcoarse; mlapiImWBT_[level] = GetTranspose(ImBWTfine); mlapiImWBT_[level+1] = GetTranspose(ImBWTcoarse); mlapiRmod_[level] = Rmod; mlapiPmod_[level] = Pmod; mlapiS_[level] = S; // prepare for next level mlapiBWT = mlapiBWTcoarse; ImBWTfine = ImBWTcoarse; // break if coarsest level is below specified size if (mlapiAsplit.GetNumGlobalRows() <= maxcoarsesize) { ++level; break; } } // for (level=0; level<maxlevels-1; ++level) // do coarse smoother S.Reshape(mlapiAtildesplit_[level],coarsetype,mlparams_); mlapiS_[level] = S; // store max number of levels maxlevels_ = level+1; iscomputed_ = true; return true; }
int main(int argc, char *argv[]) { #ifdef HAVE_MPI MPI_Init(&argc,&argv); #endif if (argc != 2) { fprintf(stderr, "Usage: `%s InputFile'\n", argv[0]); fprintf(stderr, "An example of input file is reported\n"); fprintf(stderr, "in the source of this example\n"); exit(EXIT_SUCCESS); } string InputFile = argv[1]; // Initialize the workspace and set the output level Init(); try { int NumPDEEqns; Operator A; ReadSAMISMatrix("mtx.dat", A, NumPDEEqns); Teuchos::ParameterList List = ReadParameterList(InputFile.c_str()); int MaxLevels = List.get("max levels", 10); int AdditionalCandidates = List.get("additional candidates", 2); int limKer = List.get("limit kernel", -1); if (AdditionalCandidates == 0 && limKer == 0) limKer = -1; // create multilevel preconditioner, do not compute hierarchy MultiLevelAdaptiveSA Prec(A, List, NumPDEEqns); if (limKer) { MultiVector NS; ReadSAMISKernel("ker.dat", NS, limKer); Prec.SetNullSpace(NS); Prec.AdaptCompute(true, AdditionalCandidates); } else { Prec.AdaptCompute(false, AdditionalCandidates); } MultiVector LHS(A.GetDomainSpace()); MultiVector RHS(A.GetRangeSpace()); LHS.Random(); RHS = 0.0; // Set krylov: type unless specified in the config. file if (List.isParameter("krylov: type") == 0) List.set("krylov: type","cg_condnum"); Krylov(A, LHS, RHS, Prec, List); Finalize(); } catch (const int e) { cerr << "Caught integer exception, code = " << e << endl; } catch (...) { cerr << "Caught exception..." << endl; } #ifdef HAVE_MPI MPI_Finalize() ; #endif return(0); }
std::unique_ptr<SeqPreconditioner> constructPrecond(Operator& opA, const Dune::Amg::SequentialInformation&) const { const double relax = 0.9; std::unique_ptr<SeqPreconditioner> precond(new SeqPreconditioner(opA.getmat(), relax)); return precond; }
/***************************************************************************************************** * show -> debug * ****************************************************************************************************/ void Syntactic::show(){ TokenType *token = ast->getRoot(); Attrib *attrib; TList *list; Operator *op; IFElse *__ift; Each *each; while( token ){ switch(token->getClasse()){ case ASSIGN: attrib = (Attrib *)token; cout<<attrib->getIdentificador()->getToken()<<endl; cout<<attrib->getToken()<<endl; switch(attrib->getExpression()->getClasse()){ case LIST: list = (TList *) attrib->getExpression(); list->showItens(); break; case OPERATOR: op = (Operator *) attrib->getExpression(); cout<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<endl; break; case INTEGER: case FLOAT: case STRING: cout<<attrib->getExpression()->getToken()<<endl; break; } break; case RESERVADO: if(token->getToken() == "if"){ __ift = (IFElse *) token; op = (Operator *) __ift->getExpression(); cout<<"if("<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<")"<<endl; switch(__ift->getBlockIF()->getClasse()){ case ASSIGN: attrib = (Attrib *) __ift->getBlockIF(); cout<<"{"<<attrib->getIdentificador()->getToken()<<attrib->getToken(); switch(attrib->getExpression()->getClasse()){ case LIST: list = (TList *) attrib->getExpression(); cout<<"~("; list->showItens(); cout<<")}"<<endl; break; case OPERATOR: op = (Operator *) attrib->getExpression(); cout<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<"}"<<endl; break; case INTEGER: case FLOAT: case STRING: cout<<attrib->getExpression()->getToken()<<"}"<<endl; break; } } if(__ift->getElseBlock()){ switch(__ift->getElseBlock()->getClasse()){ case ASSIGN: attrib = (Attrib *) __ift->getElseBlock(); cout<<"{"<<attrib->getIdentificador()->getToken()<<attrib->getToken(); switch(attrib->getExpression()->getClasse()){ case LIST: list = (TList *) attrib->getExpression(); cout<<"~("; list->showItens(); cout<<")}"<<endl; break; case OPERATOR: op = (Operator *) attrib->getExpression(); cout<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<"}"<<endl; break; case INTEGER: case FLOAT: case STRING: cout<<attrib->getExpression()->getToken()<<"}"<<endl; break; } } } } else{ each = (Each *) token; op = (Operator *) each->getExpression(); __ift = (IFElse *) each->getBlock(); cout<<"each("<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<")"<<endl; cout<<"{"<<__ift->getToken(); op = (Operator *) __ift->getExpression(); cout<<"("<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<")"<<endl; attrib = (Attrib *) __ift->getBlockIF(); cout<<"{"<<attrib->getIdentificador()->getToken()<<attrib->getToken(); op = (Operator *) attrib->getExpression(); cout<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<"}"<<endl; attrib = (Attrib *) __ift->getElseBlock(); cout<<"else{"<<attrib->getIdentificador()->getToken()<<attrib->getToken(); op = (Operator *) attrib->getExpression(); cout<<op->getLeft()->getToken()<<op->getToken()<<op->getRight()->getToken()<<"}}"; } } token = token->getNext(); } }
virtual std::string asString() { return lhs->asString() + " " + op.asString() + " " + rhs->asString(); }
// returns the output field Field* ProtoInterpreter::sexp_to_graph(SExpr* s, AM* space, Env *env) { V3 << "Interpret: " << ce2s(s) << " in " << ce2s(space) << endl; if(s->isSymbol()) { // All other symbols are looked up in the environment CompilationElement* elt = env->lookup(dynamic_cast<SE_Symbol &>(*s).name); if(elt==NULL) { V4 << "Symbolic literal?\n"; ProtoType* val = symbolic_literal(dynamic_cast<SE_Symbol &>(*s).name); if(val) { V4 << "- Yes\n"; return dfg->add_literal(val,space,s); } return field_err(s,space,"Couldn't find definition of "+s->to_str()); } else if(elt->isA("Field")) { V4 << "Found field: " << ce2s(elt) << endl; Field* f = &dynamic_cast<Field &>(*elt); if(f->domain==space) { return f; } if(f->domain->child_of(space)) { ierror(s,"Direct reference to child space in parent:"+ce2s(s)); } else { // implicit restriction OI *oi = new OperatorInstance(s,Env::core_op("restrict"),space); oi->add_input(f); if(space->selector) oi->add_input(space->selector); return oi->output; } } else if(elt->isA("Operator")) { V4 << "Lambda literal: " << ce2s(elt) << endl; return dfg->add_literal(new ProtoLambda(&dynamic_cast<Operator &>(*elt)), space, s); } else if(elt->isA("MacroSymbol")) { V4 << "Macro: " << ce2s(elt) << endl; return sexp_to_graph(dynamic_cast<MacroSymbol &>(*elt).pattern,space,env); } else return field_err(s,space,"Can't interpret "+elt->type_of()+" "+ s->to_str()+" as field"); } else if(s->isScalar()) { // Numbers are literals V4 << "Numeric literal.\n"; return dfg->add_literal(new ProtoScalar(dynamic_cast<SE_Scalar &>(*s).value), space,s); } else { // it must be a list // Lists are special forms or function applicatios SE_List* sl = &dynamic_cast<SE_List &>(*s); if(sl->len()==0) return field_err(sl,space,"Expression has no members"); if(sl->op()->isSymbol()) { // check if it's a special form string opname = dynamic_cast<SE_Symbol &>(*sl->op()).name; if(opname=="let") { return let_to_graph(sl,space,env,false); } else if(opname=="let*") { return let_to_graph(sl,space,env,true); } else if(opname=="all") { // evaluate children, returning last field Field* last=NULL; V4 << "Found 'all' construct\n"; for(int j=1;j<sl->len();j++) last = sexp_to_graph((*sl)[j],space,env); return last; } else if(opname=="restrict"){ return restrict_to_graph(sl,space,env); } else if(opname=="def" && sl->len()==3) { // variable definition SExpr *def=(*sl)[1], *exp=(*sl)[2]; if(!def->isSymbol()) return field_err(sl,space,"def name not a symbol: "+def->to_str()); Field* f = sexp_to_graph(exp,space,env); env->force_bind(dynamic_cast<SE_Symbol &>(*def).name,f); V4 << "Defined variable: " << ce2s(f) << endl; return f; } else if(opname=="def" || opname=="primitive" || opname=="lambda" || opname=="fun") { Operator* op = sexp_to_op(s,env); if(!(opname=="lambda" || opname=="fun")) return NULL; return dfg->add_literal(new ProtoLambda(op),space,s); } else if(opname=="annotate") { SE_List_iter li(sl); li.get_next(); // make iterator, discard op string name = li.get_token("operator name"); CE* p = env->lookup(name); if(p==NULL) { compile_error(sl,"Can't find primitve '"+name+"' to annotate"); } else if(!p->isA("Primitive")) { compile_error(sl,"Can't annotate '"+name+"': not a primitive"); } else { // add in attributes parse_primitive_attributes(&li, &dynamic_cast<Primitive &>(*p)); } return NULL; // annotations are like primitives: nothing returned } else if(opname=="letfed" || opname=="letfed+") { return letfed_to_graph(sl,space,env,opname=="letfed"); } else if(opname=="macro") { V4 << "Defining macro\n"; sexp_to_macro(sl,env); return NULL; } else if(opname=="include") { for(int j=1;j<sl->len();j++) { SExpr *ex = (*sl)[j]; V4 << "Including file: "<<ce2s(ex)<<endl; if(ex->isSymbol()) interpret_file(dynamic_cast<SE_Symbol &>(*ex).name); else compile_error(ex,"File name "+ex->to_str()+" is not a symbol"); } return NULL; } else if(opname=="quote") { if(sl->len()!=2) return field_err(sl,space,"Quote requires an argument: "+s->to_str()); V4 << "Creating quote literal\n"; return dfg->add_literal(quote_to_literal_type((*sl)[1]),space,s); } else if(opname=="quasiquote") { return field_err(sl,space,"Quasiquote only allowed in macros: "+sl->to_str()); } // check if it's a macro CompilationElement* ce = env->lookup(opname); if(ce && ce->isA("Macro")) { V4 << "Applying macro\n"; SExpr* new_expr; if(ce->isA("MacroOperator")) { new_expr = expand_macro(&dynamic_cast<MacroOperator &>(*ce),sl); if(new_expr->attributes.count("DUMMY")) // Mark of a failure return field_err(s,space,"Macro expansion failed on "+s->to_str()); } else { // it's a MacroSymbol new_expr = sl->copy(); dynamic_cast<SE_List &>(*new_expr).children[0] = dynamic_cast<Macro &>(*ce).pattern; } return sexp_to_graph(new_expr,space,env); } } // if we didn't return yet, it's an ordinary composite expression Operator *op = sexp_to_op(sl->op(),env); if(op->marked(":protected")) compile_warn(op,"operator '"+op->name+"' not intended for direct use."); OperatorInstance *oi = new OperatorInstance(s,op,space); for(vector<SExpr*>::iterator it=sl->args(); it!=sl->children.end(); it++) { Field* sub = sexp_to_graph(*it,space,env); // operator defs, primitives, and macros return null & are ignored if(sub) oi->add_input(sub); } if(!op->signature->legal_length(oi->inputs.size())) { compile_error(s,"Called "+ce2s(op)+" with "+i2s(oi->inputs.size())+ " arguments; it requires "+op->signature->num_arg_str()); } V4 << "Added operator "<<ce2s(oi)<<endl; return oi->output; } ierror("Fell through sexp_to_graph w/o returning for: "+s->to_str()); }
/* * Runs the GDE3 algorithm. * @return a <code>SolutionSet</code> that is a set of non dominated solutions * as a result of the algorithm execution */ SolutionSet * GDE3::execute() { int populationSize; int maxIterations; int evaluations; int iterations; SolutionSet * population; SolutionSet * offspringPopulation; Distance * distance; Comparator * dominance; Operator * crossoverOperator; Operator * selectionOperator; distance = new Distance(); dominance = new DominanceComparator(); Solution ** parent; //Read the parameters populationSize = *(int *) getInputParameter("populationSize"); maxIterations = *(int *) getInputParameter("maxIterations"); //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; iterations = 0; //Read the operators crossoverOperator = operators_["crossover"]; selectionOperator = operators_["selection"]; // Create the initial solutionSet Solution * newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(problem_); problem_->evaluate(newSolution); problem_->evaluateConstraints(newSolution); evaluations++; population->add(newSolution); } //for // Generations ... while (iterations < maxIterations) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize * 2); for (int i = 0; i < populationSize; i++){ // Obtain parents. Two parameters are required: the population and the // index of the current individual void ** object1 = new void*[2]; object1[0] = population; object1[1] = &i; parent = (Solution **) (selectionOperator->execute(object1)); delete[] object1; Solution * child ; // Crossover. Two parameters are required: the current individual and the // array of parents void ** object2 = new void*[2]; object2[0] = population->get(i); object2[1] = parent; child = (Solution *) (crossoverOperator->execute(object2)); delete[] object2; delete[] parent; problem_->evaluate(child) ; problem_->evaluateConstraints(child); evaluations++ ; // Dominance test int result ; result = dominance->compare(population->get(i), child) ; if (result == -1) { // Solution i dominates child offspringPopulation->add(new Solution(population->get(i))); delete child; } // if else if (result == 1) { // child dominates offspringPopulation->add(child) ; } // else if else { // the two solutions are non-dominated offspringPopulation->add(child) ; offspringPopulation->add(new Solution(population->get(i))); } // else } // for // Ranking the offspring population Ranking * ranking = new Ranking(offspringPopulation); int remain = populationSize; int index = 0; SolutionSet * front = NULL; for (int i = 0; i < populationSize; i++) { delete population->get(i); } population->clear(); // Obtain the next front front = ranking->getSubfront(index); while ((remain > 0) && (remain >= front->size())){ //Assign crowding distance to individuals distance->crowdingDistanceAssignment(front,problem_->getNumberOfObjectives()); //Add the individuals of this front for (int k = 0; k < front->size(); k++ ) { population->add(new Solution(front->get(k))); } // for //Decrement remain remain = remain - front->size(); //Obtain the next front index++; if (remain > 0) { front = ranking->getSubfront(index); } // if } // while // remain is less than front(index).size, insert only the best one if (remain > 0) { // front contains individuals to insert while (front->size() > remain) { distance->crowdingDistanceAssignment(front,problem_->getNumberOfObjectives()); Comparator * crowdingComparator = new CrowdingComparator(); int indexWorst = front->indexWorst(crowdingComparator); delete crowdingComparator; delete front->get(indexWorst); front->remove(indexWorst); } for (int k = 0; k < front->size(); k++) { population->add(new Solution(front->get(k))); } remain = 0; } // if delete ranking; delete offspringPopulation; iterations ++ ; } // while delete dominance; delete distance; // Return the first non-dominated front Ranking * ranking = new Ranking(population); SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size()); for (int i=0;i<ranking->getSubfront(0)->size();i++) { result->add(new Solution(ranking->getSubfront(0)->get(i))); } delete ranking; delete population; return result; } // execute
bool ExpressionTreeUtils::fixExprPrecedence(Expression*& top, Expression* e) { if ( dynamic_cast<Value*> (e)) return false; if ( dynamic_cast<Empty*> (e)) return false; Operator* op = dynamic_cast<Operator*> (e); bool more_iterations_needed = true; while (more_iterations_needed) { more_iterations_needed = false; // Fix all children for (int operand = 0; operand < op->size(); ++operand) more_iterations_needed = fixExprPrecedence(top, op->at(operand)) || more_iterations_needed; } //Look left if (op->descriptor()->prefix().isEmpty()) { Operator* left = dynamic_cast<Operator*> (op->first()); if (left && left->descriptor()->postfix().isEmpty()) { if (op->descriptor()->precedence() < left->descriptor()->precedence() // Must rotate because of precedence // Must rotate because of associativity. This assumes that the associativity of different operators at the same precedence level is the same. || ( (op->descriptor()->precedence() == left->descriptor()->precedence()) && op->descriptor()->associativity() == OperatorDescriptor::RightAssociative) ) { rotateRight(top, left, op); return true; } } } //Look right if (op->descriptor()->postfix().isEmpty()) { Operator* right = dynamic_cast<Operator*> (op->last()); if (right && right->descriptor()->prefix().isEmpty()) { if (op->descriptor()->precedence() < right->descriptor()->precedence() // Must rotate because of precedence // Must rotate because of associativity. This assumes that the associativity of different operators at the same precedence level is the same. || ( (op->descriptor()->precedence() == right->descriptor()->precedence()) && op->descriptor()->associativity() == OperatorDescriptor::LeftAssociative) ) { rotateLeft(top, right, op); return true; } } } return false; }
void ExpressionTreeUtils::grow(Expression*& top, Operator* op, bool leftside) { bool rightside = !leftside; // Can't grow if there is no parent if ( !op->parent() ) return; // Can't grow from a side where there is no delimiter if ( (leftside && op->descriptor()->prefix().isEmpty() ) || (rightside && op->descriptor()->postfix().isEmpty()) ) return; Operator* parent = op->parent(); // Get context int delim_begin; int delim_end; op->globalDelimiterBoundaries(leftside ? 0 : op->descriptor()->numOperands(), delim_begin, delim_end); ExpressionContext c = top->findContext(leftside ? delim_begin: delim_end); // If this is an expression in the middle of two delimiters that belong to the same operator // this typically means that it can not be grown any more from only a single side... bool wrap_parent = false; if ( ( leftside && (c.leftType() == ExpressionContext::None || c.leftType() == ExpressionContext::OpBoundary) ) || ( rightside && (c.rightType() == ExpressionContext::None || c.rightType() == ExpressionContext::OpBoundary) ) ) { // .. EXCEPT: when both delimiters are the same as the delimiter we're trying to grow and the // direction opposite of the growth direction is an end delimiter. In that case we simply // engulf the entire parent. op->globalDelimiterBoundaries(leftside ? op->descriptor()->numOperands() : 0, delim_begin, delim_end); ExpressionContext c_other = top->findContext(leftside ? delim_end : delim_begin ); if ( ( leftside && c_other.rightType() == ExpressionContext::OpBoundary && c_other.rightText() == op->descriptor()->postfix() && c_other.rightDelim() == c_other.rightOp()->size()) || ( rightside && c_other.leftType() == ExpressionContext::OpBoundary && c_other.leftText() == op->descriptor()->prefix() && c_other.leftDelim() == 0) ) wrap_parent = true; else return; } // Special case when the parent ends with a pre/postfix in the direction we're growing. // In that case we must wrap the whole operator as we can not break the delimiters. wrap_parent = wrap_parent || ( !(leftside && parent->descriptor()->prefix().isEmpty()) && !(rightside && parent->descriptor()->postfix().isEmpty())); if (wrap_parent) { Expression* placeholder = new Empty(); replace(top, parent, placeholder); replace(top, op, leftside ? op->first(true) : op->last(true)); if (leftside) op->prepend(parent); else op->append(parent); delete replace(top, placeholder, op); return; } // Find the expression that must be wrapped Operator* top_op = parent; Operator* child = op; while ( (leftside ? top_op->last() : top_op->first()) != child) { child = top_op; top_op = top_op->parent(); if (!top_op) return; } Expression* to_wrap = leftside ? top_op->first()->smallestRightmostSubExpr() : top_op->last()->smallestLeftmostSubExpr(); // Do the exchange -------------------------------------- // Disconnect top_op from the the entire tree and from it's first and last // Note that if we've reached this point then first and last must be two different nodes Expression* top_op_placeholder = new Empty(); replace(top, top_op, top_op_placeholder); Expression* top_op_last = top_op->last(true); // Special case when rightside: top_op_last could be identical to to_wrap Expression* top_op_first = top_op->first(true); // Special case when leftside: top_op_first could be identical to to_wrap // Disconnect the to_wrap expression if not yet disconnected Expression* to_wrap_placeholder = nullptr; if ( (leftside && to_wrap != top_op_first) || (rightside && to_wrap != top_op_last) ) { to_wrap_placeholder = new Empty(); replace(top, to_wrap, to_wrap_placeholder); } // Disconnect the old_wrapped expression Expression* old_wrap = leftside ? op->first(true) : op->last(true); // This is the content that was previously wrapped // Disconnect the left and right children of top_op. // Make the necessary connections if (leftside) { op->prepend(top_op); top_op->prepend(to_wrap); top_op->append(old_wrap); //Consider the special case if (top_op_first == to_wrap) { delete replace(top, top_op_placeholder, top_op_last ); } else { delete replace(top, top_op_placeholder, top_op_first ); delete replace(top, to_wrap_placeholder, top_op_last); } } else { op->append(top_op); top_op->prepend(old_wrap); top_op->append(to_wrap); //Consider the special case if (top_op_last == to_wrap) { delete replace(top, top_op_placeholder, top_op_first ); } else { delete replace(top, top_op_placeholder, top_op_last ); delete replace(top, to_wrap_placeholder, top_op_first); } } fixTop(top); }
CostEstimation* AlgebraManager::getCostEstimation( const int algId, const int opId, const int funId){ Operator* op = getOperator(algId,opId); return op?op->getCostEstimation(funId):0; }
bool AlgebraManager::findOperator(const string& name, const ListExpr argList, ListExpr& resultList, int& algId, int& opId, int& funId){ ListExpr typeError = nl->SymbolAtom(Symbol::TYPEERROR()); NestedList* nl_orig = NList::getNLRef(); NList::setNLRef(nl); int mode = 0; // normal mode, search for matching arglist string algName =""; if(nl->HasLength(argList,2)){ if(nl->IsEqual(nl->First(argList),"algebra") && nl->AtomType(nl->Second(argList)==SymbolType)){ mode = 1; // search within a specific algebra algName = nl->SymbolValue(nl->Second(argList)); stringutils::toLower(algName); if(algName=="all"){ mode = 2; // search all algebras, return first hit } } } for(unsigned int a=0;a<algebra.size();a++){ Algebra* alg = algebra[a]; if(alg!=0){ string an = algebraNames[a]; stringutils::toLower(an); if(mode==0 || mode==2 || an==algName){ for(int o=0; o< alg->GetNumOps(); o++){ Operator* op = alg->GetOperator(o); if(op->GetName() == name){ if(mode==0){ try{ ListExpr res = op->CallTypeMapping(argList); if(!nl->Equal(res,typeError)){ // appropriate operator found algId = a; opId = o; funId = op->Select(argList); resultList = res; NList::setNLRef(nl_orig); return true; } } catch (...){ cerr << "Problem in Typemapping of operator " << op->GetName() << " in Algebra" << GetAlgebraName(a) << endl; cerr << "Throws an exception when called with " << nl->ToString(argList) << endl; } } else { // mode <>0 algId = a; opId = o; funId = 0; resultList = nl->TheEmptyList(); NList::setNLRef(nl_orig); return true; } } } } // fitting algebra name } } algId = 0; opId = 0; resultList = nl->TheEmptyList(); NList::setNLRef(nl_orig); return false; }