void SimulatorParameters::loadSolverParameters(){
		ifstream fid;
		string str;
		// read solver parameters
		string solver(parametersPath + "/solver.dat");
		fid.open(solver.c_str());
		if ( !fid.is_open() ) throw Exception(__LINE__,__FILE__,"solver.dat could not be opened or it doesn't exist.\n");

		// start reading file
		setPositionToRead(fid,"absolute convergence tolerance");
		fid >> _abstol;

		setPositionToRead(fid,"relative convergence tolerance for KSP solver");
		fid >> _rtol;

		setPositionToRead(fid,"relative convergence tolerance for external iteration");
		fid >> _rtol2;

		setPositionToRead(fid,"convergence tolerance in terms of the norm of the change in the solution between steps");
		fid >> _dtol;

		setPositionToRead(fid,"maximum number of iterations");
		fid >> _maxit;

		setPositionToRead(fid,"Sets number of iterations at which GMRES, FGMRES and LGMRES restarts:");
		fid >> _Krylov_restart;


		// Load a 'database' to set a preconditioner chosen by user. <private>
		setPreconditionerDataBase();

		// Read solver.dat and check which preconditioner user chose.
		string::size_type pos;
		int numpc = (int)mapPC.size(); // number of preconditioners presented on data base.
		setPositionToRead(fid,"Define a preconditioner (Default: none)");
		for (int i=0; i<numpc; i++) {
			getline(fid,str,'\n');

			// search for chosen option
			pos = str.find("(x)",0);

			// if marked with 'x', search in 'str' for pre-conditioner available
			if (pos != string::npos){
				std::map<std::string,PCType>::iterator miter = mapPC.begin();
				while (miter != mapPC.end()){
					pos = str.find(miter->first,0);
					if (pos != string::npos){				// miter->first: string name
						pctype = miter->second;				// miter->second preconditioner
					}
					miter++;
				}
			}
		}

		// read pressure solver scheme for EBFV1 formulation
		str.clear();
		setPositionToRead(fid,"Use <defect-correction> scheme for EBFV1 pressure solver?: (default: matrix-free scheme)");
		getline(fid,str);
		pos = str.find("(x)",0);
		if (pos != string::npos) {
			setUseDefectCorrection();
			if (!P_pid()) printf("Using defect-correction scheme for EBFV1 pressure solver.\n");
		}

		fid.close();
	}
void CellBasedPdeHandler<DIM>::SolvePdeAndWriteResultsToFile(unsigned samplingTimestepMultiple)
{
    // Record whether we are solving PDEs on a coarse mesh
    bool using_coarse_pde_mesh = (mpCoarsePdeMesh != NULL);

    // If solving PDEs on a coarse mesh, each PDE should have an averaged source term; otherwise none should
    assert(!mPdeAndBcCollection.empty());
    for (unsigned pde_index=0; pde_index<mPdeAndBcCollection.size(); pde_index++)
    {
        assert(mPdeAndBcCollection[pde_index]);
        assert(mPdeAndBcCollection[pde_index]->HasAveragedSourcePde() == using_coarse_pde_mesh || dynamic_cast<MultipleCaBasedCellPopulation<DIM>*>(mpCellPopulation));
    }

    // Make sure the cell population is in a nice state
    mpCellPopulation->Update();

    // Store a pointer to the (population-level or coarse) mesh
    TetrahedralMesh<DIM,DIM>* p_mesh;
    if (using_coarse_pde_mesh)
    {
        p_mesh = mpCoarsePdeMesh;
    }
    else
    {
        // If not using a coarse PDE mesh, we must be using a MeshBasedCellPopulation
        p_mesh = &(static_cast<MeshBasedCellPopulation<DIM>*>(mpCellPopulation)->rGetMesh());
    }

    // Loop over elements of mPdeAndBcCollection
    for (unsigned pde_index=0; pde_index<mPdeAndBcCollection.size(); pde_index++)
    {
        // Get pointer to this PdeAndBoundaryConditions object
        PdeAndBoundaryConditions<DIM>* p_pde_and_bc = mPdeAndBcCollection[pde_index];

        // Set up boundary conditions
        std::auto_ptr<BoundaryConditionsContainer<DIM,DIM,1> > p_bcc = ConstructBoundaryConditionsContainer(p_pde_and_bc, p_mesh);

        // If the solution at the previous timestep exists...
        PetscInt previous_solution_size = 0;
        if (p_pde_and_bc->GetSolution())
        {
            VecGetSize(p_pde_and_bc->GetSolution(), &previous_solution_size);
        }

        // ...then record whether it is the correct size...
        bool is_previous_solution_size_correct = (previous_solution_size == (int)p_mesh->GetNumNodes());

        // ...and if it is, store it as an initial guess for the PDE solver
        Vec initial_guess;
        if (is_previous_solution_size_correct)
        {
            // This Vec is copied by the solver's Solve() method, so must be deleted here too
            VecDuplicate(p_pde_and_bc->GetSolution(), &initial_guess);
            VecCopy(p_pde_and_bc->GetSolution(), initial_guess);
            p_pde_and_bc->DestroySolution();
        }
        else
        {
            ///\todo enable the coarse PDE mesh to change size, e.g. for a growing domain (#630/#1891)
            if (!using_coarse_pde_mesh && p_pde_and_bc->GetSolution())
            {
                assert(previous_solution_size != 0);
                p_pde_and_bc->DestroySolution();
            }
        }

        // Create a PDE solver and solve the PDE on the (population-level or coarse) mesh
        if (p_pde_and_bc->HasAveragedSourcePde())
        {
            // When using a coarse PDE mesh, we must set up the source terms before solving the PDE.
            // Pass in mCellPdeElementMap to speed up finding cells.
            this->UpdateCellPdeElementMap();
            p_pde_and_bc->SetUpSourceTermsForAveragedSourcePde(p_mesh, &mCellPdeElementMap);


            SimpleLinearEllipticSolver<DIM,DIM> solver(p_mesh, p_pde_and_bc->GetPde(), p_bcc.get());

            // If we have an initial guess, use this when solving the system...
            if (is_previous_solution_size_correct)
            {
                p_pde_and_bc->SetSolution(solver.Solve(initial_guess));
                PetscTools::Destroy(initial_guess);
            }
            else // ...otherwise do not supply one
            {
                p_pde_and_bc->SetSolution(solver.Solve());
            }
        }
        else
        {
            CellBasedPdeSolver<DIM> solver(p_mesh, p_pde_and_bc->GetPde(), p_bcc.get());

            // If we have an initial guess, use this...
            if (is_previous_solution_size_correct)
            {
                p_pde_and_bc->SetSolution(solver.Solve(initial_guess));
                PetscTools::Destroy(initial_guess);
            }
            else // ...otherwise do not supply one
            {
                p_pde_and_bc->SetSolution(solver.Solve());
            }
        }

        // Store the PDE solution in an accessible form
        ReplicatableVector solution_repl(p_pde_and_bc->GetSolution());

        // Having solved the PDE, now update CellData
        for (typename AbstractCellPopulation<DIM>::Iterator cell_iter = mpCellPopulation->Begin();
             cell_iter != mpCellPopulation->End();
             ++cell_iter)
        {
            unsigned node_index = mpCellPopulation->GetLocationIndexUsingCell(*cell_iter);
            double solution_at_node = 0.0;

            if (using_coarse_pde_mesh)
            {
                // When using a coarse PDE mesh, the cells are not nodes of the mesh, so we must interpolate

                // Find the element in the coarse mesh that contains this cell. CellElementMap has been updated so use this.
                unsigned elem_index = mCellPdeElementMap[*cell_iter];
                Element<DIM,DIM>* p_element = mpCoarsePdeMesh->GetElement(elem_index);

                const ChastePoint<DIM>& node_location = mpCellPopulation->GetLocationOfCellCentre(*cell_iter);

                c_vector<double,DIM+1> weights = p_element->CalculateInterpolationWeights(node_location);
                for (unsigned i=0; i<DIM+1; i++)
                {
                    double nodal_value = solution_repl[p_element->GetNodeGlobalIndex(i)];
                    solution_at_node += nodal_value * weights(i);
                }
            }
            else
            {
                solution_at_node = solution_repl[node_index];
            }
            cell_iter->GetCellData()->SetItem(mPdeAndBcCollection[pde_index]->rGetDependentVariableName(), solution_at_node);
        }
    }

    // Write results to file if required
    SimulationTime* p_time = SimulationTime::Instance();
    if ((p_time->GetTimeStepsElapsed())%samplingTimestepMultiple == 0)
    {
        WritePdeSolution(p_time->GetTime());
    }
#define COVERAGE_IGNORE
    ///\todo enable this in the case where a coarse PDE mesh is used
    if (!using_coarse_pde_mesh)
    {
        if (mWriteDailyAverageRadialPdeSolution)
        {
            ///\todo Worry about round-off errors (#1891)
            p_time = SimulationTime::Instance();
            unsigned num_timesteps_per_day = (unsigned) (DBL_EPSILON + 24/SimulationTime::Instance()->GetTimeStep());
            if ((p_time->GetTimeStepsElapsed()) % num_timesteps_per_day == 0)
            {
                WriteAverageRadialPdeSolution(p_time->GetTime());
            }
        }
    }
#undef COVERAGE_IGNORE
}
void VDBLinearFEMSolverModule<LatticeType>::solve() {

    Eigen::PardisoLDLT<SparseMatrix,Eigen::Lower> solver(M);
    x = solver.compute(M).solve(rhs);
    //std::cout << "#iterations : " << solver.iterations() << std::endl;
    //std::cout << "error: " << solver.error() << std::endl;
    //std::cout << x.transpose() << std::endl;
    std::cout << "L2 difference: " << (rhs - M*x).norm()/rhs.norm() << std::endl;
    switch(solver.info()) {
        case Eigen::NumericalIssue:
            std::cout << "Numerical Issue!" << std::endl;
            //return false;
            break;
        case Eigen::NoConvergence:
            std::cout << "No Convergence!" << std::endl;
            //return false;
            break;
        case Eigen::InvalidInput:
            std::cout << "Invalid Input!" << std::endl;
            //return false;
            break;
        case Eigen::Success:
            std::cout << "Success!" << std::endl;
            break;
    }

    rms::VectorGridPtr velocityFieldPtr = m_obj->getVectorField();
    rms::ScalarGridPtr rigidFieldPtr = m_obj->getRigidField();
    rms::ScalarGridPtr heatFieldPtr = m_obj->getHeatField();
    rms::RGBAGridPtr materialFieldPtr = m_obj->getMaterialField();
    rms::ScalarGrid::ConstAccessor heatAccessor = heatFieldPtr->getConstAccessor();
    rms::ScalarGrid::ConstAccessor rigidAccessor = rigidFieldPtr->getConstAccessor();
    rms::RGBAGrid::ConstAccessor materialAccessor = materialFieldPtr->getConstAccessor();
    rms::VectorGrid::ConstAccessor velocityAccessor = velocityFieldPtr->getConstAccessor();
    int count=0;

    std::cout << "About to look at heat field" << std::endl;
    Scalar scale = heatFieldPtr->transform().voxelVolume();
    StiffnessEntryStorage store(scale,integrator);//TODO: need to fix this
    std::cout << "Mincoord: " << m_minCoord << std::endl;
    vdb::CoordBBox bbox = m_obj->getDistanceField()->evalActiveVoxelBoundingBox();
    std::cout << bbox.min() << " " << bbox.max() << std::endl;
    m_minCoord = bbox.min();
    for(rms::ScalarGrid::ValueOnCIter it =  m_obj->getDistanceField()->cbeginValueOn(); it; ++it) {
        if(it.getValue() >= 0) continue;
        Index3 idx = VDBtoLatticeCoord(it.getCoord());
        //std::cout << "True index: " << idx << " " << it.getCoord() << std::endl;
        /*
           if(m_obj->getVertex(idx.i,idx.j,idx.k) == -1) {
           std::cout << "bottomleftinner lattice index doesn't exist, clearly lattice just isn't populated"<< std::endl;
           }
         */
        const vdb::Coord vdbcoord = m_minCoord + vdb::Coord(idx.i,idx.j,idx.k);

        for(VDBVoxelNodeIterator<LatticeType> alpha(m_obj->getDOFs(),idx); alpha; ++alpha) {
            const Index3 & alpha_index = alpha.index();
            const vdb::Coord alpha_vdbcoord = m_minCoord + vdb::Coord(alpha_index.i,alpha_index.j,alpha_index.k);
            const int32_t alpha_value = alpha.value();
            const int32_t alphaind = mat_ind(alpha_value,0);
            //const LinearElasticVertexProperties & alpha_props = m_vertex_properties[alpha_value];
            //alpha sets the matrix, betas set the rhs values for alpha
            if(rigidAccessor.getValue(alpha_vdbcoord) < 0) {
                std::cout << alpha_vdbcoord << ": ";
                std::cout << "Rigid!" << std::endl;
                std::cout << rhs(alphaind+0) << " ";
                std::cout << rhs(alphaind+1) << " ";
                std::cout << rhs(alphaind+2) << std::endl;
                std::cout << x(alphaind+0) << " ";
                std::cout << x(alphaind+1) << " ";
                std::cout << x(alphaind+2) << std::endl;
            }
        }
    }
}
Example #4
0
void summarizer_bwt::do_summary(const function_namet &function_name, 
				local_SSAt &SSA,
				const summaryt &old_summary,
				summaryt &summary,
				bool context_sensitive)
{
  bool sufficient = options.get_bool_option("sufficient");
  status() << "Computing preconditions" << eom;

  // solver
  incremental_solvert &solver = ssa_db.get_solver(function_name);
  solver.set_message_handler(get_message_handler());

  template_generator_summaryt template_generator(
    options,ssa_db,ssa_unwinder.get(function_name));
  template_generator.set_message_handler(get_message_handler());
  template_generator(solver.next_domain_number(),SSA,false);

  exprt::operandst c;
  c.push_back(old_summary.fw_precondition);
  c.push_back(old_summary.fw_invariant);
  c.push_back(ssa_inliner.get_summaries(SSA)); //forward summaries
  exprt::operandst postcond;
  ssa_inliner.get_summaries(SSA,false,postcond,c); //backward summaries
  collect_postconditions(function_name, SSA, summary, postcond,sufficient);
  if(!sufficient)
  {
    c.push_back(conjunction(postcond)); 
  }
  else //sufficient
  {
    c.push_back(not_exprt(conjunction(postcond))); 
  }

  if(!template_generator.out_vars().empty())
  {
    ssa_analyzert analyzer;
    analyzer.set_message_handler(get_message_handler());
    analyzer(solver,SSA,conjunction(c),template_generator);
    analyzer.get_result(summary.bw_transformer,template_generator.inout_vars());
    analyzer.get_result(summary.bw_invariant,template_generator.loop_vars());
    analyzer.get_result(summary.bw_precondition,template_generator.out_vars());

    //statistics
    solver_instances += analyzer.get_number_of_solver_instances();
    solver_calls += analyzer.get_number_of_solver_calls();
  }
  else // TODO: yet another workaround for ssa_analyzer not being able to handle empty templates properly
  {
    solver << SSA;
    solver.new_context();
    solver << SSA.get_enabling_exprs();
    solver << conjunction(c);
    exprt result = true_exprt();
    if(solver()==decision_proceduret::D_UNSATISFIABLE) result = false_exprt();
    solver.pop_context();
    summary.bw_transformer = result;
    summary.bw_invariant = result;
    summary.bw_precondition = result;
  }

  if(sufficient)
  {
    summary.bw_transformer = not_exprt(summary.bw_transformer);
    summary.bw_invariant = not_exprt(summary.bw_invariant);
    summary.bw_precondition = not_exprt(summary.bw_precondition);
  }

  if(context_sensitive && !summary.bw_postcondition.is_true())
  {
    summary.bw_transformer = 
      implies_exprt(summary.bw_postcondition,summary.bw_transformer);
    summary.bw_invariant = 
      implies_exprt(summary.bw_postcondition,summary.bw_invariant);
    summary.bw_precondition = 
      implies_exprt(summary.bw_postcondition,summary.bw_precondition);
  }
}
    void FdBlackScholesAsianEngine::calculate() const {

        QL_REQUIRE(arguments_.exercise->type() == Exercise::European,
                   "European exercise supported only");
        QL_REQUIRE(arguments_.averageType == Average::Arithmetic,
                   "Arithmetic averaging supported only");
        QL_REQUIRE(   arguments_.runningAccumulator == 0
                   || arguments_.pastFixings > 0,
                   "Running average requires at least one past fixing");

        // 1. Mesher
        const ext::shared_ptr<StrikedTypePayoff> payoff =
            ext::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
        const Time maturity = process_->time(arguments_.exercise->lastDate());
        const ext::shared_ptr<Fdm1dMesher> equityMesher(
            new FdmBlackScholesMesher(xGrid_, process_, maturity,
                                      payoff->strike()));

        const Real spot = process_->x0();
        QL_REQUIRE(spot > 0.0, "negative or null underlying given");

        const Real avg = (arguments_.runningAccumulator == 0)
                 ? spot : arguments_.runningAccumulator/arguments_.pastFixings;

        const Real normInvEps = InverseCumulativeNormal()(1-0.0001);
        const Real sigmaSqrtT 
            = process_->blackVolatility()->blackVol(maturity, payoff->strike())
                                                        *std::sqrt(maturity);
        const Real r = sigmaSqrtT*normInvEps;

        Real xMin = std::min(std::log(avg)  - 0.25*r, std::log(spot) - 1.5*r);
        Real xMax = std::max(std::log(avg)  + 0.25*r, std::log(spot) + 1.5*r);

        const ext::shared_ptr<Fdm1dMesher> averageMesher(
            new FdmBlackScholesMesher(aGrid_, process_, maturity,
                                      payoff->strike(), xMin, xMax));

        const ext::shared_ptr<FdmMesher> mesher (
            new FdmMesherComposite(equityMesher, averageMesher));

        // 2. Calculator
        ext::shared_ptr<FdmInnerValueCalculator> calculator(
                                new FdmLogInnerValue(payoff, mesher, 1));

        // 3. Step conditions
        std::list<ext::shared_ptr<StepCondition<Array> > > stepConditions;
        std::list<std::vector<Time> > stoppingTimes;

        // 3.1 Arithmetic average step conditions
        std::vector<Time> averageTimes;
        for (Size i=0; i<arguments_.fixingDates.size(); ++i) {
            Time t = process_->time(arguments_.fixingDates[i]);
            QL_REQUIRE(t >= 0, "Fixing dates must not contain past date");
            averageTimes.push_back(t);
        }
        stoppingTimes.push_back(std::vector<Time>(averageTimes));
        stepConditions.push_back(ext::shared_ptr<StepCondition<Array> >(
                new FdmArithmeticAverageCondition(
                        averageTimes, arguments_.runningAccumulator,
                        arguments_.pastFixings, mesher, 0)));

        ext::shared_ptr<FdmStepConditionComposite> conditions(
                new FdmStepConditionComposite(stoppingTimes, stepConditions));

        // 4. Boundary conditions
        const FdmBoundaryConditionSet boundaries;

        // 5. Solver
        FdmSolverDesc solverDesc = { mesher, boundaries, conditions,
                                     calculator, maturity, tGrid_, 0 };
        ext::shared_ptr<FdmSimple2dBSSolver> solver(
              new FdmSimple2dBSSolver(
                              Handle<GeneralizedBlackScholesProcess>(process_),
                              payoff->strike(), solverDesc, schemeDesc_));

        results_.value = solver->valueAt(spot, avg);
        results_.delta = solver->deltaAt(spot, avg, spot*0.01);
        results_.gamma = solver->gammaAt(spot, avg, spot*0.01);
    }
