/*!\file: solver_nonlinear.cpp
 * \brief: core of a non-linear solution, using fixed-point method 
 */ 

#include "../toolkits/toolkits.h"
#include "../classes/objects/objects.h"
#include "../io/io.h"
#include "../EnumDefinitions/EnumDefinitions.h"
#include "../modules/modules.h"
#include "../solutions/solutions.h"
#include "./solvers.h"

void solver_nonlinear(FemModel* femmodel,bool conserve_loads){

	/*intermediary: */
	Matrix<IssmDouble>* Kff = NULL;
	Matrix<IssmDouble>* Kfs = NULL;
	Vector<IssmDouble>* ug  = NULL;
	Vector<IssmDouble>* old_ug = NULL;
	Vector<IssmDouble>* uf  = NULL;
	Vector<IssmDouble>* old_uf = NULL;
	Vector<IssmDouble>* pf  = NULL;
	Vector<IssmDouble>* df  = NULL;
	Vector<IssmDouble>* ys  = NULL;

	Loads* savedloads=NULL;
	bool converged;
	int constraints_converged;
	int num_unstable_constraints;
	int count;

	/*parameters:*/
	int min_mechanical_constraints;
	int max_nonlinear_iterations;
	int configuration_type;

	/*Recover parameters: */
	femmodel->parameters->FindParam(&min_mechanical_constraints,DiagnosticRiftPenaltyThresholdEnum);
	femmodel->parameters->FindParam(&max_nonlinear_iterations,DiagnosticMaxiterEnum);
	femmodel->parameters->FindParam(&configuration_type,ConfigurationTypeEnum);
	femmodel->UpdateConstraintsx();

	/*Were loads requested as output? : */
	if(conserve_loads){
		savedloads = static_cast<Loads*>(femmodel->loads->Copy());
	}

	count=1;
	converged=false;

	/*Start non-linear iteration using input velocity: */
	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices,femmodel->loads, femmodel->materials, femmodel->parameters);
	Reducevectorgtofx(&uf, ug, femmodel->nodes,femmodel->parameters);

	//Update once again the solution to make sure that vx and vxold are similar (for next step in transient or steadystate)
	InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
	InputUpdateFromSolutionx(femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);

	for(;;){

		//save pointer to old velocity
		xdelete(&old_ug);old_ug=ug;
		xdelete(&old_uf);old_uf=uf;

		femmodel->SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL);
		CreateNodalConstraintsx(&ys,femmodel->nodes,configuration_type);
		Reduceloadx(pf, Kfs, ys); xdelete(&Kfs);
		Solverx(&uf, Kff, pf, old_uf, df, femmodel->parameters);
		Mergesolutionfromftogx(&ug, uf,ys,femmodel->nodes,femmodel->parameters);xdelete(&ys);

		convergence(&converged,Kff,pf,uf,old_uf,femmodel->parameters); xdelete(&Kff); xdelete(&pf); xdelete(&df);
		InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
		InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);

		ConstraintsStatex(&constraints_converged, &num_unstable_constraints, femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters);
		if(VerboseConvergence()) _pprintLine_("   number of unstable constraints: " << num_unstable_constraints);

		//rift convergence
		if (!constraints_converged) {
			if (converged){
				if (num_unstable_constraints <= min_mechanical_constraints) converged=true;
				else converged=false;
			}
		}

		/*Increase count: */
		count++;
		if(converged==true){
			bool max_iteration_state=false;
			int tempStep=1;
			IssmDouble tempTime=1.0;
			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
			break;
		}
		if(count>=max_nonlinear_iterations){
			_pprintLine_("   maximum number of nonlinear iterations (" << max_nonlinear_iterations << ") exceeded"); 
			converged=true;
			InputUpdateFromConstantx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,converged,ConvergedEnum);
			InputUpdateFromSolutionx( femmodel->elements,femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,ug);		
			bool max_iteration_state=true;
			int tempStep=1;
			IssmDouble tempTime=1.0;
			femmodel->results->AddObject(new GenericExternalResult<bool>(femmodel->results->Size()+1, MaxIterationConvergenceFlagEnum, max_iteration_state, tempStep, tempTime));
			break;
		}
	}

	if(VerboseConvergence()) _pprintLine_("\n   total number of iterations: " << count-1);

	/*clean-up*/
	if(conserve_loads){
		delete femmodel->loads;
		femmodel->loads=savedloads;
	}
	xdelete(&uf);
	xdelete(&ug);
	xdelete(&old_ug);
	xdelete(&old_uf);
}
