// Helper function to determine whether a Fad type is real
      static bool is_fad_real(const FadType& x) {
	if (x.size() == 0)
	  return true;
	if (Teuchos::ScalarTraits<ValueT>::isComplex) {
	  if (!is_complex_real(x.val()))
	    return false;
	  for (int i=0; i<x.size(); i++)
	    if (!is_complex_real(x.fastAccessDx(i)))
	      return false;
	}
	return true;
      }
      static bool isnaninf(const FadType& x) { 
	if (Teuchos::ScalarTraits<ValueT>::isnaninf(x.val()))
	  return true;
	for (int i=0; i<x.size(); i++)
	  if (Teuchos::ScalarTraits<ValueT>::isnaninf(x.dx(i)))
	    return true;
	return false;
      }
      static magnitudeType magnitude(const FadType& a) {
#ifdef TEUCHOS_DEBUG
	TEUCHOS_SCALAR_TRAITS_NAN_INF_ERR(
	  a, "Error, the input value to magnitude(...) a = " << a << 
	  " can not be NaN!" );
	TEST_FOR_EXCEPTION(is_fad_real(a) == false, std::runtime_error,
			   "Complex magnitude is not a differentiable "
			   "function of complex inputs.");
#endif
	//return std::fabs(a); 
	magnitudeType b(a.size(), 
			Teuchos::ScalarTraits<ValueT>::magnitude(a.val()));
	if (Teuchos::ScalarTraits<ValueT>::real(a.val()) >= 0)
	  for (int i=0; i<a.size(); i++)
	    b.fastAccessDx(i) = 
	      Teuchos::ScalarTraits<ValueT>::magnitude(a.fastAccessDx(i));
	else
	  for (int i=0; i<a.size(); i++)
	    b.fastAccessDx(i) = 
	      -Teuchos::ScalarTraits<ValueT>::magnitude(a.fastAccessDx(i));
	return b;
      }