Example #6
0
int main(int argc, char **argv)
{
    bool dump_to_stdout = false;
    ifstream inFile;
    ofstream fs_out;
    string test_name = "";

    //-----------------------------------------------------------
    // initialize
    //-----------------------------------------------------------


    if ((argc == 2) && (strcmp (argv[1], "stdout") == 0))
    {
        dump_to_stdout = true;
        cout.precision (numeric_limits<double>::digits10);
    }
    else
    {
        // reference states generated using thr implementation of
        // the algorithm in Octave/MATLAB
        inFile.open ("./data/ip_states_inv.dat");
        //inFile.open ("./data/states_chol_downdate.dat");
        test_name = "test_05";
    }
    init_01 test_05 (test_name);



    smpc::solver_ip solver(
            test_05.wmg->N, 
            2000, 
            150, 
            0.02, 
            1, 
            1e-3,
            1e-2,
            100, 
            15, 
            0.01, 
            0.5,
            0,
            smpc::SMPC_IP_BS_LOGBAR,
            true);


    double err = 0;
    double max_err = 0;
    double max_err_first_state = 0;


    fs_out.open(test_05.fs_out_filename.c_str(), fstream::app);
    fs_out.precision (numeric_limits<double>::digits10);
    fs_out << endl << endl;
    fs_out << "CoM_ZMP = [";
   


    for(;;)
    {
        //------------------------------------------------------
        if (test_05.wmg->formPreviewWindow(*test_05.par) == WMG_HALT)
        {
            if (dump_to_stdout == false)
            {
                cout << "EXIT (halt = 1)" << endl;
            }
            break;
        }
        //------------------------------------------------------

        //------------------------------------------------------
        solver.set_parameters (test_05.par->T, test_05.par->h, test_05.par->h0, test_05.par->angle, test_05.par->fp_x, test_05.par->fp_y, test_05.par->lb, test_05.par->ub);
        solver.form_init_fp (test_05.par->fp_x, test_05.par->fp_y, test_05.par->init_state, test_05.par->X);
        solver.solve();
        solver.get_next_state(test_05.par->init_state);
        //------------------------------------------------------

        solver.get_next_state(test_05.X_tilde);
        fs_out << endl << test_05.par->init_state.x() << " " << test_05.par->init_state.y() << " " << test_05.X_tilde.x() << " " << test_05.X_tilde.y() << ";";


        if (dump_to_stdout)
        {
            for (unsigned int i = 0; i < test_05.wmg->N*SMPC_NUM_VAR; i++)
            {
                cout << test_05.par->X[i] << endl;
            }
        }
        else
        {
            printf ("-------------------------------------\nOBJ: ");
            for (unsigned int i = 0; i < solver.objective_log.size(); ++i)
            {   
                printf ("% 8e ", solver.objective_log[i]);
            }
            printf ("\n-------------------------------------\n");


            //------------------------------------------------------
            // compare with reference results
            for (unsigned int i = 0; i < test_05.wmg->N*SMPC_NUM_VAR; i++)
            {
                double dataref;

                inFile >> dataref;
                err = abs(test_05.par->X[i] - dataref);
                if ((i < 6) && (err > max_err_first_state))
                {
                    max_err_first_state = err;
                }
                if (err > max_err)
                {
                    max_err = err;
                }
                printf("value: % 8e   ref: % 8e   err: % 8e\n", test_05.par->X[i], dataref, err);
            }
            cout << "Max. error (first state, all steps): " << max_err_first_state << endl;
            cout << "Max. error (all states, all steps): " << max_err << endl;
            //------------------------------------------------------
        }
    }
    inFile.close();

    fs_out << "];" << endl;
    fs_out << "plot (CoM_ZMP(:,1), CoM_ZMP(:,2), 'b');" << endl;
    fs_out << "plot (CoM_ZMP(:,3), CoM_ZMP(:,4), 'ks','MarkerSize',5);" << endl;
    fs_out.close();

    return 0;
}
Example #7
0
bool test_lin_indep(Shapeset *shapeset) {
	_F_
	printf("I. linear independency\n");

	UMFPackMatrix mat;
	UMFPackVector rhs;
	UMFPackLinearSolver solver(&mat, &rhs);

	ShapeFunction fu(shapeset), fv(shapeset);

	int n =
		Hex::NUM_VERTICES * 1 +			// 1 vertex fn
		Hex::NUM_EDGES * shapeset->get_num_edge_fns(H3D_MAX_ELEMENT_ORDER) +
		Hex::NUM_FACES * shapeset->get_num_face_fns(order2_t(H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER)) +
		shapeset->get_num_bubble_fns(Ord3(H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER));

	printf("number of functions = %d\n", n);

	int *fn_idx = new int [n];
	int m = 0;
	// vertex fns
	for (int i = 0; i < Hex::NUM_VERTICES; i++, m++)
		fn_idx[m] = shapeset->get_vertex_index(i);
	// edge fns
	for (int i = 0; i < Hex::NUM_EDGES; i++) {
		int order = H3D_MAX_ELEMENT_ORDER;
		int *edge_idx = shapeset->get_edge_indices(i, 0, order);
		for (int j = 0; j < shapeset->get_num_edge_fns(order); j++, m++)
			fn_idx[m] = edge_idx[j];
	}
	// face fns
	for (int i = 0; i < Hex::NUM_FACES; i++) {
		order2_t order(H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER);
		int *face_idx = shapeset->get_face_indices(i, 0, order);
		for (int j = 0; j < shapeset->get_num_face_fns(order); j++, m++)
			fn_idx[m] = face_idx[j];
	}
	// bubble
	Ord3 order(H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER, H3D_MAX_ELEMENT_ORDER);
	int *bubble_idx = shapeset->get_bubble_indices(order);
	for (int j = 0; j < shapeset->get_num_bubble_fns(order); j++, m++)
		fn_idx[m] = bubble_idx[j];


	// precalc structure
	mat.prealloc(n);
	for (int i = 0; i < n; i++)
		for (int j = 0; j < n; j++)
			mat.pre_add_ij(i, j);
	mat.alloc();
	rhs.alloc(n);

	printf("assembling matrix ");

	for (int i = 0; i < n; i++) {
		fu.set_active_shape(fn_idx[i]);

		printf(".");
		fflush(stdout);			// prevent caching of output (to see that it did not freeze)

		for (int j = 0; j < n; j++) {
			fv.set_active_shape(fn_idx[j]);

			double value = l2_product(&fu, &fv);

			mat.add(i, j, value);
		}
	}
	printf("\n");

	for (int i = 0; i < n; i++)
		rhs.add(i, 0.0);

	printf("solving matrix\n");

	// solve the system
	if (solver.solve()) {
		double *sln = solver.get_solution();
		bool indep = true;
		for (int i = 1; i < n + 1; i++) {
			if (sln[i] >= EPS) {
				indep = false;
				break;
			}
		}

		if (indep)
			printf("ok\n");
		else
			printf("Shape functions are not linearly independent\n");
	}
	else {
		printf("Shape functions are not linearly independent\n");
	}

	delete [] fn_idx;

	return true;
}
Example #8
0
// Advance a dynamic body to its first time of contact
// and adjust the position to ensure clearance.
void b2World::SolveTOI(b2Body* body)
{
	// Find the minimum contact.
	b2Contact* toiContact = NULL;
	float32 toi = 1.0f;
	b2Body* toiOther = NULL;
	bool found;
	int32 count;
	int32 iter = 0;

	bool bullet = body->IsBullet();

	// Iterate until all contacts agree on the minimum TOI. We have
	// to iterate because the TOI algorithm may skip some intermediate
	// collisions when objects rotate through each other.
	do
	{
		count = 0;
		found = false;
		for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next)
		{
			if (ce->contact == toiContact)
			{
				continue;
			}

			b2Body* other = ce->other;
			b2BodyType type = other->GetType();

			// Only bullets perform TOI with dynamic bodies.
			if (bullet == true)
			{
				// Bullets only perform TOI with bodies that have their TOI resolved.
				if ((other->m_flags & b2Body::e_toiFlag) == 0)
				{
					continue;
				}

				// No repeated hits on non-static bodies
				if (type != b2_staticBody && (ce->contact->m_flags & b2Contact::e_bulletHitFlag) != 0)
				{
						continue;
				}
			}
			else if (type == b2_dynamicBody)
			{
				continue;
			}

			// Check for a disabled contact.
			b2Contact* contact = ce->contact;
			if (contact->IsEnabled() == false)
			{
				continue;
			}

			// Prevent infinite looping.
			if (contact->m_toiCount > 10)
			{
				continue;
			}

			b2Fixture* fixtureA = contact->m_fixtureA;
			b2Fixture* fixtureB = contact->m_fixtureB;

			// Cull sensors.
			if (fixtureA->IsSensor() || fixtureB->IsSensor())
			{
				continue;
			}

			b2Body* bodyA = fixtureA->m_body;
			b2Body* bodyB = fixtureB->m_body;

			// Compute the time of impact in interval [0, minTOI]
			b2TOIInput input;
			input.proxyA.Set(fixtureA->GetShape());
			input.proxyB.Set(fixtureB->GetShape());
			input.sweepA = bodyA->m_sweep;
			input.sweepB = bodyB->m_sweep;
			input.tMax = toi;

			b2TOIOutput output;
			b2TimeOfImpact(&output, &input);

			if (output.state == b2TOIOutput::e_touching && output.t < toi)
			{
				toiContact = contact;
				toi = output.t;
				toiOther = other;
				found = true;
			}

			++count;
		}

		++iter;
	} while (found && count > 1 && iter < 50);

	if (toiContact == NULL)
	{
		body->Advance(1.0f);
		return;
	}

	b2Sweep backup = body->m_sweep;
	body->Advance(toi);
	toiContact->Update(m_contactManager.m_contactListener);
	if (toiContact->IsEnabled() == false)
	{
		// Contact disabled. Backup and recurse.
		body->m_sweep = backup;
		SolveTOI(body);
	}

	++toiContact->m_toiCount;

	// Update all the valid contacts on this body and build a contact island.
	b2Contact* contacts[b2_maxTOIContacts];
	count = 0;
	for (b2ContactEdge* ce = body->m_contactList; ce && count < b2_maxTOIContacts; ce = ce->next)
	{
		b2Body* other = ce->other;
		b2BodyType type = other->GetType();

		// Only perform correction with static bodies, so the
		// body won't get pushed out of the world.
		if (type == b2_dynamicBody)
		{
			continue;
		}

		// Check for a disabled contact.
		b2Contact* contact = ce->contact;
		if (contact->IsEnabled() == false)
		{
			continue;
		}

		b2Fixture* fixtureA = contact->m_fixtureA;
		b2Fixture* fixtureB = contact->m_fixtureB;

		// Cull sensors.
		if (fixtureA->IsSensor() || fixtureB->IsSensor())
		{
			continue;
		}

		// The contact likely has some new contact points. The listener
		// gives the user a chance to disable the contact.
		if (contact != toiContact)
		{
			contact->Update(m_contactManager.m_contactListener);
		}

		// Did the user disable the contact?
		if (contact->IsEnabled() == false)
		{
			// Skip this contact.
			continue;
		}

		if (contact->IsTouching() == false)
		{
			continue;
		}

		contacts[count] = contact;
		++count;
	}

	// Reduce the TOI body's overlap with the contact island.
	b2TOISolver solver(&m_stackAllocator);
	solver.Initialize(contacts, count, body);

	const float32 k_toiBaumgarte = 0.75f;
	bool solved = false;
	for (int32 i = 0; i < 20; ++i)
	{
		bool contactsOkay = solver.Solve(k_toiBaumgarte);
		if (contactsOkay)
		{
			solved = true;
			break;
		}
	}

	if (toiOther->GetType() != b2_staticBody)
	{
			toiContact->m_flags |= b2Contact::e_bulletHitFlag;
	}
}
  void FootstepPlanner::planCB(
    const jsk_footstep_msgs::PlanFootstepsGoal::ConstPtr& goal)
  {
    boost::mutex::scoped_lock lock(mutex_);
    latest_header_ = goal->goal_footstep.header;
    JSK_ROS_INFO("planCB");
    // check message sanity
    if (goal->initial_footstep.footsteps.size() == 0) {
      JSK_ROS_ERROR("no initial footstep is specified");
      as_.setPreempted();
      return;
    }
    if (goal->goal_footstep.footsteps.size() != 2) {
      JSK_ROS_ERROR("Need to specify 2 goal footsteps");
      as_.setPreempted();
      return;
    }
    if (use_pointcloud_model_ && !pointcloud_model_) {
      JSK_ROS_ERROR("No pointcloud model is yet available");
      as_.setPreempted();
      return;
    }
    //ros::WallDuration timeout(goal->timeout.expectedCycleTime().toSec());
    ros::WallDuration timeout(10.0);
    Eigen::Vector3f footstep_size(footstep_size_x_, footstep_size_y_, 0.000001);
    ////////////////////////////////////////////////////////////////////
    // set start state
    // 0 is always start
    Eigen::Affine3f start_pose;
    tf::poseMsgToEigen(goal->initial_footstep.footsteps[0].pose, start_pose);
    FootstepState::Ptr start(FootstepState::fromROSMsg(
                               goal->initial_footstep.footsteps[0],
                               footstep_size,
                               Eigen::Vector3f(resolution_x_,
                                               resolution_y_,
                                               resolution_theta_)));
    graph_->setStartState(start);
    if (project_start_state_) {
      if (!graph_->projectStart()) {
        JSK_ROS_ERROR("Failed to project start state");
        publishText(pub_text_,
                    "Failed to project start",
                    ERROR);

        as_.setPreempted();
        return;
      }
    }

    ////////////////////////////////////////////////////////////////////
    // set goal state
    jsk_footstep_msgs::Footstep left_goal, right_goal;
    for (size_t i = 0; i < goal->goal_footstep.footsteps.size(); i++) {
      FootstepState::Ptr goal_state(FootstepState::fromROSMsg(
                                      goal->goal_footstep.footsteps[i],
                                      footstep_size,
                                      Eigen::Vector3f(resolution_x_,
                                                      resolution_y_,
                                                      resolution_theta_)));
      if (goal_state->getLeg() == jsk_footstep_msgs::Footstep::LEFT) {
        graph_->setLeftGoalState(goal_state);
        left_goal = goal->goal_footstep.footsteps[i];
      }
      else if (goal_state->getLeg() == jsk_footstep_msgs::Footstep::RIGHT) {
        graph_->setRightGoalState(goal_state);
        right_goal = goal->goal_footstep.footsteps[i];
      }
      else {
        JSK_ROS_ERROR("unknown goal leg");
        as_.setPreempted();
        return;
      }
    }
    if (project_goal_state_) {
      if (!graph_->projectGoal()) {
        JSK_ROS_ERROR("Failed to project goal");
        as_.setPreempted();
        publishText(pub_text_,
                    "Failed to project goal",
                    ERROR);
        return;
      }
    }
    // set parameters
    if (use_transition_limit_) {
      graph_->setTransitionLimit(
        TransitionLimitXYZRPY::Ptr(new TransitionLimitXYZRPY(
                                     transition_limit_x_,
                                     transition_limit_y_,
                                     transition_limit_z_,
                                     transition_limit_roll_,
                                     transition_limit_pitch_,
                                     transition_limit_yaw_)));
    }
    else {
      graph_->setTransitionLimit(TransitionLimitXYZRPY::Ptr());
    }
    graph_->setLocalXMovement(local_move_x_);
    graph_->setLocalYMovement(local_move_y_);
    graph_->setLocalThetaMovement(local_move_theta_);
    graph_->setLocalXMovementNum(local_move_x_num_);
    graph_->setLocalYMovementNum(local_move_y_num_);
    graph_->setLocalThetaMovementNum(local_move_theta_num_);
    graph_->setPlaneEstimationMaxIterations(plane_estimation_max_iterations_);
    graph_->setPlaneEstimationMinInliers(plane_estimation_min_inliers_);
    graph_->setPlaneEstimationOutlierThreshold(plane_estimation_outlier_threshold_);
    graph_->setSupportCheckXSampling(support_check_x_sampling_);
    graph_->setSupportCheckYSampling(support_check_y_sampling_);
    graph_->setSupportCheckVertexNeighborThreshold(support_check_vertex_neighbor_threshold_);
    // Solver setup
    FootstepAStarSolver<FootstepGraph> solver(graph_,
                                              close_list_x_num_,
                                              close_list_y_num_,
                                              close_list_theta_num_,
                                              profile_period_,
                                              cost_weight_,
                                              heuristic_weight_);
    if (heuristic_ == "step_cost") {
      solver.setHeuristic(boost::bind(&FootstepPlanner::stepCostHeuristic, this, _1, _2));
    }
    else if (heuristic_ == "zero") {
      solver.setHeuristic(boost::bind(&FootstepPlanner::zeroHeuristic, this, _1, _2));
    }
    else if (heuristic_ == "straight") {
      solver.setHeuristic(boost::bind(&FootstepPlanner::straightHeuristic, this, _1, _2));
    }
    else if (heuristic_ == "straight_rotation") {
      solver.setHeuristic(boost::bind(&FootstepPlanner::straightRotationHeuristic, this, _1, _2));
    }
    else {
      JSK_ROS_ERROR("Unknown heuristics");
      as_.setPreempted();
      return;
    }
    solver.setProfileFunction(boost::bind(&FootstepPlanner::profile, this, _1, _2));
    ros::WallTime start_time = ros::WallTime::now();
    std::vector<SolverNode<FootstepState, FootstepGraph>::Ptr> path = solver.solve(timeout);
    ros::WallTime end_time = ros::WallTime::now();
    double planning_duration = (end_time - start_time).toSec();
    JSK_ROS_INFO_STREAM("took " << planning_duration << " sec");
    JSK_ROS_INFO_STREAM("path: " << path.size());
    if (path.size() == 0) {
      JSK_ROS_ERROR("Failed to plan path");
      publishText(pub_text_,
                  "Failed to plan",
                  ERROR);
      as_.setPreempted();
      return;
    }
    // Convert path to FootstepArray
    jsk_footstep_msgs::FootstepArray ros_path;
    ros_path.header = goal->goal_footstep.header;
    for (size_t i = 0; i < path.size(); i++) {
      ros_path.footsteps.push_back(*path[i]->getState()->toROSMsg());
    }
    // finalize path
    if (path[path.size() - 1]->getState()->getLeg() == jsk_footstep_msgs::Footstep::LEFT) {
      ros_path.footsteps.push_back(right_goal);
      ros_path.footsteps.push_back(left_goal);
    }
    else if (path[path.size() - 1]->getState()->getLeg() == jsk_footstep_msgs::Footstep::RIGHT) {
      ros_path.footsteps.push_back(left_goal);
      ros_path.footsteps.push_back(right_goal);
    }
    result_.result = ros_path;
    as_.setSucceeded(result_);

    pcl::PointCloud<pcl::PointNormal> close_list_cloud, open_list_cloud;
    solver.openListToPointCloud(open_list_cloud);
    solver.closeListToPointCloud(close_list_cloud);
    publishPointCloud(close_list_cloud, pub_close_list_, goal->goal_footstep.header);
    publishPointCloud(open_list_cloud, pub_open_list_, goal->goal_footstep.header);
    publishText(pub_text_,
                (boost::format("Planning took %f sec\n%lu path\nopen list: %lu\nclose list:%lu")
                 % planning_duration % path.size()
                 % open_list_cloud.points.size()
                 % close_list_cloud.points.size()).str(),
                OK);
  }
    /* In the first test we use INCOMPRESSIBLE nonlinear elasticity. For incompressible elasticity, there
     * is a constraint on the deformation, which results in a pressure field (a Lagrange multiplier)
     * which is solved for together with the deformation.
     *
     * All the mechanics solvers solve for the deformation using the finite element method with QUADRATIC
     * basis functions for the deformation. This necessitates the use of a `QuadraticMesh` - such meshes have
     * extra nodes that aren't vertices of elements, in this case midway along each edge. (The displacement
     * is solved for at ''each node'' in the mesh (including internal [non-vertex] nodes), whereas the pressure
     * is only solved for at each vertex - in FEM terms, quadratic interpolation for displacement, linear
     * interpolation for pressure, which is required for stability. The pressure at internal nodes is computed
     * by linear interpolation).
     *
     */
    void TestSimpleIncompressibleProblem() throw(Exception)
    {
        /* First, define the geometry. This should be specified using the `QuadraticMesh` class, which inherits from `TetrahedralMesh`
         * and has mostly the same interface. Here we define a 0.8 by 1 rectangle, with elements 0.1 wide.
         * (`QuadraticMesh`s can also be read in using `TrianglesMeshReader`; see next tutorial/rest of code base for examples of this).
         */
        QuadraticMesh<2> mesh;
        mesh.ConstructRegularSlabMesh(0.1 /*stepsize*/, 0.8 /*width*/, 1.0 /*height*/);

        /* We use a Mooney-Rivlin material law, which applies to isotropic materials and has two parameters.
         * Restricted to 2D however, it only has one parameter, which can be thought of as the total
         * stiffness. We declare a Mooney-Rivlin law, setting the parameter to 1.
         */
        MooneyRivlinMaterialLaw<2> law(1.0);

        /* Next, the body force density. In realistic problems this will either be
         * acceleration due to gravity (ie b=(0,-9.81)) or zero if the effect of gravity can be neglected.
         * In this problem we apply a gravity-like downward force.
         */
        c_vector<double,2> body_force;
        body_force(0) =  0.0;
        body_force(1) = -2.0;


        /* Two types of boundary condition are required: displacement and traction. As with the other PDE solvers,
         * the displacement (Dirichlet) boundary conditions are specified at nodes, whereas traction (Neumann) boundary
         * conditions are specified on boundary elements.
         *
         * In this test we apply displacement boundary conditions on one surface of the mesh, the upper (Y=1.0) surface.
         * We are going to specify zero-displacement at these nodes.
         * We do not specify any traction boundary conditions, which means that (effectively) zero-traction boundary
         * conditions (ie zero pressures) are applied on the three other surfaces.
         *
         * We need to get a `std::vector` of all the node indices that we want to fix. The `NonlinearElasticityTools`
         * has a static method for helping do this: the following gets all the nodes for which Y=1.0. The second
         * argument (the '1') indicates Y . (So, for example, `GetNodesByComponentValue(mesh, 0, 10)` would get the nodes on X=10).
         */
        std::vector<unsigned> fixed_nodes = NonlinearElasticityTools<2>::GetNodesByComponentValue(mesh, 1, 1.0);

        /*
         * Before creating the solver we create a `SolidMechanicsProblemDefinition` object,  which contains
         * everything that defines the problem: mesh, material law, body force,
         * the fixed nodes and their locations, any traction boundary conditions, and the density
         * (which multiplies the body force, otherwise isn't used).
         */
        SolidMechanicsProblemDefinition<2> problem_defn(mesh);

        /* Set the material problem on the problem definition object, saying that the problem, and
         * the material law, is incompressible. All material law files can be found in
         * `continuum_mechanics/src/problem/material_laws`. */
        problem_defn.SetMaterialLaw(INCOMPRESSIBLE,&law);

        /* Set the fixed nodes, choosing zero displacement for these nodes (see later for how
         * to provide locations for the fixed nodes). */
        problem_defn.SetZeroDisplacementNodes(fixed_nodes);
        /* Set the body force and the density. (Note that the second line isn't technically
         * needed, as internally the density is initialised to 1)
         */
        problem_defn.SetBodyForce(body_force);
        problem_defn.SetDensity(1.0);

        /* Now we create the (incompressible) solver, passing in the mesh, problem definition
         * and output directory
         */
        IncompressibleNonlinearElasticitySolver<2> solver(mesh,
                                                          problem_defn,
                                                          "SimpleIncompressibleElasticityTutorial");

        /* .. and to compute the solution, just call `Solve()` */
        solver.Solve();


        /* '''Visualisation'''. Go to the folder `SimpleIncompressibleElasticityTutorial` in your test-output directory.
         * There should be 2 files, initial.nodes and solution.nodes. These are the original nodal positions and the deformed
         * positions. Each file has two columns, the x and y locations of each node. To visualise the solution in say
         * Matlab or Octave, you could do: `x=load('solution.nodes'); plot(x(:,1),x(:,2),'k*')`. For Cmgui output, see below.
         *
         * To get the actual solution from the solver, use these two methods. Note that the first
         * gets the deformed position (ie the new location, not the displacement). They are both of size
         * num_total_nodes.
         */
        std::vector<c_vector<double,2> >& r_deformed_positions = solver.rGetDeformedPosition();
        std::vector<double>& r_pressures = solver.rGetPressures();
        /* Let us obtain the values of the new position, and the pressure, at the bottom right corner node. */
        unsigned node_index = 8;
        assert( fabs(mesh.GetNode(node_index)->rGetLocation()[0] - 0.8) < 1e-6); // check that X=0.8, ie that we have the correct node,
        assert( fabs(mesh.GetNode(node_index)->rGetLocation()[1] - 0.0) < 1e-6); // check that Y=0.0, ie that we have the correct node,
        std::cout << "New position: " << r_deformed_positions[node_index](0) << " " << r_deformed_positions[node_index](1) << "\n";
        std::cout << "Pressure: " << r_pressures[node_index] << "\n";

        /* HOW_TO_TAG Continuum mechanics
         * Visualise nonlinear elasticity problems solutions, including visualisng strains
         */

        /* One visualiser is Cmgui. This method can be used to convert all the output files to Cmgui format.
         * They are placed in `[OUTPUT_DIRECTORY]/cmgui`. A script is created to easily load the data: in a
         * terminal cd to this directory and call `cmgui LoadSolutions.com`. (In this directory, the initial position is given by
         * solution_0.exnode, the deformed by solution_1.exnode).
         */
        solver.CreateCmguiOutput();

        /* The recommended visualiser is Paraview, for which Chaste must be installed with VTK. With paraview, strains (and in the future
         * stresses) can be visualised on the undeformed/deformed geometry). We can create VTK output using
         * the `VtkNonlinearElasticitySolutionWriter` class. The undeformed geometry, solution displacement, and pressure (if incompressible
         * problem) are written to file, and below we also choose to write the deformation tensor C for each element.
         */
        VtkNonlinearElasticitySolutionWriter<2> vtk_writer(solver);
        vtk_writer.SetWriteElementWiseStrains(DEFORMATION_TENSOR_C); // other options are DEFORMATION_GRADIENT_F and LAGRANGE_STRAIN_E
        vtk_writer.Write();


        /* These are just to check that nothing has been accidentally changed in this test.
         * Newton's method (with damping) was used to solve the nonlinear problem, and we check that
         * 4 iterations were needed to converge.
         */
        TS_ASSERT_DELTA(r_deformed_positions[node_index](0),  0.7980, 1e-3);
        TS_ASSERT_DELTA(r_deformed_positions[node_index](1), -0.1129, 1e-3);
        TS_ASSERT_EQUALS(solver.GetNumNewtonIterations(), 4u);
    }
    /* == Incompressible deformation: 2D shape hanging under gravity with a balancing traction ==
     *
     * We now repeat the above test but include a traction on the bottom surface (Y=0). We apply this
     * in the inward direction so that is counters (somewhat) the effect of gravity. We also show how stresses
     * and strains can be written to file.
     */
    void TestIncompressibleProblemWithTractions() throw(Exception)
    {
        /* All of this is exactly as above */
        QuadraticMesh<2> mesh;
        mesh.ConstructRegularSlabMesh(0.1 /*stepsize*/, 0.8 /*width*/, 1.0 /*height*/);

        MooneyRivlinMaterialLaw<2> law(1.0);

        c_vector<double,2> body_force;
        body_force(0) =  0.0;
        body_force(1) = -2.0;

        std::vector<unsigned> fixed_nodes = NonlinearElasticityTools<2>::GetNodesByComponentValue(mesh, 1, 1.0);

        /* Now the traction boundary conditions. We need to collect all the boundary elements on the surface which we want to
         * apply non-zero tractions, put them in a `std::vector`, and create a corresponding `std::vector` of the tractions
         * for each of the boundary elements. Note that the each traction is a 2D vector with dimensions of pressure.
         *
         * First, declare the data structures:
         */
        std::vector<BoundaryElement<1,2>*> boundary_elems;
        std::vector<c_vector<double,2> > tractions;
        /* Create a constant traction */
        c_vector<double,2> traction;
        traction(0) = 0;
        traction(1) = 1.0; // this choice of sign corresponds to an inward force (if applied to the bottom surface)
        /* Loop over boundary elements */
        for (TetrahedralMesh<2,2>::BoundaryElementIterator iter = mesh.GetBoundaryElementIteratorBegin();
             iter != mesh.GetBoundaryElementIteratorEnd();
             ++iter)
        {
            /* If the centre of the element has Y value of 0.0, it is on the surface we need */
            if (fabs((*iter)->CalculateCentroid()[1] - 0.0) < 1e-6)
            {
                /* Put the boundary element and the constant traction into the stores. */
                BoundaryElement<1,2>* p_element = *iter;
                boundary_elems.push_back(p_element);
                tractions.push_back(traction);
            }
        }
        /* A quick check */
        assert(boundary_elems.size() == 8u);

        /* Now create the problem definition object, setting the material law, fixed nodes and body force as
         * before (this time not calling `SetDensity()`, so using the default density of 1.0,
         * and also calling a method for setting tractions, which takes in the boundary elements
         * and tractions for each of those elements.
         */
        SolidMechanicsProblemDefinition<2> problem_defn(mesh);
        problem_defn.SetMaterialLaw(INCOMPRESSIBLE,&law);
        problem_defn.SetZeroDisplacementNodes(fixed_nodes);
        problem_defn.SetBodyForce(body_force);
        problem_defn.SetTractionBoundaryConditions(boundary_elems, tractions);

        /* Create solver as before */
        IncompressibleNonlinearElasticitySolver<2> solver(mesh,
                                                          problem_defn,
                                                          "IncompressibleElasticityWithTractionsTutorial");

        /* In this test we also output the stress and strain. For the former, we have to tell the solver to store
         * the stresses that are computed during the solve.
         */
        solver.SetComputeAverageStressPerElementDuringSolve();


        /* Call `Solve()` */
        solver.Solve();

        /* If VTK output is written (discussed above) strains can be visualised. Alternatively, we can create text files
         * for strains and stresses by doing the following.
         *
         * Write the final deformation gradients to file. The i-th line of this file provides the deformation gradient F,
         * written as 'F(0,0) F(0,1) F(1,0) F(1,1)', evaluated at the centroid of the i-th element. The first variable
         * can also be DEFORMATION_TENSOR_C or LAGRANGE_STRAIN_E to write C or E. The second parameter is the file name.
         */
        solver.WriteCurrentStrains(DEFORMATION_GRADIENT_F,"deformation_grad");

        /* Since we called `SetComputeAverageStressPerElementDuringSolve`, we can write the stresses to file too. However,
         * note that for each element this is not the stress evaluated at the centroid, but the mean average of the stresses
         * evaluated at the quadrature points - for technical cardiac electromechanics reasons, it is difficult to
         * define the stress at non-quadrature points.
         */
        solver.WriteCurrentAverageElementStresses("2nd_PK_stress");


        /* Another quick check */
        TS_ASSERT_EQUALS(solver.GetNumNewtonIterations(), 4u);

        /* Visualise as before by going to the output directory and doing
         * `x=load('solution.nodes'); plot(x(:,1),x(:,2),'m*')` in Matlab/octave, or by using Cmgui.
         * The effect of the traction should be clear (especially when compared to
         * the results of the first test).
         *
         * Create Cmgui output
         */
        solver.CreateCmguiOutput();

        /* This is just to check that nothing has been accidentally changed in this test */
        TS_ASSERT_DELTA(solver.rGetDeformedPosition()[8](0), 0.8561, 1e-3);
        TS_ASSERT_DELTA(solver.rGetDeformedPosition()[8](1), 0.0310, 1e-3);
    }
