/*!\file RheologyBbarAbsGradientx
 * \brief: compute misfit between observations and model
 */

#include "./RheologyBbarAbsGradientx.h"

#include "../../shared/shared.h"
#include "../../include/include.h"
#include "../../toolkits/toolkits.h"
#include "../../EnumDefinitions/EnumDefinitions.h"

void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters,bool process_units, int weight_index){

	/*Intermediary*/
	int i;
	Element* element=NULL;

	/*output: */
	IssmDouble J=0;
	IssmDouble J_sum;

	/*Compute Misfit: */
	for (i=0;i<elements->Size();i++){
		element=dynamic_cast<Element*>(elements->GetObjectByOffset(i));
		J+=element->RheologyBbarAbsGradient(process_units,weight_index);
	}

	/*Sum all J from all cpus of the cluster:*/
	#ifdef _HAVE_MPI_
	MPI_Reduce (&J,&J_sum,1,MPI_DOUBLE,MPI_SUM,0,IssmComm::GetComm() );
	MPI_Bcast(&J_sum,1,MPI_DOUBLE,0,IssmComm::GetComm());
	J=J_sum;
	#endif

	/*Assign output pointers: */
	*pJ=J;
}
