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

#include "./RheologyBbarAbsGradientx.h"

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

void RheologyBbarAbsGradientx( IssmDouble* pJ, Elements* elements,Nodes* nodes, Vertices* vertices, Loads* loads, Materials* materials,Parameters* parameters, 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(weight_index);
	}

	/*Sum all J from all cpus of the cluster:*/
	ISSM_MPI_Reduce (&J,&J_sum,1,ISSM_MPI_DOUBLE,ISSM_MPI_SUM,0,IssmComm::GetComm() );
	ISSM_MPI_Bcast(&J_sum,1,ISSM_MPI_DOUBLE,0,IssmComm::GetComm());
	J=J_sum;

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