Example #12
0
/** Compute the elastic (large!) deformation of a block of material.
 *  See problem description in ref06::PulledSheetProblem for a the boundary
 *  conditions. The problem is non-linear and therefore a Newton method is
 *  used. Moreover, the applied load (displacement or traction) is divided into
 *  load steps.
 *
 *  New features:
 *  - vectorial problem: DoFs are not scalar anymore
 *  - hyper-elasticity
 *
 */
int ref06::compressible( int argc, char * argv[] )
{
    // basic attributes of the computation
    const unsigned    geomDeg  = 1;
    const unsigned    fieldDeg = 2;
    const base::Shape shape    = base::HyperCubeShape<SPACEDIM>::value;

    // typedef mat::hypel::StVenant Material;
    typedef mat::hypel::NeoHookeanCompressible Material;

    // usage message
    if ( argc != 3 ) {
        std::cout << "Usage:  " << argv[0] << "  mesh.smf input.dat \n";
        return 0;
    }

    // read name of input file
    const std::string meshFile  = boost::lexical_cast<std::string>( argv[1] );
    const std::string inputFile = boost::lexical_cast<std::string>( argv[2] );

    // read from input file
    double E, nu, pull, traction, tolerance;
    unsigned maxIter, loadSteps;
    bool dispControlled;
    {    
        //Feed properties parser with the variables to be read
        base::io::PropertiesParser prop;
        prop.registerPropertiesVar( "E",                E );
        prop.registerPropertiesVar( "nu",               nu );
        prop.registerPropertiesVar( "pull",             pull );
        prop.registerPropertiesVar( "maxIter",          maxIter );
        prop.registerPropertiesVar( "loadSteps",        loadSteps );
        prop.registerPropertiesVar( "traction",         traction );
        prop.registerPropertiesVar( "dispControlled",   dispControlled );
        prop.registerPropertiesVar( "tolerance",        tolerance );

        // Read variables from the input file
        std::ifstream inp( inputFile.c_str()  );
        VERIFY_MSG( inp.is_open(), "Cannot open input file" );
        prop.readValues( inp );
        inp.close( );

        // Make sure all variables have been found
        if ( not prop.isEverythingRead() ) {
            prop.writeUnread( std::cerr );
            VERIFY_MSG( false, "Could not find above variables" );
        }
    }

    // find base name from mesh file
    const std::string baseName = base::io::baseName( meshFile, ".smf" );

    //--------------------------------------------------------------------------
    // define a mesh
    typedef base::Unstructured<shape,geomDeg>    Mesh;
    const unsigned dim = Mesh::Node::dim;

    // create a mesh and read from input
    Mesh mesh;
    {
        std::ifstream smf( meshFile.c_str() );
        base::io::smf::readMesh( smf, mesh );
        smf.close();
    }

    // quadrature objects for volume and surface
    const unsigned kernelDegEstimate = 3;
    typedef base::Quadrature<kernelDegEstimate,shape> Quadrature;
    Quadrature quadrature;
    typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature;
    SurfaceQuadrature surfaceQuadrature;

    // Create a field
    const unsigned    doFSize = dim;
    typedef base::fe::Basis<shape,fieldDeg>        FEBasis;
    typedef base::Field<FEBasis,doFSize>           Field;
    typedef Field::DegreeOfFreedom                 DoF;
    Field field;

    // generate DoFs from mesh
    base::dof::generate<FEBasis>( mesh, field );

    // Creates a list of <Element,faceNo> pairs along the boundary
    base::mesh::MeshBoundary meshBoundary;
    meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

    // Create a boundary mesh from this list
    typedef base::mesh::BoundaryMeshBinder<Mesh::Element>::Type BoundaryMesh;
    BoundaryMesh boundaryMesh;
    {
        // Create a real mesh object from this list
        base::mesh::generateBoundaryMesh( meshBoundary.begin(),
                                          meshBoundary.end(),
                                          mesh, boundaryMesh );
    }

    // initial pull = (total amount) / (number of steps)
    const double firstPull = pull / static_cast<double>( loadSteps );

    // constrain the boundary
    base::dof::constrainBoundary<FEBasis>( meshBoundary.begin(),
                                           meshBoundary.end(),
                                           mesh, field, 
                                           boost::bind(
                                               &ref06::PulledSheet<dim>::dirichletBC<DoF>,
                                               _1, _2, dispControlled, firstPull ) );

    // Bind the fields together
    typedef base::asmb::FieldBinder<Mesh,Field> FieldBinder;
    FieldBinder fieldBinder( mesh, field );
    typedef FieldBinder::TupleBinder<1,1>::Type FTB;

    typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Field> SurfaceFieldBinder;
    SurfaceFieldBinder surfaceFieldBinder( boundaryMesh, field );
    typedef SurfaceFieldBinder::TupleBinder<1>::Type SFTB;

    // material object
    Material material( mat::Lame::lambda( E, nu), mat::Lame::mu( E, nu ) );

    // matrix kernel
    typedef solid::HyperElastic<Material,FTB::Tuple> HyperElastic;
    HyperElastic hyperElastic( material );
            
    // Number the degrees of freedom
    const std::size_t numDofs =
        base::dof::numberDoFsConsecutively( field.doFsBegin(), field.doFsEnd() );
    std::cout << "# Number of dofs " << numDofs << std::endl;

    // create table for writing the convergence behaviour of the nonlinear solves
    base::io::Table<4>::WidthArray widths = {{ 2, 5, 5, 15 }};
    base::io::Table<4> table( widths );
    table % "Step" % "Iter" % "|F|"  % "|x|";
    std::cout << "#" << table;

    // write a vtk file
    ref06::writeVTKFile( baseName, 0, mesh, field, material );


    //--------------------------------------------------------------------------
    // Loop over load steps
    //--------------------------------------------------------------------------
    for ( unsigned step = 0; step < loadSteps; step++ ) {

        // rescale constraints in every load step: (newValue / oldValue)
        const double  pullFactor =
            (step == 0 ?
             static_cast<double>( step+1 ) :
             static_cast<double>( step+1 )/ static_cast<double>(step) );

        // scale constraints
        base::dof::scaleConstraints( field, pullFactor );

        //----------------------------------------------------------------------
        // Nonlinear iterations
        //----------------------------------------------------------------------
        unsigned iter = 0;
        while ( iter < maxIter ) {

            table % step % iter;
    
            // Create a solver object
            typedef base::solver::Eigen3           Solver;
            Solver solver( numDofs );

            // apply traction boundary condition, if problem is not disp controlled
            if ( not dispControlled ) {
                
                // value of applied traction
                const double tractionFactor =
                    traction * 
                    static_cast<double>(step+1) / static_cast<double>( loadSteps );

                // apply traction load
                base::asmb::neumannForceComputation<SFTB>(
                    surfaceQuadrature, solver,
                    surfaceFieldBinder,
                    boost::bind( &ref06::PulledSheet<dim>::neumannBC,
                                 _1, _2, tractionFactor ) );
            }

            // residual forces
            base::asmb::computeResidualForces<FTB>( quadrature, solver,
                                                    fieldBinder,
                                                    hyperElastic );
            
            // Compute element stiffness matrices and assemble them
            base::asmb::stiffnessMatrixComputation<FTB>( quadrature, solver,
                                                         fieldBinder,
                                                         hyperElastic );

            // Finalise assembly
            solver.finishAssembly();

            // norm of residual 
            const double conv1 = solver.norm();
            table % conv1;

            // convergence via residual norm
            if ( conv1 < tolerance * E ) { // note the tolerance multiplier
                std::cout << table;
                break;
            }

            // Solve
            //solver.choleskySolve();
            solver.cgSolve();
            
            // distribute results back to dofs
            base::dof::addToDoFsFromSolver( solver, field );

            // norm of displacement increment
            const double conv2 = solver.norm();
            table % conv2;
            std::cout << table;
            iter++;
            
            // convergence via increment
            if ( conv2 < tolerance ) break;
        }
        // Finished non-linear iterations
        //----------------------------------------------------------------------

        // warning
        if ( iter == maxIter ) {
            std::cout << "# (WW) Step " << step << " has not converged within "
                      << maxIter << " iterations \n";
        }

        // write a vtk file
        ref06::writeVTKFile( baseName, step+1, mesh, field, material );
        
    }
    // Finished load steps
    //--------------------------------------------------------------------------
    
    return 0;
}
Example #13
0
const Vector<T> PDESolver<T,lFunc,rFunc,bFunc,tFunc,force>::solve() const
{
  U solver;
  return solver(m_A,m_B);
}
Example #14
0
int main(int argc, char **args) 
{
  // Test variable.
  int success_test = 1;

  if (argc < 2) error("Not enough parameters.");

  // Load the mesh.
	Mesh mesh;
  H3DReader mloader;
  if (!mloader.load(args[1], &mesh)) error("Loading mesh file '%s'.", args[1]);

	// Initialize the space.
	int mx = 2;
	Ord3 order(mx, mx, mx);
	H1Space space(&mesh, bc_types, NULL, order);
#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
	space.set_essential_bc_values(essential_bc_values);
#endif
	// Initialize the weak formulation.
	WeakForm wf;
	wf.add_vector_form(form_0<double, scalar>, form_0<Ord, Ord>);
#if defined LIN_NEUMANN || defined LIN_NEWTON
	wf.add_vector_form_surf(form_0_surf<double, scalar>, form_0_surf<Ord, Ord>);
#endif
#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
	// preconditioner
	wf.add_matrix_form(precond_0_0<double, scalar>, precond_0_0<Ord, Ord>, HERMES_SYM);
#endif

	// Initialize the FE problem.
	DiscreteProblem fep(&wf, &space);

#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
	// use ML preconditioner to speed-up things
	MlPrecond pc("sa");
	pc.set_param("max levels", 6);
	pc.set_param("increasing or decreasing", "decreasing");
	pc.set_param("aggregation: type", "MIS");
	pc.set_param("coarse: type", "Amesos-KLU");
#endif

	NoxSolver solver(&fep);
#if defined LIN_DIRICHLET || defined NLN_DIRICHLET
//	solver.set_precond(&pc);
#endif

	info("Solving.");
	Solution sln(&mesh);
	if(solver.solve()) Solution::vector_to_solution(solver.get_solution(), &space, &sln);
  else error ("Matrix solver failed.\n");
	

		Solution ex_sln(&mesh);
		ex_sln.set_exact(exact_solution);

		// Calculate exact error.
  info("Calculating exact error.");
  Adapt *adaptivity = new Adapt(&space, HERMES_H1_NORM);
  bool solutions_for_adapt = false;
  double err_exact = adaptivity->calc_err_exact(&sln, &ex_sln, solutions_for_adapt, HERMES_TOTAL_ERROR_ABS);

  if (err_exact > EPS)
		// Calculated solution is not precise enough.
		success_test = 0;

  if (success_test) {
    info("Success!");
    return ERR_SUCCESS;
  }
  else {
    info("Failure!");
    return ERR_FAILURE;
  }
}
Example #15
0
bool refiner_wpt::refine_prefix(
  predicatest &predicates, 
  abstract_modelt &abstract_model,
  const fail_infot &fail_info)
{
  status("Refining set of predicates according to counterexample (WP)");

  reset_num_predicates_added();

  bool found_new=false;

  // keep track of the loops that we're in (may be nested)
  std::list<fail_infot::induction_infot> loops;
  exprt invariant;
  if(fail_info.use_invariants)
    status("Using recurrence predicates detected by loop detection.");
  
  print(10, "refiner_wpt::refine_prefix_async 1");
  
  print(10, "Inconsistent prefix:");

  for(abstract_counterexamplet::stepst::const_reverse_iterator 
      r_it=fail_info.steps.rbegin();
      r_it!=fail_info.steps.rend();
      r_it++)
  {
    std::stringstream str;

    abstract_programt::targett abstract_pc=r_it->pc;

    goto_programt::const_targett concrete_pc=
      abstract_pc->code.concrete_pc;

    if(concrete_pc->is_goto())
      str << "GUARD: " << (r_it->branch_taken?"(":"!(")
                << from_expr(concrete_model.ns, "", concrete_pc->guard) << ")";
    else if(concrete_pc->is_assert())
      str << "ASSERT: "
                << from_expr(concrete_model.ns, "", concrete_pc->guard);
    else if(concrete_pc->is_location())
      str << "LOC" << std::endl;
    else if(concrete_pc->is_other() || concrete_pc->is_assign() || concrete_pc->is_decl())
      str << from_expr(concrete_model.ns, "", concrete_pc->code);
    else
    {
      str << concrete_pc->type;
    }

    str << "  // " << (concrete_pc->location);

    str << std::endl << "**********";

    print(10, str.str());
  }

  
  {
    // get the constraint causing the failure

    exprt predicate=fail_info.guard;

    #ifdef DEBUG
    std::cout << "P start0: " 
              << from_expr(concrete_model.ns, "", predicate) << std::endl;
    #endif

    simplify(predicate, concrete_model.ns);

    abstract_counterexamplet::stepst::const_iterator 
      it=--fail_info.steps.end();

    // there must be at least two steps, or it's odd
    assert(it!=fail_info.steps.begin());

    {
      abstract_programt::targett abstract_pc=it->pc;

      #ifdef DEBUG
      std::cout << "P start1: " 
                << from_expr(concrete_model.ns, "", predicate) << std::endl;
      #endif

      add_predicates(
        abstract_pc, predicates, predicate, found_new, FROM);
    }
      
    // now do the WPs
    goto_symex_statet renaming_state;
    renaming_state.source.thread_nr=it->thread_nr;
    renaming_state.rename(predicate, concrete_model.ns, goto_symex_statet::L0);

    for(it--; // skip last instruction
        it!=fail_info.steps.begin();
        it--)
    {
      #ifdef DEBUG
      std::cout << "refiner_wpt::refine_prefix_async 2\n";
      #endif

      // handle loops 
      if(fail_info.use_invariants)
      {
        if(it->is_loop_begin())
        {
          loops.pop_back(); // pop induction_info if we leave loop
          
#ifdef DEBUG
          std::cout << "INV: "
                    << from_expr(concrete_model.ns, "", invariant) << std::endl;
#endif           
          
          exprt wp(ID_and, typet(ID_bool));
          wp.operands().resize(2);
          wp.op0().swap(invariant);
          wp.op1().swap(predicate);
          predicate.swap(wp);
        }
        else if (it->is_loop_end())
        {
          push_induction_info(fail_info, it, loops);
          invariant.make_true();
        }
      }

      if(!it->is_state())
        continue;

      if(predicate.is_true() && found_new)
      {
        // ok, refuted it, done
        break;
      }
        
      // add the predicate

      goto_programt::const_targett concrete_pc=
        it->pc->code.concrete_pc;
        
      abstract_programt::targett abstract_pc=it->pc;
        
      #ifdef DEBUG
      std::cout << from_expr(concrete_model.ns, "", predicate) << std::endl;
      #endif
      
      exprt no_tid_predicate=predicate;
      renaming_state.get_original_name(no_tid_predicate);
      add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, TO);

      // skip irrelevant instructions
      if(!it->relevant) continue;

      exprt pred_bak=predicate;
#ifdef DEBUG
      goto_programt tmp;
      tmp.output_instruction(concrete_model.ns, "", std::cerr, concrete_pc);
#endif

      // compute weakest precondition
      switch(it->pc->type)
      {
      case ASSUME:
        // we only do this for assumptions
        // if we haven't found a new predicate so far
        if(1/*!found_new*/)
        {
          exprt tid_guard=concrete_pc->guard;
          renaming_state.source.thread_nr=it->thread_nr;
          renaming_state.rename(tid_guard, concrete_model.ns, goto_symex_statet::L0);
          predicate=implies_exprt(tid_guard, predicate);
          simplify(predicate, concrete_model.ns);
        }
        break;

      case GOTO:
        {
          exprt tid_guard=concrete_pc->guard;
          if(!it->branch_taken) tid_guard.make_not();
          renaming_state.source.thread_nr=it->thread_nr;
          renaming_state.rename(tid_guard, concrete_model.ns, goto_symex_statet::L0);
          predicate=implies_exprt(tid_guard, predicate);
          simplify(predicate, concrete_model.ns);
        }
        break;

      case OTHER:
    	/* Ignore if user-specified predicate, otherwise treat like assign */
    	if(it->pc->code.concrete_pc->code.get_statement()==ID_user_specified_predicate || it->pc->code.concrete_pc->code.get_statement()==ID_user_specified_parameter_predicates || it->pc->code.concrete_pc->code.get_statement()==ID_user_specified_return_predicates)
    		break;
      case DECL:
      case ASSIGN:
        #ifdef DEBUG
        std::cout << "OTHER/ASSIGN/DECL\n";
        #endif

        {
          codet tid_tmp_code;
          if(!fail_info.use_invariants ||
             !get_instruction(concrete_pc, loops, tid_tmp_code, invariant))
            tid_tmp_code=to_code(concrete_pc->code);

#ifdef DEBUG
          std::cout << "A P before: " << from_expr(concrete_model.ns, "", predicate) << std::endl;
          std::cout << "Code:     " << from_expr(concrete_model.ns, "", tid_tmp_code) << std::endl;
#endif
          
          // compute weakest precondition
          if(tid_tmp_code.get_statement()==ID_assign)
            approximate_nondet(to_code_assign(tid_tmp_code).rhs());
          renaming_state.source.thread_nr=it->thread_nr;
          renaming_state.rename(tid_tmp_code, concrete_model.ns, goto_symex_statet::L0);
          exprt predicate_wp=wp(tid_tmp_code, predicate, concrete_model.ns);
      
          simplify(predicate_wp, concrete_model.ns);
          predicate=predicate_wp;

#ifdef DEBUG
          std::cout << "A P after:  " << from_expr(concrete_model.ns, "", predicate) << std::endl;
#endif
        }
        break;

      default:
        // ignore
        break;
      }

#ifdef DEBUG
          std::cout << "B P to-check:  " << from_expr(concrete_model.ns, "", predicate) << std::endl;
#endif
          
      if(pred_bak != predicate)
      {
        satcheckt satcheck;
        bv_pointerst solver(concrete_model.ns, satcheck);
        solver.unbounded_array=boolbvt::U_NONE;
        literalt li=make_pos(concrete_model.ns, solver, predicate);
        satcheck.set_assumptions(bvt(1, li));
        propt::resultt result=satcheck.prop_solve();
        assert(propt::P_SATISFIABLE==result || propt::P_UNSATISFIABLE==result);
        if(propt::P_UNSATISFIABLE==result)
          predicate.make_false();
        else
        {
          satcheck.set_assumptions(bvt(1, li.negation()));
          propt::resultt result=satcheck.prop_solve();
          assert(propt::P_SATISFIABLE==result || propt::P_UNSATISFIABLE==result);
          if(propt::P_UNSATISFIABLE==result)
          {
            predicate.make_true();
            if(it->pc->type==ASSIGN)
            {
              const codet &code=concrete_pc->code;
              if(code.get_statement()==ID_assign)
              {
                equal_exprt pred_new(to_code_assign(code).lhs(),
                    to_code_assign(code).rhs());
                simplify(pred_new, concrete_model.ns);
#ifdef DEBUG
                std::cout << "Adding new predicate as we arrived at TRUE: "
                  << from_expr(concrete_model.ns, "", pred_new) << std::endl;
#endif
                no_tid_predicate=pred_new;
                renaming_state.get_original_name(no_tid_predicate);
                add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, FROM);
              }
            }
            else if(it->pc->type==ASSUME || it->pc->type==GOTO)
            {
              exprt pred_new=concrete_pc->guard;
              simplify(pred_new, concrete_model.ns);
#ifdef DEBUG
              std::cout << "Adding new predicate as we arrived at TRUE: "
                << from_expr(concrete_model.ns, "", pred_new) << std::endl;
#endif
              no_tid_predicate=pred_new;
              renaming_state.get_original_name(no_tid_predicate);
              add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, FROM);
            }
          }
        }
      }
      
      #ifdef DEBUG
      std::cout << "B P after:   " << from_expr(concrete_model.ns, "", predicate) << std::endl;
      #endif

      no_tid_predicate=predicate;
      renaming_state.get_original_name(no_tid_predicate);
      add_predicates(abstract_pc, predicates, no_tid_predicate, found_new, FROM);
    }

    if(!predicate.is_true() && fail_info.warn_on_failure)
    {
      warning("Failed to refute spurious trace with WPs (got "+
              from_expr(concrete_model.ns, "", predicate)+")");
    }
  }

  if(found_new && fail_info.use_invariants)
  {
    add_induction_predicates(
      fail_info,
      abstract_model,
      predicates);
  }
  
  // make sure we have progress
  return !found_new;
}
/*!
  \internal
  Minimize the original objective.
*/
qreal QSimplex::solveMin()
{
    return solver(Minimum);
}
int Benchmark(ToolParam &tool_param, CommonSettings &settings) {

  BenchmarkParam benchmark_param = tool_param.benchmark(settings.param_index);
  TrainParam train_param = tool_param.train(
      benchmark_param.has_train_index() ? benchmark_param.train_index() : 0);
  ProcessParam process_param = tool_param.process(
      benchmark_param.has_process_index() ?
          benchmark_param.process_index() : 0);

  int warmup_runs =
      benchmark_param.has_warmup_runs() ? benchmark_param.warmup_runs() : 0;
  int bench_runs =
      benchmark_param.has_bench_runs() ? benchmark_param.bench_runs() : 1;

  if (!benchmark_param.has_output()) {
    LOG(FATAL)<< "Missing output path for benchmarking.";

  }

  double tmp_time = 0;

  // Create output directories
  bofs::path benchpath(benchmark_param.output());
  bofs::create_directories(benchpath);

  std::string proto_solver = train_param.solver();
  std::string process_net = process_param.process_net();

  std::chrono::time_point<std::chrono::high_resolution_clock> t_start, t_end;

  // Benchmark block 1: Training Net
  if (benchmark_param.has_train_index()) {
    caffe::SolverParameter solver_param;
    caffe::ReadProtoFromTextFileOrDie(proto_solver, &solver_param);
    shared_ptr<caffe::Solver<float> > solver(
        caffe::GetSolver<float>(solver_param));
    boost::shared_ptr<caffe::Net<float>> net = solver->net();
    net->layers()[0]->device_context()->ResetPeakMemoryUsage();

    std::vector<double> layer_forward_times(net->layers().size());
    std::vector<double> layer_backward_times(net->layers().size());

    double total_forward_time = 0;
    double total_backward_time = 0;

    for (int run = 0; run < warmup_runs + bench_runs; ++run) {
      FillNet(net->layers()[1], net->layers()[0], train_param.input().labels());

      tmp_time = 0;

      // Benchmark 1: Layer wise measurements (forward)
      for (int l = 0; l < net->layers().size(); ++l) {
        t_start = std::chrono::high_resolution_clock::now();
        net->ForwardFromTo(l, l);
        Caffe::Synchronize(net->layers()[l]->device_context()->id());
        t_end = std::chrono::high_resolution_clock::now();
        tmp_time += (t_end - t_start).count();
        if (run >= warmup_runs) {
          layer_forward_times[l] += (t_end - t_start).count();
        }
      }
      LOG(INFO) << "Forward pass: " << std::setprecision(10)
          << (tmp_time)/((double)1e6) << " ms";

      tmp_time = 0;

      // Benchmark 2: Layer wise measurements (backward)
      for (int l = net->layers().size() - 1; l >= 0; --l) {
        t_start = std::chrono::high_resolution_clock::now();
        net->BackwardFromTo(l, l);
        Caffe::Synchronize(net->layers()[l]->device_context()->id());
        t_end = std::chrono::high_resolution_clock::now();
        tmp_time += (t_end - t_start).count();
        if (run >= warmup_runs) {
          layer_backward_times[l] += (t_end - t_start).count();
        }
      }
      LOG(INFO) << "Backward pass: " << std::setprecision(10)
          << (tmp_time)/((double)1e6) << " ms";

    }

    for (int run = 0; run < warmup_runs + bench_runs; ++run) {
      FillNet(net->layers()[1], net->layers()[0], train_param.input().labels());

      // Benchmark 3: Whole forward pass
      t_start = std::chrono::high_resolution_clock::now();
      net->ForwardPrefilled();
      Caffe::Synchronize(
          net->layers()[net->layers().size() - 1]->device_context()->id());
      t_end = std::chrono::high_resolution_clock::now();
      LOG(INFO) << "Forward pass: " << std::setprecision(10)
          << (double)((t_end - t_start).count())/((double)1e6) << " ms";
      if (run >= warmup_runs) {
        total_forward_time += (t_end - t_start).count();
      }

      // Benchmark 4: Whole backward pass
      t_start = std::chrono::high_resolution_clock::now();
      net->Backward();
      Caffe::Synchronize(net->layers()[0]->device_context()->id());
      t_end = std::chrono::high_resolution_clock::now();
      LOG(INFO) << "Backward pass: " << std::setprecision(10)
          << (double)((t_end - t_start).count())/((double)1e6) << " ms";
      if (run >= warmup_runs) {
        total_backward_time += (t_end - t_start).count();
      }
    }

    // Write outputs
    std::vector<std::string> layers = net->layer_names();

    {
      bofs::path filep = benchpath;
      filep /= ("/train_forward_layers_timings.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());
      for (int l = 0; l < net->layers().size(); ++l) {
        out_file << l << ";" << layers[l] << ";"
                 << std::setprecision(10)
                 << layer_forward_times[l] / ((double) bench_runs * 1e6)
                 << std::endl;
      }
      out_file.close();
    }

    {
      bofs::path filep = benchpath;
      filep /= ("/train_backward_layers_timings.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());
      for (int l = 0; l < net->layers().size(); ++l) {
        out_file << l << ";" << layers[l] << ";"
                 << std::setprecision(10)
                 << layer_backward_times[l] / ((double) bench_runs * 1e6)
                 << std::endl;
      }
      out_file.close();
    }

    {
      bofs::path filep = benchpath;
      filep /= ("/train_total_timings.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());

      out_file << "Forward;" << std::setprecision(10)
               << total_forward_time / ((double) bench_runs * 1e6)
               << std::endl;

      out_file << "Backward;" << std::setprecision(10)
               << total_backward_time / ((double) bench_runs * 1e6)
               << std::endl;
      out_file.close();
    }

    {
      bofs::path filep = benchpath;
      filep /= ("/train_memory_usage.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());

      out_file << "Peak memory usage;"
          << net->layers()[0]->device_context()->peak_memory_usage()
          << std::endl;
      out_file.close();
    }

  }

  // Benchmark block 2: Processing Net
  if (benchmark_param.has_process_index()) {
    Net<float> net(process_net, caffe::TEST);
    net.layers()[0]->device_context()->ResetPeakMemoryUsage();

    std::vector<double> layer_forward_times(net.layers().size());
    double total_forward_time = 0;

    // Benchmark 1: Layer wise measurements (forward)
    for (int run = 0; run < warmup_runs + bench_runs; ++run) {
      FillNet(net.layers()[0], NULL, train_param.input().labels());

      tmp_time = 0;
      // Benchmark 1: Layer wise measurements (forward)
      for (int l = 0; l < net.layers().size(); ++l) {
        t_start = std::chrono::high_resolution_clock::now();
        net.ForwardFromTo(l, l);
        Caffe::Synchronize(net.layers()[l]->device_context()->id());
        t_end = std::chrono::high_resolution_clock::now();
        tmp_time += (t_end - t_start).count();
        if (run >= warmup_runs) {
          layer_forward_times[l] += (t_end - t_start).count();
        }
      }
      LOG(INFO) << "Forward pass: " << std::setprecision(10)
          << (tmp_time)/((double)1e6) << " ms";
    }

    // Benchmark 2: Whole forward pass
    for (int run = 0; run < warmup_runs + bench_runs; ++run) {
      FillNet(net.layers()[0], NULL, train_param.input().labels());
      t_start = std::chrono::high_resolution_clock::now();
      net.ForwardPrefilled();
      Caffe::Synchronize(
          net.layers()[net.layers().size() - 1]->device_context()->id());
      t_end = std::chrono::high_resolution_clock::now();
      LOG(INFO) << "Forward pass: " << std::setprecision(10)
          << (double)((t_end - t_start).count())/((double)1e6) << " ms";
      if (run >= warmup_runs) {
        total_forward_time += (t_end - t_start).count();
      }
    }

    // Write outputs
    std::vector<std::string> layers = net.layer_names();

    {
      bofs::path filep = benchpath;
      filep /= ("/process_forward_layers_timings.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());
      for (int l = 0; l < net.layers().size(); ++l) {
        out_file << l << ";" << layers[l] << ";"
                 << std::setprecision(10)
                 << layer_forward_times[l] / ((double) bench_runs * 1e6)
                 << std::endl;
      }
      out_file.close();
    }

    {
      bofs::path filep = benchpath;
      filep /= ("/process_total_timings.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());

      out_file << "Forward;" << std::setprecision(10)
               << total_forward_time / ((double) bench_runs * 1e6)
               << std::endl;
      out_file.close();
    }

    {
      bofs::path filep = benchpath;
      filep /= ("/process_memory_usage.csv");

      std::ofstream out_file;
      out_file.open(filep.string());
      assert(out_file.is_open());

      out_file << "Peak memory usage;"
          << net.layers()[0]->device_context()->peak_memory_usage()
          << std::endl;
      out_file.close();
    }
  }

  return 0;
}
/*!
  \internal
  Maximize the original objective.
*/
qreal QSimplex::solveMax()
{
    return solver(Maximum);
}
bool strategy_solver_binsearcht::iterate(invariantt &_inv)
{
  tpolyhedra_domaint::templ_valuet &inv=
    static_cast<tpolyhedra_domaint::templ_valuet &>(_inv);

  bool improved=false;

  solver.new_context(); // for improvement check

  exprt inv_expr=tpolyhedra_domain.to_pre_constraints(inv);

#if 0
  debug() << "improvement check: " << eom;
  debug() << "pre-inv: " << from_expr(ns, "", inv_expr) << eom;
#endif

  solver << inv_expr;

  exprt::operandst strategy_cond_exprs;
  tpolyhedra_domain.make_not_post_constraints(
    inv, strategy_cond_exprs, strategy_value_exprs);

  strategy_cond_literals.resize(strategy_cond_exprs.size());

#if 0
  debug() << "post-inv: ";
#endif
  for(std::size_t i=0; i<strategy_cond_exprs.size(); i++)
  {
#if 0
    debug() << (i>0 ? " || " : "") << from_expr(ns, "", strategy_cond_exprs[i]);
#endif
    strategy_cond_literals[i]=solver.convert(strategy_cond_exprs[i]);
    // solver.set_frozen(strategy_cond_literals[i]);
    strategy_cond_exprs[i]=literal_exprt(strategy_cond_literals[i]);
  }
#if 0
  debug() << eom;
#endif

  solver << or_exprt(disjunction(strategy_cond_exprs),
		     literal_exprt(assertion_check));

#if 0
  debug() << "solve(): ";
#endif

  if(solver()==decision_proceduret::D_SATISFIABLE) // improvement check
  {
#if 0
    debug() << "SAT" << eom;
#endif

#if 0
    for(std::size_t i=0; i<solver.formula.size(); i++)
    {
      debug() << "literal: " << solver.formula[i]
              << " " << solver.l_get(solver.formula[i]) << eom;
    }

    for(std::size_t i=0; i<tpolyhedra_domain.template_size(); i++)
    {
      exprt c=tpolyhedra_domain.get_row_post_constraint(i, inv[i]);
      debug() << "cond: " << from_expr(ns, "", c) << " "
              << from_expr(ns, "", solver.get(c)) << eom;
      debug() << "expr: " << from_expr(ns, "", strategy_value_exprs[i]) << " "
              << from_expr(
                ns, "", simplify_const(solver.get(strategy_value_exprs[i])))
              << eom;
      debug() << "guards: "
              << from_expr(ns, "", tpolyhedra_domain.templ[i].pre_guard) << " "
              << from_expr(
                ns, "", solver.get(tpolyhedra_domain.templ[i].pre_guard))
              << eom;
      debug() << "guards: "
              << from_expr(ns, "", tpolyhedra_domain.templ[i].post_guard)
              << " "
              << from_expr(
                ns, "", solver.get(tpolyhedra_domain.templ[i].post_guard))
              << eom;
    }
#endif


    std::size_t row=0;
    for(; row<strategy_cond_literals.size(); row++)
    {
      if(solver.l_get(strategy_cond_literals[row]).is_true())
        break;  // we've found a row to improve
    }

    if(row==strategy_cond_literals.size())
    { // No, we haven't found one.
      // This can only happen if the assertions failed.
      solver.pop_context();
      return FAILED;
    }

    debug() << "improving row: " << row << eom;
    std::set<tpolyhedra_domaint::rowt> improve_rows;
    improve_rows.insert(row);

    tpolyhedra_domaint::row_valuet upper=
      tpolyhedra_domain.get_max_row_value(row);
    tpolyhedra_domaint::row_valuet lower=
      simplify_const(solver.get(strategy_value_exprs[row]));

    solver.pop_context();  // improvement check

    solver.new_context(); // symbolic value system

    exprt pre_inv_expr=
      tpolyhedra_domain.to_symb_pre_constraints(inv, improve_rows);

    solver << pre_inv_expr;

    exprt post_inv_expr=tpolyhedra_domain.get_row_symb_post_constraint(row);

    solver << post_inv_expr;

#if 0
    debug() << "symbolic value system: " << eom;
    debug() << "pre-inv: " << from_expr(ns, "", pre_inv_expr) << eom;
    debug() << "post-inv: " << from_expr(ns, "", post_inv_expr) << eom;
#endif

    while(tpolyhedra_domain.less_than(lower, upper))
    {
      tpolyhedra_domaint::row_valuet middle=
        tpolyhedra_domain.between(lower, upper);
      if(!tpolyhedra_domain.less_than(lower, middle))
        middle=upper;

      // row_symb_value >= middle
      exprt c=
        tpolyhedra_domain.get_row_symb_value_constraint(row, middle, true);

#if 0
      debug() << "upper: " << from_expr(ns, "", upper) << eom;
      debug() << "middle: " << from_expr(ns, "", middle) << eom;
      debug() << "lower: " << from_expr(ns, "", lower) << eom;
#endif

      solver.new_context(); // binary search iteration

#if 0
      debug() << "constraint: " << from_expr(ns, "", c) << eom;
#endif

      solver << c;

      if(solver()==decision_proceduret::D_SATISFIABLE)
      {
#if 0
        debug() << "SAT" << eom;
#endif

#if 0
        for(std::size_t i=0; i<tpolyhedra_domain.template_size(); i++)
        {
          debug() << from_expr(ns, "", tpolyhedra_domain.get_row_symb_value(i))
                  << " " << from_expr(
                    ns, "", solver.get(tpolyhedra_domain.get_row_symb_value(i)))
                  << eom;
        }
#endif

#if 0
        for(const auto &rm : renaming_map)
        {
          debug() << "replace_map (1st): "
                  << from_expr(ns, "", rm.first) << " "
                  << from_expr(ns, "", solver.get(rm.first)) << eom;
          debug() << "replace_map (2nd): "
                  << from_expr(ns, "", rm.second) << " "
                  << from_expr(ns, "", solver.get(rm.second)) << eom;
        }
#endif

        lower=simplify_const(
          solver.get(tpolyhedra_domain.get_row_symb_value(row)));
      }
      else
      {
#if 0
        debug() << "UNSAT" << eom;
#endif

#if 0
        for(std::size_t i=0; i<solver.formula.size(); ++i)
        {
          if(solver.solver->is_in_conflict(solver.formula[i]))
            debug() << "is_in_conflict: " << solver.formula[i] << eom;
          else
            debug() << "not_in_conflict: " << solver.formula[i] << eom;
        }
#endif

        if(!tpolyhedra_domain.less_than(middle, upper))
          middle=lower;
        upper=middle;
      }
      solver.pop_context(); // binary search iteration
    }

    debug() << "update value: " << from_expr(ns, "", lower) << eom;

    solver.pop_context();  // symbolic value system

    tpolyhedra_domain.set_row_value(row, lower, inv);
    improved=true;
  }
  else
  {
#if 0
    debug() << "UNSAT" << eom;
#endif

#ifdef DEBUG_FORMULA
    for(std::size_t i=0; i<solver.formula.size(); ++i)
    {
      if(solver.solver->is_in_conflict(solver.formula[i]))
        debug() << "is_in_conflict: " << solver.formula[i] << eom;
      else
        debug() << "not_in_conflict: " << solver.formula[i] << eom;
    }
#endif

    solver.pop_context(); // improvement check
  }

  return improved;
}
Example #20
0
void UpdateResolver::solve()
{
  //
  // get table name to update
  if ((this->statement->left->tag != K_IDENT) && (this->statement->left->getDataType() != aq::tnode::tnodeDataType::NODE_DATA_STRING))
  {
    throw aq::generic_error(aq::generic_error::INVALID_QUERY, "invalid table name");
  }
  std::string tableName = this->statement->left->getData().val_str;
  this->table = this->base.getTable(tableName);

  //
  // get columns to update and there values
  aq::tnode * setNode = this->statement->next;
  if (setNode == NULL)
  {
    throw aq::generic_error(aq::generic_error::INVALID_QUERY, "missing SET statement in UPDATE query");
  }
  std::list<aq::tnode*> set_list;
  aq::toNodeListToStdList(setNode, set_list);
  for (auto& n : set_list)
  {
    if (n->tag != K_EQ)
    {
      throw aq::generic_error(aq::generic_error::INVALID_QUERY, "only = operator is allowed in SET clause");
    }
    if ((!n->left) || (n->left->tag != K_IDENT))
    {
      throw aq::generic_error(aq::generic_error::INVALID_QUERY, "left side of operator = in SET clause should be a unique column identifier");
    }
    if (!n->right)
    {
      throw aq::generic_error(aq::generic_error::INVALID_QUERY, "right side of operator = in SET clause should be a value");
    }
    std::string column = n->left->getData().val_str;
    col_handler_t ch;
    ch.column = this->table->getColumn(column);
    ch.item = aq::GetItem(*n->right);
    bool cache = false;
    ch.mapper = aq::build_column_mapper<aq::FileMapper>(ch.column->Type, settings.dataPath.c_str(), this->table->ID, ch.column->ID, ch.column->Size, settings.packSize, cache, aq::FileMapper::mode_t::WRITE);
    if (columns.find(column) != columns.end())
    {
      throw aq::generic_error(aq::generic_error::INVALID_QUERY, "column [%s] appears several times in SET clause", column.c_str());
    }
    columns.insert(std::make_pair(column, ch));
  }

  //
  // get rows to update
  std::vector<size_t> indexes;
  aq::tnode * whereNode = setNode->next;
  if (whereNode != NULL)
  {
    aq::tnode * select = new aq::tnode(K_SELECT);
    select->left = new aq::tnode(K_PERIOD);
    select->left->left = new aq::tnode(K_IDENT);
    select->left->right = new aq::tnode(K_COLUMN);
    select->left->left->set_string_data(tableName.c_str());
    select->left->right->set_string_data(columns.begin()->first.c_str());
    select->next = new aq::tnode(K_FROM);
    select->next->left = new aq::tnode(K_IDENT);
    select->next->left->set_string_data(tableName.c_str());
    select->next->next = whereNode;

    auto handler = boost::make_shared<UpdateResolver>(*this); // ugly and risky
    boost::shared_ptr<RowWritter_Intf> rowHandler(handler);

    unsigned int id_generator = 1;
    aq::QueryResolver solver(select, &settings, aqEngine, base, id_generator);
    solver.solve(rowHandler);
  }

}
Example #21
0
int main(int argc, char *argv[])
{
  int    *update;                  /* vector elements updated on this node. */
  int    *bindx;
  double *val;
  double *xguess, *b, *xexact;
  int    n_nonzeros;
  int    N_update;           /* # of block unknowns updated on this node    */
  int    numLocalEquations;
                                 /* Number scalar equations on this node */
  int    numGlobalEquations; /* Total number of equations */
  int    *numNz, *ColInds;
  int    row,     *col_inds, numEntries;
  double *row_vals;

  int i;

#ifdef EPETRA_MPI
  MPI_Init(&argc,&argv);
  Epetra_MpiComm comm(MPI_COMM_WORLD);
#else
  Epetra_SerialComm comm;
#endif

  cout << comm << endl;

  if(argc != 2) cerr << "error: enter name of data file on command line" << endl; 

  /* Set exact solution to NULL */
  xexact = NULL;

  /* Read matrix file and distribute among processors.  
     Returns with this processor's set of rows */ 

    Trilinos_Util_read_hb(argv[1], comm.MyPID(), &numGlobalEquations, &n_nonzeros,
             &val,  &bindx, &xguess, &b, &xexact);

  Trilinos_Util_distrib_msr_matrix(comm, &numGlobalEquations, &n_nonzeros, &N_update,
		  &update, &val, &bindx, &xguess, &b, &xexact);

  numLocalEquations = N_update;

  /* Make numNzBlks - number of block entries in each block row */

  numNz = new int[numLocalEquations];
  for (i=0; i<numLocalEquations; i++) numNz[i] = bindx[i+1] - bindx[i] + 1;

  /* Make ColInds - Exactly bindx, offset by diag (just copy pointer) */
  ColInds = bindx+numLocalEquations+1;

  Epetra_Map map(numGlobalEquations, numLocalEquations, update, 0, comm);
 
  Epetra_CrsMatrix A(Copy, map, numNz);
  
  /* Add  rows one-at-a-time */

  for (row=0; row<numLocalEquations; row++) {
      row_vals = val + bindx[row];
      col_inds = bindx + bindx[row];
      numEntries = bindx[row+1] - bindx[row];
      assert(A.InsertGlobalValues(update[row], numEntries, row_vals, col_inds)==0);
      assert(A.InsertGlobalValues(update[row], 1, val+row, update+row)==0);
    }
  
  assert(A.FillComplete()==0);   
  
  Epetra_Vector xx(Copy, map, xexact);

  Epetra_Vector bb(Copy, map, b);



  // Construct a Petra Linear Problem

  Epetra_Vector x(map);
  Epetra_LinearProblem problem(&A, &x, &bb);
  // Construct a solver object for this problem
  AztecOO solver(problem);


  // Assert symmetric
  // problem->AssertSymmetric();

  // Set Problem Difficulty Level
  //problem->SetPDL(easy);

  //solver.SetAztecOption(AZ_precond, AZ_none);
  solver.SetAztecOption(AZ_precond, AZ_dom_decomp);
  //solver.SetAztecOption(AZ_precond, AZ_ls);
  //solver.SetAztecOption(AZ_scaling, 8);
  solver.SetAztecOption(AZ_subdomain_solve, AZ_ilut);
  //solver.SetAztecOption(AZ_subdomain_solve, AZ_bilu_ifp);
  bool bilu = false;
  //solver.SetAztecOption(AZ_output, 0);
  //solver.SetAztecOption(AZ_graph_fill, 2);
  solver.SetAztecOption(AZ_overlap, 0);
  //solver.SetAztecOption(AZ_reorder, 0);
  //solver.SetAztecOption(AZ_poly_ord, 9);
  solver.SetAztecParam(AZ_ilut_fill, 1.0);
  solver.SetAztecParam(AZ_drop, 0.0);
  //double rthresh = 1.01;
  //cout << "Rel threshold = " << rthresh << endl;
  //solver.SetAztecParam(AZ_rthresh, rthresh);
  //double athresh = 1.0e-2;
  //cout << "Abs threshold = " << athresh << endl;
  //solver.SetAztecParam(AZ_athresh, athresh);

  //solver.SetAztecOption(AZ_/conv, AZ_noscaled);
  //solver.SetAztecParam(AZ_ill_cond_thresh, 1.0e12);


  int Niters = 400;
  solver.SetAztecOption(AZ_kspace, Niters);
  
  double norminf = A.NormInf();
  double normone = A.NormOne();
  if (comm.MyPID()==0) 
    cout << "\n Inf-norm of A before scaling = " << norminf 
	 << "\n One-norm of A before scaling = " << normone<< endl << endl;


  if (bilu) {
    int NumTrials = 3;
    double athresholds[] = {0.0, 1.0E-14, 1.0E-3};
    double rthresholds[] = {0.0, 1.0E-14, 1.0E-3};
    double condestThreshold = 1.0E16;
    double maxFill = 4.0;
    int maxKspace = 4*Niters;
    solver.SetAdaptiveParams(NumTrials, athresholds, rthresholds, condestThreshold, maxFill, maxKspace);
  }
  else {
    int NumTrials = 7;
    double athresholds[] = {0.0, 1.0E-12, 1.0E-12, 1.0E-5, 1.0E-5, 1.0E-2, 1.0E-2};
    double rthresholds[] = {1.0, 1.0,     1.01,    1.0,    1.01,   1.01,   1.1   };
    double condestThreshold = 1.0E16;
    double maxFill = 4.0;
    int maxKspace = 4*Niters;
    solver.SetAdaptiveParams(NumTrials, athresholds, rthresholds, condestThreshold, maxFill, maxKspace);
  }

  Epetra_Time timer(comm);
  solver.AdaptiveIterate(Niters, 1, 5.0e-7);
  double atime = timer.ElapsedTime();
  if (comm.MyPID()==0) cout << "AdaptiveIterate total time = " << atime << endl;

  
  norminf = A.NormInf();
  normone = A.NormOne();
  if (comm.MyPID()==0) 
    cout << "\n Inf-norm of A after  scaling = " << norminf  
	 << "\n One-norm of A after  scaling = " << normone << endl << endl; 

  Epetra_Vector bcomp(map);
  assert(A.Multiply(false, x, bcomp)==0);
 
  Epetra_Vector resid(map); 
 
  assert(resid.Update(1.0, bb, -1.0, bcomp, 0.0)==0);

  double residual;
  assert(resid.Norm2(&residual)==0);
  if (comm.MyPID()==0) cout << "Residual    = " << residual << endl;

  assert(resid.Update(1.0, xx, -1.0, x, 0.0)==0);

  assert(resid.Norm2(&residual)==0);
  if (comm.MyPID()==0) 
    cout << "2-norm of difference between computed and exact solution  = " << residual << endl;

  if (residual>1.0e-5) {
    cout << "Difference between computed and exact solution is large..." << endl
	 << "Computing norm of A times this difference.  If this norm is small, then matrix is singular" 
	 << endl;
    assert(A.Multiply(false, resid, bcomp)==0);
    assert(bcomp.Norm2(&residual)==0);
  if (comm.MyPID()==0) 
    cout << "2-norm of A times difference between computed and exact solution  = " << residual << endl;
  
  }
  free ((void *) xguess);
  free ((void *) b);
  free ((void *) xexact);
  free ((void *) val);
  free ((void *) bindx);
  free ((void *) update);

  delete [] numNz;

				       
#ifdef EPETRA_MPI
  MPI_Finalize() ;
#endif

return 0 ;
}
Example #22
0
int main(int argc, char *argv[]) {

#ifdef HAVE_MPI
  MPI_Init(&argc,&argv);
  Epetra_MpiComm comm (MPI_COMM_WORLD);
#else
  Epetra_SerialComm comm;
#endif

  int MyPID = comm.MyPID();

  bool verbose = false;
  bool verbose1 = false; 
  // Check if we should print results to standard out
  if (argc > 1) {
    if ((argv[1][0] == '-') && (argv[1][1] == 'v')) {
      verbose1 = true;
      if (MyPID==0) verbose = true;
    }
  }

  if (verbose1) cout << comm << endl;


  // Uncomment the next three lines to debug in mpi mode
  //int tmp;
  //if (MyPID==0) cin >> tmp;
  //comm.Barrier();

  Epetra_CrsMatrix * A; 
  EPETRA_CHK_ERR(EpetraExt::MatlabFileToCrsMatrix("A.dat", comm, A));

  Epetra_Vector  x(A->OperatorDomainMap()); 
  Epetra_Vector  b(A->OperatorRangeMap());
  x.Random();
  A->Apply(x,b); // Generate RHS from x
  Epetra_Vector xx(x); // Copy x to xx for later use

  Epetra_LinearProblem problem(A, &x, &b);
  // Construct a solver object for this problem

  AztecOO solver(problem);
  solver.SetAztecOption(AZ_precond, AZ_none);
  if (!verbose1) solver.SetAztecOption(AZ_output, AZ_none);
  solver.SetAztecOption(AZ_kspace, A->NumGlobalRows());
  AztecOO_Operator AOpInv(&solver, A->NumGlobalRows());
  Epetra_InvOperator AInvOp(&AOpInv);

  EPETRA_CHK_ERR(EpetraExt::OperatorToMatlabFile("Ainv.dat", AInvOp));

  comm.Barrier();

  Epetra_CrsMatrix * AInv; 
  EPETRA_CHK_ERR(EpetraExt::MatlabFileToCrsMatrix("Ainv.dat", comm, AInv));

  EPETRA_CHK_ERR(AInv->Apply(b,x));

  EPETRA_CHK_ERR(x.Update(1.0, xx, -1.0));
  double residual = 0.0;
  EPETRA_CHK_ERR(x.Norm2(&residual));
  if (verbose) cout << "Norm of difference between computed x and exact x = " << residual << endl;
  int ierr = checkValues(residual,0.0,"Norm of difference between computed A1x1 and A1x1 from file", verbose);

  
  delete A;
  delete AInv;


  #ifdef HAVE_MPI
  MPI_Finalize() ;
#endif

  return(ierr);
}
Example #23
0
bool summarizer_bwt::check_postcondition(
  const function_namet &function_name,
  const local_SSAt &SSA,
  local_SSAt::nodest::const_iterator n_it, 
  local_SSAt::nodet::function_callst::const_iterator f_it,
  const exprt &precondition,
  bool context_sensitive)
{
  assert(f_it->function().id()==ID_symbol); //no function pointers
  irep_idt fname = to_symbol_expr(f_it->function()).get_identifier();

  status() << "Checking precondition of " << fname << eom;

  bool precondition_holds = false;
  exprt assertion;

  if(!summary_db.exists(fname)) return true; //nothing to do

  summaryt summary = summary_db.get(fname);

  if(summary.bw_precondition.is_nil()) return false; //there is work to do

  if(!context_sensitive ||
     summary.fw_precondition.is_true())  //precondition trivially holds
  {
    status() << "Precondition trivially holds, replacing by summary." 
	     << eom;
    summaries_used++;
    precondition_holds = true;
  }
  else
  {
    assertion = summary.bw_precondition;

    //getting globals at call site
    local_SSAt::var_sett cs_globals_in; 
    SSA.get_globals(n_it->location,cs_globals_in);

    ssa_inliner.rename_to_caller(f_it,summary.params,
				 cs_globals_in,summary.globals_in,assertion);

    debug() << "precondition assertion: " << 
      from_expr(SSA.ns,"",assertion) << eom;

    precondition_holds = false;
  }

  if(precondition_holds) return true;

  assert(!assertion.is_nil());

  // postcondition check
  // solver
  incremental_solvert &solver = ssa_db.get_solver(function_name);
  solver.set_message_handler(get_message_handler());
  solver << SSA;

  solver.new_context();
  solver << SSA.get_enabling_exprs();

  solver << precondition;
  solver << ssa_inliner.get_summaries(SSA);

  //add postcondition
  solver << not_exprt(assertion);

  switch(solver())
  {
  case decision_proceduret::D_SATISFIABLE: {
    precondition_holds = false;

    status() << "Precondition does not hold, need to recompute summary." << eom;
    break; }
  case decision_proceduret::D_UNSATISFIABLE: {
    precondition_holds = true;

    status() << "Precondition holds, replacing by summary." << eom;
    summaries_used++;
                
    break; }
  default: assert(false); break;
  }

  return precondition_holds;
}
Example #24
0
int main() {

  /* Define simulation parameters */
  #ifdef OPENMP
  int num_threads = omp_get_num_procs();
  #else
  int num_threads = 1;
  #endif
  double track_spacing = 0.1;
  int num_azim = 4;
  double tolerance = 1e-5;
  int max_iters = 1000;

  /* Set logging information */
  set_log_level("NORMAL");
  log_printf(TITLE, "Simulating the OECD's C5G7 Benchmark Problem...");

  /* Define material properties */
  log_printf(NORMAL, "Defining material properties...");

  const size_t num_groups = 7;
  std::map<std::string, std::array<double, num_groups> > nu_sigma_f;
  std::map<std::string, std::array<double, num_groups> > sigma_f;
  std::map<std::string, std::array<double, num_groups*num_groups> > sigma_s;
  std::map<std::string, std::array<double, num_groups> > chi;
  std::map<std::string, std::array<double, num_groups> > sigma_t;

  /* Define water cross-sections */
  nu_sigma_f["Water"] = std::array<double, num_groups> {0, 0, 0, 0, 0, 0, 0};
  sigma_f["Water"] = std::array<double, num_groups> {0, 0, 0, 0, 0, 0, 0};
  sigma_s["Water"] = std::array<double, num_groups*num_groups>
      {0.0444777, 0.1134, 7.2347E-4, 3.7499E-6, 5.3184E-8, 0.0, 0.0,
      0.0, 0.282334, 0.12994, 6.234E-4, 4.8002E-5, 7.4486E-6, 1.0455E-6,
      0.0, 0.0, 0.345256, 0.22457, 0.016999, 0.0026443, 5.0344E-4,
      0.0, 0.0, 0.0, 0.0910284, 0.41551, 0.063732, 0.012139,
      0.0, 0.0, 0.0, 7.1437E-5, 0.139138, 0.51182, 0.061229,
      0.0, 0.0, 0.0, 0.0, 0.0022157, 0.699913, 0.53732,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.13244, 2.4807};
  chi["Water"] = std::array<double, num_groups> {0, 0, 0, 0, 0, 0, 0};
  sigma_t["Water"] = std::array<double, num_groups> {0.159206, 0.41297,
    0.59031, 0.58435, 0.718, 1.25445, 2.65038};

  /* Define UO2 cross-sections */
  nu_sigma_f["UO2"] = std::array<double, num_groups> {0.02005998, 0.002027303,
    0.01570599, 0.04518301, 0.04334208, 0.2020901, 0.5257105};
  sigma_f["UO2"] = std::array<double, num_groups> {0.00721206, 8.19301E-4,
    0.0064532, 0.0185648, 0.0178084, 0.0830348, 0.216004};
  sigma_s["UO2"] = std::array<double, num_groups*num_groups>
      {0.127537, 0.042378, 9.4374E-6, 5.5163E-9, 0.0, 0.0, 0.0,
      0.0, 0.324456, 0.0016314, 3.1427E-9, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.45094, 0.0026792, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.452565, 0.0055664, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.2525E-4, 0.271401, 0.010255, 1.0021E-8,
      0.0, 0.0, 0.0, 0.0, 0.0012968, 0.265802, 0.016809,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0085458, 0.27308};
  chi["UO2"] = std::array<double, num_groups> {0.58791, 0.41176, 3.3906E-4,
    1.1761E-7, 0.0, 0.0, 0.0};
  sigma_t["UO2"] = std::array<double, num_groups> {0.177949, 0.329805,
    0.480388, 0.554367, 0.311801, 0.395168, 0.564406};

  /* Define MOX-4.3% cross-sections */
  nu_sigma_f["MOX-4.3%%"] = std::array<double, num_groups> {0.021753,
    0.002535103, 0.01626799, 0.0654741, 0.03072409, 0.666651, 0.7139904};
  sigma_f["MOX-4.3%%"] = std::array<double, num_groups> {0.00762704,
    8.76898E-4, 0.00569835, 0.0228872, 0.0107635, 0.232757, 0.248968};
  sigma_s["MOX-4.3%%"] = std::array<double, num_groups*num_groups>
      {0.128876, 0.041413, 8.229E-6, 5.0405E-9, 0.0, 0.0, 0.0,
      0.0, 0.325452, 0.0016395, 1.5982E-9, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.453188, 0.0026142, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.457173, 0.0055394, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.6046E-4, 0.276814, 0.0093127, 9.1656E-9,
      0.0, 0.0, 0.0, 0.0, 0.0020051, 0.252962, 0.01485,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0084948, 0.265007};
  chi["MOX-4.3%%"] = std::array<double, num_groups> {0.58791, 0.41176,
    3.3906E-4, 1.1761E-7, 0.0, 0.0, 0.0};
  sigma_t["MOX-4.3%%"] = std::array<double, num_groups> {0.178731, 0.330849,
    0.483772, 0.566922, 0.426227, 0.678997, 0.68285};

  /* Define MOX-7% cross-sections */
  nu_sigma_f["MOX-7%%"] = std::array<double, num_groups> {0.02381395,
    0.003858689, 0.024134, 0.09436622, 0.04576988, 0.9281814, 1.0432};
  sigma_f["MOX-7%%"] = std::array<double, num_groups> {0.00825446, 0.00132565,
    0.00842156, 0.032873, 0.0159636, 0.323794, 0.362803};
  sigma_s["MOX-7%%"] = std::array<double, num_groups*num_groups>
      {0.130457, 0.041792, 8.5105E-6, 5.1329E-9, 0.0, 0.0, 0.0,
      0.0, 0.328428, 0.0016436, 2.2017E-9, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.458371, 0.0025331, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.463709, 0.0054766, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.7619E-4, 0.282313, 0.0087289, 9.0016E-9,
      0.0, 0.0, 0.0, 0.0, 0.002276, 0.249751, 0.013114,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0088645, 0.259529};
  chi["MOX-7%%"] = std::array<double, num_groups> {0.58791, 0.41176, 3.3906E-4,
    1.1761E-7, 0.0, 0.0, 0.0};
  sigma_t["MOX-7%%"] = std::array<double, num_groups> {0.181323, 0.334368,
    0.493785, 0.591216, 0.474198, 0.833601, 0.853603};

  /* Define MOX-8.7% cross-sections */
  nu_sigma_f["MOX-8.7%%"] = std::array<double, num_groups> {0.025186,
    0.004739509, 0.02947805, 0.11225, 0.05530301, 1.074999, 1.239298};
  sigma_f["MOX-8.7%%"] = std::array<double, num_groups> {0.00867209,
    0.00162426, 0.0102716, 0.0390447, 0.0192576, 0.374888, 0.430599};
  sigma_s["MOX-8.7%%"] = std::array<double, num_groups*num_groups>
      {0.131504, 0.042046, 8.6972E-6, 5.1938E-9, 0.0, 0.0, 0.0,
      0.0, 0.330403, 0.0016463, 2.6006E-9, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.461792, 0.0024749, 0.0, 0.0, 0.0,
      0.0, 0.0, 0.0, 0.468021, 0.005433, 0.0, 0.0,
      0.0, 0.0, 0.0, 1.8597E-4, 0.285771, 0.0083973, 8.928E-9,
      0.0, 0.0, 0.0, 0.0, 0.0023916, 0.247614, 0.012322,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.0089681, 0.256093};
  chi["MOX-8.7%%"] = std::array<double, num_groups> {0.58791, 0.41176,
    3.3906E-4, 1.1761E-7, 0.0, 0.0, 0.0};
  sigma_t["MOX-8.7%%"] = std::array<double, num_groups> {0.183045, 0.336705,
    0.500507, 0.606174, 0.502754, 0.921028, 0.955231};

  /* Define fission chamber cross-sections */
  nu_sigma_f["Fission Chamber"] = std::array<double, num_groups> {1.323401E-8,
    1.4345E-8, 1.128599E-6, 1.276299E-5, 3.538502E-7, 1.740099E-6,
    5.063302E-6};
  sigma_f["Fission Chamber"] = std::array<double, num_groups> {4.79002E-9,
    5.82564E-9, 4.63719E-7, 5.24406E-6, 1.4539E-7, 7.14972E-7, 2.08041E-6};
  sigma_s["Fission Chamber"] = std::array<double, num_groups*num_groups>
      {0.0661659, 0.05907, 2.8334E-4, 1.4622E-6, 2.0642E-8, 0.0, 0.0,
      0.0, 0.240377, 0.052435, 2.499E-4, 1.9239E-5, 2.9875E-6, 4.214E-7,
      0.0, 0.0, 0.183425, 0.092288, 0.0069365, 0.001079, 2.0543E-4,
      0.0, 0.0, 0.0, 0.0790769, 0.16999, 0.02586, 0.0049256,
      0.0, 0.0, 0.0, 3.734E-5, 0.099757, 0.20679, 0.024478,
      0.0, 0.0, 0.0, 0.0, 9.1742E-4, 0.316774, 0.23876,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.049793, 1.0991};
  chi["Fission Chamber"] = std::array<double, num_groups> {0.58791, 0.41176,
    3.3906E-4, 1.1761E-7, 0.0, 0.0, 0.0};
  sigma_t["Fission Chamber"] = std::array<double, num_groups> {0.126032,
    0.29316, 0.28425, 0.28102, 0.33446, 0.56564, 1.17214};

  /* Define guide tube cross-sections */
  nu_sigma_f["Guide Tube"] = std::array<double, num_groups> {0, 0, 0, 0, 0,
    0, 0};
  sigma_f["Guide Tube"] = std::array<double, num_groups> {0, 0, 0, 0, 0, 0, 0};
  sigma_s["Guide Tube"] = std::array<double, num_groups*num_groups>
      {0.0661659, 0.05907, 2.8334E-4, 1.4622E-6, 2.0642E-8, 0.0, 0.0,
      0.0, 0.240377, 0.052435, 2.499E-4, 1.9239E-5, 2.9875E-6, 4.214E-7,
      0.0, 0.0, 0.183297, 0.092397, 0.0069446, 0.0010803, 2.0567E-4,
      0.0, 0.0, 0.0, 0.0788511, 0.17014, 0.025881, 0.0049297,
      0.0, 0.0, 0.0, 3.7333E-5, 0.0997372, 0.20679, 0.024478,
      0.0, 0.0, 0.0, 0.0, 9.1726E-4, 0.316765, 0.23877,
      0.0, 0.0, 0.0, 0.0, 0.0, 0.049792, 1.09912};
  chi["Guide Tube"] = std::array<double, num_groups> {0, 0, 0, 0, 0, 0, 0};
  sigma_t["Guide Tube"] = std::array<double, num_groups> {0.126032, 0.29316,
    0.28424, 0.28096, 0.33444, 0.56564, 1.17215};

  /* Create materials */
  log_printf(NORMAL, "Creating materials...");
  std::map<std::string, Material*> materials;

  std::map<std::string, std::array<double, num_groups> >::iterator it;
  int id_num = 0;
  for (it = sigma_t.begin(); it != sigma_t.end(); it++) {

    std::string name = it->first;
    materials[name] = new Material(id_num, name.c_str());
    materials[name]->setNumEnergyGroups(num_groups);
    id_num++;

    materials[name]->setSigmaF(sigma_f[name].data(), num_groups);
    materials[name]->setNuSigmaF(nu_sigma_f[name].data(), num_groups);
    materials[name]->setSigmaS(sigma_s[name].data(), num_groups*num_groups);
    materials[name]->setChi(chi[name].data(), num_groups);
    materials[name]->setSigmaT(sigma_t[name].data(), num_groups);
  }

  /* Create surfaces */
  XPlane left(-32.13);
  XPlane right(32.13);
  YPlane top(32.13);
  YPlane bottom(-32.13);

  left.setBoundaryType(REFLECTIVE);
  right.setBoundaryType(VACUUM);
  top.setBoundaryType(REFLECTIVE);
  bottom.setBoundaryType(VACUUM);

  /* Create circles for the fuel as well as to discretize the moderator into
     rings */
  ZCylinder fuel_radius(0.0, 0.0, 0.54);
  ZCylinder moderator_inner_radius(0.0, 0.0, 0.58);
  ZCylinder moderator_outer_radius(0.0, 0.0, 0.62);

  /* Create cells and universes */
  log_printf(NORMAL, "Creating cells...");

  /* Moderator rings */
  Cell* moderator_ring1 = new Cell(21, "mod1");
  Cell* moderator_ring2 = new Cell(1, "mod2");
  Cell* moderator_ring3 = new Cell(2, "mod3");
  moderator_ring1->setNumSectors(8);
  moderator_ring2->setNumSectors(8);
  moderator_ring3->setNumSectors(8);
  moderator_ring1->setFill(materials["Water"]);
  moderator_ring2->setFill(materials["Water"]);
  moderator_ring3->setFill(materials["Water"]);
  moderator_ring1->addSurface(+1, &fuel_radius);
  moderator_ring1->addSurface(-1, &moderator_inner_radius);
  moderator_ring2->addSurface(+1, &moderator_inner_radius);
  moderator_ring2->addSurface(-1, &moderator_outer_radius);
  moderator_ring3->addSurface(+1, &moderator_outer_radius);

  /* UO2 pin cell */
  Cell* uo2_cell = new Cell(3, "uo2");
  uo2_cell->setNumRings(3);
  uo2_cell->setNumSectors(8);
  uo2_cell->setFill(materials["UO2"]);
  uo2_cell->addSurface(-1, &fuel_radius);

  Universe* uo2 = new Universe();
  uo2->addCell(uo2_cell);
  uo2->addCell(moderator_ring1);
  uo2->addCell(moderator_ring2);
  uo2->addCell(moderator_ring3);

  /* 4.3% MOX pin cell */
  Cell* mox43_cell = new Cell(4, "mox43");
  mox43_cell->setNumRings(3);
  mox43_cell->setNumSectors(8);
  mox43_cell->setFill(materials["MOX-4.3%%"]);
  mox43_cell->addSurface(-1, &fuel_radius);

  Universe* mox43 = new Universe();
  mox43->addCell(mox43_cell);
  mox43->addCell(moderator_ring1);
  mox43->addCell(moderator_ring2);
  mox43->addCell(moderator_ring3);

  /* 7% MOX pin cell */
  Cell* mox7_cell = new Cell(5, "mox7");
  mox7_cell->setNumRings(3);
  mox7_cell->setNumSectors(8);
  mox7_cell->setFill(materials["MOX-7%%"]);
  mox7_cell->addSurface(-1, &fuel_radius);

  Universe* mox7 = new Universe();
  mox7->addCell(mox7_cell);
  mox7->addCell(moderator_ring1);
  mox7->addCell(moderator_ring2);
  mox7->addCell(moderator_ring3);

  /* 8.7% MOX pin cell */
  Cell* mox87_cell = new Cell(6, "mox87");
  mox87_cell->setNumRings(3);
  mox87_cell->setNumSectors(8);
  mox87_cell->setFill(materials["MOX-8.7%%"]);
  mox87_cell->addSurface(-1, &fuel_radius);

  Universe* mox87 = new Universe();
  mox87->addCell(mox87_cell);
  mox87->addCell(moderator_ring1);
  mox87->addCell(moderator_ring2);
  mox87->addCell(moderator_ring3);

  /* Fission chamber pin cell */
  Cell* fission_chamber_cell = new Cell(7, "fc");
  fission_chamber_cell->setNumRings(3);
  fission_chamber_cell->setNumSectors(8);
  fission_chamber_cell->setFill(materials["Fission Chamber"]);
  fission_chamber_cell->addSurface(-1, &fuel_radius);

  Universe* fission_chamber = new Universe();
  fission_chamber->addCell(fission_chamber_cell);
  fission_chamber->addCell(moderator_ring1);
  fission_chamber->addCell(moderator_ring2);
  fission_chamber->addCell(moderator_ring3);

  /* Guide tube pin cell */
  Cell* guide_tube_cell = new Cell(8, "gtc");
  guide_tube_cell->setNumRings(3);
  guide_tube_cell->setNumSectors(8);
  guide_tube_cell->setFill(materials["Guide Tube"]);
  guide_tube_cell->addSurface(-1, &fuel_radius);

  Universe* guide_tube = new Universe();
  guide_tube->addCell(guide_tube_cell);
  guide_tube->addCell(moderator_ring1);
  guide_tube->addCell(moderator_ring2);
  guide_tube->addCell(moderator_ring3);

  /* Reflector */
  Cell* reflector_cell = new Cell(9, "rc");
  reflector_cell->setFill(materials["Water"]);

  Universe* reflector = new Universe();
  reflector->addCell(reflector_cell);

  /* Cells */
  Cell* assembly1_cell = new Cell(10, "ac1");
  Cell* assembly2_cell = new Cell(11, "ac2");
  Cell* refined_reflector_cell = new Cell(12, "rrc");
  Cell* right_reflector_cell = new Cell(13,"rrc2");
  Cell* corner_reflector_cell = new Cell(14, "crc");
  Cell* bottom_reflector_cell = new Cell(15, "brc");

  Universe* assembly1 = new Universe();
  Universe* assembly2 = new Universe();
  Universe* refined_reflector = new Universe();
  Universe* right_reflector = new Universe();
  Universe* corner_reflector = new Universe();
  Universe* bottom_reflector = new Universe();

  assembly1->addCell(assembly1_cell);
  assembly2->addCell(assembly2_cell);
  refined_reflector->addCell(refined_reflector_cell);
  right_reflector->addCell(right_reflector_cell);
  corner_reflector->addCell(corner_reflector_cell);
  bottom_reflector->addCell(bottom_reflector_cell);

  /* Root Cell* */
  Cell* root_cell = new Cell(16, "root");
  root_cell->addSurface(+1, &left);
  root_cell->addSurface(-1, &right);
  root_cell->addSurface(-1, &top);
  root_cell->addSurface(+1, &bottom);

  Universe* root_universe = new Universe();
  root_universe->addCell(root_cell);

  /* Create lattices */
  log_printf(NORMAL, "Creating lattices...");

  /* Top left, bottom right 17 x 17 assemblies */
  Lattice* assembly1_lattice = new Lattice();
  assembly1_lattice->setWidth(1.26, 1.26);
  Universe* matrix1[17*17];
  {
    int mold[17*17] =  {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1,
                        1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 2, 1, 1, 2, 1, 1, 3, 1, 1, 2, 1, 1, 2, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1,
                        1, 1, 1, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

    std::map<int, Universe*> names = {{1, uo2}, {2, guide_tube},
                                      {3, fission_chamber}};
    for (int n=0; n<17*17; n++)
      matrix1[n] = names[mold[n]];

    assembly1_lattice->setUniverses(1, 17, 17, matrix1);
  }
  assembly1_cell->setFill(assembly1_lattice);

  /* Top right, bottom left 17 x 17 assemblies */
  Lattice* assembly2_lattice = new Lattice();
  assembly2_lattice->setWidth(1.26, 1.26);
  Universe* matrix2[17*17];
  {
    int mold[17*17] =  {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                        1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
                        1, 2, 2, 2, 2, 4, 2, 2, 4, 2, 2, 4, 2, 2, 2, 2, 1,
                        1, 2, 2, 4, 2, 3, 3, 3, 3, 3, 3, 3, 2, 4, 2, 2, 1,
                        1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 1,
                        1, 2, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 2, 1,
                        1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1,
                        1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1,
                        1, 2, 4, 3, 3, 4, 3, 3, 5, 3, 3, 4, 3, 3, 4, 2, 1,
                        1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1,
                        1, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1,
                        1, 2, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 3, 3, 4, 2, 1,
                        1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 1,
                        1, 2, 2, 4, 2, 3, 3, 3, 3, 3, 3, 3, 2, 4, 2, 2, 1,
                        1, 2, 2, 2, 2, 4, 2, 2, 4, 2, 2, 4, 2, 2, 2, 2, 1,
                        1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1,
                        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

    std::map<int, Universe*> names = {{1, mox43}, {2, mox7}, {3, mox87},
                                      {4, guide_tube}, {5, fission_chamber}};
    for (int n=0; n<17*17; n++)
      matrix2[n] = names[mold[n]];

    assembly2_lattice->setUniverses(1, 17, 17, matrix2);
  }
  assembly2_cell->setFill(assembly2_lattice);

  /* Sliced up water cells - semi finely spaced */
  Lattice* refined_ref_lattice = new Lattice();
  refined_ref_lattice->setWidth(0.126, 0.126);
  Universe* refined_ref_matrix[10*10];
  for (int n=0; n<10*10; n++)
    refined_ref_matrix[n] = reflector;
  refined_ref_lattice->setUniverses(1, 10, 10, refined_ref_matrix);
  refined_reflector_cell->setFill(refined_ref_lattice);

  /* Sliced up water cells - right side of geometry */
  Lattice* right_ref_lattice = new Lattice();
  right_ref_lattice->setWidth(1.26, 1.26);
  Universe* right_ref_matrix[17*17];
  for (int i=0; i<17; i++) {
    for (int j=0; j<17; j++) {
      int index =  17*j + i;
      if (i<11)
        right_ref_matrix[index] = refined_reflector;
      else
        right_ref_matrix[index] = reflector;
    }
  }
  right_ref_lattice->setUniverses(1, 17, 17, right_ref_matrix);
  right_reflector_cell->setFill(right_ref_lattice);

  /* Sliced up water cells for bottom corner of geometry */
  Lattice* corner_ref_lattice = new Lattice();
  corner_ref_lattice->setWidth(1.26, 1.26);
  Universe* corner_ref_matrix[17*17];
  for (int i=0; i<17; i++) {
    for (int j=0; j<17; j++) {
      int index = 17*j + i;
      if (i<11 && j<11)
        corner_ref_matrix[index] = refined_reflector;
      else
        corner_ref_matrix[index] = reflector;
    }
  }
  corner_ref_lattice->setUniverses(1, 17, 17, corner_ref_matrix);
  corner_reflector_cell->setFill(corner_ref_lattice);

  /* Sliced up water cells for bottom of geometry */
  Lattice* bottom_ref_lattice = new Lattice();
  bottom_ref_lattice->setWidth(1.26, 1.26);
  Universe* bottom_ref_matrix[17*17];
  for (int i=0; i<17; i++) {
    for (int j=0; j<17; j++) {
      int index = 17*j + i;
      if (j<11)
        bottom_ref_matrix[index] = refined_reflector;
      else
        bottom_ref_matrix[index] = reflector;
    }
  }
  bottom_ref_lattice->setUniverses(1, 17, 17, bottom_ref_matrix);
  bottom_reflector_cell->setFill(bottom_ref_lattice);

  /* 4 x 4 core to represent two bundles and water */
  Lattice* full_geometry = new Lattice();
  full_geometry->setWidth(21.42, 21.42);
  Universe* universes[] = {
    assembly1,        assembly2,        right_reflector,
    assembly2,        assembly1,        right_reflector,
    bottom_reflector, bottom_reflector, corner_reflector};
  full_geometry->setUniverses(1, 3, 3, universes);
  root_cell->setFill(full_geometry);

  /* Create CMFD mesh */
  log_printf(NORMAL, "Creating CMFD mesh...");

  Cmfd cmfd;
  cmfd.setSORRelaxationFactor(1.5);
  cmfd.setLatticeStructure(51, 51);
  int cmfd_group_structure[3] = {1,4,8};
  cmfd.setGroupStructure(cmfd_group_structure, 3);

  /* Create the geometry */
  log_printf(NORMAL, "Creating geometry...");
  Geometry geometry;
  geometry.setRootUniverse(root_universe);
  geometry.setCmfd(&cmfd);

  /* Generate tracks */
  log_printf(NORMAL, "Initializing the track generator...");
  TrackGenerator track_generator(&geometry, num_azim, track_spacing);
  track_generator.setNumThreads(num_threads);
  track_generator.generateTracks();

  /* Run simulation */
  CPUSolver solver(&track_generator);
  solver.setNumThreads(num_threads);
  solver.setConvergenceThreshold(tolerance);
  solver.computeEigenvalue(max_iters);
  solver.printTimerReport();

  return 0;
}
Example #25
0
void IterativeSolver::execute()
{
  RDM::RDSolver& mysolver = solver().as_type< RDM::RDSolver >();

  /// @todo this configuration sould be in constructor but does not work there

  configure_option_recursively( "iterator", this->uri() );

  // access components (out of loop)

  CActionDirector& boundary_conditions =
      access_component( "cpath:../BoundaryConditions" ).as_type<CActionDirector>();

  CActionDirector& domain_discretization =
      access_component( "cpath:../DomainDiscretization" ).as_type<CActionDirector>();

  CAction& synchronize = mysolver.actions().get_child("Synchronize").as_type<CAction>();

  Component& cnorm = post_actions().get_child("ComputeNorm");
  cnorm.configure_option("Field", mysolver.fields().get_child( RDM::Tags::residual() ).follow()->uri() );

  // iteration loop

  Uint iter = 1; // iterations start from 1 ( max iter zero will do nothing )
  property("iteration") = iter;


  while( ! stop_condition() ) // non-linear loop
  {
    // (1) the pre actions - cleanup residual, pre-process something, etc

    pre_actions().execute();

    // (2) domain discretization

    domain_discretization.execute();

    // (3) apply boundary conditions

    boundary_conditions.execute();

    // (4) update

    update().execute();

    // (5) update

    synchronize.execute();

    // (6) the post actions - compute norm, post-process something, etc

    post_actions().execute();

    // output convergence info

    /// @todo move current rhs as a prpoerty of the iterate or solver components
    if( Comm::PE::instance().rank() == 0 )
    {
      Real rhs_norm = cnorm.properties().value<Real>("Norm");
      CFinfo << "iter ["    << std::setw(4)  << iter << "]"
             << "L2(rhs) [" << std::setw(12) << rhs_norm << "]" << CFendl;

      if ( is_nan(rhs_norm) || is_inf(rhs_norm) )
        throw FailedToConverge(FromHere(),
                               "Solution diverged after "+to_str(iter)+" iterations");
    }

    // raise signal that iteration is done

    raise_iteration_done();

    // increment iteration

    property("iteration") = ++iter; // update the iteration number

  }
}
	void resolve_dependency(::boost::unit_test::test_suite& suite, const DependencyContainer& dependency) {
		DependencySolver solver(suite);
		solver.resolve(dependency);
	}
Example #27
0
	void fillHoleLinear(std::vector<double> &data, const int width, const int height, const std::vector<bool> &mask) {
		CHECK_EQ(data.size(), mask.size());
		CHECK_EQ(width * height, (int)data.size());
		int invalidnum = 0;

		//invalidcoord: size of invalidnum
		//invalidindx: size of depthnum

		vector<int> invalidcoord;
		vector<int> invalidindex(data.size());

		for (int i = 0; i < data.size(); i++) {
			if (!mask[i]) {
				invalidnum++;
				invalidcoord.push_back(i);
				invalidindex[i] = invalidnum - 1;
			}
		}
		//construct matrix A and B
		SparseMatrix<double> A(invalidnum, invalidnum);
		VectorXd B(invalidnum);
		for(int i=0; i<invalidnum; ++i)
			B[i] = 0.0;

		typedef Triplet<double> TripletD;
		vector<TripletD> triplets;
		triplets.reserve(invalidnum * 4);
		for (int i = 0; i < invalidnum; i++) {
			//(x,y) is the coordinate of invalid pixel
			int x = invalidcoord[i] % width;
			int y = invalidcoord[i] / width;
			int count = 0;
			if (y * width + x - 1 < data.size()) {
				count++;
				if (!mask[y * width + x - 1])
					triplets.push_back(TripletD(i, invalidindex[y * width + x - 1], -1));
				else
					B[i] += data[y * width + x - 1];
			}
			if (y * width + x + 1 < data.size()) {
				count++;
				if (!mask[y * width + x + 1])
					triplets.push_back(TripletD(i, invalidindex[y * width + x + 1], -1));
				else
					B[i] += data[y * width + x + 1];
			}
			if ((y - 1) * width + x < data.size()) {
				count++;
				if (!mask[(y - 1) * width + x])
					triplets.push_back(TripletD(i, invalidindex[(y - 1) * width + x], -1));
				else
					B[i] += data[(y - 1) * width + x];
			}
			if ((y + 1) * width + x < data.size()) {
				count++;
				if (!mask[(y + 1) * width + x])
					triplets.push_back(TripletD(i, invalidindex[(y + 1) * width + x], -1));
				else
					B[i] += data[(y + 1) * width + x];
			}
			triplets.push_back(TripletD(i, i, (double) count));
		}
		A.setFromTriplets(triplets.begin(), triplets.end());

		//Solve the linear problem
		SimplicialLDLT<SparseMatrix<double> > solver(A);
		VectorXd solution = solver.solve(B);
		for (int i = 0; i < invalidnum; i++)
			data[invalidcoord[i]] = solution[i];

	}
Example #28
0
int Train(ToolParam &tool_param, CommonSettings &settings) {

  if (tool_param.train_size() <= settings.param_index) {
    LOG(FATAL)<< "Train parameter index does not exist.";
  }

  TrainParam train_param = tool_param.train(settings.param_index);
  InputParam input_param = train_param.input();

  if(!(input_param.has_patch_size() && input_param.has_padding_size() && input_param.has_labels() && input_param.has_channels())) {
    LOG(FATAL) << "Patch size, padding size, label count or channel count parameter missing.";
  }
  int patch_size = input_param.patch_size();
  int padding_size = input_param.padding_size();
  unsigned int nr_labels = input_param.labels();
  unsigned int nr_channels = input_param.channels();

  std::string proto_solver = "";
  if(!train_param.has_solver()) {
    LOG(FATAL) << "Solver prototxt file argument missing";
  }

  proto_solver = train_param.solver();

  caffe::SolverParameter solver_param;
  caffe::ReadProtoFromTextFileOrDie(proto_solver, &solver_param);

  int test_interval = solver_param.has_test_interval()?solver_param.test_interval():-1;

  shared_ptr<caffe::Solver<float> > solver(
      caffe::GetSolver<float>(solver_param));

  if(train_param.has_solverstate()) {
    // Continue from previous solverstate
    const char* solver_state_c = train_param.solverstate().c_str();
    solver->Restore(solver_state_c);
  }

  // Get handles to the test and train network of the Caffe solver
  boost::shared_ptr<caffe::Net<float>> train_net = solver->net();
  boost::shared_ptr<caffe::Net<float>> test_net;
  if(solver->test_nets().size() > 0) {
    test_net = solver->test_nets()[0];
  }

  // Overwrite label count from the desired count to the pre-consolidation count
  if(input_param.has_preprocessor()) {
    PreprocessorParam preprocessor_param = input_param.preprocessor();
    if(preprocessor_param.has_label_consolidate()) {
      nr_labels = preprocessor_param.label_consolidate().label_size();
    }
  }

  TrainImageProcessor image_processor(patch_size, nr_labels);

  if(input_param.has_preprocessor()) {

    PreprocessorParam preprocessor_param = input_param.preprocessor();

    image_processor.SetBorderParams(input_param.has_padding_size(), padding_size / 2);
    image_processor.SetRotationParams(preprocessor_param.has_rotation() && preprocessor_param.rotation());
    image_processor.SetPatchMirrorParams(preprocessor_param.has_mirror() && preprocessor_param.mirror());
    image_processor.SetNormalizationParams(preprocessor_param.has_normalization() && preprocessor_param.normalization());

    if(preprocessor_param.has_label_consolidate()) {
      LabelConsolidateParam label_consolidate_param = preprocessor_param.label_consolidate();
      std::vector<int> con_labels;
      for(int cl = 0; cl < label_consolidate_param.label_size(); ++ cl) {
        con_labels.push_back(label_consolidate_param.label(cl));
      }
      image_processor.SetLabelConsolidateParams(preprocessor_param.has_label_consolidate(), con_labels);
    }

    if(preprocessor_param.has_histeq()) {
      PrepHistEqParam histeq_param = preprocessor_param.histeq();
      std::vector<float> label_boost(nr_labels, 1.0);
      for(int i = 0; i < histeq_param.label_boost().size(); ++i) {
        label_boost[i] = histeq_param.label_boost().Get(i);
      }
      image_processor.SetLabelHistEqParams(true, histeq_param.has_patch_prior()&&histeq_param.patch_prior(), histeq_param.has_masking()&&histeq_param.masking(), label_boost);
    }

    if(preprocessor_param.has_crop()) {
      PrepCropParam crop_param = preprocessor_param.crop();
      image_processor.SetCropParams(crop_param.has_imagecrop()?crop_param.imagecrop():0, crop_param.has_labelcrop()?crop_param.labelcrop():0);
    }

    if(preprocessor_param.has_clahe()) {
      PrepClaheParam clahe_param = preprocessor_param.clahe();
      image_processor.SetClaheParams(true, clahe_param.has_clip()?clahe_param.clip():4.0);
    }

    if(preprocessor_param.has_blur()) {
      PrepBlurParam blur_param = preprocessor_param.blur();
      image_processor.SetBlurParams(true, blur_param.has_mean()?blur_param.mean():0.0, blur_param.has_std()?blur_param.std():0.1, blur_param.has_ksize()?blur_param.ksize():5);
    }

  }

  if(!(input_param.has_raw_images() && input_param.has_label_images())) {
    LOG(FATAL) << "Raw images or label images folder missing.";
  }

  std::set<std::string> filetypes = CreateImageTypesSet();

  int error;
  std::vector<std::vector<bofs::path>> training_set = LoadTrainingSetItems(filetypes, input_param.raw_images(),input_param.label_images(),&error);

  unsigned int ijsum = 0;
  // Preload and preprocess all images
  for (unsigned int i = 0; i < training_set.size(); ++i) {
    std::vector<bofs::path> training_item = training_set[i];

    std::vector<cv::Mat> raw_stack;
    std::vector<std::vector<cv::Mat>> labels_stack(training_item.size() - 1);

    std::string type = bofs::extension(training_item[0]);
    std::transform(type.begin(), type.end(), type.begin(), ::tolower);

    if(type == ".tif" || type == ".tiff") {
      // TIFF and multipage TIFF mode
      raw_stack = LoadTiff(training_item[0].string(), nr_channels);
    } else {
      // All other image types
      cv::Mat raw_image = cv::imread(training_item[0].string(), nr_channels == 1 ? CV_LOAD_IMAGE_GRAYSCALE :
          CV_LOAD_IMAGE_COLOR);
      raw_stack.push_back(raw_image);
    }

    for(unsigned int k = 0; k < training_item.size() - 1; ++k) {
      std::string type = bofs::extension(training_item[k+1]);
      std::transform(type.begin(), type.end(), type.begin(), ::tolower);
      if(type == ".tif" || type == ".tiff") {
        std::vector<cv::Mat> label_stack = LoadTiff(training_item[k+1].string(), 1);
        labels_stack[k] = label_stack;
      }
      else {
        std::vector<cv::Mat> label_stack;
        cv::Mat label_image = cv::imread(training_item[k+1].string(), CV_LOAD_IMAGE_GRAYSCALE);
        label_stack.push_back(label_image);
        labels_stack[k] = label_stack;
      }
    }

    for (unsigned int j = 0; j < raw_stack.size(); ++j) {
      std::vector<cv::Mat> label_images;
      for(unsigned int k = 0; k < labels_stack.size(); ++k) {
        label_images.push_back(labels_stack[k][j]);
      }

      if(label_images.size() > 1 && nr_labels != 2 && label_images.size() < nr_labels) {
        // Generate complement label
        cv::Mat clabel(label_images[0].rows, label_images[0].cols, CV_8UC(1), 255.0);
        for(unsigned int k = 0; k < label_images.size(); ++k) {
          cv::subtract(clabel,label_images[k],clabel);
        }
        label_images.push_back(clabel);
      }

      image_processor.SubmitImage(raw_stack[j], ijsum, label_images);
      ++ijsum;
    }
  }

  image_processor.Init();

  std::vector<long> labelcounter(nr_labels + 1);

  int train_iters = solver_param.has_max_iter()?solver_param.max_iter():0;

  // Do the training
  for (int i = 0; i < train_iters; ++i) {
    std::vector<cv::Mat> patch = image_processor.DrawPatchRandom();

    std::vector<cv::Mat> images;
    std::vector<cv::Mat> labels;

    images.push_back(patch[0]);
    labels.push_back(patch[1]);

    // TODO: Only enable in debug or statistics mode
    for (int y = 0; y < patch_size; ++y) {
      for (int x = 0; x < patch_size; ++x) {
        labelcounter[patch[1].at<float>(y, x) + 1] += 1;
      }
    }

    if(settings.debug) {
      for (unsigned int k = 0; k < nr_labels + 1; ++k) {
        std::cout << "Label: " << k << ", " << labelcounter[k] << std::endl;
      }
    }

    if(settings.graphic) {

      cv::Mat test;

      double minVal, maxVal;
      cv::minMaxLoc(patch[1], &minVal, &maxVal);
      patch[1].convertTo(test, CV_32FC1, 1.0 / (maxVal - minVal),
          -minVal * 1.0 / (maxVal - minVal));

      std::vector<cv::Mat> tv;
      tv.push_back(test);
      tv.push_back(test);
      tv.push_back(test);
      cv::Mat tvl;

      cv::merge(tv, tvl);

      cv::Mat patchclone = patch[0].clone();

      tvl.copyTo(
          patchclone(
              cv::Rect(padding_size / 2, padding_size / 2, patch_size,
                  patch_size)));

      cv::imshow(OCVDBGW, patchclone);
      cv::waitKey(10);
    }

    // The labels
    std::vector<int> lalabels;
    lalabels.push_back(0);
    boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(
        train_net->layers()[0])->AddMatVector(labels, lalabels);

    // The images
    std::vector<int> imlabels;
    imlabels.push_back(0);
    boost::dynamic_pointer_cast<caffe::MemoryDataLayer<float>>(
        train_net->layers()[1])->AddMatVector(images, imlabels);

    solver->Step(1);

    if(test_interval > -1 && i % test_interval == 0) {
      // TODO: Run tests with the testset and testnet
      // TODO: Apply ISBI and other quality measures (cross, rand, pixel, warp, loss)
      // TODO: Write out statistics to file
    }
  }

  LOG(INFO) << "Training done!";

  return 0;
}
Example #29
0
//------------------------------------------------------------------------------
int main( int argc, char * argv[] )
{
    //--------------------------------------------------------------------------
    const unsigned    geomDeg   = 1;
    const unsigned    dim       = 2;
    // degrees of lowest-order TH element
    const unsigned    fieldDegU = 2; 
    const unsigned    fieldDegP = 1;

    const unsigned    tiOrder   = 1;
    typedef  base::time::BDF<tiOrder> MSM;
    
    const base::Shape shape     = base::SimplexShape<dim>::value;
    const base::Shape surfShape = base::SimplexShape<dim-1>::value;

    //--------------------------------------------------------------------------
    if ( argc != 2 ) {
        std::cout << "Usage:  " << argv[0] << " input.dat \n\n";
        return -1;
    }

    const std::string inputFile = boost::lexical_cast<std::string>( argv[1] );

    //--------------------------------------------------------------------------
    std::string meshFile, surfFile;
    double viscosity, density, tolerance, penaltyFactor, stepSize;
    unsigned maxIter, numSteps;
    {    
        //Feed properties parser with the variables to be read
        base::io::PropertiesParser prop;
        prop.registerPropertiesVar( "meshFile",         meshFile );
        prop.registerPropertiesVar( "surfFile",         surfFile );
        prop.registerPropertiesVar( "viscosity",        viscosity );
        prop.registerPropertiesVar( "density",          density );
        prop.registerPropertiesVar( "maxIter",          maxIter );
        prop.registerPropertiesVar( "tolerance",        tolerance );
        prop.registerPropertiesVar( "penaltyFactor",    penaltyFactor );
        prop.registerPropertiesVar( "stepSize",         stepSize );
        prop.registerPropertiesVar( "numSteps",         numSteps );

        // Read variables from the input file
        std::ifstream inp( inputFile.c_str()  );
        VERIFY_MSG( inp.is_open(), "Cannot open input file" );
        prop.readValues( inp );
        inp.close( );

        // Make sure all variables have been found
        if ( not prop.isEverythingRead() ) {
            prop.writeUnread( std::cerr );
            VERIFY_MSG( false, "Could not find above variables" );
        }
    }

    const std::string baseName = base::io::baseName( meshFile, ".smf" );

    //--------------------------------------------------------------------------
    typedef base::Unstructured<shape,geomDeg>     Mesh;

    Mesh mesh;
    {
        std::ifstream smf( meshFile.c_str() );
        VERIFY_MSG( smf.is_open(), "Cannot open mesh file" );
        base::io::smf::readMesh( smf, mesh );
        smf.close();
    }

    //--------------------------------------------------------------------------
    // Surface mesh
    typedef base::Unstructured<surfShape,1,dim>    SurfMesh;

    SurfMesh surfMesh;
    {
        std::ifstream smf( surfFile.c_str() );
        base::io::smf::readMesh( smf, surfMesh );
        smf.close();
    }

    //--------------------------------------------------------------------------
    // Compute the level set data
    typedef base::cut::LevelSet<dim> LevelSet;
    std::vector<LevelSet> levelSet;
    const bool isSigned = true;
    base::cut::bruteForce( mesh, surfMesh, isSigned, levelSet );

    const unsigned kernelDegEstimate = 5;

    //--------------------------------------------------------------------------
    // Make cut cell structure
    typedef base::cut::Cell<shape> Cell;
    std::vector<Cell> cells;
    base::cut::generateCutCells( mesh, levelSet, cells );

    // Quadrature 
    typedef base::cut::Quadrature<kernelDegEstimate,shape> CutQuadrature;
    CutQuadrature quadrature( cells, true );

    // for surface
    typedef base::SurfaceQuadrature<kernelDegEstimate,shape> SurfaceQuadrature;
    SurfaceQuadrature surfaceQuadrature;

    //------------------------------------------------------------------------------
    // Finite element bases
    const unsigned    nHist = MSM::numSteps;
    
    const unsigned    doFSizeU = dim;
    typedef base::fe::Basis<shape,fieldDegU>                FEBasisU;
    typedef base::cut::ScaledField<FEBasisU,doFSizeU,nHist> Velocity;
    Velocity velocity;
    base::dof::generate<FEBasisU>( mesh, velocity );
    
    const unsigned    doFSizeP = 1;
    typedef base::fe::Basis<shape,fieldDegP>                FEBasisP;
    typedef base::cut::ScaledField<FEBasisP,doFSizeP,nHist> Pressure;
    Pressure pressure;
    base::dof::generate<FEBasisP>( mesh, pressure );

    const unsigned    doFSizeS = dim;
    typedef base::fe::Basis<surfShape,1>              FEBasisS;
    typedef base::Field<FEBasisS,doFSizeS>            SurfField;
    SurfField surfVelocity, surfForces;
    base::dof::generate<FEBasisS>( surfMesh, surfVelocity );
    base::dof::generate<FEBasisS>( surfMesh, surfForces   );

    // set initial condition to the identity 
    base::dof::setField( surfMesh, surfVelocity,
                         boost::bind( &surfaceVelocity<dim,
                                      SurfField::DegreeOfFreedom>, _1, _2 ) );


    // boundary datum    
    base::cut::TransferSurfaceDatum<SurfMesh,SurfField,Mesh::Element>
        s2d( surfMesh, surfVelocity, levelSet );
    
    //--------------------------------------------------------------------------
    //  surface mesh
    typedef base::mesh::BoundaryMeshBinder<Mesh>::Type BoundaryMesh;
    BoundaryMesh boundaryMesh, immersedMesh;

    // from boundary
    {
        // identify list of element boundary faces
        base::mesh::MeshBoundary meshBoundary;
        meshBoundary.create( mesh.elementsBegin(), mesh.elementsEnd() );

        // generate a mesh from that list (with a filter)
        base::mesh::generateBoundaryMesh( meshBoundary.begin(),
                                          meshBoundary.end(),
                                          mesh, boundaryMesh,
                                          boost::bind( &boundaryFilter<dim>, _1 ) );

        // make a surface mesh from the implicit surface
        base::cut::generateSurfaceMesh<Mesh,Cell>( mesh, cells, immersedMesh );
    }

    // the composite field with geometry, velocity and pressure
    typedef base::asmb::FieldBinder<Mesh,Velocity,Pressure> Field;
    Field field( mesh, velocity, pressure );

    // define the system blocks (U,U), (U,P), and (P,U)
    typedef Field::TupleBinder<1,1,1>::Type TopLeft;
    typedef Field::TupleBinder<1,2>::Type   TopRight;
    typedef Field::TupleBinder<2,1>::Type   BotLeft;


    std::vector<double> supportsU, supportsP;
    std::size_t numDoFsU = std::distance( velocity.doFsBegin(), velocity.doFsEnd() );
    supportsU.resize( numDoFsU );
    std::size_t numDoFsP = std::distance( pressure.doFsBegin(), pressure.doFsEnd() );
    supportsP.resize( numDoFsP );

    base::cut::supportComputation( mesh, velocity, quadrature, supportsU );
    base::cut::supportComputation( mesh, pressure, quadrature, supportsP );

    velocity.scaleAndTagBasis( supportsU, 1.e-8 );
    pressure.scaleAndTagBasis( supportsP, 1.e-8 ); 
    //velocity.tagBasis( supportsU, 1.e-8 );
    //pressure.tagBasis( supportsP, 1.e-8 ); 

    // Fix one pressure dof
    // Pressure::DoFPtrIter pIter = pressure.doFsBegin();
    // std::advance( pIter, std::distance( pressure.doFsBegin(), pressure.doFsEnd() )/5 );
    // (*pIter) -> constrainValue( 0, 0.0 );

    // Number of DoFs after constraint application!
    numDoFsU =
        base::dof::numberDoFsConsecutively( velocity.doFsBegin(), velocity.doFsEnd() );
    std::cout << "# Number of velocity dofs " << numDoFsU << std::endl;

    numDoFsP =
        base::dof::numberDoFsConsecutively( pressure.doFsBegin(), pressure.doFsEnd(),
            numDoFsU );
    std::cout << "# Number of pressure dofs " << numDoFsP << std::endl;

    // kernels
    typedef fluid::StressDivergence<  TopLeft::Tuple>  StressDivergence;
    typedef fluid::Convection<        TopLeft::Tuple>  Convection;
    typedef fluid::PressureGradient<  TopRight::Tuple> GradP;
    typedef fluid::VelocityDivergence<BotLeft::Tuple>  DivU;

    StressDivergence stressDivergence( viscosity );
    Convection       convection(       density );
    GradP            gradP;
    DivU             divU( true );

    // for surface fields
    typedef base::asmb::SurfaceFieldBinder<BoundaryMesh,Velocity,Pressure> SurfaceFieldBinder;
    typedef SurfaceFieldBinder::TupleBinder<1,1,1>::Type STBUU;
    typedef SurfaceFieldBinder::TupleBinder<1,2  >::Type STBUP;
    SurfaceFieldBinder   boundaryFieldBinder(  boundaryMesh, velocity, pressure );
    SurfaceFieldBinder   immersedFieldBinder(  immersedMesh, velocity, pressure );

    std::ofstream forces( "forces.dat" );

    for ( unsigned step = 0; step < numSteps; step++ ) {

        const double time = step * stepSize;
        const double factor = ( time < 1.0 ? time : 1.0 );
    
        std::cout << step << ":  time=" << time << ", factor=" << factor
                  << "\n";

        //base::dof::clearDoFs( velocity );
        //base::dof::clearDoFs( pressure );
        
        //--------------------------------------------------------------------------
        // Nonlinear iterations
        unsigned iter = 0;
        while( iter < maxIter ) {

            // Create a solver object
            typedef base::solver::Eigen3           Solver;
            Solver solver( numDoFsU + numDoFsP );

            std::cout << "* Iteration " << iter << std::flush;

            // compute inertia terms, d/dt, due to time integration
            base::time::computeInertiaTerms<TopLeft,MSM>( quadrature, solver,
                                                          field, stepSize, step,
                                                          density );
    
            // Compute system matrix
            base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver,
                                                             field, stressDivergence );

            base::asmb::stiffnessMatrixComputation<TopLeft>( quadrature, solver,
                                                             field, convection );

            base::asmb::stiffnessMatrixComputation<TopRight>( quadrature, solver,
                                                              field, gradP );

            base::asmb::stiffnessMatrixComputation<BotLeft>( quadrature, solver,
                                                             field, divU );
            // compute residual forces
            base::asmb::computeResidualForces<TopLeft >( quadrature, solver, field,
                                                         stressDivergence );
            base::asmb::computeResidualForces<TopLeft >( quadrature, solver, field, convection );
            base::asmb::computeResidualForces<TopRight>( quadrature, solver, field, gradP );
            base::asmb::computeResidualForces<BotLeft >( quadrature, solver, field, divU );
        
            // Parameter classes
            base::nitsche::OuterBoundary ob( viscosity );
            base::nitsche::ImmersedBoundary<Cell> ib( viscosity, cells );

            // Penalty method
            base::nitsche::penaltyLHS<STBUU>( surfaceQuadrature, solver,
                                              boundaryFieldBinder, ob, penaltyFactor );
        
            base::nitsche::penaltyRHS<STBUU>( surfaceQuadrature, solver, boundaryFieldBinder, 
                                              boost::bind( &dirichlet<dim>, _1, factor),
                                              ob, penaltyFactor );

            base::nitsche::penaltyLHS<STBUU>( surfaceQuadrature, solver,
                                              immersedFieldBinder, ib, penaltyFactor );
        
            base::nitsche::penaltyRHS2<STBUU>( surfaceQuadrature, solver, immersedFieldBinder,
                                               s2d, ib, penaltyFactor );

            // Nitsche terms
            base::nitsche::primalEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                   boundaryFieldBinder, ob );
            base::nitsche::dualEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                 boundaryFieldBinder, ob );
            base::nitsche::energyRHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                             boundaryFieldBinder,
                                             boost::bind( &dirichlet<dim>, _1, factor),
                                             ob );
        
            base::nitsche::primalEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                   boundaryFieldBinder, ob );
            base::nitsche::dualEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                 boundaryFieldBinder, ob );
         
            base::nitsche::energyRHS<STBUP>( gradP, surfaceQuadrature, solver,
                                             boundaryFieldBinder,
                                             boost::bind( &dirichlet<dim>, _1, factor), ob );

            base::nitsche::energyResidual<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                  boundaryFieldBinder, ob );
            
            base::nitsche::energyResidual<STBUP>( gradP, surfaceQuadrature, solver,
                                                  boundaryFieldBinder, ob );

            base::nitsche::primalEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                   immersedFieldBinder, ib );
            base::nitsche::dualEnergyLHS<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                 immersedFieldBinder, ib );

            base::nitsche::energyRHS2<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                              immersedFieldBinder, s2d, ib );
            
            base::nitsche::primalEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                   immersedFieldBinder, ib );
            base::nitsche::dualEnergyLHS<STBUP>( gradP, surfaceQuadrature, solver,
                                                 immersedFieldBinder, ib );

            base::nitsche::energyRHS2<STBUP>( gradP, surfaceQuadrature, solver,
                                              immersedFieldBinder, s2d, ib );

            base::nitsche::energyResidual<STBUU>( stressDivergence, surfaceQuadrature, solver,
                                                  immersedFieldBinder, ib );

            base::nitsche::energyResidual<STBUP>( gradP, surfaceQuadrature, solver,
                                                  immersedFieldBinder, ib );
        
            // Finalise assembly
            solver.finishAssembly();

            // check convergence via solver norms
            const double residualNorm = solver.norm();
            std::cout << " |R| = " << residualNorm << std::flush;

            if ( residualNorm < tolerance * viscosity) {
                std::cout << std::endl;
                break;
            }

            // Solve
            solver.superLUSolve();

            // distribute results back to dofs
            base::dof::addToDoFsFromSolver( solver, velocity );
            base::dof::addToDoFsFromSolver( solver, pressure );
            //base::dof::setDoFsFromSolver( solver, pressure );
        
            // check convergence via solver norms
            const double incrementNorm = solver.norm(0, numDoFsU );
            std::cout << " |dU| = " << incrementNorm << std::endl;

            // push history
            base::dof::pushHistory( velocity );
            base::dof::pushHistory( pressure );
        
            if ( incrementNorm < tolerance ) break;

            iter++;

        }

        writeVTKFile( baseName, step, mesh, velocity, pressure, levelSet, viscosity );
        {
            base::Vector<dim>::Type sumOfForces = base::constantVector<dim>( 0. );
            
            typedef Field::TupleBinder<1,2>::Type UP;
            //typedef fluid::Stress<UP::Tuple> Stress;
            //Stress stress( viscosity );
            typedef fluid::Traction<UP::Tuple> Traction;
            Traction traction( viscosity );
                
            base::cut::ComputeSurfaceForces<SurfMesh,SurfField,
                                            SurfaceQuadrature,STBUP::Tuple,Traction>
                computeSurfaceForces( surfMesh, surfForces, surfaceQuadrature, levelSet, traction );

            SurfaceFieldBinder::FieldIterator first = immersedFieldBinder.elementsBegin();
            SurfaceFieldBinder::FieldIterator  last = immersedFieldBinder.elementsEnd();
            for ( ; first != last; ++first ) {
                
                sumOfForces +=
                    computeSurfaceForces( STBUP::makeTuple( *first ) );
                
            }

            writeSurfaceVTKFile( baseName, step, surfMesh, surfVelocity, surfForces );


            std::cout << "  F= " << sumOfForces.transpose() << " \n";

            forces << time << " " << sumOfForces.transpose() << std::endl;;
        }

    }

    forces.close();

    return 0;
}
Example #30
0
int solver(int *board[36][36], int solutions)
{
    int *copy[36][36];
    int invalidflag, space, status;

    //fill a copy board
    for (row = 0; row < 36; row++)
        for (col = 0; col < 36; col++)
            copy[row][col] = board[row][col];


    //fill in a new place
    for (row = 0; row < boardrow; row++)
    {
        for (col = 0; col < boardcol; col++)
        {
            //check if default board is broken
            if (copy[row][col] != 0)
            {
                if (checkinvalid(copy, row, col) == 1)
                    return -1;
            }

            //found EMPTY space
            else
            {
                //fill in the empty space
                for (space = 1; space <= boardrow; space++)
                {
                    //put in new value
                    copy[row][col] = space;

                    //check if duplicates
                    invalidflag = checkinvalid(copy, row, col);


                    //if it has passed, go to next level
                    if (invalidflag == 0)
                    {
                        status = solver(copy, 0); //RECURSION

                        if ( status > 0)
                        {
                            return status; //exit strategy
                        }

                        else if ( status == -1 )
                            return -1; //already-broken matrix, EJECT!
                    }
                }

                //didn't pass
                return 0; //broken matrix, WE HAVE TO GO BACK
            }
        }
    }

    //no more empty spaces, only a complete board gets here
    solutions++;

    if (solutions == 1)
    {
        //save old board:
        for (row = 0; row < 36; row++)
        {
            for (col = 0; col < 36; col++)
            {
                temp2[row][col] = data[row][col];
                data[row][col] = copy[row][col];
            }
        }

        //print first solution
        printboard(data);
    }

    return solutions;
}