/*!\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* Kff = NULL;
	Matrix* Kfs = NULL;
	Vector* ug  = NULL;
	Vector* old_ug = NULL;
	Vector* uf  = NULL;
	Vector* old_uf = NULL;
	Vector* pf  = NULL;
	Vector* df  = NULL;
	Vector* ys  = NULL;
	
	Loads* loads=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);
	UpdateConstraintsx(femmodel->nodes,femmodel->constraints,femmodel->parameters);

	/*Were loads requested as output? : */
	if(conserve_loads) loads=(Loads*)femmodel->loads->Copy(); //protect loads from being modified by the solution
	else               loads=(Loads*)femmodel->loads;         //modify loads  in this solution

	count=1;
	converged=false;

	/*Start non-linear iteration using input velocity: */
	GetSolutionFromInputsx(&ug, femmodel->elements, femmodel->nodes, femmodel->vertices, 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;

		SystemMatricesx(&Kff, &Kfs, &pf, &df, NULL,femmodel->elements,femmodel->nodes,femmodel->vertices,loads,femmodel->materials,femmodel->parameters);
		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,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 BoolExternalResult(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 BoolExternalResult(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 loads;
	xdelete(&uf);
	xdelete(&ug);
	xdelete(&old_ug);
	xdelete(&old_uf);
}
