diff --git a/include/cantera/base/Array.h b/include/cantera/base/Array.h index 8962d0acb..cc075c85c 100644 --- a/include/cantera/base/Array.h +++ b/include/cantera/base/Array.h @@ -124,18 +124,6 @@ public: m_data.resize(n*m, v); } - //! Copy the data from one array into another without doing any checking - /*! - * This differs from the assignment operator as no resizing is done and memcpy() is used. - * @param y Array to be copied - * @deprecated To be removed after Cantera 2.2. - */ - void copyData(const Array2D& y) { - warn_deprecated("Array2D::copyData", "To be removed after Cantera 2.2."); - size_t n = sizeof(doublereal) * m_nrows * m_ncols; - (void) memcpy(DATA_PTR(m_data), y.ptrColumn(0), n); - } - //! Append a column to the existing matrix using a std vector /*! * This operation will add a column onto the existing matrix. diff --git a/include/cantera/base/ctexceptions.h b/include/cantera/base/ctexceptions.h index fbb0194ae..148374b15 100644 --- a/include/cantera/base/ctexceptions.h +++ b/include/cantera/base/ctexceptions.h @@ -55,37 +55,6 @@ namespace Cantera * preprocessor symbol is defined, e.g. with the compiler option -DNDEBUG. */ -//! Enum containing Cantera's behavior for situations where overflow or underflow of real variables -//! may occur. -/*! - * Note this frequently occurs when taking exponentials of delta Gibbs energies of reactions - * or when taking the exponentials of logs of activity coefficients. - */ -enum CT_RealNumber_Range_Behavior { - - //! For this specification of range behavior, nothing is done. This is the fastest - //! behavior when all calculations are believed to be ranged well. For situations - //! where there are range errors, NaN's or INF's will be introduced. - DONOTHING_CTRB = -1, - - //! For this specification of range behavior, the overflow or underflow calculation is changed. - //! Cantera will proceed by bounding the real number to maintain its viability, silently - //! changing the actual answer. - CHANGE_OVERFLOW_CTRB, - - //! When an overflow or underflow occurs, Cantera will throw an error - THROWON_OVERFLOW_CTRB, - - //! Cantera will use the fenv check capability introduced in C99 to check for - //! overflow and underflow conditions at crucial points. - //! It will throw an error if these conditions occur. - FENV_CHECK_CTRB, - - //! Cantera will throw an error in debug mode but will not in production mode. - //! (default) - THROWON_OVERFLOW_DEBUGMODEONLY_CTRB -}; - //! Base class for exceptions thrown by Cantera classes. /*! diff --git a/include/cantera/base/ctml.h b/include/cantera/base/ctml.h index 0b01ac93c..81ade7bce 100644 --- a/include/cantera/base/ctml.h +++ b/include/cantera/base/ctml.h @@ -673,49 +673,6 @@ XML_Node* getByTitle(const XML_Node& node, const std::string& title); void getString(const XML_Node& node, const std::string& titleString, std::string& valueString, std::string& typeString); -//! This function attempts to read a named child node and returns with the -//! contents in the value string. title attribute named "titleString" -/*! - * This function will read a child node to the current XML node, with the name - * "string". It must have a title attribute, named titleString, and the body - * of the XML node will be read into the valueString output argument. - * - * If the child node is not found then the empty string is returned. - * - * Example: - * - * Code snippet: - * @code - * const XML_Node &node; - * std::string valueString; - * std::string typeString; - * std::string nameString = "timeIncrement"; - * getString(XML_Node& node, nameString, valueString, valueString, typeString); - * @endcode - * - * Reads the following the snippet in the XML file: - * - * - * valueString - * <\nameString> - * - * or alternatively as a retrofit and special case, it also reads the - * following case: - * - * - * valueString - * <\string> - * - * @param node Reference to the XML_Node object of the parent XML element - * @param[in] nameString Name of the XML Node - * @param[out] valueString Value string that is found in the child node. - * @param[out] typeString String type. This is an optional output variable. - * It is filled with the attribute "type" of the XML entry. - * @deprecated To be removed after Cantera 2.2. - */ -void getNamedStringValue(const XML_Node& node, const std::string& nameString, std::string& valueString, - std::string& typeString); - //! This function reads a child node with the name, nameString, and returns //! its XML value as the return string /*! diff --git a/include/cantera/base/global.h b/include/cantera/base/global.h index 1201f9353..ca4f199a5 100644 --- a/include/cantera/base/global.h +++ b/include/cantera/base/global.h @@ -172,9 +172,6 @@ void writelogendl(); void writeline(char repeat, size_t count, bool endl_after=true, bool endl_before=false); -//! @copydoc Application::Messages::logerror -void error(const std::string& msg); - //! @copydoc Application::warn_deprecated void warn_deprecated(const std::string& method, const std::string& extra=""); diff --git a/include/cantera/base/stringUtils.h b/include/cantera/base/stringUtils.h index b0bb79e37..a71796895 100644 --- a/include/cantera/base/stringUtils.h +++ b/include/cantera/base/stringUtils.h @@ -95,48 +95,6 @@ std::string lowercase(const std::string& s); compositionMap parseCompString(const std::string& ss, const std::vector& names=std::vector()); -//! Parse a composition string into individual key:composition pairs -/*! - * @param ss original string consisting of multiple key:composition - * pairs on multiple lines - * @param w Output vector consisting of single key:composition - * items in each index. - * @deprecated Unused. To be removed after Cantera 2.2. - */ -void split(const std::string& ss, std::vector& w); - -//! Interpret a string as a list of floats, and convert it to a vector -//! of floats -/*! - * @param str String input vector - * @param a Output pointer to a vector of floats - * @param delim character delimiter. Defaults to a space - * @return Returns the number of floats found and converted - * @deprecated Unused. To be removed after Cantera 2.2. - */ -int fillArrayFromString(const std::string& str, doublereal* const a, - const char delim = ' '); - -//! Generate a logfile name based on an input file name -/*! - * It tries to find the basename. Then, it appends a .log to it. - * - * @param infile Input file name - * @return Returns a logfile name - * @deprecated Unused function to be removed after Cantera 2.2. - */ -std::string logfileName(const std::string& infile); - -//! Get the file name without the path or extension -/*! - * @param fullPath Input file name consisting - * of the full file name - * - * @return Returns the basename - * @deprecated Unused function to be removed after Cantera 2.2. - */ -std::string getBaseName(const std::string& fullPath); - //! Translate a string into one integer value /*! * No error checking is done on the conversion. The c stdlib function diff --git a/include/cantera/base/utilities.h b/include/cantera/base/utilities.h index e97058833..8ba3b5545 100644 --- a/include/cantera/base/utilities.h +++ b/include/cantera/base/utilities.h @@ -90,26 +90,6 @@ inline doublereal dot5(const V& x, const V& y) x[4]*y[4]; } -//! Templated Inner product of two vectors of length 6 -/*! - * If either \a x - * or \a y has length greater than 4, only the first 4 elements - * will be used. - * - * @param x first reference to the templated class V - * @param y second reference to the templated class V - * @return - * This class returns a hard-coded type, doublereal. - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline doublereal dot6(const V& x, const V& y) -{ - warn_deprecated("dot6", "To be removed after Cantera 2.2."); - return x[0]*y[0] + x[1]*y[1] + x[2]*y[2] + x[3]*y[3] + - x[4]*y[4] + x[5]*y[5]; -} - //! Function that calculates a templated inner product. /*! * This inner product is templated twice. The output variable is hard coded @@ -161,50 +141,6 @@ inline void scale(InputIter begin, InputIter end, std::transform(begin, end, out, timesConstant(scale_factor)); } -/*! - * Multiply elements of an array, y, by a scale factor, f and add the - * result to an existing array, x. This is essentially a templated daxpy_ - * operation. - * - * The template arguments are: template - * - * Simple Code Example of the functionality; - * @code - * double x[10], y[10], f; - * for (i = 0; i < n; i++) { - * y[i] += f * x[i] - * } - * @endcode - * Example of the function call to implement the simple code example - * @code - * double x[10], y[10], f; - * increment_scale(x, x+10, y, f); - * @endcode - * - * It is templated with three parameters. The first template - * is the iterator, InputIter, which controls access to y[]. - * The second template is the iterator OutputIter, which controls - * access to y[]. The third iterator is S, which is f. - * - * @param begin InputIter Iterator for beginning of y[] - * @param end inputIter Iterator for end of y[] - * @param out OutputIter Iterator for beginning of x[] - * @param scale_factor Scale Factor to multiply y[i] by - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void increment_scale(InputIter begin, InputIter end, - OutputIter out, S scale_factor) -{ - warn_deprecated("increment_scale", - "To be removed after Cantera 2.2."); - for (; begin != end; ++begin, ++out) { - *out += scale_factor * *begin; - } -} - - //! Multiply each entry in x by the corresponding entry in y. /*! * The template arguments are: template @@ -239,44 +175,6 @@ inline void multiply_each(OutputIter x_begin, OutputIter x_end, } } -//! Invoke method 'resize' with argument \a m for a sequence of objects (templated version) -/*! - * The template arguments are: template - * - * Simple code Equivalent: - * \code - * vector *> VV; - * for (n = 0; n < 20; n++) { - * vector *vp = VV[n]; - * vp->resize(m); - * } - * \endcode - * Example of function call usage to implement the simple code example: - * \code - * vector *> VV; - * resize_each(m, &VV[0], &VV[20]); - * \endcode - * - * @param m Integer specifying the size that each object should be resized to. - * @param begin Iterator pointing to the beginning of the sequence of object, belonging to the - * iterator class InputIter. - * @param end Iterator pointing to the end of the sequence of objects, belonging to the - * iterator class InputIter. The difference between end and begin - * determines the loop length - * - * @note This is currently unused. - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void resize_each(int m, InputIter begin, InputIter end) -{ - warn_deprecated("resize_each", - "To be removed after Cantera 2.2."); - for (; begin != end; ++begin) { - begin->resize(m); - } -} - //! The maximum absolute value (templated version) /*! * The template arguments are: template @@ -480,44 +378,6 @@ inline void scatter_mult(InputIter mult_begin, InputIter mult_end, } } - -//! Divide selected elements in an array by a contiguous sequence of divisors. -/*! - * The template arguments are: template - * - * Example: - * \code - * double divisors[] = {8.9, -2.0, 5.6}; - * int index[] = {7, 4, 13}; - * vector_fp data(20); - * ... - * // divide elements 7, 4, and 13 in data by divisors[7] divisors[4], and divisors[13] - * // respectively - * scatter_divide(divisors, divisors + 3, data.begin(), index); - * \endcode - * - * @param begin Iterator pointing to the beginning of the source vector, belonging to the - * iterator class InputIter. - * @param end Iterator pointing to the end of the source vector, belonging to the - * iterator class InputIter. The difference between end and begin - * determines the number of inner iterations. - * @param result Iterator pointing to the beginning of the output vector, belonging to the - * iterator class outputIter. - * @param index Iterator pointing to the beginning of the index vector, belonging to the - * iterator class IndexIter. - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void scatter_divide(InputIter begin, InputIter end, - OutputIter result, IndexIter index) -{ - warn_deprecated("scatter_divide", - "To be removed after Cantera 2.2."); - for (; begin != end; ++begin, ++index) { - *(result + *index) /= *begin; - } -} - //! Compute \f[ \sum_k x_k \log x_k. \f]. /*! * The template arguments are: template @@ -571,30 +431,6 @@ inline doublereal sum_xlogQ(InputIter1 begin, InputIter1 end, return sum; } -//! Scale a templated vector by a constant factor. -/*! - * The template arguments are: template - * - * This function is essentially a wrapper around the stl - * function %scale(). The function is has one template - * parameter, OutputIter. OutputIter is a templated iterator - * that points to the vector to be scaled. - * - * @param N Length of the vector - * @param alpha scale factor - double - * @param x Templated Iterator to the start of the vector - * to be scaled. - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void scale(int N, double alpha, OutputIter x) -{ - warn_deprecated("scale(int N, double alpha, OutputIter x)", - "To be removed after Cantera 2.2."); - scale(x, x+N, x, alpha); -} - - //! Templated evaluation of a polynomial of order 6 /*! * @param x Value of the independent variable - First template parameter @@ -619,22 +455,6 @@ R poly8(D x, R* c) c[2])*x + c[1])*x + c[0]); } -//! Templated evaluation of a polynomial of order 10 -/*! - * @param x Value of the independent variable - First template parameter - * @param c Pointer to the polynomial - Second template parameter - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -R poly10(D x, R* c) -{ - warn_deprecated("poly10", - "To be removed after Cantera 2.2."); - return ((((((((((c[10]*x + c[9])*x + c[8])*x + c[7])*x - + c[6])*x + c[5])*x + c[4])*x + c[3])*x - + c[2])*x + c[1])*x + c[0]); -} - //! Templated evaluation of a polynomial of order 5 /*! * @param x Value of the independent variable - First template parameter diff --git a/include/cantera/base/vec_functions.h b/include/cantera/base/vec_functions.h deleted file mode 100644 index 528c367ea..000000000 --- a/include/cantera/base/vec_functions.h +++ /dev/null @@ -1,204 +0,0 @@ -/** - * @file vec_functions.h - * Templates for operations on vector-like objects. - */ -/* - * Copyright 2001 California Institute of Technology - */ - -#ifndef CT_VEC_FUNCTIONS_H -#define CT_VEC_FUNCTIONS_H - -#include "ct_defs.h" -#include "utilities.h" -#include -#include -#include - -namespace Cantera -{ -//! Templated function that copies the first n entries from x to y. -/*! - * - * - * The templated type is the type of x and y - * - * @param n Number of elements to copy from x to y - * @param x The object x, of templated type const T& - * @param y The object y, of templated type T& - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void copyn(size_t n, const T& x, T& y) -{ - warn_deprecated("copyn", "To be removed after Cantera 2.2."); - std::copy(x.begin(), x.begin() + n, y.begin()); -} - -//! Divide each element of x by the corresponding element of y. -/*! - * This function replaces x[n] by x[n]/y[n], for 0 <= n < x.size() - * - * @param x Numerator object of the division operation with template type T - * At the end of the calculation, it contains the result. - * @param y Denominator object of the division template type T - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void divide_each(T& x, const T& y) -{ - warn_deprecated("divide_each", "To be removed after Cantera 2.2."); - std::transform(x.begin(), x.end(), y.begin(), - x.begin(), std::divides()); -} - -//! Multiply each element of x by the corresponding element of y. -/*! - * This function replaces x[n] by x[n]*y[n], for 0 <= n < x.size() - * This is a templated function with just one template type. - * - * @param x First object of the multiplication with template type T - * At the end of the calculation, it contains the result. - * @param y Second object of the multiplication with template type T - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void multiply_each(T& x, const T& y) -{ - warn_deprecated("multiply_each", "To be removed after Cantera 2.2."); - std::transform(x.begin(), x.end(), y.begin(), - x.begin(), std::multiplies()); -} - -//! Multiply each element of x by scale_factor. -/*! - * This function replaces x[n] by x[n]*scale_factor, for 0 <= n < x.size() - * - * @param x First object of the multiplication with template type T - * At the end of the calculation, it contains the result. - * @param scale_factor scale factor with template type S - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void scale(T& x, S scale_factor) -{ - warn_deprecated("scale", "To be removed after Cantera 2.2."); - scale(x.begin(), x.end(), x.begin(), scale_factor); -} - -//! Return the templated dot product of two objects -/*! - * Returns the sum of x[n]*y[n], for 0 <= n < x.size(). - * - * @param x First object of the dot product with template type T - * At the end of the calculation, it contains the result. - * @param y Second object of the dot product with template type T - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline doublereal dot_product(const T& x, const T& y) -{ - warn_deprecated("dot_product", "To be removed after Cantera 2.2."); - return std::inner_product(x.begin(), x.end(), y.begin(), 0.0); -} - -//! Returns the templated dot ratio of two objects -/** - * Returns the sum of x[n]/y[n], for 0 <= n < x.size(). - * - * @param x First object of the dot product with template type T - * At the end of the calculation, it contains the result. - * @param y Second object of the dot product with template type T - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline doublereal dot_ratio(const T& x, const T& y) -{ - warn_deprecated("dot_ratio", "To be removed after Cantera 2.2."); - return _dot_ratio(x.begin(), x.end(), y.begin(), 0.0); -} - -//! Returns a templated addition operation of two objects -/** - * Replaces x[n] by x[n] + y[n] for 0 <= n < x.size() - * - * @param x First object of the addition with template type T - * At the end of the calculation, it contains the result. - * @param y Second object of the addition with template type T - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline void add_each(T& x, const T& y) -{ - warn_deprecated("add_each", "To be removed after Cantera 2.2."); - std::transform(x.begin(), x.end(), y.begin(), - x.begin(), std::plus()); -} - -//! Templated dot ratio class -/*! - * Calculates the quantity: - * - * S += x[n]/y[n] - * - * The first templated type is the iterator type for x[] and y[]. - * The second templated type is the type of S. - * - * @param x_begin InputIter type, indicating the address of the - * first element of x - * @param x_end InputIter type, indicating the address of the - * last element of x - * @param y_begin InputIter type, indicating the address of the - * first element of y - * @param start_value S type, indicating the type of the - * accumulation result. - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline doublereal _dot_ratio(InputIter x_begin, InputIter x_end, - InputIter y_begin, S start_value) -{ - warn_deprecated("_dot_ratio", "To be removed after Cantera 2.2."); - for (; x_begin != x_end; ++x_begin, ++y_begin) { - start_value += *x_begin / *y_begin; - } - return start_value; -} - -//! Finds the entry in a vector with maximum absolute -//! value, and return this value. -/*! - * @param v Vector to be queried for maximum value, with template type T - * - * @return Returns an object of type T that is the maximum value, - * @deprecated Unused. To be removed after Cantera 2.2. - */ -template -inline T absmax(const std::vector& v) -{ - warn_deprecated("absmax", "To be removed after Cantera 2.2."); - int n = v.size(); - T maxval = 0.0; - for (int i = 0; i < n; i++) { - maxval = std::max(std::abs(v[i]), maxval); - } - return maxval; -} - -//! Write a vector to a stream -template -inline std::ostream& operator<<(std::ostream& os, const std::vector& v) -{ - size_t n = v.size(); - for (size_t i = 0; i < n; i++) { - os << v[i]; - if (i != n-1) { - os << ", "; - } - } - return os; -} - -} - -#endif diff --git a/include/cantera/equil/MultiPhase.h b/include/cantera/equil/MultiPhase.h index 3773538b9..aed3cfdf3 100644 --- a/include/cantera/equil/MultiPhase.h +++ b/include/cantera/equil/MultiPhase.h @@ -335,21 +335,6 @@ public: return m_temp; } - //! Set the mixture to a state of chemical equilibrium. - /*! - * @param XY Integer flag specifying properties to hold fixed. - * @param err Error tolerance for \f$\Delta \mu/RT \f$ for all - * reactions. Also used as the relative error tolerance for - * the outer loop. - * @param maxsteps Maximum number of steps to take in solving the fixed - * TP problem. - * @param maxiter Maximum number of "outer" iterations for problems - * holding fixed something other than (T,P). - * @param loglevel Level of diagnostic output - */ - doublereal equilibrate(int XY, doublereal err = 1.0e-9, - int maxsteps = 1000, int maxiter = 200, int loglevel = -99); - //! Equilibrate a MultiPhase object /*! * Set this mixture to chemical equilibrium by calling one of Cantera's diff --git a/include/cantera/equil/vcs_VolPhase.h b/include/cantera/equil/vcs_VolPhase.h index 6f28f3387..dc1a0aee9 100644 --- a/include/cantera/equil/vcs_VolPhase.h +++ b/include/cantera/equil/vcs_VolPhase.h @@ -362,9 +362,6 @@ public: //! Returns whether the phase is an ideal solution phase bool isIdealSoln() const; - //! Returns whether the object is using cantera calls. - bool usingCanteraCalls() const; - //! Return the index of the species that represents the //! the voltage of the phase size_t phiVarIndex() const; @@ -744,11 +741,6 @@ private: */ std::vector ListSpeciesPtr; - //! If this is true, then calculations are actually performed within - //! Cantera - //! @deprecated Will be implicitly 'true' after Cantera 2.2. - bool m_useCanteraCalls; - /** * If we are using Cantera, this is the pointer to the ThermoPhase * object. If not, this is null. diff --git a/include/cantera/equil/vcs_internal.h b/include/cantera/equil/vcs_internal.h index 08171153c..0d82bd570 100644 --- a/include/cantera/equil/vcs_internal.h +++ b/include/cantera/equil/vcs_internal.h @@ -108,110 +108,6 @@ typedef double(*VCS_FUNC_PTR)(double xval, double Vtarget, int varID, void* fptrPassthrough, int* err); -//! One dimensional root finder -/*! - * This root finder will find the root of a one dimensional equation - * \f[ - * f(x) = 0 - * \f] - * where x is a bounded quantity: \f$ x_{min} < x < x_max \f$ - * - * The function to be minimized must have the following call structure: - * - * @code - * typedef double (*VCS_FUNC_PTR)(double xval, double Vtarget, - * int varID, void *fptrPassthrough, - * int *err); @endcode - * - * xval is the current value of the x variable. Vtarget is the requested - * value of f(x), usually 0. varID is an integer that is passed through. - * fptrPassthrough is a void pointer that is passed through. err is a return - * error indicator. err = 0 is the norm. anything else is considered a fatal - * error. The return value of the function is the current value of f(xval). - * - * @param xmin Minimum permissible value of the x variable - * @param xmax Maximum permissible value of the x parameter - * @param itmax Maximum number of iterations - * @param func function pointer, pointing to the function to be - * minimized - * @param fptrPassthrough Pointer to void that gets passed through - * the rootfinder, unchanged, to the func. - * @param FuncTargVal Target value of the function. This is usually set - * to zero. - * @param varID Variable ID. This is usually set to zero. - * @param xbest Pointer to the initial value of x on input. On output - * This contains the root value. - * @param printLvl Print level of the routine. - * - * Following is a nontrial example for vcs_root1d() in which the position of a - * cylinder floating on the water is calculated. - * - * @code - * #include - * #include - * - * #include "equil/vcs_internal.h" - * - * const double g_cgs = 980.; - * const double mass_cyl = 0.066; - * const double diam_cyl = 0.048; - * const double rad_cyl = diam_cyl / 2.0; - * const double len_cyl = 5.46; - * const double vol_cyl = Pi * diam_cyl * diam_cyl / 4 * len_cyl; - * const double rho_cyl = mass_cyl / vol_cyl; - * const double rho_gas = 0.0; - * const double rho_liq = 1.0; - * const double sigma = 72.88; - * // Contact angle in radians - * const double alpha1 = 40.0 / 180. * Pi; - * - * double func_vert(double theta1, double h_2, double rho_c) { - * double f_grav = - Pi * rad_cyl * rad_cyl * rho_c * g_cgs; - * double tmp = rad_cyl * rad_cyl * g_cgs; - * double tmp1 = theta1 + sin(theta1) * cos(theta1) - 2.0 * h_2 / rad_cyl * sin(theta1); - * double f_buoy = tmp * (Pi * rho_gas + (rho_liq - rho_gas) * tmp1); - * double f_sten = 2 * sigma * sin(theta1 + alpha1 - Pi); - * return f_grav + f_buoy + f_sten; - * } - * double calc_h2_farfield(double theta1) { - * double rhs = sigma * (1.0 + cos(alpha1 + theta1)); - * rhs *= 2.0; - * rhs = rhs / (rho_liq - rho_gas) / g_cgs; - * double sign = -1.0; - * if (alpha1 + theta1 < Pi) sign = 1.0; - * double res = sign * sqrt(rhs); - * return res + rad_cyl * cos(theta1); - * } - * double funcZero(double xval, double Vtarget, int varID, void *fptrPassthrough, int *err) { - * double theta = xval; - * double h2 = calc_h2_farfield(theta); - * return func_vert(theta, h2, rho_cyl); - * } - * int main () { - * double thetamax = Pi; - * double thetamin = 0.0; - * int maxit = 1000; - * int iconv; - * double thetaR = Pi/2.0; - * int printLvl = 4; - * - * iconv = vcsUtil_root1d(thetamin, thetamax, maxit, - * funcZero, - * (void *) 0, 0.0, 0, - * &thetaR, printLvl); - * printf("theta = %g\n", thetaR); - * double h2Final = calc_h2_farfield(thetaR); - * printf("h2Final = %g\n", h2Final); - * return 0; - * } - * @endcode - * @deprecated Unused. To be removed after Cantera 2.2. - */ -int vcsUtil_root1d(double xmin, double xmax, size_t itmax, VCS_FUNC_PTR func, - void* fptrPassthrough, - double FuncTargVal, int varID, double* xbest, - int printLvl = 0); - //! determine the l2 norm of a vector of doubles /*! * @param vec vector of doubles @@ -232,16 +128,6 @@ double vcs_l2norm(const std::vector vec); */ size_t vcs_optMax(const double* x, const double* xSize, size_t j, size_t n); -//! Returns the maximum integer in a list -/*! - * @param vector pointer to a vector of ints - * @param length length of the integer vector - * - * @return returns the max integer value in the list - * @deprecated Unused. To be removed after Cantera 2.2. - */ -int vcs_max_int(const int* vector, int length); - //! Returns a const char string representing the type of the //! species given by the first argument /*! diff --git a/include/cantera/equil/vcs_solve.h b/include/cantera/equil/vcs_solve.h index 9dac4f68d..cec713383 100644 --- a/include/cantera/equil/vcs_solve.h +++ b/include/cantera/equil/vcs_solve.h @@ -1449,40 +1449,6 @@ private: std::vector m_wx; public: - //! Calculate the rank of a matrix and return the rows and columns that - //! will generate an independent basis for that rank - /* - * Choose the optimum component species basis for the calculations, - * finding the rank and set of linearly independent rows for that - * calculation. Then find the set of linearly indepedent element columns - * that can support that rank. This is done by taking the transpose of the - * matrix and redoing the same calculation. (there may be a better way to - * do this. I don't know.) - * - * @param[in] awtmp Vector of mole numbers which will be used to - * construct a ranking for how to pick the basis species. This is - * largely ignored here. - * @param[in] numSpecies Number of species. This is the number of rows in - * the matrix. - * @param[in] matrix This is the formula matrix. Nominally, the rows are - * species, while the columns are element compositions. However, - * this routine is totally general, so that the rows and columns - * can be anything. - * @param[in] numElemConstraints Number of element constraints - * - * @param[out] usedZeroedSpecies If true, then a species with a zero - * concentration was used as a component. - * @param[out] compRes Vector of rows which are linearly independent. - * (these are the components) - * @param[out] elemComp Vector of columns which are linearly independent - * (These are the actionable element constraints). - * - * @return Returns number of components. This is the rank of the matrix - * @deprecated To be removed after Cantera 2.2. - */ - int vcs_rank(const double* awtmp, size_t numSpecies, const double* matrix, size_t numElemConstraints, - std::vector &compRes, std::vector &elemComp, int* const usedZeroedSpecies) const; - //! value of the number of species used to malloc data structures size_t NSPECIES0; diff --git a/include/cantera/equil/vcs_species_thermo.h b/include/cantera/equil/vcs_species_thermo.h index 08a846e30..c4b296d19 100644 --- a/include/cantera/equil/vcs_species_thermo.h +++ b/include/cantera/equil/vcs_species_thermo.h @@ -86,10 +86,6 @@ public: //! parameter that is used in the VCS_SSVOL_CONSTANT model. double SSStar_Vol0; - //! If true, this object will call Cantera to do its member calculations. - //! @deprecated Will always behave as if 'true' after Cantera 2.2 - bool UseCanteraCalls; - int m_VCS_UnitsFormat; VCS_SPECIES_THERMO(size_t indexPhase, size_t indexSpeciesPhase); diff --git a/include/cantera/kinetics/ElectrodeKinetics.h b/include/cantera/kinetics/ElectrodeKinetics.h deleted file mode 100644 index 887546386..000000000 --- a/include/cantera/kinetics/ElectrodeKinetics.h +++ /dev/null @@ -1,129 +0,0 @@ -/** - * @file ElectrodeKinetics.h - * - * @ingroup chemkinetics - */ -/* - * Copyright (2005) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#ifndef CT_ELECTRODEKINETICS_H -#define CT_ELECTRODEKINETICS_H - -#include "InterfaceKinetics.h" - - -namespace Cantera -{ - - -//! A kinetics manager for heterogeneous reaction mechanisms. The -//! reactions are assumed to occur at a 2D interface between two 3D phases. -/*! - * This class is a slight addition to the InterfaceKinetics class, adding - * several concepts. First we explicitly identify the electrode and solution - * phases. We will also assume that there is an electron phase. - * - * @ingroup chemkinetics - * @deprecated Unfinished implementation to be removed after Cantera 2.2. - */ -class ElectrodeKinetics : public InterfaceKinetics -{ -public: - //! Constructor - /*! - * @param thermo The optional parameter may be used to initialize - * the object with one ThermoPhase object. - * HKM Note -> Since the interface kinetics - * object will probably require multiple ThermoPhase - * objects, this is probably not a good idea - * to have this parameter. - */ - ElectrodeKinetics(thermo_t* thermo = 0); - - /// Destructor. - virtual ~ElectrodeKinetics(); - - //! Copy Constructor - ElectrodeKinetics(const ElectrodeKinetics& right); - - //! Assignment operator - ElectrodeKinetics& operator=(const ElectrodeKinetics& right); - - //! Duplication function - /*! - * @param tpVector Vector of ThermoPhase pointers. These are shallow pointers to the - * ThermoPhase objects that will comprise the phases for the new object. - * - * @return Returns the duplicated object as the base class Kinetics object. - */ - virtual Kinetics* duplMyselfAsKinetics(const std::vector & tpVector) const; - - virtual int type() const; - - //! Identify the metal phase and the electrons species - /*! - * We fill in the internal variables, metalPhaseIndex_ and kElectronIndex_ here - */ - void identifyMetalPhase(); - - //! Internal routine that updates the Rates of Progress of the reactions - /*! - * This is actually the guts of the functionality of the object - */ - virtual void updateROP(); - - double calcForwardROP_BV(size_t irxn, size_t iBeta, double ioc, double nStoich, double nu, doublereal ioNet); - - double calcForwardROP_BV_NoAct(size_t irxn, size_t iBeta, double ioc, double nStoich, double nu, doublereal ioNet); - - bool getExchangeCurrentDensityFormulation(size_t irxn, doublereal& nStoich, doublereal& OCV, doublereal& io, - doublereal& overPotential, doublereal& beta, doublereal& resistance); - - //! Calculate the open circuit voltage of a given reaction - /*! - * If the reaction has no electron transport, then return 0.0 - * - * @param irxn Reaction id - */ - double openCircuitVoltage(size_t irxn); - - double calcCurrentDensity(double nu, double nStoich, double io, double beta, double temp, doublereal resistivity = 0.0) const; - - double solveCurrentRes(doublereal nu, doublereal nStoich, doublereal ioc, doublereal beta, doublereal temp, - doublereal resistivity = 0.0, int iprob = 0) const; - - //! Prepare the class for the addition of reactions - /*! - * (virtual from Kinetics) - * We determine the metal phase and solution phase here - */ - virtual void init(); - - virtual void finalize(); - - //! Vector of additional information about each reaction - /*! - * This vector contains information about the phase mole change for each reaction, - * for example. - */ - std::vector rmcVector; - -protected: - //! Index of the metal phase in the list of phases for this kinetics object. This is the electron phase. - size_t metalPhaseIndex_; - - //! Index of the solution phase in the list of phases for this surface - size_t solnPhaseIndex_; - - //! Index of the electrons species in the list of species for this surface kinetics, if none set it to -1 - size_t kElectronIndex_; - - - -}; -} - -#endif diff --git a/include/cantera/kinetics/ExtraGlobalRxn.h b/include/cantera/kinetics/ExtraGlobalRxn.h deleted file mode 100644 index 039d582c8..000000000 --- a/include/cantera/kinetics/ExtraGlobalRxn.h +++ /dev/null @@ -1,121 +0,0 @@ -/** - * @file ReactingVolDomain.h - * - */ -/* - * Copyright (2005) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#ifndef EXTRAGLOBALRXN_H -#define EXTRAGLOBALRXN_H - -#include "cantera/kinetics/InterfaceKinetics.h" -#include -#include - -namespace Cantera -{ - -//! Class describing an extra global reaction, which is defined as -//! a linear combination of actuals reactions, global or mass-action, creating a global stoichiometric result -/*! - * This is useful for defining thermodynamics of global processes that occur - * on a surface or in a homogeneous phase. - * - * The class is set up via the function setupElemRxnVector(RxnVector, specialSpecies) which defines - * the vector of stoichiometric coefficients representing the base reaction to combine in order to - * achieve the global result that's to be calculated. specialSpecies is the index of the species - * within the kinetics object that is used to identify the global reaction. Rates of progress - * are defined in terms of the production rate of the special species. - * - * @deprecated Unfinished implementation to be removed after Cantera 2.2. - */ -class ExtraGlobalRxn -{ - -public: - //! Constructor takes a default kinetics pointer - /*! - * @param[in] k_ptr Pointer to a Kinetics class that will be used as the basis - * for constructing this class. - */ - ExtraGlobalRxn(Kinetics* k_ptr); - - //! Destructor - virtual ~ExtraGlobalRxn() {} - - void setupElemRxnVector(double* RxnVector, - int specialSpecies = -1); - std::string reactionString(); - double deltaSpecValue(double* speciesVectorProperty); - - std::vector& reactants(); - std::vector& products(); - bool isReversible(); - - double ROPValue(double* ROPKinVector); - double FwdROPValue(double* FwdROPElemKinVector, double* RevROPElemKinVector); - double RevROPValue(double* FwdROPElemKinVector, double* RevROPElemKinVector); - - double reactantStoichCoeff(int kKin); - double productStoichCoeff(int kKin); - bool m_ThisIsASurfaceRxn; - double deltaRxnVecValue(double* rxnVectorProperty); - - //! This kinetics operator is associated with just one - //! homogeneous phase, associated with tpList[0] phase - /*! - * Kinetics object pointer - */ - Kinetics* m_kinetics; - - //! This kinetics operator is associated with multiple - //! homogeneous and surface phases. - /*! - * This object owns the Kinetics object - */ - InterfaceKinetics* m_InterfaceKinetics; - - int m_nKinSpecies; - - //! Number of reactants in the global reaction - int m_nReactants; - - //! Vector of reactants that make up the global reaction - /*! - * This is a list of reactants using the kinetic species index - */ - std::vector m_Reactants; - - //! Vector of reactant stoichiometries that make up the global reaction - /*! - * This is a list of reactant stoichiometries. The species index is given in - * the member m_Reactants using the kinetic species index. - */ - std::vector m_ReactantStoich; - - int m_nProducts; - std::vector m_Products; - std::vector m_ProductStoich; - - int m_nNetSpecies; - std::vector m_NetSpecies; - std::vector m_netStoich; - - int m_nRxns; - std::vector m_ElemRxnVector; - - int m_SpecialSpecies; - bool m_SpecialSpeciesProduct; - int m_SS_index; - - int iphaseKin; - bool m_ok; - bool m_reversible; - - -}; -} -#endif diff --git a/include/cantera/kinetics/InterfaceKinetics.h b/include/cantera/kinetics/InterfaceKinetics.h index 1f4507cf0..d48fb0d8d 100644 --- a/include/cantera/kinetics/InterfaceKinetics.h +++ b/include/cantera/kinetics/InterfaceKinetics.h @@ -10,7 +10,6 @@ #include "cantera/thermo/mix_defs.h" #include "Kinetics.h" -#include "cantera/kinetics/RxnMolChange.h" #include "Reaction.h" #include "cantera/base/utilities.h" #include "RateCoeffMgr.h" @@ -21,34 +20,6 @@ namespace Cantera // forward declarations class SurfPhase; class ImplicitSurfChem; -class RxnMolChange; - -//! forward orders -//! @deprecated Incomplete implementation to be removed after Cantera 2.2. -class RxnOrders { - - public: - //! constructors - RxnOrders() {} - - RxnOrders(const RxnOrders &right); - - ~RxnOrders() {} - - RxnOrders& operator=(const RxnOrders &right); - - //! Fill in the structure with the array. - /*! - * @param[in] Size of length kinetic species. The entries the values of the orders - */ - int fill(const vector_fp& fullForwardOrders); - - //! ID's of the kinetic species - std::vector kinSpeciesIDs_; - - //! Orders of the kinetic species - vector_fp kinSpeciesOrders_; -}; //! A kinetics manager for heterogeneous reaction mechanisms. The //! reactions are assumed to occur at a 2D interface between two 3D phases. @@ -568,25 +539,6 @@ protected: */ vector_int m_ctrxn_ecdf; - //! Vector of booleans indicating whether the charge transfer reaction rate constant - //! is described by an exchange current density rate constant expression - /*! - * Length is equal to the number of reactions with charge transfer coefficients, m_ctrxn[] - * - * Some reactions have zero in this list, those that don't need special treatment. - * @deprecated To be removed after Cantera 2.2. - */ - std::vector m_ctrxn_ROPOrdersList_; - - //! Reaction Orders for the case where the forwards rate of progress is being calculated. - /*! - * Length is equal to the number of reactions with charge transfer coefficients, m_ctrxn[] - * - * Some reactions have zero in this list, indicating that the calculation isn't necessary. - * @deprecated To be removed after Cantera 2.2. - */ - std::vector m_ctrxn_FwdOrdersList_; - vector_fp m_ctrxn_resistivity_; //! Vector of standard concentrations diff --git a/include/cantera/kinetics/Kinetics.h b/include/cantera/kinetics/Kinetics.h index 99ad9d406..1d2b56833 100644 --- a/include/cantera/kinetics/Kinetics.h +++ b/include/cantera/kinetics/Kinetics.h @@ -648,32 +648,6 @@ public: throw NotImplementedError("Kinetics::getActivityConcentrations"); } - /** - * Returns a read-only reference to the vector of reactant - * index numbers for reaction i. - * - * @param i reaction index - * @deprecated To be removed after Cantera 2.2. - */ - virtual const std::vector& reactants(size_t i) const { - warn_deprecated("Kinetics::reactants", - "To be removed after Cantera 2.2."); - return m_reactants[i]; - } - - /** - * Returns a read-only reference to the vector of product - * index numbers for reaction i. - * - * @param i reaction index - * @deprecated To be removed after Cantera 2.2. - */ - virtual const std::vector& products(size_t i) const { - warn_deprecated("Kinetics::products", - "To be removed after Cantera 2.2."); - return m_products[i]; - } - /** * Flag specifying the type of reaction. The legal values and * their meaning are specific to the particular kinetics @@ -969,34 +943,6 @@ protected: //! Vector of Reaction objects represented by this Kinetics manager std::vector > m_reactions; - /** - * This is a vector of vectors containing the reactants for - * each reaction. The outer vector is over the number of - * reactions, m_ii. The inner vector is a list of species - * indices. If the stoichiometric coefficient for a reactant - * is greater than one, then the reactant is listed - * contiguously in the vector a number of times equal to its - * stoichiometric coefficient. - * NOTE: These vectors will be wrong if there are real - * stoichiometric coefficients in the expression. - * @deprecated To be removed after Cantera 2.2. - */ - std::vector > m_reactants; - - /** - * This is a vector of vectors containing the products for - * each reaction. The outer vector is over the number of - * reactions, m_ii. The inner vector is a list of species - * indices. If the stoichiometric coefficient for a product is - * greater than one, then the reactant is listed contiguously - * in the vector a number of times equal to its stoichiometric - * coefficient. - * NOTE: These vectors will be wrong if there are real - * stoichiometric coefficients in the expression. - * @deprecated To be removed after Cantera 2.2. - */ - std::vector > m_products; - //! m_rrxn is a vector of maps, containing the reactant //! stoichiometric coefficient information /*! diff --git a/include/cantera/kinetics/RxnMolChange.h b/include/cantera/kinetics/RxnMolChange.h deleted file mode 100644 index 957c0f4e9..000000000 --- a/include/cantera/kinetics/RxnMolChange.h +++ /dev/null @@ -1,118 +0,0 @@ -/** - * @file RxnMolChange.cpp - * - */ -/* - * Copyright (2005) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#ifndef RXNMOLCHANGE_H -#define RXNMOLCHANGE_H - - -#include - -namespace Cantera -{ -class ExtraGlobalRxn; -class Kinetics; - - -//! Class that includes some bookeeping entries for a reaction or a global reaction defined on a surface -/*! - * Note that all indexes refer to a specific interfacial or homogeneous kinetics object. It does not - * refer to the Phase list indexes. - * @deprecated Unfinished implementation to be removed after Cantera 2.2. - */ -class RxnMolChange -{ -public: - //! Main constructor for the class - /*! - * @param kinPtr Pointer to the kinetics base class - * @param irxn Specific reaction index. - */ - RxnMolChange(Kinetics* kinPtr, int irxn); - - //! Destructor - ~RxnMolChange() {} - - //! Constructor for the object if the object refers to a global reaction - /*! - * @param kinPtr Pointer to the kinetics base class - * @param egr Specific reaction index. - */ - RxnMolChange(Kinetics* kinPtr, ExtraGlobalRxn* egr); - - //! Vector of mole changes for each phase in the Kinetics object due to the current reaction - /*! - * This is the sum of the product stoichiometric coefficient minum the reactant stoichioemtric coefficient - * for all the species in a phase. - * The index is over all the phases listed in the Kinetics object. - */ - std::vector m_phaseMoleChange; - - std::vector m_phaseReactantMoles; - - std::vector m_phaseProductMoles; - - //! Vector of mass changes for each phase in the Kinetics object due to the current reaction - /*! - * This is the sum of the product stoichiometric coefficient minum the reactant stoichioemtric coefficient - * index multiplied by the molecular weight for all species in a phase. - * The index is over all of the phases listed in the Kinetics object. - */ - std::vector m_phaseMassChange; - - //! Vector of mass changes for each phase in the Kinetics object due to the current reaction - /*! - * This is the sum of the product stoichiometric coefficient minum the reactant stoichioemtric coefficient - * index multiplied by the charg for all species in a phase. - * The index is over all of the phases listed in the Kinetics object. - */ - std::vector m_phaseChargeChange; - - //! Vector of phase types in the reaction - /*! - * Collection of eosTypes for all phases in the kinetics object - * The index is over all of the phases listed in the Kinetics object. - */ - std::vector m_phaseTypes; - - //! Vector of phase dimensions for the reaction - /*! - * Collection of nDims for all phases in the kinetics object - * The index is over all of the phases listed in the Kinetics object. - */ - std::vector m_phaseDims; - - //! Number of phases in the kientics object - int m_nPhases; - - //! Shallow pointer pointing to the kinetics object - Kinetics* m_kinBase; - - //! Reaction number within the kinetics object - /*! - * If this is neg 1, then this reaction refers to a global reaction - * specified by the m_egr pointer. - */ - int m_iRxn; - - //! Maximum change in charge of any phase due to this reaction - double m_ChargeTransferInRxn; - - //! Electrochemical beta parameter for the reaction - double m_beta; - - //! Pointer to the specification of the global reaction - /*! - * This is 0, if the class refers to a single reaction in the kinetics object - */ - ExtraGlobalRxn* m_egr; -}; -} - -#endif diff --git a/include/cantera/kinetics/RxnRates.h b/include/cantera/kinetics/RxnRates.h index 5841ac960..ac034e9dc 100644 --- a/include/cantera/kinetics/RxnRates.h +++ b/include/cantera/kinetics/RxnRates.h @@ -55,19 +55,6 @@ public: void update_C(const doublereal* c) { } - /** - * Update the value of the logarithm of the rate constant. - * - * Note, this function should never be called for negative A values. - * If it does then it will produce a negative overflow result, and - * a zero net forwards reaction rate, instead of a negative reaction - * rate constant that is the expected result. - * @deprecated. To be removed after Cantera 2.2 - */ - doublereal update(doublereal logT, doublereal recipT) const { - return m_logA + m_b*logT - m_E*recipT; - } - /** * Update the value of the natural logarithm of the rate constant. */ @@ -86,18 +73,6 @@ public: return m_A * std::exp(m_b*logT - m_E*recipT); } - //! @deprecated. To be removed after Cantera 2.2 - void writeUpdateRHS(std::ostream& s) const { - s << " exp(" << m_logA; - if (m_b != 0.0) { - s << " + " << m_b << " * tlog"; - } - if (m_E != 0.0) { - s << " - " << m_E << " * rt"; - } - s << ");" << std::endl; - } - //! Return the pre-exponential factor *A* (in m, kmol, s to powers depending //! on the reaction order) double preExponentialFactor() const { @@ -115,11 +90,6 @@ public: return m_E; } - //! @deprecated. To be removed after Cantera 2.2 - static bool alwaysComputeRate() { - return false; - } - protected: doublereal m_logA, m_b, m_E, m_A; }; @@ -177,18 +147,6 @@ public: } } - /** - * Update the value of the logarithm of the rate constant. - * - * This calculation is not safe for negative values of - * the preexponential. - * @deprecated. To be removed after Cantera 2.2 - */ - doublereal update(doublereal logT, doublereal recipT) const { - return m_logA + m_acov + m_b*logT - - (m_E + m_ecov)*recipT + m_mcov; - } - /** * Update the value the rate constant. * @@ -205,11 +163,6 @@ public: return m_E + m_ecov; } - //! @deprecated. To be removed after Cantera 2.2 - static bool alwaysComputeRate() { - return true; - } - protected: doublereal m_logA, m_b, m_E, m_A; doublereal m_acov, m_ecov, m_mcov; @@ -262,14 +215,6 @@ public: rDeltaP_ = 1.0 / (logP2_ - logP1_); } - /** - * Update the value of the logarithm of the rate constant. - * @deprecated. To be removed after Cantera 2.2 - */ - doublereal update(doublereal logT, doublereal recipT) const { - return std::log(updateRC(logT, recipT)); - } - /** * Update the value the rate constant. * @@ -300,16 +245,6 @@ public: return std::exp(log_k1 + (log_k2-log_k1) * (logP_-logP1_) * rDeltaP_); } - //! @deprecated. To be removed after Cantera 2.2 - doublereal activationEnergy_R() const { - throw CanteraError("Plog::activationEnergy_R", "Not implemented"); - } - - //! @deprecated. To be removed after Cantera 2.2 - static bool alwaysComputeRate() { - return false; - } - //! Check to make sure that the rate expression is finite over a range of //! temperatures at each interpolation pressure. This is potentially an //! issue when one of the Arrhenius expressions at a particular pressure @@ -386,14 +321,6 @@ public: } } - /** - * Update the value of the base-10 logarithm of the rate constant. - * @deprecated. To be removed after Cantera 2.2 - */ - doublereal update(doublereal logT, doublereal recipT) const { - return std::log10(updateRC(logT, recipT)); - } - /** * Update the value the rate constant. * @@ -414,16 +341,6 @@ public: return std::pow(10, logk); } - //! @deprecated. To be removed after Cantera 2.2 - doublereal activationEnergy_R() const { - return 0.0; - } - - //! @deprecated. To be removed after Cantera 2.2 - static bool alwaysComputeRate() { - return false; - } - //! Minimum valid temperature [K] double Tmin() const { return Tmin_; diff --git a/include/cantera/kinetics/StoichManager.h b/include/cantera/kinetics/StoichManager.h index 8ddcd533a..fa1ae3509 100644 --- a/include/cantera/kinetics/StoichManager.h +++ b/include/cantera/kinetics/StoichManager.h @@ -135,12 +135,6 @@ static doublereal ppow(doublereal x, doublereal order) } } -//! @deprecated To be removed after Cantera 2.2 -inline static std::string fmt(const std::string& r, size_t n) -{ - return r + "[" + int2str(n) + "]"; -} - /** * Handles one species in a reaction. * See @ref Stoichiometry @@ -191,31 +185,6 @@ public: return 1; } - //! @deprecated To be removed after Cantera 2.2 - void writeMultiply(const std::string& r, std::map& out) { - out[m_rxn] = fmt(r, m_ic0); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementReaction(const std::string& r, std::map& out) { - out[m_rxn] += " + "+fmt(r, m_ic0); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementReaction(const std::string& r, std::map& out) { - out[m_rxn] += " - "+fmt(r, m_ic0); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementSpecies(const std::string& r, std::map& out) { - out[m_ic0] += " + "+fmt(r, m_rxn); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementSpecies(const std::string& r, std::map& out) { - out[m_ic0] += " - "+fmt(r, m_rxn); - } - private: //! Reaction number size_t m_rxn; @@ -273,35 +242,6 @@ public: return 2; } - //! @deprecated To be removed after Cantera 2.2 - void writeMultiply(const std::string& r, std::map& out) { - out[m_rxn] = fmt(r, m_ic0) + " * " + fmt(r, m_ic1); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementReaction(const std::string& r, std::map& out) { - out[m_rxn] += " + "+fmt(r, m_ic0)+" + "+fmt(r, m_ic1); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementReaction(const std::string& r, std::map& out) { - out[m_rxn] += " - "+fmt(r, m_ic0)+" - "+fmt(r, m_ic1); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementSpecies(const std::string& r, std::map& out) { - std::string s = " + "+fmt(r, m_rxn); - out[m_ic0] += s; - out[m_ic1] += s; - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementSpecies(const std::string& r, std::map& out) { - std::string s = " - "+fmt(r, m_rxn); - out[m_ic0] += s; - out[m_ic1] += s; - } - private: //! Reaction index -> index into the ROP vector size_t m_rxn; @@ -363,36 +303,6 @@ public: return 3; } - //! @deprecated To be removed after Cantera 2.2 - void writeMultiply(const std::string& r, std::map& out) { - out[m_rxn] = fmt(r, m_ic0) + " * " + fmt(r, m_ic1) + " * " + fmt(r, m_ic2); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementReaction(const std::string& r, std::map& out) { - out[m_rxn] += " + "+fmt(r, m_ic0)+" + "+fmt(r, m_ic1)+" + "+fmt(r, m_ic2); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementReaction(const std::string& r, std::map& out) { - out[m_rxn] += " - "+fmt(r, m_ic0)+" - "+fmt(r, m_ic1)+" - "+fmt(r, m_ic2); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementSpecies(const std::string& r, std::map& out) { - std::string s = " + "+fmt(r, m_rxn); - out[m_ic0] += s; - out[m_ic1] += s; - out[m_ic2] += s; - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementSpecies(const std::string& r, std::map& out) { - std::string s = " - "+fmt(r, m_rxn); - out[m_ic0] += s; - out[m_ic1] += s; - out[m_ic2] += s; - } private: size_t m_rxn; size_t m_ic0; @@ -484,51 +394,6 @@ public: -= m_stoich[n]*input[m_ic[n]]; } - //! @deprecated To be removed after Cantera 2.2 - void writeMultiply(const std::string& r, std::map& out) { - out[m_rxn] = ""; - for (size_t n = 0; n < m_n; n++) { - if (m_order[n] == 1.0) { - out[m_rxn] += fmt(r, m_ic[n]); - } else { - out[m_rxn] += "pow("+fmt(r, m_ic[n])+","+fp2str(m_order[n])+")"; - } - if (n < m_n-1) { - out[m_rxn] += " * "; - } - } - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementReaction(const std::string& r, std::map& out) { - for (size_t n = 0; n < m_n; n++) { - out[m_rxn] += " + "+fp2str(m_stoich[n]) + "*" + fmt(r, m_ic[n]); - } - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementReaction(const std::string& r, std::map& out) { - for (size_t n = 0; n < m_n; n++) { - out[m_rxn] += " - "+fp2str(m_stoich[n]) + "*" + fmt(r, m_ic[n]); - } - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementSpecies(const std::string& r, std::map& out) { - std::string s = fmt(r, m_rxn); - for (size_t n = 0; n < m_n; n++) { - out[m_ic[n]] += " + "+fp2str(m_stoich[n]) + "*" + s; - } - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementSpecies(const std::string& r, std::map& out) { - std::string s = fmt(r, m_rxn); - for (size_t n = 0; n < m_n; n++) { - out[m_ic[n]] += " - "+fp2str(m_stoich[n]) + "*" + s; - } - } - private: //! Length of the m_ic vector @@ -616,56 +481,6 @@ inline static void _decrementReactions(InputIter begin, } } -//! @deprecated To be removed after Cantera 2.2 -template -inline static void _writeIncrementSpecies(InputIter begin, InputIter end, - const std::string& r, std::map& out) -{ - for (; begin != end; ++begin) { - begin->writeIncrementSpecies(r, out); - } -} - -//! @deprecated To be removed after Cantera 2.2 -template -inline static void _writeDecrementSpecies(InputIter begin, InputIter end, - const std::string& r, std::map& out) -{ - for (; begin != end; ++begin) { - begin->writeDecrementSpecies(r, out); - } -} - -//! @deprecated To be removed after Cantera 2.2 -template -inline static void _writeIncrementReaction(InputIter begin, InputIter end, - const std::string& r, std::map& out) -{ - for (; begin != end; ++begin) { - begin->writeIncrementReaction(r, out); - } -} - -//! @deprecated To be removed after Cantera 2.2 -template -inline static void _writeDecrementReaction(InputIter begin, InputIter end, - const std::string& r, std::map& out) -{ - for (; begin != end; ++begin) { - begin->writeDecrementReaction(r, out); - } -} - -//! @deprecated To be removed after Cantera 2.2 -template -inline static void _writeMultiply(InputIter begin, InputIter end, - const std::string& r, std::map& out) -{ - for (; begin != end; ++begin) { - begin->writeMultiply(r, out); - } -} - /* * This class handles operations involving the stoichiometric * coefficients on one side of a reaction (reactant or product) for @@ -840,46 +655,6 @@ public: _decrementReactions(m_cn_list.begin(), m_cn_list.end(), input, output); } - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementSpecies(const std::string& r, std::map& out) { - _writeIncrementSpecies(m_c1_list.begin(), m_c1_list.end(), r, out); - _writeIncrementSpecies(m_c2_list.begin(), m_c2_list.end(), r, out); - _writeIncrementSpecies(m_c3_list.begin(), m_c3_list.end(), r, out); - _writeIncrementSpecies(m_cn_list.begin(), m_cn_list.end(), r, out); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementSpecies(const std::string& r, std::map& out) { - _writeDecrementSpecies(m_c1_list.begin(), m_c1_list.end(), r, out); - _writeDecrementSpecies(m_c2_list.begin(), m_c2_list.end(), r, out); - _writeDecrementSpecies(m_c3_list.begin(), m_c3_list.end(), r, out); - _writeDecrementSpecies(m_cn_list.begin(), m_cn_list.end(), r, out); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeIncrementReaction(const std::string& r, std::map& out) { - _writeIncrementReaction(m_c1_list.begin(), m_c1_list.end(), r, out); - _writeIncrementReaction(m_c2_list.begin(), m_c2_list.end(), r, out); - _writeIncrementReaction(m_c3_list.begin(), m_c3_list.end(), r, out); - _writeIncrementReaction(m_cn_list.begin(), m_cn_list.end(), r, out); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeDecrementReaction(const std::string& r, std::map& out) { - _writeDecrementReaction(m_c1_list.begin(), m_c1_list.end(), r, out); - _writeDecrementReaction(m_c2_list.begin(), m_c2_list.end(), r, out); - _writeDecrementReaction(m_c3_list.begin(), m_c3_list.end(), r, out); - _writeDecrementReaction(m_cn_list.begin(), m_cn_list.end(), r, out); - } - - //! @deprecated To be removed after Cantera 2.2 - void writeMultiply(const std::string& r, std::map& out) { - _writeMultiply(m_c1_list.begin(), m_c1_list.end(), r, out); - _writeMultiply(m_c2_list.begin(), m_c2_list.end(), r, out); - _writeMultiply(m_c3_list.begin(), m_c3_list.end(), r, out); - _writeMultiply(m_cn_list.begin(), m_cn_list.end(), r, out); - } - private: std::vector m_c1_list; std::vector m_c2_list; diff --git a/include/cantera/kinetics/importKinetics.h b/include/cantera/kinetics/importKinetics.h index 78b726e23..a562c8927 100644 --- a/include/cantera/kinetics/importKinetics.h +++ b/include/cantera/kinetics/importKinetics.h @@ -19,16 +19,6 @@ namespace Cantera { -//! Rules for parsing and installing reactions -//! @deprecated Unused. To be removed after Cantera 2.2. -struct ReactionRules { - ReactionRules(); - bool skipUndeclaredSpecies; - bool skipUndeclaredThirdBodies; - bool allowNegativeA; -}; - - //! Install information about reactions into the kinetics object, kin. /*! * At this point, parent usually refers to the phase XML element. diff --git a/include/cantera/matlab.h b/include/cantera/matlab.h index 2582b7075..d19ac932c 100644 --- a/include/cantera/matlab.h +++ b/include/cantera/matlab.h @@ -11,7 +11,6 @@ int xml_get_XML_File(const char* file, int debug); int xml_del(int i); int xml_clear(); int xml_copy(int i); -int xml_assign(int i, int j); int xml_build(int i, const char* file); int xml_preprocess_and_build(int i, const char* file, int debug); int xml_attrib(int i, const char* key, char* value); diff --git a/include/cantera/numerics/BEulerInt.h b/include/cantera/numerics/BEulerInt.h deleted file mode 100644 index d9573cdc3..000000000 --- a/include/cantera/numerics/BEulerInt.h +++ /dev/null @@ -1,578 +0,0 @@ -/** - * @file BEulerInt.h - */ - -/* - * Copyright 2004 Sandia Corporation. Under the terms of Contract - * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government - * retains certain rights in this software. - * See file License.txt for licensing information. - */ -#ifndef CT_BEULERINT_H -#define CT_BEULERINT_H - -#include "cantera/numerics/Integrator.h" -#include "cantera/numerics/ResidJacEval.h" -#include "cantera/numerics/GeneralMatrix.h" - -#define OPT_SIZE 10 - -#define SUCCESS 0 -#define FAILURE 1 - -#define STEADY 0 -#define TRANSIENT 1 - -namespace Cantera -{ - -enum BEulerMethodType { - BEulerFixedStep, - BEulerVarStep -}; - -/** - * Exception class thrown when a BEuler error is encountered. - */ -class BEulerErr : public CanteraError -{ -public: - /** - * Exception thrown when a BEuler error is encountered. We just call the - * Cantera Error handler in the initialization list. - */ - explicit BEulerErr(const std::string& msg); -}; - - -#define BEULER_JAC_ANAL 2 -#define BEULER_JAC_NUM 1 - -/*! - * Wrapper class for 'beuler' integrator - * We derive the class from the class Integrator - * @deprecated Unused. To be removed after Cantera 2.2. - */ -class BEulerInt : public Integrator -{ -public: - /*! - * Constructor. Default settings: dense Jacobian, no user-supplied - * Jacobian function, Newton iteration. - */ - BEulerInt(); - - virtual ~BEulerInt(); - - virtual void setTolerances(double reltol, size_t n, double* abstol); - virtual void setTolerances(double reltol, double abstol); - virtual void setProblemType(int probtype); - - //! Find the initial conditions for y and ydot. - virtual void initializeRJE(double t0, ResidJacEval& func); - virtual void reinitializeRJE(double t0, ResidJacEval& func); - virtual double integrateRJE(double tout, double tinit = 0.0); - - // This routine advances the calculations one step using a predictor - // corrector approach. We use an implicit algorithm here. - virtual doublereal step(double tout); - - //! Set the solution weights. This is a very important routine as it affects - //! quite a few operations involving convergence. - virtual void setSolnWeights(); - - virtual double& solution(size_t k) { - return m_y_n[k]; - } - double* solution() { - return &m_y_n[0]; - } - int nEquations() const { - return m_neq; - } - - //! Return the total number of function evaluations - virtual int nEvals() const; - virtual void setMethodBEMT(BEulerMethodType t); - virtual void setIterator(IterType t); - virtual void setMaxStep(double hmax); - virtual void setMaxNumTimeSteps(int); - virtual void setNumInitialConstantDeltaTSteps(int); - - void print_solnDelta_norm_contrib(const double* const soln0, - const char* const s0, - const double* const soln1, - const char* const s1, - const char* const title, - const double* const y0, - const double* const y1, - double damp, - int num_entries); - - //! This routine controls when the solution is printed - /*! - * @param printSolnStepInterval If greater than 0, then the soln is - * printed every printSolnStepInterval steps. - * @param printSolnNumberToTout The solution is printed at regular - * invervals a total of "printSolnNumberToTout" times. - * @param printSolnFirstSteps The solution is printed out the first - * "printSolnFirstSteps" steps. After these steps the - * other parameters determine the printing. default = 0 - * @param dumpJacobians Dump Jacobians to disk. - */ - virtual void setPrintSolnOptions(int printSolnStepInterval, - int printSolnNumberToTout, - int printSolnFirstSteps = 0, - bool dumpJacobians = false); - - //! Set the options for the nonlinear method - /*! - * Defaults are set in the .h file. These are the defaults: - * min_newt_its = 0 - * matrixConditioning = false - * colScaling = false - * rowScaling = true - */ - void setNonLinOptions(int min_newt_its = 0, - bool matrixConditioning = false, - bool colScaling = false, - bool rowScaling = true); - virtual void setPrintFlag(int print_flag); - - //! Set the column scaling vector at the current time - virtual void setColumnScales(); - - /** - * Calculate the solution error norm. if printLargest is true, then a table - * of the largest values is printed to standard output. - */ - virtual double soln_error_norm(const double* const, - bool printLargest = false); - virtual void setInitialTimeStep(double delta_t); - - /*! - * Function called by to evaluate the Jacobian matrix and the current - * residual at the current time step. - * @param J = Jacobian matrix to be filled in - * @param f = Right hand side. This routine returns the current - * value of the RHS (output), so that it does - * not have to be computed again. - */ - void beuler_jac(GeneralMatrix& J, double* const f, - double, double, double* const, double* const, int); - -protected: - //! Internal routine that sets up the fixed length storage based on - //! the size of the problem to solve. - void internalMalloc(); - - /*! - * Function to calculate the predicted solution vector, m_y_pred_n for the - * (n+1)th time step. This routine can be used by a first order - forward - * Euler / backward Euler predictor / corrector method or for a second order - * Adams-Bashforth / Trapezoidal Rule predictor / corrector method. See - * Nachos documentation Sand86-1816 and Gresho, Lee, Sani LLNL report UCRL - - * 83282 for more information. - * - * on input: - * - * N - number of unknowns - * order - indicates order of method - * = 1 -> first order forward Euler/backward Euler - * predictor/corrector - * = 2 -> second order Adams-Bashforth/Trapezoidal Rule - * predictor/corrector - * - * delta_t_n - magnitude of time step at time n (i.e., = t_n+1 - t_n) - * delta_t_nm1 - magnitude of time step at time n - 1 (i.e., = t_n - t_n-1) - * y_n[] - solution vector at time n - * y_dot_n[] - acceleration vector from the predictor at time n - * y_dot_nm1[] - acceleration vector from the predictor at time n - 1 - * - * on output: - * - * m_y_pred_n[] - predicted solution vector at time n + 1 - */ - void calc_y_pred(int); - - /*! - * Function to calculate the acceleration vector ydot for the first or - * second order predictor/corrector time integrator. This routine can be - * called by a first order - forward Euler / backward Euler predictor / - * corrector or for a second order Adams - Bashforth / Trapezoidal Rule - * predictor / corrector. See Nachos documentation Sand86-1816 and Gresho, - * Lee, Sani LLNL report UCRL - 83282 for more information. - * - * on input: - * - * N - number of local unknowns on the processor - * This is equal to internal plus border unknowns. - * order - indicates order of method - * = 1 -> first order forward Euler/backward Euler - * predictor/corrector - * = 2 -> second order Adams-Bashforth/Trapezoidal Rule - * predictor/corrector - * - * delta_t_n - Magnitude of the current time step at time n - * (i.e., = t_n - t_n-1) - * y_curr[] - Current Solution vector at time n - * y_nm1[] - Solution vector at time n-1 - * ydot_nm1[] - Acceleration vector at time n-1 - * - * on output: - * - * ydot_curr[] - Current acceleration vector at time n - * - * Note we use the current attribute to denote the possibility that - * y_curr[] may not be equal to m_y_n[] during the nonlinear solve - * because we may be using a look-ahead scheme. - */ - void calc_ydot(int, double*, double*); - - /*! - * Calculates the time step truncation error estimate from a very simple - * formula based on Gresho et al. This routine can be called for a first - * order - forward Euler/backward Euler predictor/ corrector and for a - * second order Adams- Bashforth/Trapezoidal Rule predictor/corrector. See - * Nachos documentation Sand86-1816 and Gresho, Lee, LLNL report UCRL - - * 83282 for more information. - * - * on input: - * - * abs_error - Generic absolute error tolerance - * rel_error - Generic relative error tolerance - * x_coor[] - Solution vector from the implicit corrector - * x_pred_n[] - Solution vector from the explicit predictor - * - * on output: - * - * delta_t_n - Magnitude of next time step at time t_n+1 - * delta_t_nm1 - Magnitude of previous time step at time t_n - */ - double time_error_norm(); - - /*! - * Time step control function for the selection of the time step size based on - * a desired accuracy of time integration and on an estimate of the relative - * error of the time integration process. This routine can be called for a - * first order - forward Euler/backward Euler predictor/ corrector and for a - * second order Adams- Bashforth/Trapezoidal Rule predictor/corrector. See - * Nachos documentation Sand86-1816 and Gresho, Lee, Sani LLNL report UCRL - - * 83282 for more information. - * - * on input: - * - * order - indicates order of method - * = 1 -> first order forward Euler/backward Euler - * predictor/corrector - * = 2 -> second order forward Adams-Bashforth/Trapezoidal - * rule predictor/corrector - * - * delta_t_n - Magnitude of time step at time t_n - * delta_t_nm1 - Magnitude of time step at time t_n-1 - * rel_error - Generic relative error tolerance - * time_error_factor - Estimated value of the time step truncation error - * factor. This value is a ratio of the computed - * error norms. The premultiplying constants - * and the power are not yet applied to normalize the - * predictor/corrector ratio. (see output value) - * - * on output: - * - * return - delta_t for the next time step - * If delta_t is negative, then the current time step is - * rejected because the time-step truncation error is - * too large. The return value will contain the negative - * of the recommended next time step. - * - * time_error_factor - This output value is normalized so that - * values greater than one indicate the current time - * integration error is greater than the user - * specified magnitude. - */ - double time_step_control(int m_order, double time_error_factor); - - //! Solve a nonlinear system - /*! - * Find the solution to F(X, xprime) = 0 by damped Newton iteration. On - * entry, y_comm[] contains an initial estimate of the solution and - * ydot_comm[] contains an estimate of the derivative. - * On successful return, y_comm[] contains the converged solution - * and ydot_comm[] contains the derivative - * - * @param y_comm[] Contains the input solution. On output y_comm[] contains - * the converged solution - * @param ydot_comm Contains the input derivative solution. On output - * y_comm[] contains the converged derivative solution - * @param CJ Inverse of the time step - * @param time_curr Current value of the time - * @param jac Jacobian - * @param num_newt_its number of Newton iterations - * @param num_linear_solves number of linear solves - * @param num_backtracks number of backtracs - * @param loglevel Log level - */ - int solve_nonlinear_problem(double* const y_comm, - double* const ydot_comm, double CJ, - double time_curr, - GeneralMatrix& jac, - int& num_newt_its, - int& num_linear_solves, - int& num_backtracks, - int loglevel); - - /** - * Compute the undamped Newton step. The residual function is - * evaluated at the current time, t_n, at the current values of the - * solution vector, m_y_n, and the solution time derivative, m_ydot_n, - * but the Jacobian is not recomputed. - */ - void doNewtonSolve(double, double*, double*, double*, - GeneralMatrix&, int); - - - //! Bound the Newton step while relaxing the solution - /*! - * Return the factor by which the undamped Newton step 'step0' - * must be multiplied in order to keep all solution components in - * all domains between their specified lower and upper bounds. - * Other bounds may be applied here as well. - * - * Currently the bounds are hard coded into this routine: - * - * Minimum value for all variables: - 0.01 * m_ewt[i] - * Maximum value = none. - * - * Thus, this means that all solution components are expected - * to be numerical greater than zero in the limit of time step - * truncation errors going to zero. - * - * Delta bounds: The idea behind these is that the Jacobian - * couldn't possibly be representative if the - * variable is changed by a lot. (true for - * nonlinear systems, false for linear systems) - * Maximum increase in variable in any one Newton iteration: factor of 2 - * Maximum decrease in variable in any one Newton iteration: factor of 5 - * - * @param y Current value of the solution - * @param step0 Current raw step change in y[] - * @param loglevel Log level. This routine produces output if loglevel - * is greater than one - * - * @return Returns the damping coefficient - */ - double boundStep(const double* const y, const double* const step0, int loglevel); - - /*! - * On entry, step0 must contain an undamped Newton step for the - * solution x0. This method attempts to find a damping coefficient - * such that the next undamped step would have a norm smaller than - * that of step0. If successful, the new solution after taking the - * damped step is returned in y1, and the undamped step at y1 is - * returned in step1. - */ - int dampStep(double, const double*, const double*, - const double*, double*, double*, - double*, double&, GeneralMatrix&, int&, bool, int&); - - //! Compute Residual Weights - void computeResidWts(GeneralMatrix& jac); - - //! Filter a new step - double filterNewStep(double, double*, double*); - - //! Get the next time to print out - double getPrintTime(double time_current); - - /********************** Member data ***************************/ - /********************* - * METHOD FLAGS - *********************/ - - //! IterType is used to specify how the nonlinear equations are - //! to be relaxed at each time step. - IterType m_iter; - /** - * MethodType is used to specify how the time step is to be - * chosen. Currently, there are two choices, one is a fixed - * step method while the other is based on a predictor-corrector - * algorithm and a time-step truncation error tolerance. - */ - BEulerMethodType m_method; - /** - * m_jacFormMethod determines how a matrix is formed. - */ - int m_jacFormMethod; - /** - * m_rowScaling is a boolean. If true then row sum scaling - * of the Jacobian matrix is carried out when solving the - * linear systems. - */ - bool m_rowScaling; - /** - * m_colScaling is a boolean. If true, then column scaling - * is performed on each solution of the linear system. - */ - bool m_colScaling; - /** - * m_matrixConditioning is a boolean. If true, then the - * Jacobian and every RHS is multiplied by the inverse - * of a matrix that is suppose to reduce the condition - * number of the matrix. This is done before row scaling. - */ - bool m_matrixConditioning; - /** - * If m_itol =1 then each component has an individual - * value of atol. If m_itol = 0, the all atols are equal. - */ - int m_itol; - - //! Relative time truncation error tolerances - double m_reltol; - - /** - * Absolute time truncation error tolerances, when uniform - * for all variables. - */ - double m_abstols; - /** - * Vector of absolute time truncation error tolerance - * when not uniform for all variables. - */ - vector_fp m_abstol; - - //! Error Weights. This is a surprisingly important quantity. - vector_fp m_ewt; - - //! Maximum step size - double m_hmax; - - //! Maximum integration order - int m_maxord; - - //! Current integration order - int m_order; - - //! Time step number - int m_time_step_num; - int m_time_step_attempts; - - //! Max time steps allowed - int m_max_time_step_attempts; - /** - * Number of initial time steps to take where the time truncation error - * tolerances are not checked. Instead the delta T is uniform - */ - int m_numInitialConstantDeltaTSteps; - - //! Failure Counter -> keeps track of the number of consecutive failures - int m_failure_counter; - - //! Minimum Number of Newton Iterations per nonlinear step. default = 0 - int m_min_newt_its; - /************************ - * PRINTING OPTIONS - ************************/ - /** - * Step Interval at which to print out the solution - * default = 1; - * If set to zero, there is no printout - */ - int m_printSolnStepInterval; - /** - * Number of evenly spaced printouts of the solution - * If zero, there is no printout from this option - * default 1 - * If set to zero there is no printout. - */ - int m_printSolnNumberToTout; - - //! Number of initial steps that the solution is printed out. default = 0 - int m_printSolnFirstSteps; - - //! Dump Jacobians to disk. default false - bool m_dumpJacobians; - - /********************* - * INTERNAL SOLUTION VALUES - *********************/ - - //! Number of equations in the ode integrator - int m_neq; - vector_fp m_y_n; - vector_fp m_y_nm1; - vector_fp m_y_pred_n; - vector_fp m_ydot_n; - vector_fp m_ydot_nm1; - /************************ - * TIME VARIABLES - ************************/ - - //! Initial time at the start of the integration - double m_t0; - - //! Final time - double m_time_final; - - double time_n; - double time_nm1; - double time_nm2; - double delta_t_n; - double delta_t_nm1; - double delta_t_nm2; - double delta_t_np1; - - //! Maximum permissible time step - double delta_t_max; - - vector_fp m_resid; - vector_fp m_residWts; - vector_fp m_wksp; - ResidJacEval* m_func; - vector_fp m_rowScales; - vector_fp m_colScales; - - //! Pointer to the Jacobian representing the time dependent problem - GeneralMatrix* tdjac_ptr; - - /** - * Determines the level of printing for each time - * step. - * 0 -> absolutely nothing is printed for - * a single time step. - * 1 -> One line summary per time step - * 2 -> short description, points of interest - * 3 -> Lots printed per time step (default) - */ - int m_print_flag; - /*************************************************************************** - * COUNTERS OF VARIOUS KINDS - ***************************************************************************/ - - //! Number of function evaluations - int m_nfe; - - /** - * Number of Jacobian Evaluations and - * factorization steps (they are the same) - */ - int m_nJacEval; - - //! Number of total Newton iterations - int m_numTotalNewtIts; - - //! Total number of linear iterations - int m_numTotalLinearSolves; - - //! Total number of convergence failures. - int m_numTotalConvFails; - - //! Total Number of time truncation error failures - int m_numTotalTruncFails; - - int num_failures; -}; - -} // namespace - -#endif // CT_BEULER diff --git a/include/cantera/numerics/BandMatrix.h b/include/cantera/numerics/BandMatrix.h index dfdad36cc..0cdfa623d 100644 --- a/include/cantera/numerics/BandMatrix.h +++ b/include/cantera/numerics/BandMatrix.h @@ -270,14 +270,6 @@ public: */ virtual doublereal* const* colPts(); - //! Copy the data from one array into another without doing any checking - /*! - * This differs from the assignment operator as no resizing is done and memcpy() is used. - * @param y Array to be copied - * @deprecated To be removed after Cantera 2.2. - */ - virtual void copyData(const GeneralMatrix& y); - //! Check to see if we have any zero rows in the Jacobian /*! * This utility routine checks to see if any rows are zero. diff --git a/include/cantera/numerics/GeneralMatrix.h b/include/cantera/numerics/GeneralMatrix.h index 82f6ed1a6..33b5cb886 100644 --- a/include/cantera/numerics/GeneralMatrix.h +++ b/include/cantera/numerics/GeneralMatrix.h @@ -174,14 +174,6 @@ public: */ virtual doublereal operator()(size_t i, size_t j) const = 0; - //! Copy the data from one array into another without doing any checking - /*! - * This differs from the assignment operator as no resizing is done and memcpy() is used. - * @param y Array to be copied - * @deprecated To be removed after Cantera 2.2. - */ - virtual void copyData(const GeneralMatrix& y) = 0; - //! Return an iterator pointing to the first element /*! * We might drop this later diff --git a/include/cantera/numerics/NonlinearSolver.h b/include/cantera/numerics/NonlinearSolver.h deleted file mode 100644 index 307b09697..000000000 --- a/include/cantera/numerics/NonlinearSolver.h +++ /dev/null @@ -1,1285 +0,0 @@ -/** - * @file NonlinearSolver.h - * Class that calculates the solution to a nonlinear, dense, set - * of equations (see \ref numerics - * and class \link Cantera::NonlinearSolver NonlinearSolver\endlink). - */ - -/* - * $Date$ - * $Revision$ - */ -/* - * Copyright 2004 Sandia Corporation. Under the terms of Contract - * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government - * retains certain rights in this software. - * See file License.txt for licensing information. - */ - -#ifndef CT_NONLINEARSOLVER_H -#define CT_NONLINEARSOLVER_H - -#include "cantera/numerics/ResidJacEval.h" -#include "cantera/numerics/SquareMatrix.h" - -namespace Cantera -{ - -//@{ -/// @name Constant which determines the type of the nonlinear solve -/*! - * I think steady state is the only option I'm gunning for - */ -//! The nonlinear problem is part of a pseudo time dependent calculation (NOT TESTED) -#define NSOLN_TYPE_PSEUDO_TIME_DEPENDENT 2 -//! The nonlinear problem is part of a time dependent calculation -#define NSOLN_TYPE_TIME_DEPENDENT 1 -//! The nonlinear problem is part of a steady state calculation -#define NSOLN_TYPE_STEADY_STATE 0 -//@} - - -//@{ -/// @name Constant which determines the Return int from the nonlinear solver -/*! - * This int is returned from the nonlinear solver - */ -//! The nonlinear solve is successful. -#define NSOLN_RETN_SUCCESS 1 -//! Problem isn't solved yet -#define NSOLN_RETN_CONTINUE 0 -//! The nonlinear problem started to take too small an update step. This indicates that either the -//! Jacobian is bad, or a constraint is being bumped up against. -#define NSOLN_RETN_FAIL_STEPTOOSMALL -1 -//! The nonlinear problem didn't solve the problem -#define NSOLN_RETN_FAIL_DAMPSTEP -2 -//! The nonlinear problem's Jacobian is singular -#define NSOLN_RETN_MATRIXINVERSIONERROR -3 -//! The nonlinear problem's Jacobian formation produced an error -#define NSOLN_RETN_JACOBIANFORMATIONERROR -4 -//! The nonlinear problem's base residual produced an error -#define NSOLN_RETN_RESIDUALFORMATIONERROR -5 -//! The nonlinear problem's max number of iterations has been exceeded -#define NSOLN_RETN_MAXIMUMITERATIONSEXCEEDED -7 -//@} -//@} - -//@{ -/// @name Constant which determines the type of the Jacobian -//! The Jacobian will be calculated from a numerical method -#define NSOLN_JAC_NUM 1 -//! The Jacobian is calculated from an analytical function -#define NSOLN_JAC_ANAL 2 -//@} - - -//! Class that calculates the solution to a nonlinear system -/*! - * This is a small nonlinear solver that can solve highly nonlinear problems that - * must use a dense matrix to relax the system. - * - * Newton's method is used. - * - * Damping is used extensively when relaxing the system. - * - * The basic idea is that we predict a direction that is parameterized by an overall coordinate - * value, beta, from zero to one, This may or may not be the same as the value, damp, - * depending upon whether the direction is straight. - * - * TIME STEP TYPE - * - * The code solves a nonlinear problem. Frequently the nonlinear problem is created from time-dependent - * residual. Whenever you change the solution vector, you are also changing the derivative of the - * solution vector. Therefore, the code has the option of altering ydot, a vector of time derivatives - * of the solution in tandem with the solution vector and then feeding a residual and Jacobian routine - * with the time derivatives as well as the solution. The code has support for a backwards euler method - * and a second order Adams-Bashforth or Trapezoidal Rule. - * - * In order to use these methods, the solver must be initialized with delta_t and m_y_nm1[i] to specify - * the conditions at the previous time step. For second order methods, the time derivative at t_nm1 must - * also be supplied, m_ydot_nm1[i]. Then the solution type NSOLN_TYPE_TIME_DEPENDENT may be used to - * solve the problem. - * - * For steady state problem whose residual doesn't have a solution time derivative in it, you should - * use the NSOLN_TYPE_STEADY_STATE problem type. - * - * We have a NSOLN_TYPE_PSEUDO_TIME_DEPENDENT defined. However, this is not implemented yet. This would - * be a pseudo time dependent calculation, where an optional time derivative could be added in order to - * help equilibrate a nonlinear steady state system. The time transient is not important in and of - * itself. Many physical systems have a time dependence to them that provides a natural way to relax - * the nonlinear system. - * - * MATRIX SCALING - * - * @code - * NonlinearSolver *nls = new NonlinearSolver(&r1); - * int solnType = NSOLN_TYPE_STEADY_STATE ; - * nls->setDeltaBoundsMagnitudes(deltaBounds); - * nls->solve_nonlinear_problem(solnType, y_comm, ydot_comm, CJ, time_curr, jac, - * num_newt_its, num_linear_solves, numBacktracks, - * loglevelInput); - * @endcode - * - * @ingroup numerics - * @deprecated Unused. To be removed after Cantera 2.2. - */ -class NonlinearSolver -{ -public: - //! Default constructor - /*! - * @param func Residual and Jacobian evaluator function object - */ - NonlinearSolver(ResidJacEval* func); - - //!Copy Constructor - NonlinearSolver(const NonlinearSolver& right); - - //! Destructor - virtual ~NonlinearSolver(); - - //! Assignment operator - NonlinearSolver& operator=(const NonlinearSolver& right); - - //! Create solution weights for convergence criteria - /*! - * We create soln weights from the following formula - * - * wt[i] = rtol * abs(y[i]) + atol[i] - * - * The program always assumes that atol is specific - * to the solution component - * - * @param y vector of the current solution values - */ - void createSolnWeights(const doublereal* const y); - - //! L2 norm of the delta of the solution vector - /*! - * calculate the norm of the solution vector. This will - * involve the column scaling of the matrix - * - * The third argument has a default of false. However, if true, then a - * table of the largest values is printed out to standard output. - * - * @param delta_y Vector to take the norm of - * @param title Optional title to be printed out - * @param printLargest int indicating how many specific lines should be printed out - * @param dampFactor Current value of the damping factor. Defaults to 1. - * only used for printout out a table. - * - * @return Returns the L2 norm of the delta - */ - doublereal solnErrorNorm(const doublereal* const delta_y, const char* title = 0, int printLargest = 0, - const doublereal dampFactor = 1.0) const; - - //! L2 norm of the residual of the equation system - /*! - * Calculate the norm of the residual vector. This may - * involve using the row sum scaling from the matrix problem. - * - * The third argument has a default of false. However, if true, then a - * table of the largest values is printed out to standard output. - * - * @param resid Vector of the residuals - * @param title Optional title to be printed out - * @param printLargest Number of specific entries to be printed - * @param y Current value of y - only used for printouts - * - * @return Returns the L2 norm of the delta - */ - doublereal residErrorNorm(const doublereal* const resid, const char* title = 0, const int printLargest = 0, - const doublereal* const y = 0) const; - - //! Compute the current residual - /*! - * The current value of the residual is stored in the internal work array - * m_resid, which is defined as mutable - * - * @param time_curr Value of the time - * @param typeCalc Type of the calculation - * @param y_curr Current value of the solution vector - * @param ydot_curr Current value of the time derivative of the solution vector - * @param evalType Base evaluation type. Defaults to Base_ResidEval - * - * @return Returns a flag to indicate that operation is successful. - * 1 Means a successful operation. - * 0 or neg value Means an unsuccessful operation. - */ - int doResidualCalc(const doublereal time_curr, const int typeCalc, const doublereal* const y_curr, - const doublereal* const ydot_curr, - const ResidEval_Type_Enum evalType = Base_ResidEval) const; - - //! Compute the undamped Newton step - /*! - * The residual function is evaluated at the current time, t_n, at the - * current values of the solution vector, m_y_n, and the solution time - * derivative, m_ydot_n. The Jacobian is not recomputed. - * - * A factored Jacobian is reused, if available. If a factored Jacobian - * is not available, then the Jacobian is factored. Before factoring, - * the Jacobian is row and column-scaled. Column scaling is not - * recomputed. The row scales are recomputed here, after column - * scaling has been implemented. - * - * @param time_curr Current value of the time - * @param y_curr Current value of the solution - * @param ydot_curr Current value of the solution derivative. - * @param delta_y return value of the raw change in y - * @param jac Jacobian - * - * @return Returns the result code from LAPACK. A zero means success. - * Anything else indicates a failure. - */ - int doNewtonSolve(const doublereal time_curr, const doublereal* const y_curr, - const doublereal* const ydot_curr, doublereal* const delta_y, - GeneralMatrix& jac); - - //! Compute the Newton step, either by direct Newton's or by solving a - //! close problem that is represented by a Hessian - /*! - * This is algorith A.6.5.1 in Dennis / Schnabel - * - * Compute the QR decomposition - * - * Compute the undamped Newton step. The residual function is - * evaluated at the current time, t_n, at the current values of the - * solution vector, m_y_n, and the solution time derivative, m_ydot_n. - * The Jacobian is not recomputed. - * - * A factored Jacobian is reused, if available. If a factored Jacobian - * is not available, then the Jacobian is factored. Before factoring, - * the Jacobian is row and column-scaled. Column scaling is not - * recomputed. The row scales are recomputed here, after column - * scaling has been implemented. - * - * @param y_curr Current value of the solution - * @param ydot_curr Current value of the solution derivative. - * @param delta_y return value of the raw change in y - * @param jac Jacobian - * - * Internal input - * --------------- - * internal m_resid Stored residual is used as input - * - * @return Returns the result code from LAPACK. A zero means success. Anything - * else indicates a failure. - */ - int doAffineNewtonSolve(const doublereal* const y_curr, const doublereal* const ydot_curr, - doublereal* const delta_y, GeneralMatrix& jac); - - //! Calculate the length of the current trust region in terms of the solution error norm - /*! - * We carry out a norm of deltaX_trust_ first. Then, we multiply that value - * by trustDelta_ - */ - doublereal trustRegionLength() const; - - //! Set default deulta bounds amounts - /*! - * Delta bounds are set to 0.01 for all unknowns arbitrarily and capriciously - * Then, for each call to the nonlinear solver - * Then, they are increased to 1000 x atol - * then, they are increased to 0.1 fab(y[i]) - */ - void setDefaultDeltaBoundsMagnitudes(); - - //! Adjust the step minimums - void adjustUpStepMinimums(); - - //! Set the delta Bounds magnitudes by hand - /*! - * @param deltaBoundsMagnitudes set the deltaBoundsMagnitude vector - */ - void setDeltaBoundsMagnitudes(const doublereal* const deltaBoundsMagnitudes); - -protected: - //! Readjust the trust region vectors - /*! - * The trust region is made up of the trust region vector calculation and the trustDelta_ value - * We periodically recalculate the trustVector_ values so that they renormalize to the - * correct length. We change the trustDelta_ values regularly - * - * The trust region calculate is based on - * - * || delta_x dot 1/trustDeltaX_ || <= trustDelta_ - */ - void readjustTrustVector(); - - //! Fill a dogleg solution step vector - /*! - * Previously, we have filled up deltaX_Newton_[], deltaX_CP_[], and Nuu_, so that - * this routine is straightforward. - * - * @param leg Leg of the dog leg you are on (0, 1, or 2) - * @param alpha Relative length along the dog length that you are on. - * @param deltaX Vector to be filled up - */ - void fillDogLegStep(int leg, doublereal alpha, std::vector & deltaX) const; - - //! Calculate the trust distance of a step in the solution variables - /*! - * The trust distance is defined as the length of the step according to the norm wrt to the trust region. - * We calculate the trust distance by the following method. - * - * trustDist = || delta_x dot 1/trustDeltaX_ || - * - * @param deltaX Current value of deltaX - */ - doublereal calcTrustDistance(std::vector const& deltaX) const; - -public: - //! Bound the step - /*! - * Return the factor by which the undamped Newton step 'step0' - * must be multiplied in order to keep all solution components in - * all domains between their specified lower and upper bounds. - * Other bounds may be applied here as well. - * - * Currently the bounds are hard coded into this routine: - * - * Minimum value for all variables: - 0.01 * m_ewt[i] - * Maximum value = none. - * - * Thus, this means that all solution components are expected - * to be numerical greater than zero in the limit of time step - * truncation errors going to zero. - * - * Delta bounds: The idea behind these is that the Jacobian - * couldn't possibly be representative if the - * variable is changed by a lot. (true for - * nonlinear systems, false for linear systems) - * Maximum increase in variable in any one Newton iteration: - * factor of 2 - * Maximum decrease in variable in any one Newton iteration: - * factor of 5 - * - * @param y Current solution value of the old step - * @param step0 Proposed step change in the solution - * - * @return Returns the damping factor determined by the bounds calculation - */ - doublereal boundStep(const doublereal* const y, const doublereal* const step0); - - //! Set bounds constraints for all variables in the problem - /*! - * @param y_low_bounds Vector of lower bounds - * @param y_high_bounds Vector of high bounds - */ - void setBoundsConstraints(const doublereal* const y_low_bounds, - const doublereal* const y_high_bounds); - - //! Return an editable vector of the low bounds constraints - std::vector & lowBoundsConstraintVector(); - - //! Return an editable vector of the high bounds constraints - std::vector & highBoundsConstraintVector(); - - //! Internal function to calculate the time derivative of the solution at the new step - /*! - * Previously, the user must have supplied information about the previous time step for this routine to - * work as intended. - * - * @param order of the BDF method - * @param y_curr current value of the solution - * @param ydot_curr Calculated value of the solution derivative that is consistent with y_curr - */ - void calc_ydot(const int order, const doublereal* const y_curr, doublereal* const ydot_curr) const; - - //! Function called to evaluate the Jacobian matrix and the current - //! residual vector at the current time step - /*! - * @param J Jacobian matrix to be filled in - * @param f Right hand side. This routine returns the current - * value of the RHS (output), so that it does - * not have to be computed again. - * @param time_curr Current time - * @param CJ inverse of the value of deltaT - * @param y value of the solution vector - * @param ydot value of the time derivative of the solution vector - * @param num_newt_its Number of Newton iterations - * - * @return Returns a flag to indicate that operation is successful. - * 1 Means a successful operation - * 0 Means an unsuccessful operation - */ - int beuler_jac(GeneralMatrix& J, doublereal* const f, - doublereal time_curr, doublereal CJ, doublereal* const y, - doublereal* const ydot, int num_newt_its); - - //! Apply a filtering process to the step - /*! - * @param timeCurrent Current value of the time - * @param ybase current value of the solution - * @param step0 Proposed step change in the solution - * - * @return Returns the norm of the value of the amount filtered - */ - doublereal filterNewStep(const doublereal timeCurrent, const doublereal* const ybase, doublereal* const step0); - - //! Apply a filter to the solution - /*! - * @param timeCurrent Current value of the time - * @param y_current current value of the solution - * @param ydot_current Current value of the solution derivative. - * - * @return Returns the norm of the value of the amount filtered - */ - doublereal filterNewSolution(const doublereal timeCurrent, doublereal* const y_current, - doublereal* const ydot_current); - - //! Return the factor by which the undamped Newton step 'step0' - //! must be multiplied in order to keep the update within the bounds of an accurate Jacobian. - /*! - * The idea behind these is that the Jacobian couldn't possibly be representative, if the - * variable is changed by a lot. (true for nonlinear systems, false for linear systems) - * Maximum increase in variable in any one Newton iteration: factor of 1.5 - * Maximum decrease in variable in any one Newton iteration: factor of 2 - * - * @param y Initial value of the solution vector - * @param step0 initial proposed step size - * - * @return returns the damping factor - */ - doublereal deltaBoundStep(const doublereal* const y, const doublereal* const step0); - - //! Find a damping coefficient through a look-ahead mechanism - /*! - * On entry, step_1 must contain an undamped Newton step for the - * solution y_n_curr. This method attempts to find a damping coefficient - * such that all components stay in bounds, and the next - * undamped step would have a norm smaller than - * that of step_1. If successful, the new solution after taking the - * damped step is returned in y_n_1, and the undamped step at y_n_1 is - * returned in step_2. - * - * @param time_curr Current physical time - * @param y_n_curr Base value of the solution before any steps - * are taken - * @param ydot_n_curr Base value of the time derivative of the - * solution - * @param step_1 Initial step suggested. - * @param y_n_1 Value of y1, the suggested solution after damping - * @param ydot_n_1 Value of the time derivative of the solution at y_n_1 - * @param step_2 Value of the step change from y_n_1 to y_n_2 - * @param stepNorm_2 norm of the step change in going from y_n_1 to y_n_2 - * @param jac Jacobian - * @param writetitle Write a title line - * @param num_backtracks Number of backtracks taken - * - * @return 1 Successful step was taken: Next step was less than previous step. - * s1 is calculated - * 2 Successful step: Next step's norm is less than 0.8 - * 3 Success: The final residual is less than 1.0 - * A predicted deltaSoln1 is not produced however. s1 is estimated. - * 4 Success: The final residual is less than the residual - * from the previous step. - * A predicted deltaSoln1 is not produced however. s1 is estimated. - * 0 Uncertain Success: s1 is about the same as s0 - * NSOLN_RETN_FAIL_DAMPSTEP - * Unsuccessful step. We can not find a damping factor that is suitable. - */ - int dampStep(const doublereal time_curr, const doublereal* const y_n_curr, - const doublereal* const ydot_n_curr, doublereal* const step_1, - doublereal* const y_n_1, doublereal* const ydot_n_1, doublereal* step_2, - doublereal& stepNorm_2, GeneralMatrix& jac, bool writetitle, - int& num_backtracks); - - //! Find the solution to F(X) = 0 by damped Newton iteration. - /*! - * On entry, x0 contains an initial estimate of the solution. On - * successful return, x1 contains the converged solution. - * - * SolnType = TRANSIENT -> we will assume we are relaxing a transient - * equation system for now. Will make it more general later, - * if an application comes up. - * - * @param SolnType Solution type - * @param y_comm Initial value of the solution. On return this is the converged - * value of the solution - * @param ydot_comm Initial value of the solution derivative. On return this is the - * converged value of the solution derivative. - * @param CJ Inverse of the value of deltaT - * @param time_curr Current value of the time - * @param jac Matrix that will be used to store the Jacobian - * @param num_newt_its Number of Newton iterations taken - * @param num_linear_solves Number of linear solves taken - * @param num_backtracks Number of backtracking steps taken - * @param loglevelInput Input log level determines the amount of printing. - * - * @return A positive value indicates a successful convergence - * -1 Failed convergence - */ - int solve_nonlinear_problem(int SolnType, doublereal* const y_comm, doublereal* const ydot_comm, doublereal CJ, - doublereal time_curr, GeneralMatrix& jac, int& num_newt_its, - int& num_linear_solves, int& num_backtracks, int loglevelInput); - - //! Set the values for the previous time step - /*! - * We set the values for the previous time step here. These are used in the nonlinear - * solve because they affect the calculation of ydot. - * - * @param y_nm1 Value of the solution vector at the previous time step - * @param ydot_nm1 Value of the solution vector derivative at the previous time step - */ - virtual void - setPreviousTimeStep(const std::vector& y_nm1, const std::vector& ydot_nm1); - -private: - //! Set the column scaling vector at the current time - void calcColumnScales(); - -public: - - //! Set the column scaling that are used for the inversion of the matrix - /*! - * There are three ways to do this. - * - * The first method is to set the bool useColScaling to true, leaving the scaling factors unset. - * Then, the column scales will be set to the solution error weighting factors. This has the - * effect of ensuring that all delta variables will have the same order of magnitude at convergence - * end. - * - * The second way is the explicitly set the column factors in the second argument of this function call. - * - * The final way to input the scales is to override the ResidJacEval member function call, - * - * calcSolnScales(double time_n, const double *m_y_n_curr, const double *m_y_nm1, double *m_colScales) - * - * Overriding this function call will trump all other ways to specify the column scaling factors. - * - * @param useColScaling Turn this on if you want to use column scaling in the calculations - * @param scaleFactors A vector of doubles that specifies the column factors. - */ - void setColumnScaling(bool useColScaling, const double* const scaleFactors = 0); - - //! Set the rowscaling that are used for the inversion of the matrix - /*! - * Row scaling is set here. Right now the row scaling is set internally in the code. - * - * @param useRowScaling Turn row scaling on or off. - */ - void setRowScaling(bool useRowScaling); - - //! Scale the matrix - /*! - * @param jac Jacobian - * @param y_comm Current value of the solution vector - * @param ydot_comm Current value of the time derivative of the solution vector - * @param time_curr current value of the time - * @param num_newt_its Current value of the number of newt its - */ - void scaleMatrix(GeneralMatrix& jac, doublereal* const y_comm, doublereal* const ydot_comm, - doublereal time_curr, int num_newt_its); - - //! Print solution norm contribution - /*! - * Prints out the most important entries to the update to the solution vector for the current step - * - * @param step_1 Raw update vector for the current nonlinear step - * @param stepNorm_1 Norm of the vector step_1 - * @param step_2 Raw update vector for the next solution value based on the old matrix - * @param stepNorm_2 Norm of the vector step_2 - * @param title title of the printout - * @param y_n_curr Old value of the solution - * @param y_n_1 New value of the solution after damping corrections - * @param damp Value of the damping factor - * @param num_entries Number of entries to print out - */ - void - print_solnDelta_norm_contrib(const doublereal* const step_1, const char* const stepNorm_1, - const doublereal* const step_2, const char* const stepNorm_2, - const char* const title, const doublereal* const y_n_curr, - const doublereal* const y_n_1, doublereal damp, size_t num_entries); - - //! Compute the Residual Weights - /*! - * The residual weights are defined here to be equal to the inverse of the row scaling factors used to - * row scale the matrix, after column scaling is used. They are multiplied by 10-3 because the column - * weights are also multiplied by that same quantity. - * - * The basic idea is that a change in the solution vector on the order of the convergence tolerance - * multiplied by [RJC] which is of order one after row scaling should give you the relative weight - * of the row. Values of the residual for that row can then be normalized by the value of this weight. - * When the tolerance in delta x is achieved, the tolerance in the residual is also achieved. - */ - void computeResidWts(); - - //! Return the residual weights - /*! - * @param residWts Vector of length neq_ - */ - void getResidWts(doublereal* const residWts) const; - - //! Check to see if the nonlinear problem has converged - /*! - * @param dampCode Code from the damping routine - * @param s1 Value of the norm of the step change - * - * @return integer is returned. If positive, then the problem has converged - * 1 Successful step was taken: Next step's norm is less than 1.0. - * The final residual norm is less than 1.0. - * 2 Successful step: Next step's norm is less than 0.8. - * This step's norm is less than 1.0. - * The residual norm can be anything. - * 3 Success: The final residual is less than 1.0 - * The predicted deltaSoln is below 1.0. - * 0 Not converged yet - */ - int convergenceCheck(int dampCode, doublereal s1); - - //! Set the absolute tolerances for the solution variables - /*! - * Set the absolute tolerances used in the calculation - * - * @param atol Vector of length neq_ that contains the tolerances to be used for the solution variables - */ - void setAtol(const doublereal* const atol); - - //! Set the relative tolerances for the solution variables - /*! - * Set the relative tolerances used in the calculation - * - * @param rtol single double - */ - void setRtol(const doublereal rtol); - - //! Set the relative and absolute tolerances for the Residual norm comparisons, if used - /*! - * Residual norms are used to calculate convergence within the nonlinear solver, since - * these are the norms that are associated with convergence proofs, especially for ill-conditioned systems. - * Usually the residual weights for each row are calculated by the program such that they - * correlate with the convergence requirements on the solution variables input by the user using - * the routines setAtol() and setRtol(). - * The residual weights are essentially calculated from the value - * - * residWeightNorm[i] = m_ScaleSolnNormToResNorm * sum_j ( fabs(A_i,j) ewt(j)) - * - * The factor, m_ScaleSolnNormToResNorm, is computed periodically to ensure that the solution norms - * and the residual norms are converging at the same time and thus accounts for some-illconditioning issues - * but not all. - * - * With this routine the user can override or add to the residual weighting norm evaluation by specifying - * their own vector of residual absolute and relative tolerances. - * - * The user specified tolerance for the residual is given by the following quantity - * - * residWeightNorm[i] = residAtol[i] + residRtol * m_rowWtScales[i] / neq - * - * @param residRtol scalar residual relative tolerance - * @param residAtol vector of residual absolute tolerances - * - * @param residNormHandling Parameter that sets the default handling of the residual norms - * 0 The residual weighting vector is calculated to make sure that the solution - * norms are roughly 1 when the residual norm is roughly 1. - * This is the default if this routine is not called. - * 1 Use the user residual norm specified by the parameters in this routine - * 2 Use the minimum value of the residual weights calculated by method 1 and 2. - * This is the default if this routine is called and this parameter isn't specified. - */ - void setResidualTols(double residRtol, double* residAtol, int residNormHandling = 2); - - //! Set the value of the maximum # of Newton iterations - /*! - * @param maxNewtIts Maximum number of Newton iterations - */ - void setMaxNewtIts(const int maxNewtIts); - - //! Calculate the scaling factor for translating residual norms into solution norms. - /*! - * This routine calls computeResidWts() a couple of times in the calculation of m_ScaleSolnNormToResNorm. - * A more sophisticated routine may do more with signs to get a better value. Perhaps, a series of calculations - * with different signs attached may be in order. Then, m_ScaleSolnNormToResNorm would be calculated - * as the minimum of a series of calculations. - */ - void calcSolnToResNormVector(); - - //! Calculate the steepest descent direction and the Cauchy Point where the quadratic formulation - //! of the nonlinear problem expects a minimum along the descent direction. - /*! - * @param jac Jacobian matrix: must be unfactored. - * - * @return Returns the norm of the solution update - */ - doublereal doCauchyPointSolve(GeneralMatrix& jac); - - //! This is a utility routine that can be used to print out the rates of the initial residual decline - /*! - * The residual**2 decline for various directions is printed out. The rate of decline of the - * square of the residuals multiplied by the number of equations along each direction is printed out - * This quantity can be directly related to the theory, and may be calculated from derivatives at the - * original point. - * - * ( (r)**2 * neq - (r0)**2 * neq ) / distance - * - * What's printed out: - * - * The theoretical linearized residual decline - * The actual residual decline in the steepest descent direction determined by numerical differencing - * The actual residual decline in the Newton direction determined by numerical differencing - * - * This routine doesn't need to be called for the solution of the nonlinear problem. - * - * @param time_curr Current time - * @param ydot0 INPUT Current value of the derivative of the solution vector - * @param ydot1 INPUT Time derivatives of solution at the conditions which are evaluated for success - * @param numTrials OUTPUT Counter for the number of residual evaluations - */ - void descentComparison(doublereal time_curr ,doublereal* ydot0, doublereal* ydot1, int& numTrials); - - //! Setup the parameters for the double dog leg - /*! - * The calls to the doCauchySolve() and doNewtonSolve() routines are done at the main level. This routine comes - * after those calls. We calculate the point Nuu_ here, the distances of the dog-legs, - * and the norms of the CP and Newton points in terms of the trust vectors. - */ - void setupDoubleDogleg(); - - //! Change the global lambda coordinate into the (leg,alpha) coordinate for the double dogleg - /*! - * @param lambda Global value of the distance along the double dogleg - * @param alpha relative value along the particular leg - * - * @return Returns the leg number ( 0, 1, or 2). - */ - int lambdaToLeg(const doublereal lambda, doublereal& alpha) const; - - //! Given a trust distance, this routine calculates the intersection of the this distance with the - //! double dogleg curve - /*! - * @param trustVal (INPUT) Value of the trust distance - * @param lambda (OUTPUT) Returns the internal coordinate of the double dogleg - * @param alpha (OUTPUT) Returns the relative distance along the appropriate leg - * @return leg (OUTPUT) Returns the leg ID (0, 1, or 2) - */ - int calcTrustIntersection(doublereal trustVal, doublereal& lambda, doublereal& alpha) const; - - //! Initialize the size of the trust vector. - /*! - * The algorithm we use is to set it equal to the length of the Distance to the Cauchy point. - */ - void initializeTrustRegion(); - - //! Set Trust region initialization strategy - /*! - * The default is use method 2 with a factor of 1. - * Then, on subsequent invocations of solve_nonlinear_problem() the strategy flips to method 0. - * - * @param method Method to set the strategy - * 0 No strategy - Use the previous strategy - * 1 Factor of the solution error weights - * 2 Factor of the first Cauchy Point distance - * 3 Factor of the first Newton step distance - * - * @param factor Factor to use in combination with the method - */ - void setTrustRegionInitializationMethod(int method, doublereal factor); - - //! Damp using the dog leg approach - /*! - * @param time_curr INPUT Current value of the time - * @param y_n_curr INPUT Current value of the solution vector - * @param ydot_n_curr INPUT Current value of the derivative of the solution vector - * @param step_1 INPUT First trial step for the first iteration - * @param y_n_1 INPUT First trial value of the solution vector - * @param ydot_n_1 INPUT First trial value of the derivative of the solution vector - * @param stepNorm_1 OUTPUT Norm of the vector step_1 - * @param stepNorm_2 OUTPUT Estimated norm of the vector step_2 - * @param jac INPUT Jacobian - * @param num_backtracks OUTPUT number of backtracks taken in the current damping step - * - * @return 1 Successful step was taken. The predicted residual norm is less than one - * 2 Successful step: Next step's norm is less than 0.8 - * 3 Success: The final residual is less than 1.0 - * A predicted deltaSoln1 is not produced however. s1 is estimated. - * 4 Success: The final residual is less than the residual - * from the previous step. - * A predicted deltaSoln1 is not produced however. s1 is estimated. - * 0 Uncertain Success: s1 is about the same as s0 - * -2 Unsuccessful step. - */ - int dampDogLeg(const doublereal time_curr, const doublereal* y_n_curr, - const doublereal* ydot_n_curr, std::vector & step_1, - doublereal* const y_n_1, doublereal* const ydot_n_1, - doublereal& stepNorm_1, doublereal& stepNorm_2, GeneralMatrix& jac, int& num_backtracks); - - //! Decide whether the current step is acceptable and adjust the trust region size - /*! - * This is an extension of algorithm 6.4.5 of Dennis and Schnabel. - * - * Here we decide whether to accept the current step - * At the end of the calculation a new estimate of the trust region is calculated - * - * @param time_curr INPUT Current value of the time - * @param leg INPUT Leg of the dogleg that we are on - * @param alpha INPUT Distance down that leg that we are on - * @param y_n_curr INPUT Current value of the solution vector - * @param ydot_n_curr INPUT Current value of the derivative of the solution vector - * @param step_1 INPUT Trial step - * @param y_n_1 OUTPUT Solution values at the conditions which are evaluated for success - * @param ydot_n_1 OUTPUT Time derivatives of solution at the conditions which are evaluated for success - * @param trustDeltaOld INPUT Value of the trust length at the old conditions - * - * @return This function returns a code which indicates whether the step will be accepted or not. - * 3 Step passed with flying colors. Try redoing the calculation with a bigger trust region. - * 2 Step didn't pass deltaF requirement. Decrease the size of the next trust region for a retry and return - * 0 The step passed. - * -1 The step size is now too small (||d || < 0.1). A really small step isn't decreasing the function. - * This is an error condition. - * -2 Current value of the solution vector caused a residual error in its evaluation. - * Step is a failure, and the step size must be reduced in order to proceed further. - */ - int decideStep(const doublereal time_curr, int leg, doublereal alpha, const doublereal* const y_n_curr, - const doublereal* const ydot_n_curr, - const std::vector & step_1, - const doublereal* const y_n_1, const doublereal* const ydot_n_1, doublereal trustDeltaOld); - - //! Calculated the expected residual along the double dogleg curve. - /*! - * @param leg 0, 1, or 2 representing the curves of the dogleg - * @param alpha Relative distance along the particular curve. - * - * @return Returns the expected value of the residual at that point according to the quadratic model. - * The residual at the Newton point will always be zero. - */ - doublereal expectedResidLeg(int leg, doublereal alpha) const; - - //! Here we print out the residual at various points along the double dogleg, comparing against the quadratic model - //! in a table format - /*! - * @param time_curr INPUT current time - * @param ydot0 INPUT Current value of the derivative of the solution vector for non-time dependent - * determinations - * @param legBest OUTPUT leg of the dogleg that gives the lowest residual - * @param alphaBest OUTPUT distance along dogleg for best result. - */ - void residualComparisonLeg(const doublereal time_curr, const doublereal* const ydot0, int& legBest, - doublereal& alphaBest) const; - - //! Set the print level from the nonlinear solver - /*! - * 0 -> absolutely nothing is printed for a single time step. - * 1 -> One line summary per solve_nonlinear call - * 2 -> short description, points of interest: Table of nonlinear solve - one line per iteration - * 3 -> Table is included -> More printing per nonlinear iteration (default) that occurs during the table - * 4 -> Summaries of the nonlinear solve iteration as they are occurring -> table no longer printed - * 5 -> Algorithm information on the nonlinear iterates are printed out - * 6 -> Additional info on the nonlinear iterates are printed out - * 7 -> Additional info on the linear solve is printed out. - * 8 -> Info on a per iterate of the linear solve is printed out. - * - * @param printLvl integer value - */ - void setPrintLvl(int printLvl); - - //! Parameter to turn on solution solver schemes - /*! - * @param doDogLeg Parameter to turn on the double dog leg scheme - * Default is to always use a damping scheme in the Newton Direction. - * When this is nonzero, a model trust region approach is used using a double dog leg - * with the steepest descent direction used for small step sizes. - * - * @param doAffineSolve Parameter to turn on or off the solution of the system using a Hessian - * if the matrix has a bad condition number. - */ - void setSolverScheme(int doDogLeg, int doAffineSolve); - - /* - * ----------------------------------------------------------------------------------------------------------------- - * MEMBER DATA - * ------------------------------------------------------------------------------------------------ - */ -private: - - //! Pointer to the residual and Jacobian evaluator for the - //! function - /*! - * See ResidJacEval.h for an evaluator. - */ - ResidJacEval* m_func; - - //! Solution type - int solnType_; - - //! Local copy of the number of equations - size_t neq_; - - //! Soln error weights - std::vector m_ewt; - - //! Boolean indicating whether a manual delta bounds has been input. - int m_manualDeltaStepSet; - - //! Soln Delta bounds magnitudes - std::vector m_deltaStepMinimum; - - //! Value of the delta step magnitudes - std::vector m_deltaStepMaximum; - - //! Vector containing the current solution vector within the nonlinear solver - std::vector m_y_n_curr; - - //! Vector containing the time derivative of the current solution vector within the nonlinear solver - //! (where applicable) - std::vector m_ydot_n_curr; - - //! Vector containing the solution at the previous time step - std::vector m_y_nm1; - - //! Vector containing the solution derivative at the previous time step - std::vector m_ydot_nm1; - - //! Vector containing the solution at the new point that is to be considered - std::vector m_y_n_trial; - - //! Value of the solution time derivative at the new point that is to be considered - std::vector m_ydot_trial; - - //! Value of the step to be taken in the solution - std::vector m_step_1; - - //! Vector of column scaling factors - std::vector m_colScales; - - //! Weights for normalizing the values of the residuals - /*! - * These are computed if row scaling, m_rowScaling, is turned on. They are calculated currently as the - * sum of the absolute values of the rows of the Jacobian. - */ - std::vector m_rowScales; - - //! Weights for normalizing the values of the residuals - /*! - * They are calculated as the sum of the absolute values of the Jacobian - * multiplied by the solution weight function. - * This is carried out in scaleMatrix(). - */ - std::vector m_rowWtScales; - - //! Value of the residual for the nonlinear problem - mutable std::vector m_resid; - - //! Workspace of length neq_ - mutable std::vector m_wksp; - - //! Workspace of length neq_ - mutable std::vector m_wksp_2; - - /***************************************************************************************** - * INTERNAL WEIGHTS FOR TAKING SOLUTION NORMS - ******************************************************************************************/ - //! Vector of residual weights - /*! - * These are used to establish useful and informative weighted norms of the residual vector. - */ - std::vector m_residWts; - - //! Norm of the residual at the start of each nonlinear iteration - doublereal m_normResid_0; - - //! Norm of the residual after it has been bounded - doublereal m_normResid_Bound; - - //! Norm of the residual at the end of the first leg of the current iteration - doublereal m_normResid_1; - - //! Norm of the residual at the end of the first leg of the current iteration - doublereal m_normResid_full; - - //! Norm of the solution update created by the iteration in its raw, undamped form, using the solution norm - doublereal m_normDeltaSoln_Newton; - - //! Norm of the distance to the Cauchy point using the solution norm - doublereal m_normDeltaSoln_CP; - - //! Norm of the residual for a trial calculation which may or may not be used - doublereal m_normResidTrial; - - //! Vector of the norm - doublereal m_normResidPoints[15]; - - //! Boolean indicating whether we should scale the residual - mutable bool m_resid_scaled; - - /***************************************************************************************** - * INTERNAL BOUNDARY INFO FOR SOLUTIONS - *****************************************************************************************/ - - //! Bounds vector for each species - std::vector m_y_high_bounds; - - //! Lower bounds vector for each species - std::vector m_y_low_bounds; - - //! Damping factor imposed by hard bounds and by delta bounds - doublereal m_dampBound; - - //! Additional damping factor due to bounds on the residual and solution norms - doublereal m_dampRes; - - //! Delta t for the current step - doublereal delta_t_n; - - //! Counter for the total number of function evaluations - mutable int m_nfe; - - /*********************************************************************************************** - * MATRIX INFORMATION - **************************************************************************************/ - - //! The type of column scaling used in the matrix inversion of the problem - /*! - * If 1 then colScaling = m_ewt[] - * If 2 then colScaling = user set - * if 0 then colScaling = 1.0 - */ - int m_colScaling; - - //! int indicating whether row scaling is turned on (1) or not (0) - int m_rowScaling; - - //! Total number of linear solves taken by the solver object - int m_numTotalLinearSolves; - - //! Number of local linear solves done during the current iteration - int m_numLocalLinearSolves; - - //! Total number of Newton iterations - int m_numTotalNewtIts; - -public: - //! Minimum number of Newton iterations to use - int m_min_newt_its; -private: - - //! Maximum number of Newton iterations - int maxNewtIts_; - - //! Jacobian formation method - /*! - * 1 = numerical (default) - * 2 = analytical - */ - int m_jacFormMethod; - - //! Number of Jacobian evaluations - int m_nJacEval; - - //! Current system time - /*! - * Note, we assume even for steady state problems that the residual - * is a function of a system time. - */ - doublereal time_n; - - //! Boolean indicating matrix conditioning - int m_matrixConditioning; - - //! Order of the time step method = 1 - int m_order; - - //! value of the relative tolerance to use in solving the equation set - doublereal rtol_; - - //! Base value of the absolute tolerance - doublereal atolBase_; - - //! absolute tolerance in the solution unknown - /*! - * This is used to evaluating the weighting factor - */ - std::vector atolk_; - - //! absolute tolerance in the unscaled solution unknowns - std::vector userResidAtol_; - - //! absolute tolerance in the unscaled solution unknowns - doublereal userResidRtol_; - - //! Check the residual tolerances explicitly against user input - /*! - * 0 Don't calculate residual weights from residual tolerance inputs - * 1 Calculate residual weights from residual tolerance inputs only - * 2 Calculate residual weights from a minimum of the solution error weights process and the direct residual tolerance inputs - */ - int checkUserResidualTols_; - - //! Determines the level of printing for each time step. - /*! - * 0 -> absolutely nothing is printed for a single time step. - * 1 -> One line summary per solve_nonlinear call - * 2 -> short description, points of interest: Table of nonlinear solve - one line per iteration - * 3 -> Table is included -> More printing per nonlinear iteration (default) that occurs during the table - * 4 -> Summaries of the nonlinear solve iteration as they are occurring -> table no longer printed - * Base_ShowSolution Residual called for residual printing at the end of convergence. - * 5 -> Algorithm information on the nonlinear iterates are printed out - * 6 -> Additional info on the nonlinear iterates are printed out - * Base_ShowSolution Residual called for residual printing at the end of each step. - * 7 -> Additional info on the linear solve is printed out. - * 8 -> Info on a per iterate of the linear solve is printed out. - */ - int m_print_flag; - - //! Scale factor for turning residual norms into solution norms - doublereal m_ScaleSolnNormToResNorm; - - //! Copy of the Jacobian that doesn't get overwritten when the inverse is determined - /*! - * The Jacobian stored here is the raw matrix, before any row or column scaling is carried out - */ - GeneralMatrix* jacCopyPtr_; - - //! Hessian - GeneralMatrix* HessianPtr_; - - /********************************************************************************************* - * VARIABLES ASSOCIATED WITH STEPS AND ASSOCIATED DOUBLE DOGLEG PARAMETERS - *********************************************************************************************/ - - //! Steepest descent direction. This is also the distance to the Cauchy Point - std::vector deltaX_CP_; - - //! Newton Step - This is the Newton step determined from the straight Jacobian - /* - * Newton step for the current step only - */ - std::vector deltaX_Newton_; - - //! Expected value of the residual norm at the Cauchy point if the quadratic model - //! were valid - doublereal residNorm2Cauchy_; - - //! Current leg - int dogLegID_; - - //! Current Alpha param along the leg - doublereal dogLegAlpha_; - - //! Residual dot Jd norm - /*! - * This is equal to R_hat dot J_hat d_y_descent - */ - doublereal RJd_norm_; - - //! Value of lambdaStar_ which is used to calculate the Cauchy point - doublereal lambdaStar_; - - //! Jacobian times the steepest descent direction in the normalized coordinates. - /*! - * This is equal to [ Jhat d^y_{descent} ] in the notes, Eqn. 18. - */ - std::vector Jd_; - - //! Vector of trust region values. - std::vector deltaX_trust_; - - //! Current norm of the vector deltaX_trust_ in terms of the solution norm - mutable doublereal norm_deltaX_trust_; - - //! Current value of trust radius. This is used with deltaX_trust_ to - //! calculate the max step size. - doublereal trustDelta_; - - //! Method for handling the trust region initialization - /*! - * Then, on subsequent invocations of solve_nonlinear_problem() the strategy flips to method 0. - * - * method Method to set the strategy - * 0 No strategy - Use the previous strategy - * 1 Factor of the solution error weights - * 2 Factor of the first Cauchy Point distance - * 3 Factor of the first Newton step distance - */ - int trustRegionInitializationMethod_; - - //! Factor used to set the initial trust region - doublereal trustRegionInitializationFactor_; - - //! Relative distance down the Newton step that the second dogleg starts - doublereal Nuu_; - - //! Distance of the zeroeth leg of the dogleg in terms of the solution norm - doublereal dist_R0_; - - //! Distance of the first leg of the dogleg in terms of the solution norm - doublereal dist_R1_; - - //! Distance of the second leg of the dogleg in terms of the solution norm - doublereal dist_R2_; - - //! Distance of the sum of all legs of the doglegs in terms of the solution norm - doublereal dist_Total_; - - //! Dot product of the Jd_ variable defined above with itself. - doublereal JdJd_norm_; - - //! Norm of the Newton Step wrt trust region - doublereal normTrust_Newton_; - - //! Norm of the Cauchy Step direction wrt trust region - doublereal normTrust_CP_; - - //! General toggle for turning on dog leg damping. - int doDogLeg_; - - //! General toggle for turning on Affine solve with Hessian - int doAffineSolve_; - - //! Condition number of the matrix - doublereal m_conditionNumber; - - //! Factor indicating how much trust region has been changed this iteration - output variable - doublereal CurrentTrustFactor_; - - //! Factor indicating how much trust region has been changed next iteration - output variable - doublereal NextTrustFactor_; - - //! Boolean indicating that the residual weights have been reevaluated this iteration - output variable - bool ResidWtsReevaluated_; - - //! Expected DResid_dS for the steepest descent path - output variable - doublereal ResidDecreaseSDExp_; - - //! Actual DResid_dS for the steepest descent path - output variable - doublereal ResidDecreaseSD_; - - //! Expected DResid_dS for the Newton path - output variable - doublereal ResidDecreaseNewtExp_; - - //! Actual DResid_dS for the Newton path - output variable - doublereal ResidDecreaseNewt_; - - /******************************************************************************************* - * STATIC VARIABLES - *****************************************************************************************/ - -public: - //! Turn off printing of time - /*! - * Necessary to do for test suites - */ - static bool s_TurnOffTiming; - - //! Turn on or off printing of the Jacobian - static bool s_print_NumJac; - - //! Turn on extra printing of dogleg information - static bool s_print_DogLeg; - - //! Turn on solving both the Newton and Hessian systems and comparing the results - /*! - * This is off by default - */ - static bool s_doBothSolvesAndCompare; - - //! This toggle turns off the use of the Hessian when it is warranted by the condition number. - /*! - * This is a debugging option. - */ - static bool s_alwaysAssumeNewtonGood; - -}; - -} - -#endif diff --git a/include/cantera/numerics/SquareMatrix.h b/include/cantera/numerics/SquareMatrix.h index 2b2d55980..a9e68e68e 100644 --- a/include/cantera/numerics/SquareMatrix.h +++ b/include/cantera/numerics/SquareMatrix.h @@ -89,9 +89,6 @@ public: return Array2D::operator()(i, j); } - //! @deprecated To be removed after Cantera 2.2. - virtual void copyData(const GeneralMatrix& y); - virtual doublereal operator()(size_t i, size_t j) const { return Array2D::operator()(i, j); } diff --git a/include/cantera/numerics/solveProb.h b/include/cantera/numerics/solveProb.h deleted file mode 100644 index 4047bf19a..000000000 --- a/include/cantera/numerics/solveProb.h +++ /dev/null @@ -1,448 +0,0 @@ -/** - * @file solveProb.h Header file for implicit nonlinear solver with the option - * of a pseudotransient (see \ref numerics and class \link - * Cantera::solveProb solveProb\endlink). - */ - -/* - * Copyright 2004 Sandia Corporation. Under the terms of Contract - * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government - * retains certain rights in this software. - * See file License.txt for licensing information. - */ - -#ifndef SOLVEPROB_H -#define SOLVEPROB_H -/** - * @defgroup solverGroup Solvers for Equation Systems - */ - -#include "cantera/numerics/SquareMatrix.h" -#include "ResidEval.h" - -//! Solution Methods -/*! - * Flag to specify the solution method - * - * 1: SOLVEPROB_INITIALIZE = This assumes that the initial guess supplied to the - * routine is far from the correct one. Substantial - * work plus transient time-stepping is to be expected - * to find a solution. - * 2: SOLVEPROB_RESIDUAL = Need to solve the surface problem in order to - * calculate the surface fluxes of gas-phase species. - * (Can expect a moderate change in the solution - * vector -> try to solve the system by direct - * methods - * with no damping first -> then, try time-stepping - * if the first method fails) - * A "time_scale" supplied here is used in the - * algorithm to determine when to shut off - * time-stepping. - * 3: SOLVEPROB_JACOBIAN = Calculation of the surface problem is due to the - * need for a numerical Jacobian for the gas-problem. - * The solution is expected to be very close to the - * initial guess, and accuracy is needed. - * 4: SOLVEPROB_TRANSIENT = The transient calculation is performed here for an - * amount of time specified by "time_scale". It is - * not guaranteed to be time-accurate - just stable - * and fairly fast. The solution after del_t time is - * returned, whether it's converged to a steady - * state or not. - */ -const int SOLVEPROB_INITIALIZE = 1; -const int SOLVEPROB_RESIDUAL = 2; -const int SOLVEPROB_JACOBIAN = 3; -const int SOLVEPROB_TRANSIENT = 4; - -namespace Cantera -{ -//! Method to solve a pseudo steady state of a nonlinear problem -/*! - * The following class handles the solution of a nonlinear problem. - * - * Res_ss(C) = - Res(C) = 0 - * - * Optionally a pseudo transient algorithm may be used to relax the residual if - * it is available. - * - * Res_td(C) = dC/dt - Res(C) = 0; - * - * Res_ss(C) is the steady state residual to be solved. Res_td(C) is the - * time dependent residual which leads to the steady state residual. - * - * Solution Method - * - * This routine is typically used within a residual calculation in a large code. - * It's typically invoked millions of times for large calculations, and it must - * work every time. Therefore, requirements demand that it be robust but also - * efficient. - * - * The solution methodology is largely determined by the ifunc parameter, - * that is input to the solution object. This parameter may have the following - * 4 values: - * - * 1: SOLVEPROB_INITIALIZE = This assumes that the initial guess supplied to the - * routine is far from the correct one. Substantial - * work plus transient time-stepping is to be expected - * to find a solution. - * - * 2: SOLVEPROB_RESIDUAL = Need to solve the nonlinear problem in order to - * calculate quantities for a residual calculation - * (Can expect a moderate change in the solution - * vector -> try to solve the system by direct methods - * with no damping first -> then, try time-stepping - * if the first method fails) - * A "time_scale" supplied here is used in the - * algorithm to determine when to shut off - * time-stepping. - * - * 3: SOLVEPROB_JACOBIAN = Calculation of the surface problem is due to the - * need for a numerical Jacobian for the gas-problem. - * The solution is expected to be very close to the - * initial guess, and extra accuracy is needed because - * solution variables have been delta'd from - * nominal values to create Jacobian entries. - * - * 4: SOLVEPROB_TRANSIENT = The transient calculation is performed here for an - * amount of time specified by "time_scale". It is - * not guaranteed to be time-accurate - just stable - * and fairly fast. The solution after del_t time is - * returned, whether it's converged to a steady - * state or not. This is a poor man's time stepping - * algorithm. - * - * Pseudo time stepping algorithm: - * The time step is determined from sdot[], so that the time step - * doesn't ever change the value of a variable by more than 100%. - * - * This algorithm does use a damped Newton's method to relax the equations. - * Damping is based on a "delta damping" technique. The solution unknowns - * are not allowed to vary too much between iterations. - * - * EXTRA_ACCURACY:A constant that is the ratio of the required update norm in - * this Newton iteration compared to that in the nonlinear solver. - * A value of 0.1 is used so surface species are safely overconverged. - * - * Functions called: - *---------------------------------------------------------------------------- - * - * ct_dgetrf -- First half of LAPACK direct solve of a full Matrix - * - * ct_dgetrs -- Second half of LAPACK direct solve of a full matrix. Returns - * solution vector in the right-hand-side vector, resid. - * - *---------------------------------------------------------------------------- - * - * @ingroup solverGroup - * @deprecated Unused. To be removed after Cantera 2.2. - */ -class solveProb -{ -public: - - //! Constructor for the object - solveProb(ResidEval* resid); - - virtual ~solveProb() {} - -private: - - //! Unimplemented private copy constructor - solveProb(const solveProb& right); - - //! Unimplemented private assignment operator - solveProb& operator=(const solveProb& right); - -public: - //! Main routine that actually calculates the pseudo steady state - //! of the surface problem - /*! - * The actual converged solution is returned as part of the - * internal state of the InterfaceKinetics objects. - * - * @param ifunc Determines the type of solution algorithm to be - * used. Possible values are SOLVEPROB_INITIALIZE , - * SOLVEPROB_RESIDUAL SOLVEPROB_JACOBIAN SOLVEPROB_TRANSIENT . - * - * @param time_scale Time over which to integrate the surface equations, - * where applicable - * - * @param reltol Relative tolerance to use - * - * @return Returns 1 if the surface problem is successfully solved. - * Returns -1 if the surface problem wasn't solved successfully. - * Note the actual converged solution is returned as part of the - * internal state of the InterfaceKinetics objects. - */ - int solve(int ifunc, doublereal time_scale, doublereal reltol); - - //! Report the current state of the solution - /*! - * @param[out] CSoln solution vector for the nonlinear problem - */ - virtual void reportState(doublereal* const CSoln) const; - - //! Set the bottom and top bounds on the solution vector - /*! - * The default is for the bottom is 0.0, while the default for the top is 1.0 - * - * @param botBounds Vector of bottom bounds - * @param topBounds vector of top bounds - */ - virtual void setBounds(const doublereal botBounds[], const doublereal topBounds[]); - - void setAtol(const doublereal atol[]); - void setAtolConst(const doublereal atolconst); - -private: - //! Printing routine that gets called at the start of every invocation - virtual void print_header(int ioflag, int ifunc, doublereal time_scale, - doublereal reltol, - doublereal netProdRate[]); - -#ifdef DEBUG_SOLVEPROB - //! Prints out the residual and Jacobian - virtual void printResJac(int ioflag, int neq, const Array2D& Jac, - doublereal resid[], doublereal wtResid[], doublereal norm); -#endif - - //! Printing routine that gets called after every iteration - virtual void printIteration(int ioflag, doublereal damp, size_t label_d, size_t label_t, - doublereal inv_t, doublereal t_real, int iter, - doublereal update_norm, doublereal resid_norm, - doublereal netProdRate[], doublereal CSolnSP[], - doublereal resid[], - doublereal wtSpecies[], size_t dim, bool do_time); - - //! Print a summary of the solution - virtual void printFinal(int ioflag, doublereal damp, size_t label_d, size_t label_t, - doublereal inv_t, doublereal t_real, int iter, - doublereal update_norm, doublereal resid_norm, - doublereal netProdRateKinSpecies[], const doublereal CSolnSP[], - const doublereal resid[], - const doublereal wtSpecies[], const doublereal wtRes[], - size_t dim, bool do_time); - - //! Calculate a conservative delta T to use in a pseudo-steady state - //! algorithm - /*! - * This routine calculates a pretty conservative 1/del_t based - * on MAX_i(sdot_i/(X_i*SDen0)). This probably guarantees - * diagonal dominance. - * - * Small surface fractions are allowed to intervene in the del_t - * determination, no matter how small. This may be changed. - * Now minimum changed to 1.0e-12, - * - * Maximum time step set to time_scale. - * - * @param netProdRateSolnSP Output variable. Net production rate - * of all of the species in the solution vector. - * @param Csoln output variable. - * Mole fraction of all of the species in the solution vector - * @param label Output variable. Pointer to the value of the - * species index (kindexSP) that is controlling - * the time step - * @param label_old Output variable. Pointer to the value of the - * species index (kindexSP) that controlled - * the time step at the previous iteration - * @param label_factor Output variable. Pointer to the current - * factor that is used to indicate the same species - * is controlling the time step. - * - * @param ioflag Level of the output requested. - * - * @return Returns the 1. / delta T to be used on the next step - */ - virtual doublereal calc_t(doublereal netProdRateSolnSP[], doublereal Csoln[], - size_t* label, size_t* label_old, - doublereal* label_factor, int ioflag); - - //! Calculate the solution and residual weights - /*! - * Calculate the weighting factors for norms wrt both the species - * concentration unknowns and the residual unknowns. - * @param wtSpecies Weights to use for the soln unknowns. These - * are in concentration units - * @param wtResid Weights to sue for the residual unknowns. - * - * @param CSolnSP Solution vector for the surface problem - */ - virtual void calcWeights(doublereal wtSpecies[], doublereal wtResid[], - const doublereal CSolnSP[]); - -#ifdef DEBUG_SOLVEPROB - //! Utility routine to print a header for high lvls of debugging - /*! - * @param ioflag Lvl of debugging - * @param damp lvl of damping - * @param inv_t Inverse of the value of delta T - * @param t_real Value of the time - * @param iter Iteration number - * @param do_time boolean indicating whether time stepping is taking - * place - */ - virtual void printIterationHeader(int ioflag, doublereal damp, - doublereal inv_t, doublereal t_real, int iter, - bool do_time); -#endif - - //! Main Function evaluation - /*! - * This calculates the net production rates of all species - * - * @param resid output Vector of residuals, length = m_neq - * @param CSolnSP Vector of species concentrations, unknowns in the - * problem, length = m_neq - * @param CSolnSPOld Old Vector of species concentrations, unknowns in the - * problem, length = m_neq - * @param do_time Calculate a time dependent residual - * @param deltaT Delta time for time dependent problem. - */ - virtual void fun_eval(doublereal* const resid, const doublereal* const CSolnSP, - const doublereal* const CSolnSPOld, const bool do_time, const doublereal deltaT); - - //! Main routine that calculates the current residual and Jacobian - /*! - * @param JacCol Vector of pointers to the tops of columns of the - * Jacobian to be evaluated. - * @param resid output Vector of residuals, length = m_neq - * @param CSolnSP Vector of species concentrations, unknowns in the - * problem, length = m_neq. These are tweaked in order - * to derive the columns of the Jacobian. - * @param CSolnSPOld Old Vector of species concentrations, unknowns in the - * problem, length = m_neq - * @param do_time Calculate a time dependent residual - * @param deltaT Delta time for time dependent problem. - */ - virtual void resjac_eval(std::vector& JacCol, doublereal* resid, - doublereal* CSolnSP, - const doublereal* CSolnSPOld, const bool do_time, - const doublereal deltaT); - - //! This function calculates a damping factor for the Newton iteration update - //! vector, dxneg, to insure that all solution components stay within prescribed bounds - /*! - * The default for this class is that all solution components are bounded between zero and one. - * this is because the original unknowns were mole fractions and surface site fractions. - * - * dxneg[] = negative of the update vector. - * - * The constant "APPROACH" sets the fraction of the distance to the boundary - * that the step can take. If the full step would not force any fraction - * outside of the bounds, then Newton's method is mostly allowed to operate normally. - * There is also some solution damping employed. - * - * @param x Vector of the current solution components - * @param dxneg Vector of the negative of the full solution update vector. - * @param dim Size of the solution vector - * @param label return int, stating which solution component caused the most damping. - */ - virtual doublereal calc_damping(doublereal x[], doublereal dxneg[], size_t dim, size_t* label); - - //! residual function pointer to be solved. - ResidEval* m_residFunc; - - //! Total number of equations to solve in the implicit problem. - /*! - * Note, this can be zero, and frequently is - */ - size_t m_neq; - - //! m_atol is the absolute tolerance in real units. - vector_fp m_atol; - - //! m_rtol is the relative error tolerance. - doublereal m_rtol; - - //! maximum value of the time step - /*! - * units = seconds - */ - doublereal m_maxstep; - - //! Temporary vector with length MAX(1, m_neq) - vector_fp m_netProductionRatesSave; - - //! Temporary vector with length MAX(1, m_neq) - vector_fp m_numEqn1; - - //! Temporary vector with length MAX(1, m_neq) - vector_fp m_numEqn2; - - //! Temporary vector with length MAX(1, m_neq) - vector_fp m_CSolnSave; - - //! Solution vector - /*! - * length MAX(1, m_neq) - */ - vector_fp m_CSolnSP; - - //! Saved initial solution vector - /*! - * length MAX(1, m_neq) - */ - vector_fp m_CSolnSPInit; - - //! Saved solution vector at the old time step - /*! - * length MAX(1, m_neq) - */ - vector_fp m_CSolnSPOld; - - //! Weights for the residual norm calculation - /*! - * length MAX(1, m_neq) - */ - vector_fp m_wtResid; - - //! Weights for the species concentrations norm calculation - /*! - * length MAX(1, m_neq) - */ - vector_fp m_wtSpecies; - - //! Residual for the surface problem - /*! - * The residual vector of length "dim" that, that has the value - * of "sdot" for surface species. The residuals for the bulk - * species are a function of the sdots for all species in the bulk - * phase. The last residual of each phase enforces {Sum(fractions) - * = 1}. After linear solve (dgetrf_ & dgetrs_), resid holds the - * update vector. - * - * length MAX(1, m_neq) - */ - vector_fp m_resid; - - //! Vector of pointers to the top of the columns of the Jacobians - /*! - * The "dim" by "dim" computed Jacobian matrix for the - * local Newton's method. - */ - std::vector m_JacCol; - - //! Jacobian - /*! - * m_neq by m_neq computed Jacobian matrix for the local Newton's method. - */ - SquareMatrix m_Jac; - - //! Top bounds for the solution vector - /*! - * This defaults to 1.0 - */ - vector_fp m_topBounds; - - //! Bottom bounds for the solution vector - /*! - * This defaults to 0.0 - */ - vector_fp m_botBounds; - -public: - int m_ioflag; -}; -} -#endif diff --git a/include/cantera/oneD/StFlow.h b/include/cantera/oneD/StFlow.h index b234c9a40..e4be1a418 100644 --- a/include/cantera/oneD/StFlow.h +++ b/include/cantera/oneD/StFlow.h @@ -124,28 +124,11 @@ public: m_do_energy[j] = false; } - /*! - * Set the mass fraction fixed point for species k at grid point j, and - * disable the species equation so that the solution will be held to this - * value. Note: in practice, the species are hardly ever held fixed. - */ - void setMassFraction(size_t j, size_t k, doublereal y) { - m_fixedy(k,j) = y; - m_do_species[k] = true; - } - //! The fixed temperature value at point j. doublereal T_fixed(size_t j) const { return m_fixedtemp[j]; } - //! The fixed mass fraction value of species k at point j. - //! @deprecated Unused. To be removed after Cantera 2.2. - doublereal Y_fixed(size_t k, size_t j) const { - warn_deprecated("StFlow::Y_fixed", "To be removed after Cantera 2.2."); - return m_fixedy(k,j); - } - // @} virtual std::string componentName(size_t n) const; @@ -253,44 +236,10 @@ public: } } - //! @deprecated Species equations are always solved. To be removed after - //! Cantera 2.2. - bool doSpecies(size_t k) { - warn_deprecated("StFlow::doSpecies", "To be removed after Cantera 2.2."); - return m_do_species[k]; - } bool doEnergy(size_t j) { return m_do_energy[j]; } - //! @deprecated Species equations are always solved. To be removed after - //! Cantera 2.2. - void solveSpecies(size_t k=npos) { - warn_deprecated("StFlow::solveSpecies", "To be removed after Cantera 2.2."); - if (k == npos) { - for (size_t i = 0; i < m_nsp; i++) { - m_do_species[i] = true; - } - } else { - m_do_species[k] = true; - } - needJacUpdate(); - } - - //! @deprecated Species equations are always solved. To be removed after - //! Cantera 2.2. - void fixSpecies(size_t k=npos) { - warn_deprecated("StFlow::fixSpecies", "To be removed after Cantera 2.2."); - if (k == npos) { - for (size_t i = 0; i < m_nsp; i++) { - m_do_species[i] = false; - } - } else { - m_do_species[k] = false; - } - needJacUpdate(); - } - void integrateChem(doublereal* x,doublereal dt); //! Change the grid size. Called after grid refinement. @@ -534,7 +483,6 @@ protected: vector_fp m_qdotRadiation; // fixed T and Y values - Array2D m_fixedy; //!< @deprecated vector_fp m_fixedtemp; vector_fp m_zfix; vector_fp m_tfix; diff --git a/include/cantera/thermo/DebyeHuckel.h b/include/cantera/thermo/DebyeHuckel.h index f4fe0ba9c..65120f158 100644 --- a/include/cantera/thermo/DebyeHuckel.h +++ b/include/cantera/thermo/DebyeHuckel.h @@ -839,41 +839,6 @@ public: */ virtual doublereal standardConcentration(size_t k=0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * On return uA contains the powers of the units (MKS assumed) - * of the standard concentrations and generalized concentrations - * for the kth species. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //! Get the array of non-dimensional activities at //! the current solution temperature, pressure, and solution concentration. /*! diff --git a/include/cantera/thermo/FixedChemPotSSTP.h b/include/cantera/thermo/FixedChemPotSSTP.h index a24576054..546ae3c00 100644 --- a/include/cantera/thermo/FixedChemPotSSTP.h +++ b/include/cantera/thermo/FixedChemPotSSTP.h @@ -320,39 +320,6 @@ public: */ virtual void getStandardChemPotentials(doublereal* mu0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units: - * - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(doublereal* uA, int k = 0, - int sizeUA = 6) const; - //@} /// @name Partial Molar Properties of the Solution /// These properties are handled by the parent class, SingleSpeciesTP diff --git a/include/cantera/thermo/GibbsExcessVPSSTP.h b/include/cantera/thermo/GibbsExcessVPSSTP.h index 587c34a8b..7e90bbdda 100644 --- a/include/cantera/thermo/GibbsExcessVPSSTP.h +++ b/include/cantera/thermo/GibbsExcessVPSSTP.h @@ -231,33 +231,6 @@ public: */ virtual doublereal logStandardConc(size_t k=0) const; - /** - * Returns the units of the standard and generalized - * concentrations Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - - //! Get the array of non-dimensional activities (molality //! based for this class and classes that derive from it) at //! the current solution temperature, pressure, and solution concentration. diff --git a/include/cantera/thermo/HMWSoln.h b/include/cantera/thermo/HMWSoln.h index d1e0258e6..c763af22b 100644 --- a/include/cantera/thermo/HMWSoln.h +++ b/include/cantera/thermo/HMWSoln.h @@ -1644,37 +1644,6 @@ public: */ virtual doublereal standardConcentration(size_t k=0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //! Get the array of non-dimensional activities at //! the current solution temperature, pressure, and solution concentration. /*! diff --git a/include/cantera/thermo/IdealGasPhase.h b/include/cantera/thermo/IdealGasPhase.h index d1c2e2dc4..fac66f11d 100644 --- a/include/cantera/thermo/IdealGasPhase.h +++ b/include/cantera/thermo/IdealGasPhase.h @@ -418,69 +418,6 @@ public: */ virtual doublereal cv_mole() const; - /** - * @returns species translational/rotational specific heat at - * constant volume. Inferred from the species gas - * constant and number of translational/rotational - * degrees of freedom. The translational/rotational - * modes are assumed to be fully populated, and are - * given by - * \f[ - * C^{tr}_{v,s} \equiv \frac{\partial e^{tr}_s}{\partial T} = \frac{5}{2} R_s - * \f] - * for diatomic molecules and - * \f[ - * C^{tr}_{v,s} \equiv \frac{\partial e^{tr}_s}{\partial T} = \frac{3}{2} R_s - * \f] - * for atoms. - * @deprecated To be removed after Cantera 2.2. - */ - virtual doublereal cv_tr(doublereal) const; - - /** - * @returns species translational specific heat at constant volume. - * Since the translational modes are assumed to be fully populated - * this is simply - * \f[ - * C^{trans}_{v,s} \equiv \frac{\partial e^{trans}_s}{\partial T} = \frac{3}{2} R_s - * \f] - * @deprecated To be removed after Cantera 2.2. - */ - virtual doublereal cv_trans() const; - - /** - * @returns species rotational specific heat at constant volume. - * By convention, we lump the translational/rotational components - * \f[ - * C^{tr}_{v,s} \equiv C^{trans}_{v,s} + C^{rot}_{v,s} - * \f] - * so then - * \f[ - * C^{rot}_{v,s} \equiv C^{tr}_{v,s} - C^{trans}_{v,s} - * \f] - * @deprecated To be removed after Cantera 2.2. - */ - virtual doublereal cv_rot(double atomicity) const; - - /** - * @returns species vibrational specific heat at - * constant volume, - * \f[ - * C^{vib}_{v,s} = \frac{\partial e^{vib}_{v,s} }{\partial T} - * \f] - * where the species vibration energy \f$ e^{vib}_{v,s} \f$ is - * - atom: - * 0 - * - Diatomic: - * \f[ \frac{R_s \theta_{v,s}}{e^{\theta_{v,s}/T}-1} \f] - * - General Molecule: - * \f[ - * \sum_i \frac{R_s \theta_{v,s,i}}{e^{\theta_{v,s,i}/T}-1} - * \f] - * @deprecated To be removed after Cantera 2.2. - */ - virtual doublereal cv_vib(int k, doublereal T) const; - //! @} //! @name Mechanical Equation of State //! @{ diff --git a/include/cantera/thermo/IdealMolalSoln.h b/include/cantera/thermo/IdealMolalSoln.h index f77366b9c..051726581 100644 --- a/include/cantera/thermo/IdealMolalSoln.h +++ b/include/cantera/thermo/IdealMolalSoln.h @@ -362,32 +362,6 @@ public: */ virtual doublereal standardConcentration(size_t k=0) const; - /*! - * Returns the units of the standard and generalized - * concentrations Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - /*! * Get the array of non-dimensional activities at * the current solution temperature, pressure, and diff --git a/include/cantera/thermo/IdealSolidSolnPhase.h b/include/cantera/thermo/IdealSolidSolnPhase.h index 32a0aac33..0da0b407b 100644 --- a/include/cantera/thermo/IdealSolidSolnPhase.h +++ b/include/cantera/thermo/IdealSolidSolnPhase.h @@ -412,39 +412,6 @@ public: */ virtual doublereal logStandardConc(size_t k) const; - /** - * Returns the units of the standard and general concentrations - * Note they have the same units, as their divisor is - * defined to be equal to the activity of the kth species - * in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * @param uA Output vector containing the units: - * - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * - * For EOS types other than cIdealSolidSolnPhase0, the default - * kmol/m3 holds for standard concentration units. For - * cIdealSolidSolnPhase0 type, the standard concentration is - * unitless. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //! Get the array of species activity coefficients /*! * @param ac output vector of activity coefficients. Length: m_kk diff --git a/include/cantera/thermo/IdealSolnGasVPSS.h b/include/cantera/thermo/IdealSolnGasVPSS.h index 3b8f70e3d..0c7685d6e 100644 --- a/include/cantera/thermo/IdealSolnGasVPSS.h +++ b/include/cantera/thermo/IdealSolnGasVPSS.h @@ -163,37 +163,6 @@ public: */ virtual doublereal standardConcentration(size_t k=0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //! Get the array of non-dimensional activity coefficients at //! the current solution temperature, pressure, and solution concentration. /*! diff --git a/include/cantera/thermo/MetalSHEelectrons.h b/include/cantera/thermo/MetalSHEelectrons.h index 0b342864c..e84cd2d36 100644 --- a/include/cantera/thermo/MetalSHEelectrons.h +++ b/include/cantera/thermo/MetalSHEelectrons.h @@ -335,37 +335,6 @@ public: */ virtual void getStandardChemPotentials(doublereal* mu0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(doublereal* uA, int k = 0, - int sizeUA = 6) const; - //@} /// @name Properties of the Standard State of the Species in the Solution //@{ diff --git a/include/cantera/thermo/MineralEQ3.h b/include/cantera/thermo/MineralEQ3.h index c45ecf534..2312fb6aa 100644 --- a/include/cantera/thermo/MineralEQ3.h +++ b/include/cantera/thermo/MineralEQ3.h @@ -249,39 +249,6 @@ public: */ virtual void getStandardChemPotentials(doublereal* mu0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units - * - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(doublereal* uA, int k = 0, - int sizeUA = 6) const; - //@} /// @name Properties of the Standard State of the Species in the Solution //@{ diff --git a/include/cantera/thermo/MixedSolventElectrolyte.h b/include/cantera/thermo/MixedSolventElectrolyte.h index 26247d996..3092b49b8 100644 --- a/include/cantera/thermo/MixedSolventElectrolyte.h +++ b/include/cantera/thermo/MixedSolventElectrolyte.h @@ -290,15 +290,6 @@ public: */ MixedSolventElectrolyte(XML_Node& phaseRef, const std::string& id = ""); - //! Special constructor for a hard-coded problem - /*! - * @param testProb Hard-coded value. Only the value of 1 is used. It's - * for a LiKCl system -> test to predict the eutectic and - * liquidus correctly. - * @deprecated To be removed after Cantera 2.2. - */ - MixedSolventElectrolyte(int testProb); - //! Copy constructor /*! * @param b class to be copied diff --git a/include/cantera/thermo/MolalityVPSSTP.h b/include/cantera/thermo/MolalityVPSSTP.h index b0ae47f12..26db5da16 100644 --- a/include/cantera/thermo/MolalityVPSSTP.h +++ b/include/cantera/thermo/MolalityVPSSTP.h @@ -421,32 +421,6 @@ public: */ virtual doublereal standardConcentration(size_t k=0) const; - /** - * Returns the units of the standard and generalized - * concentrations Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //! Get the array of non-dimensional activities (molality //! based for this class and classes that derive from it) at //! the current solution temperature, pressure, and solution concentration. diff --git a/include/cantera/thermo/Phase.h b/include/cantera/thermo/Phase.h index 77e8ced47..c9ed00cee 100644 --- a/include/cantera/thermo/Phase.h +++ b/include/cantera/thermo/Phase.h @@ -644,13 +644,6 @@ public: //! @copydoc Phase::mean_X(const doublereal* const Q) const doublereal mean_X(const vector_fp& Q) const; - //! Evaluate the mass-fraction-weighted mean of an array Q. - //! \f[ \sum_k Y_k Q_k \f] - //! @param[in] Q Array of species property values in mass units. - //! @return The mass-fraction-weighted mean of Q. - //! @deprecated Unused. To be removed after Cantera 2.2. - doublereal mean_Y(const doublereal* const Q) const; - //! The mean molecular weight. Units: (kg/kmol) doublereal meanMolecularWeight() const { return m_mmw; @@ -660,11 +653,6 @@ public: //! @return The indicated sum. Dimensionless. doublereal sum_xlogx() const; - //! Evaluate \f$ \sum_k X_k \log Q_k \f$. - //! @param Q Vector of length m_kk to take the log average of - //! @return The indicated sum. - //! @deprecated Unused. To be removed after Cantera 2.2. - doublereal sum_xlogQ(doublereal* const Q) const; //@} //! @name Adding Elements and Species @@ -823,16 +811,6 @@ private: //! Entropy at 298.15 K and 1 bar of stable state pure elements (J kmol-1) vector_fp m_entropy298; - -public: - //! Overflow behavior of real number calculations involving this thermo object - /*! - * The default is THROWON_OVERFLOW_CTRB - * Which throws an error in debug mode, but silently changes the answer in non-debug mode - * @deprecated To be removed after Cantera 2.2. - */ - enum CT_RealNumber_Range_Behavior realNumberRangeBehavior_; - }; } diff --git a/include/cantera/thermo/PhaseCombo_Interaction.h b/include/cantera/thermo/PhaseCombo_Interaction.h index a0c0d8c35..667d5c318 100644 --- a/include/cantera/thermo/PhaseCombo_Interaction.h +++ b/include/cantera/thermo/PhaseCombo_Interaction.h @@ -363,15 +363,6 @@ public: */ PhaseCombo_Interaction(XML_Node& phaseRef, const std::string& id = ""); - //! Special constructor for a hard-coded problem - /*! - * @param testProb Hard-coded value. Only the value of 1 is used. It's - * for a LiKCl system -> test to predict the eutectic and - * liquidus correctly. - * @deprecated To be removed after Cantera 2.2. - */ - PhaseCombo_Interaction(int testProb); - //! Copy constructor /*! * @param b class to be copied diff --git a/include/cantera/thermo/PseudoBinaryVPSSTP.h b/include/cantera/thermo/PseudoBinaryVPSSTP.h deleted file mode 100644 index 631c64e0f..000000000 --- a/include/cantera/thermo/PseudoBinaryVPSSTP.h +++ /dev/null @@ -1,227 +0,0 @@ -/** - * @file PseudoBinaryVPSSTP.h - * Header for intermediate ThermoPhase object for phases which - * employ Gibbs excess free energy based formulations - * (see \ref thermoprops - * and class \link Cantera::PseudoBinaryVPSSTP PseudoBinaryVPSSTP\endlink). - * - * Header file for a derived class of ThermoPhase that handles - * variable pressure standard state methods for calculating - * thermodynamic properties that are further based upon activities - * based on the molality scale. These include most of the methods for - * calculating liquid electrolyte thermodynamics. - */ -/* - * Copyright (2006) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ -#ifndef CT_PSEUDOBINARYVPSSTP_H -#define CT_PSEUDOBINARYVPSSTP_H - -#include "GibbsExcessVPSSTP.h" - -namespace Cantera -{ -/** - * @ingroup thermoprops - */ - -/*! - * PseudoBinaryVPSSTP is a derived class of ThermoPhase - * GibbsExcessVPSSTP that handles - * variable pressure standard state methods for calculating - * thermodynamic properties that are further based on - * expressing the Excess Gibbs free energy as a function of - * the mole fractions (or pseudo mole fractions) of constituents. - * This category is the workhorse for describing molten salts, - * solid-phase mixtures of semiconductors, and mixtures of miscible - * and semi-miscible compounds. - * - * It includes - * - regular solutions - * - Margules expansions - * - NTRL equation - * - Wilson's equation - * - UNIQUAC equation of state. - * - * This class adds additional functions onto the ThermoPhase interface - * that handles the calculation of the excess Gibbs free energy. The ThermoPhase - * class includes a member function, ThermoPhase::activityConvention() - * that indicates which convention the activities are based on. The - * default is to assume activities are based on the molar convention. - * That default is used here. - * - * All of the Excess Gibbs free energy formulations in this area employ - * symmetrical formulations. - * - * This layer will massage the mole fraction vector to implement - * cation and anion based mole numbers in an optional manner - * - * The way that it collects the cation and anion based mole numbers - * is via holding two extra ThermoPhase objects. These - * can include standard states for salts. - * - * @deprecated Incomplete and untested. To be removed after Cantera 2.2. - */ -class PseudoBinaryVPSSTP : public GibbsExcessVPSSTP -{ -public: - /// Constructor - /*! - * This doesn't do much more than initialize constants with - * default values for water at 25C. Water molecular weight - * comes from the default elements.xml file. It actually - * differs slightly from the IAPWS95 value of 18.015268. However, - * density conservation and therefore element conservation - * is the more important principle to follow. - */ - PseudoBinaryVPSSTP(); - - //! Copy constructor - /*! - * @param b class to be copied - */ - PseudoBinaryVPSSTP(const PseudoBinaryVPSSTP& b); - - /// Assignment operator - /*! - * @param b class to be copied. - */ - PseudoBinaryVPSSTP& operator=(const PseudoBinaryVPSSTP& b); - - //! Duplication routine for objects which inherit from ThermoPhase. - /*! - * This virtual routine can be used to duplicate ThermoPhase objects - * inherited from ThermoPhase even if the application only has - * a pointer to ThermoPhase to work with. - */ - virtual ThermoPhase* duplMyselfAsThermoPhase() const; - - /** - * @name Activities, Standard States, and Activity Concentrations - * - * The activity \f$a_k\f$ of a species in solution is - * related to the chemical potential by \f[ \mu_k = \mu_k^0(T) - * + \hat R T \log a_k. \f] The quantity \f$\mu_k^0(T,P)\f$ is - * the chemical potential at unit activity, which depends only - * on temperature and pressure. - * @{ - */ - - /** - * The standard concentration \f$ C^0_k \f$ used to normalize - * the generalized concentration. In many cases, this quantity - * will be the same for all species in a phase - for example, - * for an ideal gas \f$ C^0_k = P/\hat R T \f$. For this - * reason, this method returns a single value, instead of an - * array. However, for phases in which the standard - * concentration is species-specific (e.g. surface species of - * different sizes), this method may be called with an - * optional parameter indicating the species. - * - * @param k species index. Defaults to zero. - */ - virtual doublereal standardConcentration(size_t k=0) const; - - //@} - /// @name Partial Molar Properties of the Solution - //@{ - - /** - * Get the species electrochemical potentials. - * These are partial molar quantities. - * This method adds a term \f$ Fz_k \phi_k \f$ to the - * to each chemical potential. - * - * Units: J/kmol - * - * @param mu output vector containing the species electrochemical potentials. - * Length: m_kk. - */ - void getElectrochemPotentials(doublereal* mu) const; - //@} - - //! Calculate pseudo binary mole fractions - virtual void calcPseudoBinaryMoleFractions() const; - - //@} - /// @name Initialization - /// The following methods are used in the process of constructing - /// the phase and setting its parameters from a specification in an - /// input file. They are not normally used in application programs. - /// To see how they are used, see importPhase(). - - /*! - * @internal Initialize. This method is provided to allow - * subclasses to perform any initialization required after all - * species have been added. For example, it might be used to - * resize internal work arrays that must have an entry for - * each species. The base class implementation does nothing, - * and subclasses that do not require initialization do not - * need to overload this method. When importing a CTML phase - * description, this method is called just prior to returning - * from function importPhase(). - */ - virtual void initThermo(); - - /** - * Import and initialize a ThermoPhase object - * - * @param phaseNode This object must be the phase node of a - * complete XML tree - * description of the phase, including all of the - * species data. In other words while "phase" must - * point to an XML phase object, it must have - * sibling nodes "speciesData" that describe - * the species in the phase. - * @param id ID of the phase. If nonnull, a check is done - * to see if phaseNode is pointing to the phase - * with the correct id. - */ - void initThermoXML(XML_Node& phaseNode, const std::string& id); - - virtual std::string report(bool show_thermo=true, - doublereal threshold=1e-14) const; - -private: - //! Initialize lengths of local variables after all species have - //! been identified. - void initLengths(); - -protected: - int PBType_; - - //! Number of pseudo binary species - size_t numPBSpecies_; - - //! index of special species - size_t indexSpecialSpecies_; - - mutable std::vector PBMoleFractions_; - - std::vector cationList_; - size_t numCationSpecies_; - - std::vectoranionList_; - size_t numAnionSpecies_; - - std::vector passThroughList_; - size_t numPassThroughSpecies_; - size_t neutralPBindexStart; - - ThermoPhase* cationPhase_; - - ThermoPhase* anionPhase_; - - mutable std::vector moleFractionsTmp_; -}; - -#define PBTYPE_PASSTHROUGH 0 -#define PBTYPE_SINGLEANION 1 -#define PBTYPE_SINGLECATION 2 -#define PBTYPE_MULTICATIONANION 3 - -} - -#endif diff --git a/include/cantera/thermo/RedlichKisterVPSSTP.h b/include/cantera/thermo/RedlichKisterVPSSTP.h index 521b009c3..8be2943b5 100644 --- a/include/cantera/thermo/RedlichKisterVPSSTP.h +++ b/include/cantera/thermo/RedlichKisterVPSSTP.h @@ -286,15 +286,6 @@ public: */ RedlichKisterVPSSTP(XML_Node& phaseRef, const std::string& id = ""); - //! Special constructor for a hard-coded problem - /*! - * @param testProb Hard-coded value. Only the value of 1 is used. It's - * for a LiKCl system -> test to predict the eutectic and - * liquidus correctly. - * @deprecated To be removed after Cantera 2.2. - */ - RedlichKisterVPSSTP(int testProb); - //! Copy constructor /*! * @param b class to be copied diff --git a/include/cantera/thermo/RedlichKwongMFTP.h b/include/cantera/thermo/RedlichKwongMFTP.h index eb8c898c5..92dfad7a5 100644 --- a/include/cantera/thermo/RedlichKwongMFTP.h +++ b/include/cantera/thermo/RedlichKwongMFTP.h @@ -52,19 +52,6 @@ public: */ RedlichKwongMFTP(XML_Node& phaseRef, const std::string& id = ""); - //! This is a special constructor, used to replicate test problems - //! during the initial verification of the object - /*! - * test problems: - * 1: Pure CO2 problem - * input file = CO2_RedlickKwongMFTP.xml - * - * @param testProb Hard -coded test problem to instantiate. - * Current valid values are 1. - * @deprecated To be removed after Cantera 2.2. - */ - RedlichKwongMFTP(int testProb); - //! Copy Constructor /*! * Copy constructor for the object. Constructed object will be a clone of this object, but will @@ -251,38 +238,6 @@ public: */ virtual doublereal standardConcentration(size_t k=0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units: - * - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, int sizeUA = 6) const; - //! Get the array of non-dimensional activity coefficients at //! the current solution temperature, pressure, and solution concentration. /*! diff --git a/include/cantera/thermo/StatMech.h b/include/cantera/thermo/StatMech.h deleted file mode 100644 index 8231bffb6..000000000 --- a/include/cantera/thermo/StatMech.h +++ /dev/null @@ -1,171 +0,0 @@ -/** - * @file StatMech.h - * Header for a single-species standard state object derived - * from - */ -/* - * Copyright(2006) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#ifndef CT_STATMECH_H -#define CT_STATMECH_H - -#include "cantera/base/global.h" -#include "SpeciesThermoInterpType.h" - -namespace Cantera -{ - -//! Statistical mechanics -/*! - * @ingroup spthermo - * @deprecated Incomplete stub class, to be removed after Cantera 2.2. - */ -class StatMech : public SpeciesThermoInterpType -{ - -public: - - //! Empty constructor - StatMech(); - - - //! constructor used in templated instantiations - /*! - * @param n Species index - * @param tlow Minimum temperature - * @param thigh Maximum temperature - * @param pref reference pressure (Pa). - * @param coeffs Vector of coefficients used to set the - * parameters for the standard state. - */ - StatMech(int n, doublereal tlow, doublereal thigh, doublereal pref, - const doublereal* coeffs, const std::string& my_name); - - //! copy constructor - /*! - * @param b object to be copied - */ - StatMech(const StatMech& b); - - //! assignment operator - /*! - * @param b object to be copied - */ - StatMech& operator=(const StatMech& b); - - //! duplicator - virtual SpeciesThermoInterpType* - duplMyselfAsSpeciesThermoInterpType() const; - - //! Returns an integer representing the type of parameterization - virtual int reportType() const; - //! Build a series of maps for the properties needed for species - int buildmap(); - - //! Update the properties for this species, given a temperature polynomial - /*! - * This method is called with a pointer to an array containing the - * functions of temperature needed by this parameterization, and three - * pointers to arrays where the computed property values should be - * written. This method updates only one value in each array. - * - * \f[ - * \frac{C_p^0(T)}{R} = \frac{C_v^0(T)}{R} + 1 - * \f] - * - * Where, - * \f[ - * \frac{C_v^0(T)}{R} = \frac{C_v^{tr}(T)}{R} + \frac{C_v^{vib}(T)}{R} - * \f] - * - * Temperature Polynomial: - * tt[0] = t; - * - * @param tt vector of temperature polynomials - * @param cp_R Vector of Dimensionless heat capacities. (length m_kk). - * @param h_RT Vector of Dimensionless enthalpies. (length m_kk). - * @param s_R Vector of Dimensionless entropies. (length m_kk). - */ - virtual void updateProperties(const doublereal* tt, - doublereal* cp_R, doublereal* h_RT, doublereal* s_R) const; - - - //! Compute the reference-state property of one species - /*! - * Given temperature T in K, this method updates the values of the non- - * dimensional heat capacity at constant pressure, enthalpy, and entropy, - * at the reference pressure, Pref of one of the species. The species - * index is used to reference into the cp_R, h_RT, and s_R arrays. - * - * @param temp Temperature (Kelvin) - * @param cp_R Vector of Dimensionless heat capacities. (length m_kk). - * @param h_RT Vector of Dimensionless enthalpies. (length m_kk). - * @param s_R Vector of Dimensionless entropies. (length m_kk). - */ - virtual void updatePropertiesTemp(const doublereal temp, - doublereal* cp_R, doublereal* h_RT, - doublereal* s_R) const; - - //! This utility function reports back the type of parameterization and - //! all of the parameters for the species, index. - /*! - * All parameters are output variables - * - * @param n Species index - * @param type Integer type of the standard type - * @param tlow output - Minimum temperature - * @param thigh output - Maximum temperature - * @param pref output - reference pressure (Pa). - * @param coeffs Vector of coefficients used to set the - * parameters for the standard state. There are - * 12 of them, designed to be compatible - * with the multiple temperature formulation. - * coeffs[0] is equal to one. - * coeffs[1] is min temperature - * coeffs[2] is max temperature - * coeffs[3+i] from i =0,9 are the coefficients themselves - */ - virtual void reportParameters(size_t& n, int& type, - doublereal& tlow, doublereal& thigh, - doublereal& pref, - doublereal* const coeffs) const; - - //! Modify parameters for the standard state - /*! - * @param coeffs Vector of coefficients used to set the - * parameters for the standard state. - */ - virtual void modifyParameters(doublereal* coeffs); - -protected: - //! array of polynomial coefficients - vector_fp m_coeff; - - std::string sp_name; - - //*generic species struct that contains everything we need here - // achtung: add doxygen markup here - // achtung: convert doubles to realdoubles - struct species { - //Nominal T-R Degrees of freedom (cv = cfs*k*T) - doublereal cfs; - - // Mol. Wt. Molecular weight (kg/kmol) - doublereal mol_weight; - - // number of vibrational temperatures necessary - int nvib; - - // Theta_v Characteristic vibrational temperature(s) (K) - doublereal theta[5]; - }; - - std::map name_map; - -}; - -} -#endif diff --git a/include/cantera/thermo/StoichSubstance.h b/include/cantera/thermo/StoichSubstance.h index fa529c4b4..315649f94 100644 --- a/include/cantera/thermo/StoichSubstance.h +++ b/include/cantera/thermo/StoichSubstance.h @@ -165,27 +165,6 @@ public: */ virtual void getStandardChemPotentials(doublereal* mu0) const; - /** - * Returns the units of the standard and generalized - * concentrations. Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * uA[0] = kmol units - default = 0 - * uA[1] = m units - default = 0 - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //@} /// @name Partial Molar Properties of the Solution //@{ diff --git a/include/cantera/thermo/StoichSubstanceSSTP.h b/include/cantera/thermo/StoichSubstanceSSTP.h index 471465967..7a6d73ac0 100644 --- a/include/cantera/thermo/StoichSubstanceSSTP.h +++ b/include/cantera/thermo/StoichSubstanceSSTP.h @@ -312,39 +312,6 @@ public: */ virtual void getStandardChemPotentials(doublereal* mu0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * @param uA Output vector containing the units - * - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(doublereal* uA, int k = 0, - int sizeUA = 6) const; - //@} /// @name Properties of the Standard State of the Species in the Solution //@{ diff --git a/include/cantera/thermo/ThermoPhase.h b/include/cantera/thermo/ThermoPhase.h index 165bcaea4..bed234592 100644 --- a/include/cantera/thermo/ThermoPhase.h +++ b/include/cantera/thermo/ThermoPhase.h @@ -253,16 +253,6 @@ public: throw NotImplementedError("ThermoPhase::cv_mole"); } - /** - * @returns species vibrational specific heat at - * constant volume. - * @deprecated To be removed after Cantera 2.2. - */ - /// Molar heat capacity at constant volume. Units: J/kmol/K. - virtual doublereal cv_vib(int, double) const { - throw NotImplementedError("ThermoPhase::cv_vib"); - } - //! @} //! @name Mechanical Properties //! @{ @@ -437,41 +427,6 @@ public: */ virtual doublereal logStandardConc(size_t k=0) const; - //! Returns the units of the standard and generalized concentrations. - /*! - * Note they have the same units, as their - * ratio is defined to be equal to the activity of the kth - * species in the solution, which is unitless. - * - * This routine is used in print out applications where the - * units are needed. Usually, MKS units are assumed throughout - * the program and in the XML input files. - * - * The base ThermoPhase class assigns the default quantities - * of (kmol/m3) for all species. - * Inherited classes are responsible for overriding the default - * values if necessary. - * - * On return uA contains the powers of the units (MKS assumed) - * of the standard concentrations and generalized concentrations - * for the kth species. - * - * @param uA Output vector containing the units - * uA[0] = kmol units - default = 1 - * uA[1] = m units - default = -nDim(), the number of spatial - * dimensions in the Phase class. - * uA[2] = kg units - default = 0; - * uA[3] = Pa(pressure) units - default = 0; - * uA[4] = Temperature units - default = 0; - * uA[5] = time units - default = 0 - * @param k species index. Defaults to 0. - * @param sizeUA output int containing the size of the vector. - * Currently, this is equal to 6. - * @deprecated To be removed after Cantera 2.2. - */ - virtual void getUnitsStandardConc(double* uA, int k = 0, - int sizeUA = 6) const; - //! Get the array of non-dimensional activities at //! the current solution temperature, pressure, and solution concentration. /*! diff --git a/include/cantera/thermo/speciesThermoTypes.h b/include/cantera/thermo/speciesThermoTypes.h index 9f7ebd88c..4b5ab5d4d 100644 --- a/include/cantera/thermo/speciesThermoTypes.h +++ b/include/cantera/thermo/speciesThermoTypes.h @@ -58,10 +58,6 @@ //! This is implemented in the class Nasa9PolyMultiTempRegion in Nasa9Poly1MultiTempRegion #define NASA9MULTITEMP 513 -//! Properties derived from theoretical considerations -//! This is implemented in the class statmech in StatMech.h -#define STAT 111 - //! Surface Adsorbate Model for a species on a surface. //! This is implemented in the class Adsorbate. #define ADSORBATE 1024 diff --git a/include/cantera/transport/AqueousTransport.h b/include/cantera/transport/AqueousTransport.h deleted file mode 100644 index 5a5c2dc31..000000000 --- a/include/cantera/transport/AqueousTransport.h +++ /dev/null @@ -1,567 +0,0 @@ -/** - * @file AqueousTransport.h - * Header file defining class AqueousTransport - */ -// Copyright 2001 California Institute of Technology - -#ifndef CT_AQUEOUSTRAN_H -#define CT_AQUEOUSTRAN_H - -// Cantera includes -#include "TransportBase.h" -#include "cantera/numerics/DenseMatrix.h" - -namespace Cantera -{ -//! Class AqueousTransport implements mixture-averaged transport -//! properties for brine phases. -/*! - * The model is based on that described by Newman, Electrochemical Systems - * - * The velocity of species i may be described by the - * following equation p. 297 (12.1) - * - * \f[ - * c_i \nabla \mu_i = R T \sum_j \frac{c_i c_j}{c_T D_{ij}} - * (\mathbf{v}_j - \mathbf{v}_i) - * \f] - * - * This as written is degenerate by 1 dof. - * - * To fix this we must add in the definition of the mass averaged - * velocity of the solution. We will call the simple bold-faced - * \f$\mathbf{v} \f$ - * symbol the mass-averaged velocity. Then, the relation - * between \f$\mathbf{v}\f$ and the individual species velocities is - * \f$\mathbf{v}_i\f$ - * - * \f[ - * \rho_i \mathbf{v}_i = \rho_i \mathbf{v} + \mathbf{j}_i - * \f] - * where \f$\mathbf{j}_i\f$ are the diffusional fluxes of species i - * with respect to the mass averaged velocity and - * - * \f[ - * \sum_i \mathbf{j}_i = 0 - * \f] - * - * and - * - * \f[ - * \sum_i \rho_i \mathbf{v}_i = \rho \mathbf{v} - * \f] - * - * Using these definitions, we can write - * - * \f[ - * \mathbf{v}_i = \mathbf{v} + \frac{\mathbf{j}_i}{\rho_i} - * \f] - * - * \f[ - * c_i \nabla \mu_i = R T \sum_j \frac{c_i c_j}{c_T D_{ij}} - * (\frac{\mathbf{j}_j}{\rho_j} - \frac{\mathbf{j}_i}{\rho_i}) - * = R T \sum_j \frac{1}{D_{ij}} - * (\frac{x_i \mathbf{j}_j}{M_j} - \frac{x_j \mathbf{j}_i}{M_i}) - * \f] - * - * The equations that we actually solve are - * - * \f[ - * c_i \nabla \mu_i = - * = R T \sum_j \frac{1}{D_{ij}} - * (\frac{x_i \mathbf{j}_j}{M_j} - \frac{x_j \mathbf{j}_i}{M_i}) - * \f] - * and we replace the 0th equation with the following: - * - * \f[ - * \sum_i \mathbf{j}_i = 0 - * \f] - * - * When there are charged species, we replace the RHS with the - * gradient of the electrochemical potential to obtain the - * modified equation - * - * \f[ - * c_i \nabla \mu_i + c_i F z_i \nabla \Phi - * = R T \sum_j \frac{1}{D_{ij}} - * (\frac{x_i \mathbf{j}_j}{M_j} - \frac{x_j \mathbf{j}_i}{M_i}) - * \f] - * - * With this formulation we may solve for the diffusion velocities, without - * having to worry about what the mass averaged velocity is. - * - *

Viscosity Calculation

- * - * The viscosity calculation may be broken down into two parts. - * In the first part, the viscosity of the pure species are calculated - * In the second part, a mixing rule is applied, based on the - * Wilkes correlation, to yield the mixture viscosity. - * @ingroup tranprops - * @deprecated Non-functional. To be removed after Cantera 2.2. - */ -class AqueousTransport : public Transport -{ -public: - AqueousTransport(); - - virtual int model() const { - return cAqueousTransport; - } - - //! Returns the viscosity of the solution - /*! - * The viscosity is computed using the Wilke mixture rule. - * \f[ - * \mu = \sum_k \frac{\mu_k X_k}{\sum_j \Phi_{k,j} X_j}. - * \f] - * Here \f$ \mu_k \f$ is the viscosity of pure species \e k, - * and - * \f[ - * \Phi_{k,j} = \frac{\left[1 - * + \sqrt{\left(\frac{\mu_k}{\mu_j}\sqrt{\frac{M_j}{M_k}}\right)}\right]^2} - * {\sqrt{8}\sqrt{1 + M_k/M_j}} - * \f] - * @see updateViscosity_T(); - * - * Controlling update boolean m_viscmix_ok - */ - virtual doublereal viscosity(); - - //! Returns the pure species viscosities - /*! - * Controlling update boolean = m_viscwt_ok - * - * @param visc Vector of species viscosities - */ - virtual void getSpeciesViscosities(doublereal* const visc); - - //! Return a vector of Thermal diffusion coefficients [kg/m/sec]. - /*! - * The thermal diffusion coefficient \f$ D^T_k \f$ is defined - * so that the diffusive mass flux of species k induced by the - * local temperature gradient is given by the following formula - * - * \f[ - * M_k J_k = -D^T_k \nabla \ln T. - * \f] - * - * The thermal diffusion coefficient can be either positive or negative. - * - * In this method we set it to zero. - * - * @param dt On return, dt will contain the species thermal - * diffusion coefficients. Dimension dt at least as large as - * the number of species. Units are kg/m/s. - */ - virtual void getThermalDiffCoeffs(doublereal* const dt); - - //! Return the thermal conductivity of the solution - /*! - * The thermal conductivity is computed from the following mixture rule: - * \f[ - * \lambda = 0.5 \left( \sum_k X_k \lambda_k - * + \frac{1}{\sum_k X_k/\lambda_k}\right) - * \f] - * - * Controlling update boolean = m_condmix_ok - */ - virtual doublereal thermalConductivity(); - - virtual void getBinaryDiffCoeffs(const size_t ld, doublereal* const d); - - //! Get the Mixture diffusion coefficients - /*! - * For the single species case or the pure fluid case the routine returns - * the self-diffusion coefficient. This is need to avoid a NaN result. - * @param d vector of mixture diffusion coefficients - * units = m2 s-1. length = number of species - */ - virtual void getMixDiffCoeffs(doublereal* const d); - - virtual void getMobilities(doublereal* const mobil_e); - - virtual void getFluidMobilities(doublereal* const mobil_f); - - //! Specify the value of the gradient of the voltage - /*! - * @param grad_V Gradient of the voltage (length num dimensions); - */ - virtual void set_Grad_V(const doublereal* const grad_V); - - //! Specify the value of the gradient of the temperature - /*! - * @param grad_T Gradient of the temperature (length num dimensions); - */ - virtual void set_Grad_T(const doublereal* const grad_T); - - //! Specify the value of the gradient of the MoleFractions - /*! - * @param grad_X Gradient of the mole fractions(length nsp * num dimensions); - */ - virtual void set_Grad_X(const doublereal* const grad_X); - - //! Handles the effects of changes in the Temperature, internally - //! within the object. - /*! - * This is called whenever a transport property is requested. The first - * task is to check whether the temperature has changed since the last - * call to update_T(). If it hasn't then an immediate return is carried - * out. - */ - virtual void update_T(); - - //! Handles the effects of changes in the mixture concentration - /*! - * This is called the first time any transport property is requested from - * Mixture after the concentrations have changed. - */ - virtual void update_C(); - - virtual void getSpeciesFluxes(size_t ndim, const doublereal* const grad_T, - size_t ldx, const doublereal* const grad_X, - size_t ldf, doublereal* const fluxes); - - //! Return the species diffusive mass fluxes wrt to the specified averaged velocity, - /*! - * This method acts similarly to getSpeciesFluxesES() but - * requires all gradients to be preset using methods set_Grad_X(), set_Grad_V(), set_Grad_T(). - * See the documentation of getSpeciesFluxesES() for details. - * - * units = kg/m2/s - * - * Internally, gradients in the in mole fraction, temperature - * and electrostatic potential contribute to the diffusive flux - * - * The diffusive mass flux of species \e k is computed from the following formula - * - * \f[ - * j_k = - \rho M_k D_k \nabla X_k - Y_k V_c - * \f] - * - * where V_c is the correction velocity - * - * \f[ - * V_c = - \sum_j {\rho M_j D_j \nabla X_j} - * \f] - * - * @param ldf Stride of the fluxes array. Must be equal to or greater than the number of species. - * @param fluxes Output of the diffusive fluxes. Flat vector with the m_nsp in the inner loop. - * length = ldx * ndim - */ - virtual void getSpeciesFluxesExt(size_t ldf, doublereal* const fluxes); - - //! Initialize the transport object - /*! - * Here we change all of the internal dimensions to be sufficient. - * We get the object ready to do property evaluations. - * - * @param tr Transport parameters for all of the species in the phase. - */ - virtual bool initLiquid(LiquidTransportParams& tr); - - friend class TransportFactory; - - /** - * Return a structure containing all of the pertinent parameters - * about a species that was used to construct the Transport - * properties in this object. - * - * @param k Species number to obtain the properties about. - */ - class LiquidTransportData getLiquidTransportData(int k); - - //! Solve the Stefan-Maxwell equations for the diffusive fluxes. - void stefan_maxwell_solve(); - -private: - //! Local Copy of the molecular weights of the species - /*! - * Length is Equal to the number of species in the mechanism. - */ - vector_fp m_mw; - - //! Polynomial coefficients of the viscosity - /*! - * These express the temperature dependence of the pure species viscosities. - */ - std::vector m_visccoeffs; - - //! Polynomial coefficients of the conductivities - /*! - * These express the temperature dependence of the pure species conductivities - */ - std::vector m_condcoeffs; - - //! Polynomial coefficients of the binary diffusion coefficients - /*! - * These express the temperature dependence of the binary diffusivities. - * An overall pressure dependence is then added. - */ - std::vector m_diffcoeffs; - - //! Internal value of the gradient of the mole fraction vector - /*! - * m_nsp is the number of species in the fluid - * k is the species index - * n is the dimensional index (x, y, or z). It has a length - * equal to m_nDim - * - * m_Grad_X[n*m_nsp + k] - */ - vector_fp m_Grad_X; - - //! Internal value of the gradient of the Temperature vector - /*! - * Generally, if a transport property needs this in its evaluation it - * will look to this place to get it. - * - * No internal property is precalculated based on gradients. Gradients - * are assumed to be freshly updated before every property call. - */ - vector_fp m_Grad_T; - - //! Internal value of the gradient of the Electric Voltage - /*! - * Generally, if a transport property needs this in its evaluation it - * will look to this place to get it. - * - * No internal property is precalculated based on gradients. Gradients - * are assumed to be freshly updated before every property call. - */ - vector_fp m_Grad_V; - - //! Gradient of the electrochemical potential - /*! - * m_nsp is the number of species in the fluid - * k is the species index - * n is the dimensional index (x, y, or z) - * - * m_Grad_mu[n*m_nsp + k] - */ - vector_fp m_Grad_mu; - - // property values - - //! Array of Binary Diffusivities - /*! - * This has a size equal to nsp x nsp - * It is a symmetric matrix. - * D_ii is undefined. - * - * units m2/sec - */ - DenseMatrix m_bdiff; - - //! Species viscosities - /*! - * Viscosity of the species - * Length = number of species - * - * Depends on the temperature and perhaps pressure, but - * not the species concentrations - * - * controlling update boolean -> m_spvisc_ok - */ - vector_fp m_visc; - - //! Sqrt of the species viscosities - /*! - * The sqrt(visc) is used in the mixing formulas - * Length = m_nsp - * - * Depends on the temperature and perhaps pressure, but - * not the species concentrations - * - * controlling update boolean m_spvisc_ok - */ - vector_fp m_sqvisc; - - //! Internal value of the species individual thermal conductivities - /*! - * Then a mixture rule is applied to get the solution conductivities - * - * Depends on the temperature and perhaps pressure, but - * not the species concentrations - * - * controlling update boolean -> m_spcond_ok - */ - vector_fp m_cond; - - //! Polynomials of the log of the temperature - vector_fp m_polytempvec; - - //! State of the mole fraction vector. - int m_iStateMF; - - //! Local copy of the mole fractions of the species in the phase - /*! - * Update info? - * length = m_nsp - */ - vector_fp m_molefracs; - - //! Local copy of the concentrations of the species in the phase - /*! - * Update info? - * length = m_nsp - */ - vector_fp m_concentrations; - - //! Local copy of the charge of each species - /*! - * Contains the charge of each species (length m_nsp) - */ - vector_fp m_chargeSpecies; - - //! Stefan-Maxwell Diffusion Coefficients at T, P and C - /*! - * These diffusion coefficients are considered to be - * a function of Temperature, Pressure, and Concentration. - */ - DenseMatrix m_DiffCoeff_StefMax; - - //! viscosity weighting functions - DenseMatrix m_phi; - - //! Matrix of the ratios of the species molecular weights - /*! - * m_wratjk(i,j) = (m_mw[j]/m_mw[k])**0.25 - */ - DenseMatrix m_wratjk; - - //! Matrix of the ratios of the species molecular weights - /*! - * m_wratkj1(i,j) = (1.0 + m_mw[k]/m_mw[j])**0.5 - */ - DenseMatrix m_wratkj1; - - //! RHS to the Stefan-Maxwell equation - Array2D m_B; - - //! Matrix for the Stefan-Maxwell equation. - DenseMatrix m_A; - - //! Internal storage for the species LJ well depth - vector_fp m_eps; - - //! Internal storage for species polarizability - vector_fp m_alpha; - - //! Current Temperature -> locally stored - /*! - * This is used to test whether new temperature computations - * should be performed. - */ - doublereal m_temp; - - //! Current log(T) - doublereal m_logt; - - //! Current value of kT - doublereal m_kbt; - - //! Current Temperature **0.5 - doublereal m_sqrt_t; - - //! Current Temperature **0.25 - doublereal m_t14; - - //! Current Temperature **1.5 - doublereal m_t32; - - //! Current temperature function - /*! - * This is equal to sqrt(Boltzmann * T) - */ - doublereal m_sqrt_kbt; - - //! Current value of the pressure - doublereal m_press; - - //! Solution of the flux system - Array2D m_flux; - - //! saved value of the mixture thermal conductivity - doublereal m_lambda; - - //! Saved value of the mixture viscosity - doublereal m_viscmix; - - //! work space of size m_nsp - vector_fp m_spwork; - - //! Update the temperature-dependent viscosity terms. - /*! - * Updates the array of pure species viscosities, and the weighting - * functions in the viscosity mixture rule. The flag m_visc_ok is set to - * true. - */ - void updateViscosity_T(); - - //! Update the temperature-dependent parts of the mixture-averaged - //! thermal conductivity. - void updateCond_T(); - - //! Update the species viscosities - /*! - * Internal routine is run whenever the update_boolean - * m_spvisc_ok is false. This routine will calculate - * internal values for the species viscosities. - */ - void updateSpeciesViscosities(); - - //! Update the binary diffusion coefficients wrt T. - /*! - * These are evaluated from the polynomial fits at unit pressure (1 Pa). - */ - void updateDiff_T(); - - //! Boolean indicating that mixture viscosity is current - bool m_viscmix_ok; - - //! Boolean indicating that weight factors wrt viscosity is current - bool m_viscwt_ok; - - //! Flag to indicate that the pure species viscosities - //! are current wrt the temperature - bool m_spvisc_ok; - - //! Boolean indicating that mixture diffusion coeffs are current - bool m_diffmix_ok; - - //! Boolean indicating that binary diffusion coeffs are current - bool m_bindiff_ok; - - //! Flag to indicate that the pure species conductivities - //! are current wrt the temperature - bool m_spcond_ok; - - //! Boolean indicating that mixture conductivity is current - bool m_condmix_ok; - - //! Mode for fitting the species viscosities - /*! - * Either it's CK_Mode or it's cantera mode - * in CK_Mode visc is fitted to a polynomial - * in Cantera mode sqrt(visc) is fitted. - */ - int m_mode; - - //! Internal storage for the diameter - diameter - //! species interactions - DenseMatrix m_diam; - - //! Debugging flags - /*! - * Turn on to get debugging information - */ - bool m_debug; - - //! Number of dimensions - /*! - * Either 1, 2, or 3 - */ - size_t m_nDim; -}; -} -#endif diff --git a/include/cantera/transport/TransportBase.h b/include/cantera/transport/TransportBase.h index d19505e6f..4f54bb0cb 100644 --- a/include/cantera/transport/TransportBase.h +++ b/include/cantera/transport/TransportBase.h @@ -48,7 +48,6 @@ const int cDustyGasTransport = 400; const int cUserTransport = 500; const int cFtnTransport = 600; const int cLiquidTransport = 700; -const int cAqueousTransport = 750; const int cSimpleTransport = 770; const int cRadiativeTransport = 800; const int cWaterTransport = 721; diff --git a/interfaces/cython/cantera/mixture.pyx b/interfaces/cython/cantera/mixture.pyx index 96537cdfd..6df0359de 100644 --- a/interfaces/cython/cantera/mixture.pyx +++ b/interfaces/cython/cantera/mixture.pyx @@ -315,18 +315,5 @@ cdef class Mixture: process. 0 indicates no output, while larger numbers produce successively more verbose information. """ - if isinstance(solver, int): - warnings.warn('Mixture.equilibrate: Using integer solver flags is ' - 'deprecated, and will be disabled after Cantera 2.2.') - if solver == -1: - solver = 'auto' - elif solver == 1: - solver = 'gibbs' - elif solver == 2: - solver = 'vcs' - else: - raise ValueError('Unrecognized equilibrium solver ' - 'specified: "{0}"'.format(solver)) - self.mix.equilibrate(stringify(XY.upper()), stringify(solver), rtol, max_steps, max_iter, estimate_equil, log_level) diff --git a/interfaces/cython/cantera/thermo.pyx b/interfaces/cython/cantera/thermo.pyx index d459345df..e379eb310 100644 --- a/interfaces/cython/cantera/thermo.pyx +++ b/interfaces/cython/cantera/thermo.pyx @@ -328,21 +328,6 @@ cdef class ThermoPhase(_SolutionBase): :param loglevel: Set to a value > 0 to write diagnostic output. """ - if isinstance(solver, int): - warnings.warn('ThermoPhase.equilibrate: Using integer solver ' - 'flags is deprecated, and will be disabled after Cantera 2.2.') - if solver == -1: - solver = 'auto' - elif solver == 0: - solver = 'element_potential' - elif solver == 1: - solver = 'gibbs' - elif solver == 2: - solver = 'vcs' - else: - raise ValueError('Invalid equilibrium solver specified: ' - '"{0}"'.format(solver)) - self.thermo.equilibrate(stringify(XY.upper()), stringify(solver), rtol, maxsteps, maxiter, estimate_equil, loglevel) diff --git a/src/base/application.cpp b/src/base/application.cpp index f90bff53b..7b8123392 100644 --- a/src/base/application.cpp +++ b/src/base/application.cpp @@ -123,12 +123,6 @@ void Application::Messages::setLogger(Logger* _logwriter) logwriter = _logwriter; } -void Application::Messages::logerror(const std::string& msg) -{ - Cantera::warn_deprecated("Application::Messages::logerror"); - logwriter->error(msg) ; -} - void Application::Messages::writelog(const std::string& msg) { logwriter->write(msg); diff --git a/src/base/application.h b/src/base/application.h index 1c46ec9be..9a2ac1524 100644 --- a/src/base/application.h +++ b/src/base/application.h @@ -134,20 +134,6 @@ protected: //! Write an end of line character to the screen and flush output void writelogendl(); - //! Write an error message and quit. - /*! - * The default behavior is to write to the standard error stream, and - * then call exit(). Note that no end-of-line character is appended - * to the message, and so if one is desired it must be included in - * the string. Note that this default behavior will terminate the - * application Cantera is invoked from (MATLAB, Excel, etc.) If this - * is not desired, then derive a class and reimplement this method. - * - * @param msg Error message to be written to cerr. - * @deprecated To be removed after Cantera 2.2 - */ - void logerror(const std::string& msg) ; - //! Install a logger. /*! * Called by the language interfaces to install an appropriate logger. @@ -333,11 +319,6 @@ public: pMessenger->writelogendl(); } - //! @copydoc Messages::logerror - void logerror(const std::string& msg) { - pMessenger->logerror(msg); - } - //! Print a warning indicating that *method* is deprecated. Additional //! information (removal version, alternatives) can be specified in //! *extra*. Deprecation warnings are printed once per method per diff --git a/src/base/ctml.cpp b/src/base/ctml.cpp index ab27c8e04..84a29c259 100644 --- a/src/base/ctml.cpp +++ b/src/base/ctml.cpp @@ -160,25 +160,6 @@ void getString(const XML_Node& node, const std::string& titleString, std::string } } -void getNamedStringValue(const XML_Node& node, const std::string& nameString, std::string& valueString, - std::string& typeString) -{ - warn_deprecated("getNamedStringValue", "To be removed after Cantera 2.2"); - valueString = ""; - typeString = ""; - if (node.hasChild(nameString)) { - XML_Node& xc = node.child(nameString); - valueString = xc.value(); - typeString = xc["type"]; - } else { - XML_Node* s = getByTitle(node, nameString); - if (s && s->name() == "string") { - valueString = s->value(); - typeString = s->attrib("type"); - } - } -} - void getIntegers(const XML_Node& node, std::map& v) { diff --git a/src/base/global.cpp b/src/base/global.cpp index e369e6674..ccdfb954e 100644 --- a/src/base/global.cpp +++ b/src/base/global.cpp @@ -69,12 +69,6 @@ void writeline(char repeat, size_t count, bool endl_after, bool endl_before) } } -void error(const std::string& msg) -{ - warn_deprecated("error", "To be removed after Cantera 2.2"); - app()->logerror(msg); -} - void warn_deprecated(const std::string& method, const std::string& extra) { app()->warn_deprecated(method, extra); diff --git a/src/base/stringUtils.cpp b/src/base/stringUtils.cpp index d462ecb10..ba4746fa1 100644 --- a/src/base/stringUtils.cpp +++ b/src/base/stringUtils.cpp @@ -164,69 +164,6 @@ compositionMap parseCompString(const std::string& ss, return x; } -void split(const std::string& ss, std::vector& w) -{ - warn_deprecated("split", "To be removed after Cantera 2.2."); - std::string s = ss; - std::string::size_type ibegin, iend; - std::string name, num, nm; - do { - ibegin = s.find_first_not_of(", ;\n\t"); - if (ibegin != std::string::npos) { - s = s.substr(ibegin,s.size()); - iend = s.find_first_of(", ;\n\t"); - if (iend != std::string::npos) { - w.push_back(s.substr(0, iend)); - s = s.substr(iend+1, s.size()); - } else { - w.push_back(s.substr(0, s.size())); - return; - } - } - } while (s != ""); -} - -int fillArrayFromString(const std::string& str, - doublereal* const a, const char delim) -{ - warn_deprecated("fillArrayFromString", "To be removed after Cantera 2.2."); - std::string::size_type iloc; - int count = 0; - std::string num; - std::string s = str; - while (s.size() > 0) { - iloc = s.find(delim); - if (iloc > 0) { - num = s.substr(0, iloc); - s = s.substr(iloc+1,s.size()); - } else { - num = s; - s = ""; - } - a[count] = fpValueCheck(num); - count++; - } - return count; -} - -std::string getBaseName(const std::string& path) -{ - warn_deprecated("getBaseName", "To be removed after Cantera 2.2."); - std::string file; - size_t idot = path.find_last_of('.'); - size_t islash = path.find_last_of('/'); - if (idot > 0 && idot < path.size()) { - if (islash > 0 && islash < idot) { - file = path.substr(islash+1, idot-islash-1); - } else { - file = path.substr(0,idot); - } - } else { - file = path; - } - return file; -} - int intValue(const std::string& val) { return std::atoi(stripws(val).c_str()); @@ -287,14 +224,6 @@ doublereal fpValueCheck(const std::string& val) return fpValue(str); } -std::string logfileName(const std::string& infile) -{ - warn_deprecated("logfileName", "To be removed after Cantera 2.2."); - std::string logfile = getBaseName(infile); - logfile += ".log"; - return logfile; -} - std::string wrapString(const std::string& s, const int len) { int count=0; diff --git a/src/clib/Cabinet.h b/src/clib/Cabinet.h index 328d31d02..c485109f3 100644 --- a/src/clib/Cabinet.h +++ b/src/clib/Cabinet.h @@ -97,26 +97,6 @@ public: } } - /** - * Assign one object (index j) to another (index i). This method - * is not used currently, and may be removed from the class in the - * future. - * @deprecated To be removed after Cantera 2.2 - */ - static int assign(int i, int j) { - Cantera::warn_deprecated("Cabinet::assign", - "To be removed after Cantera 2.2."); - dataRef data = getData(); - try { - M* src = data[j]; - M* dest = data[i]; - *dest = *src; - return 0; - } catch (...) { - return Cantera::handleAllExceptions(-1, -999); - } - } - /** * Delete all objects but the first. */ diff --git a/src/clib/ctfunc.cpp b/src/clib/ctfunc.cpp index 96f6fce91..4c6bf919b 100644 --- a/src/clib/ctfunc.cpp +++ b/src/clib/ctfunc.cpp @@ -122,15 +122,6 @@ extern "C" { } } - int func_assign(int i, int j) - { - try { - return FuncCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - double func_value(int i, double t) { try { diff --git a/src/clib/ctfunc.h b/src/clib/ctfunc.h index a3311eab8..f5c01f7ae 100644 --- a/src/clib/ctfunc.h +++ b/src/clib/ctfunc.h @@ -11,7 +11,6 @@ extern "C" { CANTERA_CAPI int func_del(int i); CANTERA_CAPI int func_clear(); CANTERA_CAPI int func_copy(int i); - CANTERA_CAPI int func_assign(int i, int j); CANTERA_CAPI double func_value(int i, double t); CANTERA_CAPI int func_derivative(int i); CANTERA_CAPI int func_duplicate(int i); diff --git a/src/clib/ctmultiphase.cpp b/src/clib/ctmultiphase.cpp index 27336200e..2ed40c12e 100644 --- a/src/clib/ctmultiphase.cpp +++ b/src/clib/ctmultiphase.cpp @@ -55,15 +55,6 @@ extern "C" { } } - int mix_assign(int i, int j) - { - try { - return mixCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - int mix_addPhase(int i, int j, double moles) { try { diff --git a/src/clib/ctmultiphase.h b/src/clib/ctmultiphase.h index d20c20c74..5698de8bd 100644 --- a/src/clib/ctmultiphase.h +++ b/src/clib/ctmultiphase.h @@ -11,7 +11,6 @@ extern "C" { CANTERA_CAPI int mix_del(int i); CANTERA_CAPI int mix_clear(); CANTERA_CAPI int mix_copy(int i); - CANTERA_CAPI int mix_assign(int i, int j); CANTERA_CAPI int mix_addPhase(int i, int j, double moles); CANTERA_CAPI int mix_init(int i); CANTERA_CAPI size_t mix_nElements(int i); diff --git a/src/clib/ctonedim.cpp b/src/clib/ctonedim.cpp index cabad8a55..c2c5f76fd 100644 --- a/src/clib/ctonedim.cpp +++ b/src/clib/ctonedim.cpp @@ -454,22 +454,6 @@ extern "C" { } } - - int stflow_solveSpeciesEqs(int i, int flag) - { - try { - if (flag > 0) { - DomainCabinet::get(i).solveSpecies(npos); - } else { - DomainCabinet::get(i).fixSpecies(npos); - } - return 0; - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - - int stflow_solveEnergyEqn(int i, int flag) { try { diff --git a/src/clib/ctonedim.h b/src/clib/ctonedim.h index 05630cb98..2d93c5143 100644 --- a/src/clib/ctonedim.h +++ b/src/clib/ctonedim.h @@ -57,7 +57,6 @@ extern "C" { CANTERA_CAPI double stflow_pressure(int i); CANTERA_CAPI int stflow_setFixedTempProfile(int i, size_t n, double* pos, size_t m, double* temp); - CANTERA_CAPI int stflow_solveSpeciesEqs(int i, int flag); CANTERA_CAPI int stflow_solveEnergyEqn(int i, int flag); CANTERA_CAPI int sim1D_clear(); diff --git a/src/clib/ctreactor.cpp b/src/clib/ctreactor.cpp index 8e4664c94..9c72d9967 100644 --- a/src/clib/ctreactor.cpp +++ b/src/clib/ctreactor.cpp @@ -62,15 +62,6 @@ extern "C" { } } - int reactor_assign(int i, int j) - { - try { - return ReactorCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - int reactor_setInitialVolume(int i, double v) { try { @@ -249,15 +240,6 @@ extern "C" { } } - int reactornet_assign(int i, int j) - { - try { - return NetworkCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - int reactornet_setInitialTime(int i, double t) { try { @@ -504,15 +486,6 @@ extern "C" { } } - int wall_assign(int i, int j) - { - try { - return WallCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - int wall_install(int i, int n, int m) { try { diff --git a/src/clib/ctreactor.h b/src/clib/ctreactor.h index 8a3a2c4f8..6b466e662 100644 --- a/src/clib/ctreactor.h +++ b/src/clib/ctreactor.h @@ -10,7 +10,6 @@ extern "C" { CANTERA_CAPI int reactor_new(int type); CANTERA_CAPI int reactor_del(int i); CANTERA_CAPI int reactor_copy(int i); - CANTERA_CAPI int reactor_assign(int i, int j); CANTERA_CAPI int reactor_setInitialVolume(int i, double v); CANTERA_CAPI int reactor_setEnergy(int i, int eflag); CANTERA_CAPI int reactor_setThermoMgr(int i, int n); @@ -30,7 +29,6 @@ extern "C" { CANTERA_CAPI int reactornet_new(); CANTERA_CAPI int reactornet_del(int i); CANTERA_CAPI int reactornet_copy(int i); - CANTERA_CAPI int reactornet_assign(int i, int j); CANTERA_CAPI int reactornet_setInitialTime(int i, double t); CANTERA_CAPI int reactornet_setMaxTimeStep(int i, double maxstep); CANTERA_CAPI int reactornet_setTolerances(int i, double rtol, double atol); @@ -56,7 +54,6 @@ extern "C" { CANTERA_CAPI int wall_new(int type); CANTERA_CAPI int wall_del(int i); CANTERA_CAPI int wall_copy(int i); - CANTERA_CAPI int wall_assign(int i, int j); CANTERA_CAPI int wall_install(int i, int n, int m); CANTERA_CAPI int wall_setkinetics(int i, int n, int m); CANTERA_CAPI double wall_vdot(int i, double t); diff --git a/src/clib/ctrpath.cpp b/src/clib/ctrpath.cpp index c20694224..dea5aee70 100644 --- a/src/clib/ctrpath.cpp +++ b/src/clib/ctrpath.cpp @@ -51,15 +51,6 @@ extern "C" { } } - int rdiag_assign(int i, int j) - { - try { - return DiagramCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - int rdiag_detailed(int i) { try { diff --git a/src/clib/ctxml.cpp b/src/clib/ctxml.cpp index 75219348f..3b2227fba 100644 --- a/src/clib/ctxml.cpp +++ b/src/clib/ctxml.cpp @@ -84,15 +84,6 @@ extern "C" { } } - int xml_assign(int i, int j) - { - try { - return XmlCabinet::assign(i,j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - int xml_build(int i, const char* file) { try { diff --git a/src/clib/ctxml.h b/src/clib/ctxml.h index 85b26f0e3..19779a92c 100644 --- a/src/clib/ctxml.h +++ b/src/clib/ctxml.h @@ -18,7 +18,6 @@ extern "C" { CANTERA_CAPI int xml_del(int i); CANTERA_CAPI int xml_clear(); CANTERA_CAPI int xml_copy(int i); - CANTERA_CAPI int xml_assign(int i, int j); CANTERA_CAPI int xml_build(int i, const char* file); CANTERA_CAPI int xml_preprocess_and_build(int i, const char* file, int debug); CANTERA_CAPI int xml_attrib(int i, const char* key, char* value); diff --git a/src/equil/MultiPhase.cpp b/src/equil/MultiPhase.cpp index 9b46b2ce2..8270ea5ab 100644 --- a/src/equil/MultiPhase.cpp +++ b/src/equil/MultiPhase.cpp @@ -558,15 +558,6 @@ doublereal MultiPhase::volume() const return sum; } -double MultiPhase::equilibrate(int XY, doublereal err, int maxsteps, - int maxiter, int loglevel) -{ - warn_deprecated("MultiPhase::equilibrate(int XY, ...)", - "Use MultiPhase::equilibrate(string XY, ...) instead. To be removed " - "after Cantera 2.2."); - return equilibrate_MultiPhaseEquil(XY, err, maxsteps, maxiter, loglevel); -} - double MultiPhase::equilibrate_MultiPhaseEquil(int XY, doublereal err, int maxsteps, int maxiter, int loglevel) diff --git a/src/equil/vcs_MultiPhaseEquil.cpp b/src/equil/vcs_MultiPhaseEquil.cpp index 3ef8da639..8751f76bf 100644 --- a/src/equil/vcs_MultiPhaseEquil.cpp +++ b/src/equil/vcs_MultiPhaseEquil.cpp @@ -868,10 +868,6 @@ int vcs_Cantera_to_vprob(MultiPhase* mphase, VCS_PROB* vprob) plogf("Unknown Cantera EOS to VCSnonideal: %d\n", eos); } VolPhase->m_eqnState = VCS_EOS_UNK_CANTERA; - if (!VolPhase->usingCanteraCalls()) { - throw CanteraError("vcs_Cantera_to_vprob", - "vcs functions asked for, but unimplemented"); - } break; } @@ -982,7 +978,6 @@ int vcs_Cantera_to_vprob(MultiPhase* mphase, VCS_PROB* vprob) * Transfer the thermo specification of the species * vprob->SpeciesThermo[] */ - ts_ptr->UseCanteraCalls = VolPhase->usingCanteraCalls(); ts_ptr->m_VCS_UnitsFormat = VolPhase->p_VCS_UnitsFormat; /* * Add lookback connectivity into the thermo object first @@ -1020,10 +1015,6 @@ int vcs_Cantera_to_vprob(MultiPhase* mphase, VCS_PROB* vprob) } ts_ptr->SS0_Model = VCS_SS0_NOTHANDLED; ts_ptr->SSStar_Model = VCS_SSSTAR_NOTHANDLED; - if (!(ts_ptr->UseCanteraCalls)) { - throw CanteraError("vcs_Cantera_to_vprob", - "Cantera calls not being used -> aborting"); - } } /* diff --git a/src/equil/vcs_VolPhase.cpp b/src/equil/vcs_VolPhase.cpp index 715b1e897..6b316a5e8 100644 --- a/src/equil/vcs_VolPhase.cpp +++ b/src/equil/vcs_VolPhase.cpp @@ -37,7 +37,6 @@ vcs_VolPhase::vcs_VolPhase(VCS_SOLVE* owningSolverObject) : m_existence(VCS_PHASE_EXIST_NO), m_MFStartIndex(0), IndSpecies(0), - m_useCanteraCalls(false), TP_ptr(0), v_totalMoles(0.0), m_phiVarIndex(npos), @@ -80,7 +79,6 @@ vcs_VolPhase::vcs_VolPhase(const vcs_VolPhase& b) : m_isIdealSoln(b.m_isIdealSoln), m_existence(b.m_existence), m_MFStartIndex(b.m_MFStartIndex), - m_useCanteraCalls(b.m_useCanteraCalls), TP_ptr(b.TP_ptr), v_totalMoles(b.v_totalMoles), creationMoleNumbers_(0), @@ -152,7 +150,6 @@ vcs_VolPhase& vcs_VolPhase::operator=(const vcs_VolPhase& b) ListSpeciesPtr[k] = new vcs_SpeciesProperties(*(b.ListSpeciesPtr[k])); } - m_useCanteraCalls = b.m_useCanteraCalls; /* * Do a shallow copy of the ThermoPhase object pointer. * We don't duplicate the object. @@ -302,12 +299,7 @@ void vcs_VolPhase::_updateActCoeff() const m_UpToDate_AC = true; return; } - if (m_useCanteraCalls) { - TP_ptr->getActivityCoefficients(VCS_DATA_PTR(ActCoeff)); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - } + TP_ptr->getActivityCoefficients(VCS_DATA_PTR(ActCoeff)); m_UpToDate_AC = true; } @@ -321,20 +313,7 @@ double vcs_VolPhase::AC_calc_one(size_t kspec) const void vcs_VolPhase::_updateG0() const { - if (m_useCanteraCalls) { - TP_ptr->getGibbs_ref(VCS_DATA_PTR(SS0ChemicalPotential)); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - double R = vcsUtil_gasConstant(p_VCS_UnitsFormat); - for (size_t k = 0; k < m_numSpecies; k++) { - size_t kglob = IndSpecies[k]; - vcs_SpeciesProperties* sProp = ListSpeciesPtr[k]; - VCS_SPECIES_THERMO* sTherm = sProp->SpeciesThermo; - SS0ChemicalPotential[k] = - R * (sTherm->G0_R_calc(kglob, Temp_)); - } - } + TP_ptr->getGibbs_ref(VCS_DATA_PTR(SS0ChemicalPotential)); m_UpToDate_G0 = true; } @@ -348,20 +327,7 @@ double vcs_VolPhase::G0_calc_one(size_t kspec) const void vcs_VolPhase::_updateGStar() const { - if (m_useCanteraCalls) { - TP_ptr->getStandardChemPotentials(VCS_DATA_PTR(StarChemicalPotential)); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - double R = vcsUtil_gasConstant(p_VCS_UnitsFormat); - for (size_t k = 0; k < m_numSpecies; k++) { - size_t kglob = IndSpecies[k]; - vcs_SpeciesProperties* sProp = ListSpeciesPtr[k]; - VCS_SPECIES_THERMO* sTherm = sProp->SpeciesThermo; - StarChemicalPotential[k] = - R * (sTherm->GStar_R_calc(kglob, Temp_, Pres_)); - } - } + TP_ptr->getStandardChemPotentials(VCS_DATA_PTR(StarChemicalPotential)); m_UpToDate_GStar = true; } @@ -392,13 +358,8 @@ void vcs_VolPhase::setMoleFractions(const double* const xmol) void vcs_VolPhase::_updateMoleFractionDependencies() { - if (m_useCanteraCalls) { - if (TP_ptr) { - TP_ptr->setState_PX(Pres_, &(Xmol_[m_MFStartIndex])); - } - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); + if (TP_ptr) { + TP_ptr->setState_PX(Pres_, &(Xmol_[m_MFStartIndex])); } if (!m_isIdealSoln) { m_UpToDate_AC = false; @@ -625,12 +586,7 @@ void vcs_VolPhase::sendToVCS_GStar(double* const gstar) const void vcs_VolPhase::setElectricPotential(const double phi) { m_phi = phi; - if (m_useCanteraCalls) { - TP_ptr->setElectricPotential(m_phi); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); -} + TP_ptr->setElectricPotential(m_phi); // We have changed the state variable. Set uptodate flags to false m_UpToDate_AC = false; m_UpToDate_VolStar = false; @@ -650,13 +606,8 @@ void vcs_VolPhase::setState_TP(const double temp, const double pres) return; } } - if (m_useCanteraCalls) { - TP_ptr->setElectricPotential(m_phi); - TP_ptr->setState_TP(temp, pres); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - } + TP_ptr->setElectricPotential(m_phi); + TP_ptr->setState_TP(temp, pres); Temp_ = temp; Pres_ = pres; m_UpToDate_AC = false; @@ -673,18 +624,7 @@ void vcs_VolPhase::setState_T(const double temp) void vcs_VolPhase::_updateVolStar() const { - if (m_useCanteraCalls) { - TP_ptr->getStandardVolumes(VCS_DATA_PTR(StarMolarVol)); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - for (size_t k = 0; k < m_numSpecies; k++) { - size_t kglob = IndSpecies[k]; - vcs_SpeciesProperties* sProp = ListSpeciesPtr[k]; - VCS_SPECIES_THERMO* sTherm = sProp->SpeciesThermo; - StarMolarVol[k] = (sTherm->VolStar_calc(kglob, Temp_, Pres_)); - } - } + TP_ptr->getStandardVolumes(VCS_DATA_PTR(StarMolarVol)); m_UpToDate_VolStar = true; } @@ -698,22 +638,7 @@ double vcs_VolPhase::VolStar_calc_one(size_t kspec) const double vcs_VolPhase::_updateVolPM() const { - if (m_useCanteraCalls) { - TP_ptr->getPartialMolarVolumes(VCS_DATA_PTR(PartialMolarVol)); - } else { - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - for (size_t k = 0; k < m_numSpecies; k++) { - size_t kglob = IndSpecies[k]; - vcs_SpeciesProperties* sProp = ListSpeciesPtr[k]; - VCS_SPECIES_THERMO* sTherm = sProp->SpeciesThermo; - StarMolarVol[k] = (sTherm->VolStar_calc(kglob, Temp_, Pres_)); - } - for (size_t k = 0; k < m_numSpecies; k++) { - PartialMolarVol[k] = StarMolarVol[k]; - } - } - + TP_ptr->getPartialMolarVolumes(VCS_DATA_PTR(PartialMolarVol)); m_totalVol = 0.0; for (size_t k = 0; k < m_numSpecies; k++) { m_totalVol += PartialMolarVol[k] * Xmol_[k]; @@ -834,54 +759,46 @@ void vcs_VolPhase::sendToVCS_LnActCoeffJac(Array2D& np_LnACJac_VCS) void vcs_VolPhase::setPtrThermoPhase(ThermoPhase* tp_ptr) { TP_ptr = tp_ptr; - if (TP_ptr) { - m_useCanteraCalls = true; - Temp_ = TP_ptr->temperature(); - Pres_ = TP_ptr->pressure(); - setState_TP(Temp_, Pres_); - p_VCS_UnitsFormat = VCS_UNITS_MKS; - m_phi = TP_ptr->electricPotential(); - size_t nsp = TP_ptr->nSpecies(); - size_t nelem = TP_ptr->nElements(); - if (nsp != m_numSpecies) { - if (m_numSpecies != 0) { - plogf("Warning Nsp != NVolSpeces: %d %d \n", nsp, m_numSpecies); - } - resize(VP_ID_, nsp, nelem, PhaseName.c_str()); + Temp_ = TP_ptr->temperature(); + Pres_ = TP_ptr->pressure(); + setState_TP(Temp_, Pres_); + p_VCS_UnitsFormat = VCS_UNITS_MKS; + m_phi = TP_ptr->electricPotential(); + size_t nsp = TP_ptr->nSpecies(); + size_t nelem = TP_ptr->nElements(); + if (nsp != m_numSpecies) { + if (m_numSpecies != 0) { + plogf("Warning Nsp != NVolSpeces: %d %d \n", nsp, m_numSpecies); } - TP_ptr->getMoleFractions(VCS_DATA_PTR(Xmol_)); - creationMoleNumbers_ = Xmol_; - _updateMoleFractionDependencies(); + resize(VP_ID_, nsp, nelem, PhaseName.c_str()); + } + TP_ptr->getMoleFractions(VCS_DATA_PTR(Xmol_)); + creationMoleNumbers_ = Xmol_; + _updateMoleFractionDependencies(); - /* - * figure out ideal solution tag - */ - if (nsp == 1) { - m_isIdealSoln = true; - } else { - int eos = TP_ptr->eosType(); - switch (eos) { - case cIdealGas: - case cIncompressible: - case cSurf: - case cMetal: - case cStoichSubstance: - case cSemiconductor: - case cLatticeSolid: - case cLattice: - case cEdge: - case cIdealSolidSolnPhase: - m_isIdealSoln = true; - break; - default: - m_isIdealSoln = false; - }; - } + /* + * figure out ideal solution tag + */ + if (nsp == 1) { + m_isIdealSoln = true; } else { - m_useCanteraCalls = false; - warn_deprecated("m_useCanteraCalls", "Setting this flag to 'false' is " - "deprecated and will not work after Cantera 2.2."); - + int eos = TP_ptr->eosType(); + switch (eos) { + case cIdealGas: + case cIncompressible: + case cSurf: + case cMetal: + case cStoichSubstance: + case cSemiconductor: + case cLatticeSolid: + case cLattice: + case cEdge: + case cIdealSolidSolnPhase: + m_isIdealSoln = true; + break; + default: + m_isIdealSoln = false; + }; } } @@ -990,11 +907,6 @@ bool vcs_VolPhase::isIdealSoln() const return m_isIdealSoln; } -bool vcs_VolPhase::usingCanteraCalls() const -{ - return m_useCanteraCalls; -} - size_t vcs_VolPhase::phiVarIndex() const { return m_phiVarIndex; diff --git a/src/equil/vcs_rank.cpp b/src/equil/vcs_rank.cpp deleted file mode 100644 index fdd14fde6..000000000 --- a/src/equil/vcs_rank.cpp +++ /dev/null @@ -1,289 +0,0 @@ -/*! - * @file vcs_rank.cpp - * Header file for the internal class that holds the problem. - */ - -/* - * Copyright (2005) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#include "cantera/equil/vcs_solve.h" -#include "cantera/base/ctexceptions.h" - -#include -using namespace std; - -namespace Cantera { - static int basisOptMax1(const double * const molNum, - const int n) { - // int largest = 0; - - for (int i = 0; i < n; ++i) { - - if (molNum[i] > -1.0E200 && fabs(molNum[i]) > 1.0E-13) { - return i; - } - } - for (int i = 0; i < n; ++i) { - - if (molNum[i] > -1.0E200) { - return i; - } - } - return n-1; - } - - int VCS_SOLVE::vcs_rank(const double * awtmp, size_t numSpecies, const double matrix[], size_t numElemConstraints, - std::vector &compRes, std::vector& elemComp, int * const usedZeroedSpecies) const - { - warn_deprecated("VCS_SOLVE::vcs_rank", "To be removed after Cantera 2.2"); - int lindep; - size_t j, k, jl, i, l, ml; - int numComponents = 0; - - compRes.clear(); - elemComp.clear(); - vector sm(numElemConstraints*numSpecies); - vector sa(numSpecies); - vector ss(numSpecies); - - double test = -0.2512345E298; - if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) { - plogf(" "); for(i=0; i<77; i++) plogf("-"); plogf("\n"); - plogf(" --- Subroutine vcs_rank called to "); - plogf("calculate the rank and independent rows /colums of the following matrix\n"); - if (m_debug_print_lvl >= 5) { - plogf(" --- Species | "); - for (j = 0; j < numElemConstraints; j++) { - plogf(" "); - plogf(" %3d ", j); - } - plogf("\n"); - plogf(" --- -----------"); - for (j = 0; j < numElemConstraints; j++) { - plogf("---------"); - } - plogf("\n"); - for (k = 0; k < numSpecies; k++) { - plogf(" --- "); - plogf(" %3d ", k); - plogf(" |"); - for (j = 0; j < numElemConstraints; j++) { - plogf(" %8.2g", matrix[j*numSpecies + k]); - } - plogf("\n"); - } - plogf(" ---"); - plogendl(); - } - } - /* - * Calculate the maximum value of the number of components possible - * It's equal to the minimum of the number of elements and the - * number of total species. - */ - int ncTrial = static_cast(std::min(numElemConstraints, numSpecies)); - numComponents = ncTrial; - *usedZeroedSpecies = false; - - /* - * Use a temporary work array for the mole numbers, aw[] - */ - std::vector aw(numSpecies); - for (j = 0; j < numSpecies; j++) { - aw[j] = awtmp[j]; - } - - int jr = -1; - /* - * Top of a loop of some sort based on the index JR. JR is the - * current number of component species found. - */ - do { - ++jr; - /* - Top of another loop point based on finding a linearly */ - /* - independent species */ - do { - /* - * Search the remaining part of the mole number vector, AW, - * for the largest remaining species. Return its identity in K. - * The first search criteria is always the largest positive - * magnitude of the mole number. - */ - k = basisOptMax1(VCS_DATA_PTR(aw), static_cast(numSpecies)); - - if ((aw[k] != test) && fabs(aw[k]) == 0.0) { - *usedZeroedSpecies = true; - } - - - if (aw[k] == test) { - numComponents = jr; - - goto L_CLEANUP; - } - /* - * Assign a small negative number to the component that we have - * just found, in order to take it out of further consideration. - */ - aw[k] = test; - /* *********************************************************** */ - /* **** CHECK LINEAR INDEPENDENCE WITH PREVIOUS SPECIES ****** */ - /* *********************************************************** */ - /* - * Modified Gram-Schmidt Method, p. 202 Dalquist - * QR factorization of a matrix without row pivoting. - */ - jl = jr; - for (j = 0; j < numElemConstraints; ++j) { - sm[j + jr*numElemConstraints] = matrix[j*numSpecies + k]; - } - if (jl > 0) { - /* - * Compute the coefficients of JA column of the - * the upper triangular R matrix, SS(J) = R_J_JR - * (this is slightly different than Dalquist) - * R_JA_JA = 1 - */ - for (j = 0; j < jl; ++j) { - ss[j] = 0.0; - for (i = 0; i < numElemConstraints; ++i) { - ss[j] += sm[i + jr* numElemConstraints] * sm[i + j* numElemConstraints]; - } - ss[j] /= sa[j]; - } - /* - * Now make the new column, (*,JR), orthogonal to the - * previous columns - */ - for (j = 0; j < jl; ++j) { - for (l = 0; l < numElemConstraints; ++l) { - sm[l + jr*numElemConstraints] -= ss[j] * sm[l + j*numElemConstraints]; - } - } - } - /* - * Find the new length of the new column in Q. - * It will be used in the denominator in future row calcs. - */ - sa[jr] = 0.0; - for (ml = 0; ml < numElemConstraints; ++ml) { - sa[jr] += pow(sm[ml + jr * numElemConstraints], 2); - } - /* **************************************************** */ - /* **** IF NORM OF NEW ROW .LT. 1E-3 REJECT ********** */ - /* **************************************************** */ - if (sa[jr] < 1.0e-6) lindep = true; - else lindep = false; - } while(lindep); - /* ****************************************** */ - /* **** REARRANGE THE DATA ****************** */ - /* ****************************************** */ - compRes.push_back(k); - elemComp.push_back(jr); - - } while (jr < (ncTrial-1)); - - L_CLEANUP: ; - - if (numComponents == ncTrial && numElemConstraints == numSpecies) { - return numComponents; - } - - - int numComponentsR = numComponents; - - ss.resize(numElemConstraints); - sa.resize(numElemConstraints); - - - elemComp.clear(); - - aw.resize(numElemConstraints); - for (j = 0; j < numSpecies; j++) { - aw[j] = 1.0; - } - - jr = -1; - - do { - ++jr; - - do { - - k = basisOptMax1(VCS_DATA_PTR(aw), static_cast(numElemConstraints)); - - if (aw[k] == test) { - numComponents = jr; - goto LE_CLEANUP; - } - aw[k] = test; - - - jl = jr; - for (j = 0; j < numSpecies; ++j) { - sm[j + jr*numSpecies] = matrix[k*numSpecies + j]; - } - if (jl > 0) { - - for (j = 0; j < jl; ++j) { - ss[j] = 0.0; - for (i = 0; i < numSpecies; ++i) { - ss[j] += sm[i + jr* numSpecies] * sm[i + j* numSpecies]; - } - ss[j] /= sa[j]; - } - - for (j = 0; j < jl; ++j) { - for (l = 0; l < numSpecies; ++l) { - sm[l + jr*numSpecies] -= ss[j] * sm[l + j*numSpecies]; - } - } - } - - sa[jr] = 0.0; - for (ml = 0; ml < numSpecies; ++ml) { - sa[jr] += pow(sm[ml + jr * numSpecies], 2); - } - - if (sa[jr] < 1.0e-6) lindep = true; - else lindep = false; - } while(lindep); - - elemComp.push_back(k); - - } while (jr < (ncTrial-1)); - numComponents = jr; - LE_CLEANUP: ; - - if (DEBUG_MODE_ENABLED && m_debug_print_lvl >= 2) { - plogf(" --- vcs_rank found rank %d\n", numComponents); - if (m_debug_print_lvl >= 5) { - if (compRes.size() == elemComp.size()) { - printf(" --- compRes elemComp\n"); - for (int i = 0; i < (int) compRes.size(); i++) { - printf(" --- %d %d \n", (int) compRes[i], (int) elemComp[i]); - } - } else { - for (int i = 0; i < (int) compRes.size(); i++) { - printf(" --- compRes[%d] = %d \n", (int) i, (int) compRes[i]); - } - for (int i = 0; i < (int) elemComp.size(); i++) { - printf(" --- elemComp[%d] = %d \n", (int) i, (int) elemComp[i]); - } - } - } - } - - if (numComponentsR != numComponents) { - printf("vcs_rank ERROR: number of components are different: %d %d\n", numComponentsR, numComponents); - throw CanteraError("vcs_rank ERROR:", - " logical inconsistency"); - exit(-1); - } - return numComponents; - } - -} diff --git a/src/equil/vcs_root1d.cpp b/src/equil/vcs_root1d.cpp deleted file mode 100644 index 63b641e02..000000000 --- a/src/equil/vcs_root1d.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/** - * @file vcs_root1d.cpp - * Code for a one dimensional root finder program. - */ -/* - * Copyright (2006) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#include "cantera/equil/vcs_internal.h" -#include "cantera/equil/vcs_defs.h" -#include "cantera/numerics/ctlapack.h" - -#include - -namespace Cantera -{ - -#define TOL_CONV 1.0E-5 - -static void print_funcEval(FILE* fp, double xval, double fval, int its) -{ - fprintf(fp,"\n"); - fprintf(fp,"...............................................................\n"); - fprintf(fp,".................. vcs_root1d Function Evaluation .............\n"); - fprintf(fp,".................. iteration = %5d ........................\n", its); - fprintf(fp,".................. value = %12.5g ......................\n", xval); - fprintf(fp,".................. funct = %12.5g ......................\n", fval); - fprintf(fp,"...............................................................\n"); - fprintf(fp,"\n"); -} - -int vcsUtil_root1d(double xmin, double xmax, size_t itmax, - VCS_FUNC_PTR func, void* fptrPassthrough, - double FuncTargVal, int varID, - double* xbest, int printLvl) -{ - warn_deprecated("vcsUtil_root1d", "To be removed after Cantera 2.2."); - static int callNum = 0; - const char* stre = "vcs_root1d ERROR: "; - const char* strw = "vcs_root1d WARNING: "; - bool converged = false; - int err = 0; - -#ifdef DEBUG_MODE - char fileName[80]; -#else - char* fileName; -#endif - FILE* fp = 0; - - double x1, x2, xnew, f1, f2, fnew, slope; - size_t its = 0; - int posStraddle = 0; - int retn = VCS_SUCCESS; - bool foundPosF = false; - bool foundNegF = false; - bool foundStraddle = false; - double xPosF = 0.0; - double xNegF = 0.0; - double fnorm; /* A valid norm for the making the function value - * dimensionless */ - double c[9], f[3], xn1, xn2, x0 = 0.0, f0 = 0.0, root, theta, xquad; - - callNum++; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - sprintf(fileName, "rootfd_%d.log", callNum); - fp = fopen(fileName, "w"); - fprintf(fp, " Iter TP_its xval Func_val | Reasoning\n"); - fprintf(fp, "-----------------------------------------------------" - "-------------------------------\n"); - } else if (printLvl >= 3) { - plogf("WARNING: vcsUtil_root1d: printlvl >= 3, but debug mode not turned on\n"); - } - if (xmax <= xmin) { - plogf("%sxmin and xmax are bad: %g %g\n", stre, xmin, xmax); - return VCS_PUB_BAD; - } - x1 = *xbest; - if (x1 < xmin || x1 > xmax) { - x1 = (xmin + xmax) / 2.0; - } - f1 = func(x1, FuncTargVal, varID, fptrPassthrough, &err); - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - print_funcEval(fp, x1, f1, static_cast(its)); - fprintf(fp, "%-5d %-5d %-15.5E %-15.5E\n", -2, 0, x1, f1); - } - if (f1 == 0.0) { - *xbest = x1; - return VCS_SUCCESS; - } else if (f1 > 0.0) { - foundPosF = true; - xPosF = x1; - } else { - foundNegF = true; - xNegF = x1; - } - x2 = x1 * 1.1; - if (x2 > xmax) { - x2 = x1 - (xmax - xmin) / 100.; - } - f2 = func(x2, FuncTargVal, varID, fptrPassthrough, &err); - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - print_funcEval(fp, x2, f2, static_cast(its)); - fprintf(fp, "%-5d %-5d %-15.5E %-15.5E", -1, 0, x2, f2); - } - - if (FuncTargVal != 0.0) { - fnorm = fabs(FuncTargVal) + 1.0E-13; - } else { - fnorm = 0.5*(fabs(f1) + fabs(f2)) + fabs(FuncTargVal); - } - - if (f2 == 0.0) { - return retn; - } else if (f2 > 0.0) { - if (!foundPosF) { - foundPosF = true; - xPosF = x2; - } - } else { - if (!foundNegF) { - foundNegF = true; - xNegF = x2; - } - } - foundStraddle = foundPosF && foundNegF; - if (foundStraddle) { - if (xPosF > xNegF) { - posStraddle = true; - } else { - posStraddle = false; - } - } - int ipiv[3]; - int info; - - do { - /* - * Find an estimate of the next point to try based on - * a linear approximation. - */ - slope = (f2 - f1) / (x2 - x1); - if (slope == 0.0) { - plogf("%s functions evals produced the same result, %g, at %g and %g\n", - strw, f2, x1, x2); - xnew = 2*x2 - x1 + 1.0E-3; - } else { - xnew = x2 - f2 / slope; - } - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | xlin = %-9.4g", xnew); - } - - /* - * Do a quadratic fit -> Note this algorithm seems - * to work OK. The quadratic approximation doesn't kick in until - * the end of the run, when it becomes reliable. - */ - if (its > 0) { - c[0] = 1.; - c[1] = 1.; - c[2] = 1.; - c[3] = x0; - c[4] = x1; - c[5] = x2; - c[6] = pow(x0, 2); - c[7] = pow(x1, 2); - c[8] = pow(x2, 2); - f[0] = f0; - f[1] = f1; - f[2] = f2; - - ct_dgetrf(3, 3, c, 3, ipiv, info); - if (info) { - goto QUAD_BAIL; - } - ct_dgetrs(ctlapack::NoTranspose, 3, 1, c, 3, ipiv, f, 3, info); - root = f[1]* f[1] - 4.0 * f[0] * f[2]; - if (root >= 0.0) { - xn1 = (- f[1] + sqrt(root)) / (2.0 * f[2]); - xn2 = (- f[1] - sqrt(root)) / (2.0 * f[2]); - if (fabs(xn2 - x2) < fabs(xn1 - x2) && xn2 > 0.0) { - xquad = xn2; - } else { - xquad = xn1; - } - theta = fabs(xquad - xnew) / fabs(xnew - x2); - theta = std::min(1.0, theta); - xnew = theta * xnew + (1.0 - theta) * xquad; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - if (theta != 1.0) { - fprintf(fp, " | xquad = %-9.4g", xnew); - } - } - } else { - /* - * Pick out situations where the convergence may be - * accelerated. - */ - if ((sign(xnew - x2) == sign(x2 - x1)) && - (sign(x2 - x1) == sign(x1 - x0))) { - xnew += xnew - x2; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | xquada = %-9.4g", xnew); - } - } - } - } -QUAD_BAIL: - ; - - - /* - * - * Put heuristic bounds on the step jump - */ - if ((xnew > x1 && xnew < x2) || (xnew < x1 && xnew > x2)) { - /* - * - * If we are doing a jump in between two points, make sure - * the new trial is between 10% and 90% of the distance - * between the old points. - */ - slope = fabs(x2 - x1) / 10.; - if (fabs(xnew - x1) < slope) { - xnew = x1 + sign(xnew-x1) * slope; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | x10%% = %-9.4g", xnew); - } - } - if (fabs(xnew - x2) < slope) { - xnew = x2 + sign(xnew-x2) * slope; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | x10%% = %-9.4g", xnew); - } - } - } else { - /* - * If we are venturing into new ground, only allow the step jump - * to increase by 100% at each iteration - */ - slope = 2.0 * fabs(x2 - x1); - if (fabs(slope) < fabs(xnew - x2)) { - xnew = x2 + sign(xnew-x2) * slope; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | xlimitsize = %-9.4g", xnew); - } - } - } - - - if (xnew > xmax) { - xnew = x2 + (xmax - x2) / 2.0; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | xlimitmax = %-9.4g", xnew); - } - } - if (xnew < xmin) { - xnew = x2 + (x2 - xmin) / 2.0; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | xlimitmin = %-9.4g", xnew); - } - } - if (foundStraddle) { -#ifdef DEBUG_MODE - slope = xnew; -#endif - if (posStraddle) { - if (f2 > 0.0) { - if (xnew > x2) { - xnew = (xNegF + x2)/2; - } - if (xnew < xNegF) { - xnew = (xNegF + x2)/2; - } - } else { - if (xnew < x2) { - xnew = (xPosF + x2)/2; - } - if (xnew > xPosF) { - xnew = (xPosF + x2)/2; - } - } - } else { - if (f2 > 0.0) { - if (xnew < x2) { - xnew = (xNegF + x2)/2; - } - if (xnew > xNegF) { - xnew = (xNegF + x2)/2; - } - } else { - if (xnew > x2) { - xnew = (xPosF + x2)/2; - } - if (xnew < xPosF) { - xnew = (xPosF + x2)/2; - } - } - } - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - if (slope != xnew) { - fprintf(fp, " | xstraddle = %-9.4g", xnew); - } - } - } - - fnew = func(xnew, FuncTargVal, varID, fptrPassthrough, &err); - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp,"\n"); - print_funcEval(fp, xnew, fnew, static_cast(its)); - fprintf(fp, "%-5d %-5d %-15.5E %-15.5E", (int) its, 0, xnew, fnew); - } - - if (foundStraddle) { - if (posStraddle) { - if (fnew > 0.0) { - if (xnew < xPosF) { - xPosF = xnew; - } - } else { - if (xnew > xNegF) { - xNegF = xnew; - } - } - } else { - if (fnew > 0.0) { - if (xnew > xPosF) { - xPosF = xnew; - } - } else { - if (xnew < xNegF) { - xNegF = xnew; - } - } - } - } - - if (! foundStraddle) { - if (fnew > 0.0) { - if (!foundPosF) { - foundPosF = true; - xPosF = xnew; - foundStraddle = true; - posStraddle = (xPosF > xNegF); - } - } else { - if (!foundNegF) { - foundNegF = true; - xNegF = xnew; - foundStraddle = true; - posStraddle = (xPosF > xNegF); - } - } - } - - x0 = x1; - f0 = f1; - x1 = x2; - f1 = f2; - x2 = xnew; - f2 = fnew; - if (fabs(fnew / fnorm) < 1.0E-5) { - converged = true; - } - its++; - } while (! converged && its < itmax); - if (converged) { - if (printLvl >= 1) { - plogf("vcs_root1d success: convergence achieved\n"); - } - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, " | vcs_root1d success in %d its, fnorm = %g\n", (int) its, fnorm); - } - } else { - retn = VCS_FAILED_CONVERGENCE; - if (printLvl >= 1) { - plogf("vcs_root1d ERROR: maximum iterations exceeded without convergence\n"); - } - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fprintf(fp, "\nvcs_root1d failure in %lu its\n", its); - } - } - *xbest = x2; - if (DEBUG_MODE_ENABLED && printLvl >= 3) { - fclose(fp); - } - return retn; -} - -} diff --git a/src/equil/vcs_species_thermo.cpp b/src/equil/vcs_species_thermo.cpp index 485637837..4229ab053 100644 --- a/src/equil/vcs_species_thermo.cpp +++ b/src/equil/vcs_species_thermo.cpp @@ -35,7 +35,6 @@ VCS_SPECIES_THERMO::VCS_SPECIES_THERMO(size_t indexPhase, SSStar_Model(VCS_SSSTAR_CONSTANT), SSStar_Vol_Model(VCS_SSVOL_IDEALGAS), SSStar_Vol0(-1.0), - UseCanteraCalls(false), m_VCS_UnitsFormat(VCS_UNITS_UNITLESS) { SS0_Pref = 1.01325E5; @@ -56,7 +55,6 @@ VCS_SPECIES_THERMO::VCS_SPECIES_THERMO(const VCS_SPECIES_THERMO& b) : SSStar_Model(b.SSStar_Model), SSStar_Vol_Model(b.SSStar_Vol_Model), SSStar_Vol0(b.SSStar_Vol0), - UseCanteraCalls(b.UseCanteraCalls), m_VCS_UnitsFormat(b.m_VCS_UnitsFormat) { } @@ -79,7 +77,6 @@ VCS_SPECIES_THERMO::operator=(const VCS_SPECIES_THERMO& b) SSStar_Model = b.SSStar_Model; SSStar_Vol_Model = b.SSStar_Vol_Model; SSStar_Vol0 = b.SSStar_Vol0; - UseCanteraCalls = b.UseCanteraCalls; m_VCS_UnitsFormat = b.m_VCS_UnitsFormat; } return *this; @@ -94,30 +91,15 @@ double VCS_SPECIES_THERMO::GStar_R_calc(size_t kglob, double TKelvin, double pres) { double fe = G0_R_calc(kglob, TKelvin); - double T = TKelvin; - if (UseCanteraCalls) { - if (m_VCS_UnitsFormat != VCS_UNITS_MKS) { - throw CanteraError("VCS_SPECIES_THERMO::GStar_R_calc", - "Possible inconsistency"); - } - size_t kspec = IndexSpeciesPhase; - OwningPhase->setState_TP(TKelvin, pres); - fe = OwningPhase->GStar_calc_one(kspec); - double R = vcsUtil_gasConstant(m_VCS_UnitsFormat); - fe /= R; - } else { - double pref = SS0_Pref; - switch (SSStar_Model) { - case VCS_SSSTAR_CONSTANT: - break; - case VCS_SSSTAR_IDEAL_GAS: - fe += T * log(pres/ pref); - break; - default: - throw CanteraError("VCS_SPECIES_THERMO::GStar_R_calc", - "unknown SSStar model"); - } + if (m_VCS_UnitsFormat != VCS_UNITS_MKS) { + throw CanteraError("VCS_SPECIES_THERMO::GStar_R_calc", + "Possible inconsistency"); } + size_t kspec = IndexSpeciesPhase; + OwningPhase->setState_TP(TKelvin, pres); + fe = OwningPhase->GStar_calc_one(kspec); + double R = vcsUtil_gasConstant(m_VCS_UnitsFormat); + fe /= R; return fe; } @@ -125,66 +107,33 @@ double VCS_SPECIES_THERMO::VolStar_calc(size_t kglob, double TKelvin, double presPA) { double vol; - - double T = TKelvin; - if (UseCanteraCalls) { - if (m_VCS_UnitsFormat != VCS_UNITS_MKS) { - throw CanteraError("VCS_SPECIES_THERMO::VolStar_calc", - "Possible inconsistency"); - } - size_t kspec = IndexSpeciesPhase; - OwningPhase->setState_TP(TKelvin, presPA); - vol = OwningPhase->VolStar_calc_one(kspec); - } else { - switch (SSStar_Vol_Model) { - case VCS_SSVOL_CONSTANT: - vol = SSStar_Vol0; - break; - case VCS_SSVOL_IDEALGAS: - vol= GasConstant * T / presPA; - break; - default: - throw CanteraError("VCS_SPECIES_THERMO::VolStar_calc", - "unknown SSVol model"); - } + if (m_VCS_UnitsFormat != VCS_UNITS_MKS) { + throw CanteraError("VCS_SPECIES_THERMO::VolStar_calc", + "Possible inconsistency"); } + size_t kspec = IndexSpeciesPhase; + OwningPhase->setState_TP(TKelvin, presPA); + vol = OwningPhase->VolStar_calc_one(kspec); return vol; } double VCS_SPECIES_THERMO::G0_R_calc(size_t kglob, double TKelvin) { - double fe, H, S; if (SS0_Model == VCS_SS0_CONSTANT) { return SS0_feSave; } if (TKelvin == SS0_TSave) { return SS0_feSave; } - if (UseCanteraCalls) { - if (m_VCS_UnitsFormat != VCS_UNITS_MKS) { - throw CanteraError("VCS_SPECIES_THERMO::G0_R_calc", - "Possible inconsistency"); - } - size_t kspec = IndexSpeciesPhase; - OwningPhase->setState_T(TKelvin); - fe = OwningPhase->G0_calc_one(kspec); - double R = vcsUtil_gasConstant(m_VCS_UnitsFormat); - fe /= R; - } else { - switch (SS0_Model) { - case VCS_SS0_CONSTANT: - fe = SS0_feSave; - break; - case VCS_SS0_CONSTANT_CP: - H = SS0_H0 + (TKelvin - SS0_T0) * SS0_Cp0; - S = SS0_Cp0 + SS0_Cp0 * log((TKelvin / SS0_T0)); - fe = H - TKelvin * S; - break; - default: - throw CanteraError("VCS_SPECIES_THERMO::G0_R_calc", - "unknown model"); - } + if (m_VCS_UnitsFormat != VCS_UNITS_MKS) { + throw CanteraError("VCS_SPECIES_THERMO::G0_R_calc", + "Possible inconsistency"); } + size_t kspec = IndexSpeciesPhase; + OwningPhase->setState_T(TKelvin); + double fe = OwningPhase->G0_calc_one(kspec); + double R = vcsUtil_gasConstant(m_VCS_UnitsFormat); + fe /= R; SS0_feSave = fe; SS0_TSave = TKelvin; return fe; @@ -192,19 +141,14 @@ double VCS_SPECIES_THERMO::G0_R_calc(size_t kglob, double TKelvin) double VCS_SPECIES_THERMO::eval_ac(size_t kglob) { - double ac; /* * Activity coefficients are frequently evaluated on a per phase * basis. If they are, then the currPhAC[] boolean may be used * to reduce repeated work. Just set currPhAC[iph], when the * activity coefficients for all species in the phase are reevaluated. */ - if (UseCanteraCalls) { - size_t kspec = IndexSpeciesPhase; - ac = OwningPhase->AC_calc_one(kspec); - } else { - ac = 1.0; - } + size_t kspec = IndexSpeciesPhase; + double ac = OwningPhase->AC_calc_one(kspec); return ac; } diff --git a/src/equil/vcs_util.cpp b/src/equil/vcs_util.cpp index 5ceb786a2..76b28d859 100644 --- a/src/equil/vcs_util.cpp +++ b/src/equil/vcs_util.cpp @@ -59,20 +59,6 @@ size_t vcs_optMax(const double* x, const double* xSize, size_t j, size_t n) return largest; } -int vcs_max_int(const int* vector, int length) -{ - warn_deprecated("vcs_max_int", "Unused. To be removed after Cantera 2.2."); - int retn; - if (vector == NULL || length <= 0) { - return 0; - } - retn = vector[0]; - for (int i = 1; i < length; i++) { - retn = std::max(retn, vector[i]); - } - return retn; -} - double vcsUtil_gasConstant(int mu_units) { switch (mu_units) { diff --git a/src/fortran/fctxml.cpp b/src/fortran/fctxml.cpp index f1b9dc362..89c9ccb10 100644 --- a/src/fortran/fctxml.cpp +++ b/src/fortran/fctxml.cpp @@ -97,15 +97,6 @@ extern "C" { } } - status_t fxml_assign_(const integer* i, const integer* j) - { - try { - return XmlCabinet::assign(*i,*j); - } catch (...) { - return handleAllExceptions(-1, ERR); - } - } - status_t fxml_attrib_(const integer* i, const char* key, char* value, ftnlen keylen, ftnlen valuelen) { diff --git a/src/fortran/fctxml_interface.f90 b/src/fortran/fctxml_interface.f90 index 5cf6230f6..7975d1f2a 100644 --- a/src/fortran/fctxml_interface.f90 +++ b/src/fortran/fctxml_interface.f90 @@ -24,11 +24,6 @@ interface integer, intent(in) :: i end function fxml_copy - integer function fxml_assign(i, j) - integer, intent(in) :: i - integer, intent(in) :: j - end function fxml_assign - integer function fxml_preprocess_and_build(i, file) integer, intent(in) :: i character*(*), intent(in) :: file diff --git a/src/kinetics/AqueousKinetics.cpp b/src/kinetics/AqueousKinetics.cpp index e7bcc99b1..ddc2df0e9 100644 --- a/src/kinetics/AqueousKinetics.cpp +++ b/src/kinetics/AqueousKinetics.cpp @@ -12,7 +12,6 @@ #include "cantera/kinetics/AqueousKinetics.h" #include "cantera/kinetics/Reaction.h" -#include "cantera/base/vec_functions.h" using namespace std; diff --git a/src/kinetics/ElectrodeKinetics.cpp b/src/kinetics/ElectrodeKinetics.cpp deleted file mode 100644 index ad463eaa1..000000000 --- a/src/kinetics/ElectrodeKinetics.cpp +++ /dev/null @@ -1,929 +0,0 @@ -/** - * @file ElectrodeKinetics.cpp - */ - -#include "cantera/kinetics/ElectrodeKinetics.h" -#include "cantera/thermo/SurfPhase.h" -#include "cantera/base/utilities.h" -#include "cantera/base/global.h" - -#include - -using namespace std; - -namespace Cantera -{ -//============================================================================================================================ -ElectrodeKinetics::ElectrodeKinetics(thermo_t* thermo) : - InterfaceKinetics(thermo), - metalPhaseIndex_(npos), - solnPhaseIndex_(npos), - kElectronIndex_(npos) -{ - warn_deprecated("class ElectrodeKinetics", - "To be removed after Cantera 2.2."); -} -//============================================================================================================================ -ElectrodeKinetics::~ElectrodeKinetics() -{ - for (size_t i = 0; i < rmcVector.size(); i++) { - delete rmcVector[i]; - } -} -//============================================================================================================================ -ElectrodeKinetics::ElectrodeKinetics(const ElectrodeKinetics& right) : - InterfaceKinetics() - -{ - /* - * Call the assignment operator - */ - ElectrodeKinetics::operator=(right); -} -//============================================================================================================================ -ElectrodeKinetics& ElectrodeKinetics::operator=(const ElectrodeKinetics& right) -{ - /* - * Check for self assignment. - */ - if (this == &right) { - return *this; - } - - InterfaceKinetics::operator=(right); - - metalPhaseIndex_ = right.metalPhaseIndex_; - solnPhaseIndex_ = right.solnPhaseIndex_; - kElectronIndex_ = right.kElectronIndex_; - - for (size_t i = 0; i < rmcVector.size(); i++) { - delete rmcVector[i]; - } - rmcVector.resize(m_ii, 0); - for (size_t i = 0; i < m_ii; i++) { - if (right.rmcVector[i]) { - rmcVector[i] = new RxnMolChange(*(right.rmcVector[i])); - } - } - - return *this; -} -//============================================================================================================================ -int ElectrodeKinetics::type() const -{ - return cInterfaceKinetics; -} -//============================================================================================================================ -Kinetics* ElectrodeKinetics::duplMyselfAsKinetics(const std::vector & tpVector) const -{ - ElectrodeKinetics* iK = new ElectrodeKinetics(*this); - iK->assignShallowPointers(tpVector); - return iK; -} -//============================================================================================================================ -// Identify the metal phase and the electron species -void ElectrodeKinetics::identifyMetalPhase() -{ - metalPhaseIndex_ = npos; - kElectronIndex_ = npos; - solnPhaseIndex_ = npos; - size_t np = nPhases(); - // - // Identify the metal phase as the phase with the electron species (element index of 1 for element E - // Should probably also stipulate a charge of -1. - // - for (size_t iph = 0; iph < np; iph++) { - ThermoPhase* tp = m_thermo[iph]; - size_t nSpecies = tp->nSpecies(); - size_t nElements = tp->nElements(); - size_t eElectron = tp->elementIndex("E"); - if (eElectron != npos) { - for (size_t k = 0; k < nSpecies; k++) { - if (tp->nAtoms(k,eElectron) == 1) { - int ifound = 1; - for (size_t e = 0; e < nElements; e++) { - if (tp->nAtoms(k,e) != 0.0) { - if (e != eElectron) { - ifound = 0; - } - } - } - if (ifound == 1) { - metalPhaseIndex_ = iph; - kElectronIndex_ = m_start[iph] + k; - } - } - } - } - // - // Identify the solution phase as a 3D phase, with nonzero phase charge change - // in at least one reaction - // - /* - * Haven't filled in reactions yet when this is called, unlike previous treatment. - if (iph != metalPhaseIndex_) { - for (size_t i = 0; i < m_ii; i++) { - RxnMolChange* rmc = rmcVector[i]; - if (rmc->m_phaseChargeChange[iph] != 0) { - if (rmc->m_phaseDims[iph] == 3) { - solnPhaseIndex_ = iph; - break; - } - } - } - } - */ - // - // New method is to find the first multispecies 3D phase with charged species as the solution phase - // - if (iph != metalPhaseIndex_) { - ThermoPhase& tp =*( m_thermo[iph]); - size_t nsp = tp.nSpecies(); - size_t nd = tp.nDim(); - if (nd == 3 && nsp > 1) { - for (size_t k = 0; k < nsp; k++) { - if (tp.charge(k) != 0.0) { - solnPhaseIndex_ = iph; - string ss = tp.name(); - // cout << "solution phase = "<< ss << endl; - break; - } - } - } - } - - } - // - // Right now, if we don't find an electron phase, we will not error exit. Some functions will - // be turned off and the object will behave as an InterfaceKinetics object. This is needed - // because downstream electrode objects have internal reaction surfaces that don't have - // electrons. - // - /* - if (metalPhaseIndex_ == npos) { - throw CanteraError("ElectrodeKinetics::identifyMetalPhase()", - "Can't find electron phase -> treating this as an error right now"); - } - if (solnPhaseIndex_ == npos) { - throw CanteraError("ElectrodeKinetics::identifyMetalPhase()", - "Can't find solution phase -> treating this as an error right now"); - } - */ -} -//============================================================================================================================ -// virtual from InterfaceKinetics -void ElectrodeKinetics::updateROP() -{ - // evaluate rate constants and equilibrium constants at temperature and phi (electric potential) - _update_rates_T(); - // get updated activities (rates updated below) - _update_rates_C(); - - double TT = m_surf->temperature(); - double rtdf = GasConstant * TT / Faraday; - - if (m_ROP_ok) { - return; - } - // - // Copy the reaction rate coefficients, m_rfn, into m_ropf - // - copy(m_rfn.begin(), m_rfn.end(), m_ropf.begin()); - // - // Multiply by the perturbation factor - // - multiply_each(m_ropf.begin(), m_ropf.end(), m_perturb.begin()); - // - // Copy the forward rate constants to the reverse rate constants - // - copy(m_ropf.begin(), m_ropf.end(), m_ropr.begin()); - - - // - // For reverse rates computed from thermochemistry, multiply - // the forward rates copied into m_ropr by the reciprocals of - // the equilibrium constants - // - multiply_each(m_ropr.begin(), m_ropr.end(), m_rkcn.begin()); - // - // multiply ropf by the activity concentration reaction orders to obtain - // the forward rates of progress. - // - m_reactantStoich.multiply(DATA_PTR(m_actConc), DATA_PTR(m_ropf)); - // - // For reversible reactions, multiply ropr by the activity concentration products - // - m_revProductStoich.multiply(DATA_PTR(m_actConc), DATA_PTR(m_ropr)); - // - // Fix up these calculations for cases where the above formalism doesn't hold - // - double OCV = 0.0; - for (size_t iBeta = 0; iBeta < m_beta.size(); iBeta++) { - size_t irxn = m_ctrxn[iBeta]; - - int reactionType = m_rxntype[irxn]; - if (reactionType == BUTLERVOLMER_RXN) { - // - // Get the beta value - // - double beta = m_beta[iBeta]; - // - // OK, the reaction rate constant contains the current density rate constant calculation - // the rxnstoich calculation contained the dependence of the current density on the activity concentrations - // We finish up with the ROP calculation - // - int iECDFormulation = m_ctrxn_ecdf[iBeta]; - if (iECDFormulation == 0) { - throw CanteraError(" ElectrodeKinetics::updateROP()", - "Straight kfwrd with BUTLERVOLMER_RXN not handled yet"); - } - // - // Get the phase mole change structure - // - RxnMolChange* rmc = rmcVector[irxn]; - // - // Calculate the stoichiometric eletrons for the reaction - // This is the number of electrons that are the net products of the reaction - // - AssertThrow(metalPhaseIndex_ != npos, "ElectrodeKinetics::updateROP()"); - - double nStoichElectrons = - rmc->m_phaseChargeChange[metalPhaseIndex_]; - // - // Calculate the open circuit voltage of the reaction - // - getDeltaGibbs(0); - if (nStoichElectrons != 0.0) { - OCV = m_deltaG[irxn]/Faraday/ nStoichElectrons; - } else { - OCV = 0.0; - } - // - // Calculate the voltage of the electrode. - // - double voltage = m_phi[metalPhaseIndex_] - m_phi[solnPhaseIndex_]; - // - // Calculate the overpotential - // - double nu = voltage - OCV; - - // - // Find the product of the standard concentrations for ROP orders that we used above - // - const RxnOrders* ro_rop = m_ctrxn_ROPOrdersList_[iBeta]; - if (ro_rop == 0) { - throw CanteraError("ElectrodeKinetics::", "ROP orders pointer is zero ?!?"); - } - double tmp2 = 1.0; - const std::vector& kinSpeciesIDs = ro_rop->kinSpeciesIDs_; - const std::vector& kinSpeciesOrders = ro_rop->kinSpeciesOrders_; - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - size_t k = kinSpeciesIDs[j]; - double oo = kinSpeciesOrders[j]; - tmp2 *= pow(m_StandardConc[k], oo); - } - // - // Now have to divide this to get rid of standard concentrations. We should - // have used just the activities in the m_rxnstoich.multiplyReactants(DATA_PTR(m_actConc), DATA_PTR(m_ropf)); - // calculation above! - // That is because the exchange current density rate constants have the correct units in the first place. - // - m_ropf[irxn] /= tmp2; - // - // Calculate the exchange current density - // m_ropf contains the exchange current reaction rate - // - double ioc = m_ropf[irxn] * nStoichElectrons; - // - // Add in the film resistance here - // - double resist = m_ctrxn_resistivity_[iBeta]; - double exp1 = nu * nStoichElectrons * beta / rtdf; - double exp2 = - nu * nStoichElectrons * (1.0 - beta) / (rtdf); - double io = ioc * (exp(exp1) - exp(exp2)); - - if (resist != 0.0) { - io = solveCurrentRes(nu, nStoichElectrons, ioc, beta, TT, resist, 0); - } - - m_ropnet[irxn] = io / (Faraday * nStoichElectrons); - // - // Need to resurrect the forwards rate of progress -> there is some need to - // calculate each direction individually - // - m_ropf[irxn] = calcForwardROP_BV(irxn, iBeta, ioc, nStoichElectrons, nu, io); - // - // Calculate the reverse rate of progress from the difference - // - m_ropr[irxn] = m_ropf[irxn] - m_ropnet[irxn]; - - } else if (reactionType == BUTLERVOLMER_NOACTIVITYCOEFFS_RXN) { - // - // Get the beta value - // - double beta = m_beta[iBeta]; - // - // OK, the reaction rate constant contains the current density rate constant calculation - // the rxnstoich calculation contained the dependence of the current density on the activity concentrations - // We finish up with the ROP calculation - // - int iECDFormulation = m_ctrxn_ecdf[iBeta]; - if (iECDFormulation == 0) { - throw CanteraError("ElectrodeKinetics::updateROP()", - "Straight kfwrd with BUTLERVOLMER_NOACTIVITYCOEFFS_RXN not handled yet"); - } - // - // Get the phase mole change structure - // - RxnMolChange* rmc = rmcVector[irxn]; - // - // Calculate the stoichiometric eletrons for the reaction - // This is the number of electrons that are the net products of the reaction - // - double nStoichElectrons = - rmc->m_phaseChargeChange[metalPhaseIndex_]; - // - // Calculate the open circuit voltage of the reaction - // - getDeltaGibbs(0); - if (nStoichElectrons != 0.0) { - OCV = m_deltaG[irxn]/Faraday/ nStoichElectrons; - } else { - OCV = 0.0; - } - - // - // Calculate the voltage of the electrode. - // - double voltage = m_phi[metalPhaseIndex_] - m_phi[solnPhaseIndex_]; - // - // Calculate the overpotential - // - double nu = voltage - OCV; - // - // Unfortunately, we really need to recalculate everything from almost scratch - // for this case, since it widely diverges from the thermo norm. - // - // Start with the exchange current reaction rate constant, which should - // be located in m_rfn[]. - // - double ioc = m_rfn[irxn] * nStoichElectrons * m_perturb[irxn]; - // - // Now we need th mole fraction vector and we need the RxnOrders vector. - // - const RxnOrders* ro_fwd = m_ctrxn_ROPOrdersList_[iBeta]; - if (ro_fwd == 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV()", "forward orders pointer is zero ?!?"); - } - double tmp = 1.0; - double mfS = 0.0; - const std::vector& kinSpeciesIDs = ro_fwd->kinSpeciesIDs_; - const std::vector& kinSpeciesOrders = ro_fwd->kinSpeciesOrders_; - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - size_t ks = kinSpeciesIDs[j]; - thermo_t& th = speciesPhase(ks); - size_t n = speciesPhaseIndex(ks); - size_t klocal = ks - m_start[n]; - mfS = th.moleFraction(klocal); - - double oo = kinSpeciesOrders[j]; - tmp *= pow(mfS, oo); - } - ioc *= tmp; - // - // Add in the film resistance here, later - // - double resist = m_ctrxn_resistivity_[iBeta]; - double exp1 = nu * nStoichElectrons * beta / rtdf; - double exp2 = - nu * nStoichElectrons * (1.0 - beta) / (rtdf); - double io = ioc * (exp(exp1) - exp(exp2)); - if (resist != 0.0) { - io = solveCurrentRes(nu, nStoichElectrons, ioc, beta, TT, resist, 0); - } - - m_ropnet[irxn] = io / (Faraday * nStoichElectrons); - // - // Need to resurrect the forwards rate of progress -> there is some need to - // calculate each direction individually - // - m_ropf[irxn] = calcForwardROP_BV_NoAct(irxn, iBeta, ioc, nStoichElectrons, nu, io); - // - // Calculate the reverse rate of progress from the difference - // - m_ropr[irxn] = m_ropf[irxn] - m_ropnet[irxn]; - } - - } - - - - for (size_t j = 0; j != m_ii; ++j) { - m_ropnet[j] = m_ropf[j] - m_ropr[j]; - } - - /* - * For reactions involving multiple phases, we must check that the phase - * being consumed actually exists. This is particularly important for - * phases that are stoichiometric phases containing one species with a unity activity - */ - if (m_phaseExistsCheck) { - for (size_t j = 0; j != m_ii; ++j) { - if ((m_ropr[j] > m_ropf[j]) && (m_ropr[j] > 0.0)) { - for (size_t p = 0; p < nPhases(); p++) { - if (m_rxnPhaseIsProduct[j][p]) { - if (! m_phaseExists[p]) { - m_ropnet[j] = 0.0; - m_ropr[j] = m_ropf[j]; - if (m_ropf[j] > 0.0) { - for (size_t rp = 0; rp < nPhases(); rp++) { - if (m_rxnPhaseIsReactant[j][rp]) { - if (! m_phaseExists[rp]) { - m_ropnet[j] = 0.0; - m_ropr[j] = m_ropf[j] = 0.0; - } - } - } - } - } - } - if (m_rxnPhaseIsReactant[j][p]) { - if (! m_phaseIsStable[p]) { - m_ropnet[j] = 0.0; - m_ropr[j] = m_ropf[j]; - } - } - } - } else if ((m_ropf[j] > m_ropr[j]) && (m_ropf[j] > 0.0)) { - for (size_t p = 0; p < nPhases(); p++) { - if (m_rxnPhaseIsReactant[j][p]) { - if (! m_phaseExists[p]) { - m_ropnet[j] = 0.0; - m_ropf[j] = m_ropr[j]; - if (m_ropf[j] > 0.0) { - for (size_t rp = 0; rp < nPhases(); rp++) { - if (m_rxnPhaseIsProduct[j][rp]) { - if (! m_phaseExists[rp]) { - m_ropnet[j] = 0.0; - m_ropf[j] = m_ropr[j] = 0.0; - } - } - } - } - } - } - if (m_rxnPhaseIsProduct[j][p]) { - if (! m_phaseIsStable[p]) { - m_ropnet[j] = 0.0; - m_ropf[j] = m_ropr[j]; - } - } - } - } - } - } - - m_ROP_ok = true; -} -//================================================================================================================== -// -// When the BV form is used we still need to go backwards to calculate the forward rate of progress. -// This routine does that -// -double ElectrodeKinetics::calcForwardROP_BV(size_t irxn, size_t iBeta, double ioc, double nStoich, double nu, doublereal ioNet) -{ - double ropf; - doublereal rt = GasConstant * thermo(0).temperature(); - // - // Calculate gather the exchange current reaction rate constant (where does n_s appear?) - // - doublereal beta = m_beta[iBeta]; - -#ifdef DEBUG_MODE - // - // Determine whether the reaction rate constant is in an exchange current density formulation format. - // - int iECDFormulation = m_ctrxn_ecdf[iBeta]; - - if (!iECDFormulation) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV", "not handled yet"); - } - // - // Calculate the forward chemical and modify the forward reaction rate coefficient - // - const RxnOrders* ro_fwd = m_ctrxn_FwdOrdersList_[iBeta]; - if (ro_fwd == 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV()", "forward orders pointer is zero ?!?"); - } - double tmp = exp(- m_beta[iBeta] * m_deltaG0[irxn] / rt); - double tmp2 = 1.0; - const std::vector& kinSpeciesIDs = ro_fwd->kinSpeciesIDs_; - const std::vector& kinSpeciesOrders = ro_fwd->kinSpeciesOrders_; - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - size_t k = kinSpeciesIDs[j]; - double oo = kinSpeciesOrders[j]; - tmp2 *= pow(m_StandardConc[k], oo); - } - - //double tmp2 = m_ProdStanConcReac[irxn]; - tmp *= 1.0 / tmp2 / Faraday; - // - // Calculate the chemical reaction rate constant - // - double iorc = m_rfn[irxn] * m_perturb[irxn]; - double kf = iorc * tmp; - // - // Calculate the electrochemical factor - // - double eamod = m_beta[iBeta] * deltaElectricEnergy_[irxn]; - kf *= exp(- eamod / rt); - // - // Calculate the forward rate of progress - // -> get the pointer for the orders - // - tmp = 1.0; - - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - size_t k = kinSpeciesIDs[j]; - double oo = kinSpeciesOrders[j]; - tmp *= pow(m_actConc[k], oo); - } - ropf = kf * tmp; -#endif - // - // Now calculate ropf in a separate but equivalent way. - // totally equivalent way if resistivity is zero, should be equal (HKM -> Proved exactly in one case) - // - double iof = ioc; - double resistivity = m_ctrxn_resistivity_[iBeta]; - if (fabs(resistivity * ioNet) > fabs(nu)) { - ioNet = nu / resistivity; - } - if (nStoich > 0.0) { - double exp1 = nStoich * Faraday * beta * (nu - resistivity * ioNet)/ (rt); - iof *= exp(exp1); - } else { -#ifdef DEBUG_MODE - if (ioc > 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV", "ioc should be less than zero here"); - } -#endif - double exp2 = -nu * nStoich * Faraday * (1.0 - beta) / (rt); - iof = ioc * ( - exp(exp2)); - } - ropf = iof / ( Faraday * nStoich); - - return ropf; -} -//================================================================================================================== -// -// When the BV form is used we still need to go backwards to calculate the forward rate of progress. -// This routine does that -// -double ElectrodeKinetics::calcForwardROP_BV_NoAct(size_t irxn, size_t iBeta, double ioc, double nStoich, double nu, - doublereal ioNet) -{ - doublereal TT = thermo(0).temperature(); - doublereal rt = GasConstant * TT; - //doublereal rrt = 1.0/rt; - doublereal beta = m_beta[iBeta]; - -/* - // - // Calculate gather the exchange current reaction rate constant (where does n_s appear?) - // - double iorc = m_rfn[irxn] * m_perturb[irxn]; - // - // Determine whether the reaction rate constant is in an exchange current density formulation format. - // - int iECDFormulation = m_ctrxn_ecdf[iBeta]; - - if (!iECDFormulation) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV_NoAct", "not handled yet"); - } - // - // Calculate the forward chemical and modify the forward reaction rate coefficient - // (we don't use standard concentrations at all here); - // - double tmp = exp(- m_beta[iBeta] * m_deltaG0[irxn] * rrt); - double tmp2 = 1.0; - tmp *= 1.0 / tmp2 / Faraday; - // - // Calculate the chemical reaction rate constant - // - double kf = iorc * tmp; - // - // Calculate the electrochemical factor - // - double eamod = m_beta[iBeta] * deltaElectricEnergy_[irxn]; - kf *= exp(- eamod * rrt); - // - // Calculate the forward rate of progress - // -> get the pointer for the orders - // - const RxnOrders* ro_fwd = m_ctrxn_FwdOrdersList_[iBeta]; - if (ro_fwd == 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV()", "forward orders pointer is zero ?!?"); - } - tmp = 1.0; - const std::vector& kinSpeciesIDs = ro_fwd->kinSpeciesIDs_; - const std::vector& kinSpeciesOrders = ro_fwd->kinSpeciesOrders_; - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - - size_t ks = kinSpeciesIDs[j]; - thermo_t& th = speciesPhase(ks); - size_t n = speciesPhaseIndex(ks); - size_t klocal = ks - m_start[n]; - double mfS = th.moleFraction(klocal); - double oo = kinSpeciesOrders[j]; - tmp *= pow(mfS, oo); - } - double ropf = kf * tmp; -*/ -/* - if (nStoich > 0) { - double ropf = ioc / ( Faraday * nStoich); - double exp1 = nu * nStoich * Faraday * beta / (rt); - ropf *= exp(exp1); - } else { - double ropf = ioc / ( Faraday * nStoich); - double exp1 = nu * nStoich * Faraday * beta / (rt); - ropf *= exp(exp1); - } -*/ - // - // With all of the thermo issues, I'm thinking this is the best we can do - // (it certainly maintains the forward and reverse rates of progress as being positive) - // - double iof = ioc; - double resistivity = m_ctrxn_resistivity_[iBeta]; - if (fabs(resistivity * ioNet) > fabs(nu)) { - ioNet = nu / resistivity; - } - if (nStoich > 0) { - double exp1 = nStoich * Faraday * beta * (nu - resistivity * ioNet)/ (rt); - iof *= exp(exp1); - } else { -#ifdef DEBUG_MODE - if (ioc > 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV_NoAct", "ioc should be less than zero here"); - } -#endif - double exp2 = -nu * nStoich * Faraday * (1.0 - beta) / (rt); - iof = ioc * ( - exp(exp2)); - } - double ropf = iof / ( Faraday * nStoich); - return ropf; -} -//================================================================================================================== -double ElectrodeKinetics::openCircuitVoltage(size_t irxn) -{ - // - // Calculate deltaG for all reactions - // - getDeltaGibbs(0); - // - // Look up the net number of electrons that are products. - // - RxnMolChange* rmc = rmcVector[irxn]; - double nStoichElectrons = - rmc->m_phaseChargeChange[metalPhaseIndex_]; - double OCV = 0.0; - if (nStoichElectrons != 0.0) { - OCV = m_deltaG[irxn] / Faraday / nStoichElectrons; - } - return OCV; -} -//================================================================================================================== -// -// Returns the local exchange current density formulation parameters -// -bool ElectrodeKinetics:: -getExchangeCurrentDensityFormulation(size_t irxn, - doublereal& nStoichElectrons, doublereal& OCV, doublereal& io, - doublereal& overPotential, doublereal& beta, - doublereal& resistivity) -{ - size_t iBeta = npos; - beta = 0.0; - // - // Add logic to handle other reaction types -> return 0 if formulation isn't compatible - // - - // evaluate rate constants and equilibrium constants at temperature and phi (electric potential) - _update_rates_T(); - // get updated activities (rates updated below) - _update_rates_C(); - - updateExchangeCurrentQuantities(); - - RxnMolChange* rmc = rmcVector[irxn]; - // could also get this from reactant and product stoichiometry, maybe - if (metalPhaseIndex_ == npos) { - nStoichElectrons = 0; - OCV = 0.0; - return false; - } else { - nStoichElectrons = - rmc->m_phaseChargeChange[metalPhaseIndex_]; - } - - - getDeltaGibbs(0); - - if (nStoichElectrons != 0.0) { - OCV = m_deltaG[irxn] / Faraday / nStoichElectrons; - } - - for (size_t i = 0; i < m_ctrxn.size(); i++) { - if (m_ctrxn[i] == irxn) { - iBeta = i; - break; - } - } - beta = m_beta[iBeta]; - - doublereal rt = GasConstant*thermo(0).temperature(); - - - double mG0 = m_deltaG0[irxn]; - int reactionType = m_rxntype[irxn]; - - // - // Start with the forward reaction rate - // - double iO = m_rfn[irxn] * m_perturb[irxn]; - int iECDFormulation = m_ctrxn_ecdf[iBeta]; - if (! iECDFormulation) { - iO = m_rfn[irxn] * Faraday * nStoichElectrons; - if (beta > 0.0) { - double fac = exp(mG0 / (rt)); - iO *= pow(fac, beta); - // Need this step because m_rfn includes the inverse of this term, while the formulas - // only use the chemical reaction rate constant. - fac = exp( beta * deltaElectricEnergy_[irxn] / (rt)); - iO *= fac; - } - } else { - iO *= nStoichElectrons; - } - - double omb = 1.0 - beta; - if (reactionType == BUTLERVOLMER_NOACTIVITYCOEFFS_RXN) { - const RxnOrders* ro_fwd = m_ctrxn_ROPOrdersList_[iBeta]; - if (ro_fwd == 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV()", "forward orders pointer is zero ?!?"); - } - double tmp = 1.0; - const std::vector& kinSpeciesIDs = ro_fwd->kinSpeciesIDs_; - const std::vector& kinSpeciesOrders = ro_fwd->kinSpeciesOrders_; - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - size_t ks = kinSpeciesIDs[j]; - thermo_t& th = speciesPhase(ks); - size_t n = speciesPhaseIndex(ks); - size_t klocal = ks - m_start[n]; - double mfS = th.moleFraction(klocal); - - double oo = kinSpeciesOrders[j]; - tmp *= pow(mfS, oo); - } - iO *= tmp; - } else if (reactionType == BUTLERVOLMER_RXN) { - const RxnOrders* ro_fwd = m_ctrxn_ROPOrdersList_[iBeta]; - if (ro_fwd == 0) { - throw CanteraError("ElectrodeKinetics::calcForwardROP_BV()", "forward orders pointer is zero ?!?"); - } - double tmp = 1.0; - const std::vector& kinSpeciesIDs = ro_fwd->kinSpeciesIDs_; - const std::vector& kinSpeciesOrders = ro_fwd->kinSpeciesOrders_; - for (size_t j = 0; j < kinSpeciesIDs.size(); j++) { - size_t ks = kinSpeciesIDs[j]; - - double oo = kinSpeciesOrders[j]; - tmp *= pow((m_actConc[ks]/m_StandardConc[ks]), oo); - } - iO *= tmp; - } else { - for (size_t k = 0; k < m_kk; k++) { - doublereal reactCoeff = reactantStoichCoeff(k, irxn); - doublereal prodCoeff = productStoichCoeff(k, irxn); - - if (reactCoeff != 0.0) { - iO *= pow(m_actConc[k], reactCoeff*omb); - iO *= pow(m_StandardConc[k], reactCoeff*beta); - } - if (prodCoeff != 0.0) { - iO *= pow(m_actConc[k], prodCoeff*beta); - iO /= pow(m_StandardConc[k], prodCoeff*omb); - } - } - } - io = iO; - resistivity = m_ctrxn_resistivity_[iBeta]; - - double phiMetal = m_thermo[metalPhaseIndex_]->electricPotential(); - double phiSoln = m_thermo[solnPhaseIndex_]->electricPotential(); - double E = phiMetal - phiSoln; - overPotential = E - OCV; - - return true; -} -//==================================================================================================================== -double ElectrodeKinetics::calcCurrentDensity(double nu, double nStoich, double ioc, double beta, double temp, - doublereal resistivity) const -{ - double exp1 = nu * nStoich * Faraday * beta / (GasConstant * temp); - double exp2 = -nu * nStoich * Faraday * (1.0 - beta) / (GasConstant * temp); - double val = ioc * (exp(exp1) - exp(exp2)); - if (resistivity > 0.0) { - val = solveCurrentRes(nu, nStoich, ioc, beta, temp, resistivity, 0); - } - return val; -} -//================================================================================================================== -void ElectrodeKinetics::init() -{ - InterfaceKinetics::init(); - identifyMetalPhase(); -} - -void ElectrodeKinetics::finalize() -{ - InterfaceKinetics::finalize(); - // Malloc and calculate all of the quantities that go into the extra description of reactions - rmcVector.resize(m_ii, 0); - for (size_t i = 0; i < m_ii; i++) { - rmcVector[i] = new RxnMolChange(this, static_cast(i)); - } -} - -//================================================================================================================== - -double ElectrodeKinetics::solveCurrentRes(double nu, double nStoich, doublereal ioc, doublereal beta, doublereal temp, - doublereal resistivity, int iprob) const -{ - // int nits = 0; - doublereal f, dfdi, deltai, eexp1, eexp2, exp1, exp2, icurr, deltai_damp; - doublereal nFRT = nStoich * Faraday / (GasConstant * temp); - if (iprob == 0) { - eexp1 = exp(nu * nFRT * beta); - eexp2 = exp(-nu * nFRT * (1.0 - beta)) ; - - } else { - eexp1 = exp(nu * nFRT * beta); - eexp2 = 0.0; - } - icurr = ioc * (eexp1 - eexp2); - double icurrDamp = icurr; - if (fabs(resistivity * icurr) > 0.9 * fabs(nu)) { - icurrDamp = 0.9 * nu / resistivity; - } - if (iprob == 0) { - eexp1 = exp( nFRT * beta * (nu - resistivity * icurrDamp)); - eexp2 = exp(- nFRT * (1.0 - beta) * (nu - resistivity * icurrDamp)); - } else { - eexp1 = exp( nFRT * beta * (nu - resistivity * icurrDamp)); - eexp2 = 0.0; - } - icurr = ioc * (eexp1 - eexp2); - if (fabs(resistivity * icurr) > 0.99 * fabs(nu)) { - icurr = 0.99 * nu / resistivity; - } - - do { - // nits++; - if (iprob == 0) { - exp1 = nFRT * beta * (nu - resistivity * icurr); - exp2 = - nFRT * (1.0 - beta) * (nu - resistivity * icurr); - eexp1 = exp(exp1); - eexp2 = exp(exp2); - f = icurr - ioc * (eexp1 - eexp2); - dfdi = 1.0 - ioc * eexp1 * ( - beta * nFRT * resistivity ) + - ioc * eexp2 * ( (1.0 - beta) * nFRT * resistivity ); - } else { - exp1 = nFRT * beta * (nu - resistivity * icurr); - eexp1 = exp(exp1); - f = icurr - ioc * (eexp1); - dfdi = 1.0 - ioc * eexp1 * ( - beta * nFRT * resistivity ); - } - deltai = - f / dfdi; - if (fabs(deltai) > 0.1 * fabs(icurr)) { - deltai_damp = 0.1 * deltai; - if (fabs(deltai_damp) > 0.1 * fabs(icurr)) { - deltai_damp = 0.1 * icurr * (deltai_damp / fabs(deltai_damp)); - } - } else if (fabs(deltai) > 0.01 * fabs(icurr)) { - deltai_damp = 0.3 * deltai; - } else if (fabs(deltai) > 0.001 * fabs(icurr)) { - deltai_damp = 0.5 * deltai; - } else { - deltai_damp = deltai; - } - icurr += deltai_damp; - if (fabs(resistivity * icurr) > fabs(nu)) { - icurr = 0.999 * nu / resistivity; - } - - } while((fabs(deltai/icurr)> 1.0E-14) && (fabs(deltai) > 1.0E-20)); - - // printf(" its = %d\n", nits); - - return icurr; -} -//================================================================================================================== -} diff --git a/src/kinetics/ExtraGlobalRxn.cpp b/src/kinetics/ExtraGlobalRxn.cpp deleted file mode 100644 index 4a842909c..000000000 --- a/src/kinetics/ExtraGlobalRxn.cpp +++ /dev/null @@ -1,391 +0,0 @@ -/** - * @file example2.cpp - * - */ -/* - * $Id: ExtraGlobalRxn.cpp 571 2013-03-26 16:44:21Z hkmoffa $ - * - */ - -/* - * Copyright (2005) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -// Example 2 -// -// Read a mechanism, and print to the standard output stream a -// well-formatted Chemkin ELEMENT section. -// - -#include "cantera/kinetics/ExtraGlobalRxn.h" - - - -#include "cantera/numerics/DenseMatrix.h" - -// Kinetics includes -#include "cantera/kinetics.h" -#include "cantera/kinetics/InterfaceKinetics.h" -#include "cantera/thermo/SurfPhase.h" -#include "cantera/kinetics/KineticsFactory.h" - -#include -#include -#include -#include -#include - - - -using namespace std; - -namespace Cantera { - -//============================================================================================================ -static void erase_vd(std::vector& m_vec, int index) -{ - std::vector::iterator ipos; - ipos = m_vec.begin(); - ipos += index; - m_vec.erase(ipos); -} -//============================================================================================================ -static void erase_vi(std::vector& m_vec, int index) -{ - std::vector::iterator ipos; - ipos = m_vec.begin(); - ipos += index; - m_vec.erase(ipos); -} -//============================================================================================================ -//! add the species into the list of products or reactants -/*! - * Note this function gets called for both the product and reactant sides. However, it's only - * called for one side or another. - * - * @param kkinspec kinetic species index of the product - * @param - */ -static void addV(int kkinspec, double ps, std::vector& m_Products, - std::vector& m_ProductStoich) -{ - int nsize = static_cast(m_Products.size()); - for (int i = 0; i < nsize; i++) { - if (m_Products[i] == kkinspec) { - m_ProductStoich[i] += ps; - return; - } - } - m_Products.push_back(kkinspec); - m_ProductStoich.push_back(ps); -} -//============================================================================================================ -ExtraGlobalRxn::ExtraGlobalRxn(Kinetics* k_ptr) : - m_ThisIsASurfaceRxn(false), - m_kinetics(k_ptr), - m_InterfaceKinetics(0), - m_nKinSpecies(0), - m_nReactants(0), - m_nProducts(0), - m_nNetSpecies(0), - m_nRxns(0), - m_SpecialSpecies(-1), - m_SpecialSpeciesProduct(true), - iphaseKin(0), - m_ok(false), - m_reversible(true) -{ - warn_deprecated("class ExtraGlobalRxn", - "Unfinished implementation to be removed after Cantera 2.2."); - m_InterfaceKinetics = dynamic_cast(k_ptr); - if (m_InterfaceKinetics) { - m_ThisIsASurfaceRxn = true; - } - m_nRxns = static_cast(m_kinetics->nReactions()); - m_ElemRxnVector.resize(m_nRxns,0.0); - m_nKinSpecies = static_cast(m_kinetics->nTotalSpecies()); -} -//============================================================================================================ -void ExtraGlobalRxn::setupElemRxnVector(double* RxnVector, - int specialSpecies) -{ - int i; - int kkinspec; - for (size_t i = 0; i < (size_t) m_nRxns; i++) { - m_ElemRxnVector[i] = RxnVector[i]; - } - for (size_t i = 0; i < (size_t) m_nRxns; i++) { - if (RxnVector[i] > 0.0) { - for (kkinspec = 0; kkinspec < m_nKinSpecies; kkinspec++) { - double ps = m_kinetics->productStoichCoeff(kkinspec, i); - if (ps > 0.0) { - addV(kkinspec, RxnVector[i]* ps, m_Products, m_ProductStoich); - addV(kkinspec, RxnVector[i]* ps, m_NetSpecies, m_netStoich); - } - double rs = m_kinetics->reactantStoichCoeff(kkinspec, i); - if (rs > 0.0) { - addV(kkinspec, RxnVector[i] * rs, m_Reactants, m_ReactantStoich); - addV(kkinspec, -RxnVector[i] * rs, m_NetSpecies, m_netStoich); - } - } - } else if (RxnVector[i] < 0.0) { - for (kkinspec = 0; kkinspec < m_nKinSpecies; kkinspec++) { - double ps = m_kinetics->productStoichCoeff(kkinspec, i); - if (ps > 0.0) { - addV(kkinspec,- RxnVector[i]* ps, m_Reactants, m_ReactantStoich); - addV(kkinspec, RxnVector[i]* ps, m_NetSpecies, m_netStoich); - } - double rs = m_kinetics->reactantStoichCoeff(kkinspec, i); - if (rs > 0.0) { - addV(kkinspec, -RxnVector[i] * rs, m_Products, m_ProductStoich); - addV(kkinspec, -RxnVector[i] * rs, m_NetSpecies, m_netStoich); - } - } - } - } -Recheck: - for (i = 0; i < static_cast(m_Products.size()); i++) { - if (m_ProductStoich[i] == 0.0) { - erase_vi(m_Products, i); - erase_vd(m_ProductStoich, i); - goto Recheck ; - } - } - for (i = 0; i < static_cast(m_Reactants.size()); i++) { - if (m_ReactantStoich[i] == 0.0) { - erase_vi(m_Reactants, i); - erase_vd(m_ReactantStoich, i); - goto Recheck ; - } - } - for (i = 0; i < static_cast(m_NetSpecies.size()); i++) { - if (m_netStoich[i] == 0.0) { - erase_vi(m_NetSpecies, i); - erase_vd(m_netStoich, i); - goto Recheck ; - } - } - - for (i = 0; i < static_cast(m_Products.size()); i++) { - int ik = m_Products[i]; - for (int j = 0; j < static_cast(m_Reactants.size()); j++) { - int jk = m_Reactants[j]; - if (ik == jk) { - if (m_ProductStoich[i] == m_ReactantStoich[j]) { - erase_vi(m_Products, i); - erase_vd(m_ProductStoich, i); - erase_vi(m_Reactants, j); - erase_vd(m_ReactantStoich, j); - } else if (m_ProductStoich[i] > m_ReactantStoich[j]) { - m_ProductStoich[i] -= m_ReactantStoich[j]; - erase_vi(m_Reactants, j); - erase_vd(m_ReactantStoich, j); - } else { - m_ReactantStoich[j] -= m_ProductStoich[i]; - erase_vi(m_Products, i); - erase_vd(m_ProductStoich, i); - } - // We just screwed up the indexing -> restart. - goto Recheck ; - } - - } - } - m_nProducts = static_cast(m_Products.size()); - m_nReactants = static_cast(m_Reactants.size()); - m_nNetSpecies = static_cast(m_NetSpecies.size()); - - /* - * Section to assign the special species - */ - m_SpecialSpecies = specialSpecies; - if (specialSpecies == -1) { - m_SpecialSpecies = m_Products[0]; - } - bool ifound = false; - for (i = 0; i < (int) m_NetSpecies.size(); i++) { - int ik = m_NetSpecies[i]; - if (ik == m_SpecialSpecies) { - if (m_netStoich[i] > 0.0) { - m_SpecialSpeciesProduct = true; - } else { - m_SpecialSpeciesProduct = false; - } - m_SS_index = i; - ifound = true; - break; - } - } - if (!ifound) { - throw CanteraError(":setupElemRxnVector", - "Special species not a reactant or product: " - + int2str(m_SpecialSpecies)); - } - - m_ok = true; -} -//============================================================================================================ -std::string ExtraGlobalRxn::reactionString() -{ - string rs; - int k, istoich; - for (k = 0; k < m_nReactants; k++) { - int kkinspecies = m_Reactants[k]; - double stoich = m_ReactantStoich[k]; - if (stoich != 1.0) { - istoich = (int) stoich; - if (fabs((double)istoich - stoich) < 0.00001) { - rs += int2str(istoich) + " "; - } else { - rs += fp2str(stoich) + " "; - } - } - string sName = m_kinetics->kineticsSpeciesName(kkinspecies); - rs += sName; - if (k < (m_nReactants-1)) { - rs += " + "; - } - } - rs += " = "; - for (k = 0; k < m_nProducts; k++) { - int kkinspecies = m_Products[k]; - double stoich = m_ProductStoich[k]; - if (stoich != 1.0) { - istoich = (int) stoich; - if (fabs((double)istoich - stoich) < 0.00001) { - rs += int2str(istoich) + " "; - } else { - rs += fp2str(stoich) + " "; - } - } - string sName = m_kinetics->kineticsSpeciesName(kkinspecies); - rs += sName; - if (k < (m_nProducts-1)) { - rs += " + "; - } - } - return rs; -} -//============================================================================================================ - -std::vector& ExtraGlobalRxn::reactants() -{ - return m_Reactants; -} -//============================================================================================================ - -std::vector& ExtraGlobalRxn::products() -{ - return m_Products; -} - -//============================================================================================================ -bool ExtraGlobalRxn::isReversible() -{ - return m_reversible; -} -//============================================================================================================ - -double ExtraGlobalRxn::reactantStoichCoeff(int kKin) -{ - for (int k = 0; k < m_nReactants; k++) { - int kkinspec = m_Reactants[k]; - if (kkinspec == kKin) { - return m_ReactantStoich[k]; - } - } - return 0.0; -} -//============================================================================================================ -double ExtraGlobalRxn::productStoichCoeff(int kKin) -{ - for (int k = 0; k < m_nProducts; k++) { - int kkinspec = m_Products[k]; - if (kkinspec == kKin) { - return m_ProductStoich[k]; - } - } - return 0.0; -} -//============================================================================================================ - -double ExtraGlobalRxn::deltaSpecValue(double* speciesVectorProperty) -{ - int k; - double val = 0; - for (k = 0; k < m_nNetSpecies; k++) { - int kkinspec = m_NetSpecies[k]; - val += speciesVectorProperty[kkinspec] * m_netStoich[k]; - } - return val; -} -//============================================================================================================ - -double ExtraGlobalRxn::deltaRxnVecValue(double* rxnVectorProperty) -{ - double val = 0; - for (int i = 0; i < m_nRxns; i++) { - val += m_ElemRxnVector[i] * rxnVectorProperty[i]; - } - return val; -} -//============================================================================================================ -double ExtraGlobalRxn::ROPValue(double* ROPElemKinVector) -{ - double val = 0.0; - for (int i = 0; i < m_nRxns; i++) { - double kstoich = m_kinetics->productStoichCoeff(m_SpecialSpecies, i) - m_kinetics->reactantStoichCoeff(m_SpecialSpecies, i); - if (m_ElemRxnVector[i] > 0.0) { - val += ROPElemKinVector[i] * kstoich * m_ElemRxnVector[i]; - } else { - val -= ROPElemKinVector[i] * kstoich * m_ElemRxnVector[i]; - } - } - if (!m_SpecialSpeciesProduct) { - val = -val; - } - return val; -} -//============================================================================================================ -double ExtraGlobalRxn::FwdROPValue(double* FwdROPElemKinVector, - double* RevROPElemKinVector) -{ - double val = 0.0; - for (int i = 0; i < m_nRxns; i++) { - double kstoich = m_kinetics->productStoichCoeff(m_SpecialSpecies, i) - m_kinetics->reactantStoichCoeff(m_SpecialSpecies, i); - if (m_ElemRxnVector[i] > 0.0) { - val += FwdROPElemKinVector[i] * kstoich * m_ElemRxnVector[i]; - } - if (m_ElemRxnVector[i] < 0.0) { - val += RevROPElemKinVector[i] * kstoich * m_ElemRxnVector[i]; - } - } - if (!m_SpecialSpeciesProduct) { - val = -val; - } - return val; -} -//============================================================================================================ -double ExtraGlobalRxn::RevROPValue(double* FwdROPElemKinVector, - double* RevROPElemKinVector) -{ - double val = 0.0; - for (int i = 0; i < m_nRxns; i++) { - double kstoich = m_kinetics->productStoichCoeff(m_SpecialSpecies, i)- m_kinetics->reactantStoichCoeff(m_SpecialSpecies, i); - if (m_ElemRxnVector[i] > 0.0) { - val += RevROPElemKinVector[i] * kstoich * m_ElemRxnVector[i]; - } - if (m_ElemRxnVector[i] < 0.0) { - val += FwdROPElemKinVector[i] * kstoich * m_ElemRxnVector[i]; - } - } - if (!m_SpecialSpeciesProduct) { - val = -val; - } - return val; -} -//============================================================================================================ -} - diff --git a/src/kinetics/InterfaceKinetics.cpp b/src/kinetics/InterfaceKinetics.cpp index d2af00ae4..a227f27a2 100644 --- a/src/kinetics/InterfaceKinetics.cpp +++ b/src/kinetics/InterfaceKinetics.cpp @@ -43,13 +43,6 @@ InterfaceKinetics::InterfaceKinetics(thermo_t* thermo) : InterfaceKinetics::~InterfaceKinetics() { delete m_integrator; - - for (size_t i = 0; i < m_ctrxn_ROPOrdersList_.size(); i++) { - delete m_ctrxn_ROPOrdersList_[i]; - } - for (size_t i = 0; i < m_ctrxn_FwdOrdersList_.size(); i++) { - delete m_ctrxn_FwdOrdersList_[i]; - } } InterfaceKinetics::InterfaceKinetics(const InterfaceKinetics& right) @@ -113,24 +106,6 @@ InterfaceKinetics& InterfaceKinetics::operator=(const InterfaceKinetics& right) m_rxnPhaseIsProduct = right.m_rxnPhaseIsProduct; m_ioFlag = right.m_ioFlag; - for (size_t i = 0; i < m_ctrxn_ROPOrdersList_.size(); i++) { - delete m_ctrxn_ROPOrdersList_[i]; - } - m_ctrxn_ROPOrdersList_ = right.m_ctrxn_ROPOrdersList_; - for (size_t i = 0; i < m_ctrxn_ROPOrdersList_.size(); i++) { - RxnOrders* ro = right.m_ctrxn_ROPOrdersList_[i]; - m_ctrxn_ROPOrdersList_[i] = new RxnOrders(*ro); - } - - for (size_t i = 0; i < m_ctrxn_FwdOrdersList_.size(); i++) { - delete m_ctrxn_FwdOrdersList_[i]; - } - m_ctrxn_FwdOrdersList_ = right.m_ctrxn_FwdOrdersList_; - for (size_t i = 0; i < m_ctrxn_FwdOrdersList_.size(); i++) { - RxnOrders* ro = right.m_ctrxn_FwdOrdersList_[i]; - m_ctrxn_FwdOrdersList_[i] = new RxnOrders(*ro); - } - return *this; } @@ -816,29 +791,10 @@ bool InterfaceKinetics::addReaction(shared_ptr r_base) ++iter) { orders[kineticsSpeciesIndex(iter->first)] = iter->second; } - RxnOrders* ro = new RxnOrders(); - ro->fill(orders); - m_ctrxn_ROPOrdersList_.push_back(ro); - m_ctrxn_FwdOrdersList_.push_back(0); - - // Fill in the Fwd Orders dependence here for B-V reactions - if (r.reaction_type == BUTLERVOLMER_NOACTIVITYCOEFFS_RXN || - r.reaction_type == BUTLERVOLMER_RXN) { - vector_fp fwdFullorders(m_kk, 0.0); - determineFwdOrdersBV(*re, fwdFullorders); - RxnOrders* ro = new RxnOrders(); - ro->fill(fwdFullorders); - m_ctrxn_FwdOrdersList_[i] = ro; - } - } else { - m_ctrxn_ROPOrdersList_.push_back(0); - m_ctrxn_FwdOrdersList_.push_back(0); } } else { m_ctrxn_BVform.push_back(0); - m_ctrxn_ROPOrdersList_.push_back(0); - m_ctrxn_FwdOrdersList_.push_back(0); if (re->film_resistivity > 0.0) { throw CanteraError("InterfaceKinetics::addReaction()", "film resistivity set for elementary reaction"); @@ -1250,35 +1206,4 @@ void EdgeKinetics::finalize() m_finalized = true; } -RxnOrders::RxnOrders(const RxnOrders& right) : - kinSpeciesIDs_(right.kinSpeciesIDs_), - kinSpeciesOrders_(right.kinSpeciesOrders_) -{ -} - -RxnOrders& RxnOrders::operator=(const RxnOrders& right) -{ - if (this == &right) { - return *this; - } - kinSpeciesIDs_ = right.kinSpeciesIDs_; - kinSpeciesOrders_ = right.kinSpeciesOrders_; - return *this; -} - -int RxnOrders::fill(const std::vector& fullForwardOrders) -{ - int nzeroes = 0; - kinSpeciesIDs_.clear(); - kinSpeciesOrders_.clear(); - for (size_t k = 0; k < fullForwardOrders.size(); ++k) { - if (fullForwardOrders[k] != 0.0) { - kinSpeciesIDs_.push_back(k); - kinSpeciesOrders_.push_back(fullForwardOrders[k]); - ++nzeroes; - } - } - return nzeroes; -} - } diff --git a/src/kinetics/Kinetics.cpp b/src/kinetics/Kinetics.cpp index da5659569..d6a576380 100644 --- a/src/kinetics/Kinetics.cpp +++ b/src/kinetics/Kinetics.cpp @@ -53,8 +53,6 @@ Kinetics& Kinetics::operator=(const Kinetics& right) m_kk = right.m_kk; m_perturb = right.m_perturb; m_reactions = right.m_reactions; - m_reactants = right.m_reactants; - m_products = right.m_products; m_rrxn = right.m_rrxn; m_prxn = right.m_prxn; m_rxntype = right.m_rxntype; @@ -613,7 +611,6 @@ bool Kinetics::addReaction(shared_ptr r) rstoich.push_back(iter->second); m_rrxn[k][irxn] = iter->second; } - m_reactants.push_back(rk); for (Composition::const_iterator iter = r->products.begin(); iter != r->products.end(); @@ -623,7 +620,6 @@ bool Kinetics::addReaction(shared_ptr r) pstoich.push_back(iter->second); m_prxn[k][irxn] = iter->second; } - m_products.push_back(pk); // The default order for each reactant is its stoichiometric coefficient, // which can be overridden by entries in the Reaction.orders map. rorder[i] diff --git a/src/kinetics/RxnMolChange.cpp b/src/kinetics/RxnMolChange.cpp deleted file mode 100644 index b3a24a9d3..000000000 --- a/src/kinetics/RxnMolChange.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/** - * @file example2.cpp - * - * $Id: RxnMolChange.cpp 571 2013-03-26 16:44:21Z hkmoffa $ - * - */ - -/* - * Copyright (2005) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ - -#include "cantera/kinetics/RxnMolChange.h" - - -#include "cantera/thermo.h" -#include "cantera/kinetics.h" -#include "cantera/kinetics/InterfaceKinetics.h" - -#include "cantera/kinetics/ExtraGlobalRxn.h" - -#include -#include - -using namespace std; - -namespace Cantera { - -RxnMolChange::RxnMolChange(Kinetics* kinPtr, int irxn) : - m_nPhases(0), - m_kinBase(kinPtr), - m_iRxn(irxn), - m_ChargeTransferInRxn(0.0), - m_beta(0.0), - m_egr(0) -{ - warn_deprecated("class RxnMolChange", "To be removed after Cantera 2.2."); - int iph; - AssertTrace(irxn >= 0); - AssertTrace(irxn < static_cast(kinPtr->nReactions())); - - m_nPhases = static_cast(kinPtr->nPhases()); - - m_phaseMoleChange.resize(m_nPhases, 0.0); - m_phaseReactantMoles.resize(m_nPhases, 0.0); - m_phaseProductMoles.resize(m_nPhases, 0.0); - m_phaseMassChange.resize(m_nPhases, 0.0); - m_phaseChargeChange.resize(m_nPhases, 0.0); - m_phaseTypes.resize(m_nPhases, 0); - m_phaseDims.resize(m_nPhases, 0); - - int m_kk = static_cast(kinPtr->nTotalSpecies()); - - for (int kKin = 0; kKin < m_kk; kKin++) { - iph = static_cast(m_kinBase->speciesPhaseIndex(kKin)); - ThermoPhase& tpRef = m_kinBase->thermo(iph); - int kLoc = kKin - static_cast(m_kinBase->kineticsSpeciesIndex(0, iph)); - double rsc = m_kinBase->reactantStoichCoeff(kKin, irxn); - double psc = m_kinBase->productStoichCoeff(kKin, irxn); - double nsc = psc - rsc; - m_phaseMoleChange[iph] += (nsc); - m_phaseReactantMoles[iph] += rsc; - m_phaseProductMoles[iph] += psc; - double mw = tpRef.molecularWeight(kLoc); - m_phaseMassChange[iph] += (nsc) * mw; - double chg = tpRef.charge(kLoc); - m_phaseChargeChange[iph] += nsc * chg; - } - - for (iph = 0; iph < m_nPhases; iph++) { - ThermoPhase& tpRef = m_kinBase->thermo(iph); - m_phaseDims[iph] = static_cast(tpRef.nDim()); - m_phaseTypes[iph] = tpRef.eosType(); - if (m_phaseChargeChange[iph] != 0.0) { - double tmp = fabs(m_phaseChargeChange[iph]); - if (tmp > m_ChargeTransferInRxn) { - m_ChargeTransferInRxn = tmp; - } - } - } - - if (m_ChargeTransferInRxn) { - InterfaceKinetics* iK = dynamic_cast(kinPtr); - if (iK) { - m_beta = iK->electrochem_beta(irxn); - } else { - throw CanteraError("RxnMolChange", "unknown condition on charge"); - } - } - -} - -RxnMolChange::RxnMolChange(Kinetics* kinPtr, ExtraGlobalRxn* egr) : - m_nPhases(0), - m_kinBase(kinPtr), - m_iRxn(-1), - m_ChargeTransferInRxn(0.0), - m_beta(0.0), - m_egr(egr) -{ - int iph; - AssertTrace(egr != 0); - - m_nPhases = static_cast(kinPtr->nPhases()); - - m_phaseMoleChange.resize(m_nPhases, 0.0); - m_phaseReactantMoles.resize(m_nPhases, 0.0); - m_phaseProductMoles.resize(m_nPhases, 0.0); - m_phaseMassChange.resize(m_nPhases, 0.0); - m_phaseChargeChange.resize(m_nPhases, 0.0); - m_phaseTypes.resize(m_nPhases, 0); - m_phaseDims.resize(m_nPhases, 0); - - int m_kk = static_cast(kinPtr->nTotalSpecies()); - - for (int kKin = 0; kKin < m_kk; kKin++) { - iph = static_cast(m_kinBase->speciesPhaseIndex(kKin)); - ThermoPhase& tpRef = m_kinBase->thermo(iph); - int kLoc = kKin - static_cast(m_kinBase->kineticsSpeciesIndex(0, iph)); - double rsc = egr->reactantStoichCoeff(kKin); - double psc = egr->productStoichCoeff(kKin); - double nsc = psc - rsc; - m_phaseMoleChange[iph] += (nsc); - m_phaseReactantMoles[iph] += rsc; - m_phaseProductMoles[iph] += psc; - double mw = tpRef.molecularWeight(kLoc); - m_phaseMassChange[iph] += (nsc) * mw; - double chg = tpRef.charge(kLoc); - m_phaseChargeChange[iph] += nsc * chg; - } - - for (iph = 0; iph < m_nPhases; iph++) { - ThermoPhase& tpRef = m_kinBase->thermo(iph); - m_phaseDims[iph] = static_cast(tpRef.nDim()); - m_phaseTypes[iph] = tpRef.eosType(); - if (m_phaseChargeChange[iph] != 0.0) { - double tmp = fabs(m_phaseChargeChange[iph]); - if (tmp > m_ChargeTransferInRxn) { - m_ChargeTransferInRxn = tmp; - } - } - } - - if (m_ChargeTransferInRxn) { - InterfaceKinetics* iK = dynamic_cast(kinPtr); - if (iK) { - m_beta = 0.0; - } else { - throw CanteraError("RxnMolChange", "unknown condition on charge"); - } - } - -} - -} - diff --git a/src/kinetics/importKinetics.cpp b/src/kinetics/importKinetics.cpp index e62f92f42..3add8f5b8 100644 --- a/src/kinetics/importKinetics.cpp +++ b/src/kinetics/importKinetics.cpp @@ -24,14 +24,6 @@ using namespace std; namespace Cantera { -ReactionRules::ReactionRules() : - skipUndeclaredSpecies(false), - skipUndeclaredThirdBodies(false), - allowNegativeA(false) -{ -} - - bool installReactionArrays(const XML_Node& p, Kinetics& kin, std::string default_phase, bool check_for_duplicates) { diff --git a/src/matlab/mixturemethods.cpp b/src/matlab/mixturemethods.cpp index bd7e8fde7..cdfb2f9ad 100644 --- a/src/matlab/mixturemethods.cpp +++ b/src/matlab/mixturemethods.cpp @@ -46,9 +46,6 @@ void mixturemethods(int nlhs, mxArray* plhs[], case 2: iok = mix_copy(i); break; - case 3: - iok = mix_assign(i, int(v)); - break; case 4: checkNArgs(5, nrhs); moles = getDouble(prhs[4]); diff --git a/src/matlab/onedimmethods.cpp b/src/matlab/onedimmethods.cpp index 7230f49fa..a0f411d9d 100644 --- a/src/matlab/onedimmethods.cpp +++ b/src/matlab/onedimmethods.cpp @@ -279,11 +279,6 @@ void onedimmethods(int nlhs, mxArray* plhs[], nv = mxGetM(prhs[4])*mxGetN(prhs[4]); iok = stflow_setFixedTempProfile(dom, np, pos, nv, temp); break; - case 65: - checkNArgs(4, nrhs); - flag = getInt(prhs[3]); - iok = stflow_solveSpeciesEqs(dom, flag); - break; case 66: checkNArgs(4, nrhs); flag = getInt(prhs[3]); diff --git a/src/matlab/reactormethods.cpp b/src/matlab/reactormethods.cpp index 05e312a4e..abde89953 100644 --- a/src/matlab/reactormethods.cpp +++ b/src/matlab/reactormethods.cpp @@ -42,9 +42,6 @@ void reactormethods(int nlhs, mxArray* plhs[], case 2: iok = reactor_copy(i); break; - case 3: - iok = reactor_assign(i,int(v)); - break; case 4: iok = reactor_setInitialVolume(i, v); break; diff --git a/src/matlab/reactornetmethods.cpp b/src/matlab/reactornetmethods.cpp index aad6e235e..da82dbab4 100644 --- a/src/matlab/reactornetmethods.cpp +++ b/src/matlab/reactornetmethods.cpp @@ -46,9 +46,6 @@ void reactornetmethods(int nlhs, mxArray* plhs[], case 2: iok = reactornet_copy(i); break; - case 3: - iok = reactornet_assign(i,int(v)); - break; case 4: iok = reactornet_addreactor(i, int(v)); break; diff --git a/src/matlab/wallmethods.cpp b/src/matlab/wallmethods.cpp index 3aed32132..1d1b2994b 100644 --- a/src/matlab/wallmethods.cpp +++ b/src/matlab/wallmethods.cpp @@ -40,9 +40,6 @@ void wallmethods(int nlhs, mxArray* plhs[], case 2: iok = wall_copy(i); break; - case 3: - iok = wall_assign(i,int(v)); - break; case 4: m = getInt(prhs[4]); iok = wall_install(i, int(v), m); diff --git a/src/matlab/xmlmethods.cpp b/src/matlab/xmlmethods.cpp index 381717a68..b4f128d3a 100644 --- a/src/matlab/xmlmethods.cpp +++ b/src/matlab/xmlmethods.cpp @@ -66,10 +66,6 @@ void xmlmethods(int nlhs, mxArray* plhs[], case 2: iok = xml_copy(i); break; - case 3: - j = getInt(prhs[3]); - iok = xml_assign(i,j); - break; case 4: file = getString(prhs[3]); iok = xml_build(i, file); diff --git a/src/numerics/BEulerInt.cpp b/src/numerics/BEulerInt.cpp deleted file mode 100644 index 03a95b39d..000000000 --- a/src/numerics/BEulerInt.cpp +++ /dev/null @@ -1,1924 +0,0 @@ -/** - * @file BEulerInt.cpp - */ - -/* - * Copyright 2004 Sandia Corporation. Under the terms of Contract - * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government - * retains certain rights in this software. - * See file License.txt for licensing information. - */ - -#include "cantera/numerics/BEulerInt.h" -#include "cantera/numerics/SquareMatrix.h" -#include "cantera/base/global.h" - -using namespace std; - -namespace Cantera -{ - -BEulerErr::BEulerErr(const std::string& msg) : - CanteraError("BEulerInt", msg) -{ -} - -BEulerInt::BEulerInt() : - m_iter(Newton_Iter), - m_method(BEulerVarStep), - m_jacFormMethod(BEULER_JAC_NUM), - m_rowScaling(true), - m_colScaling(false), - m_matrixConditioning(false), - m_itol(0), - m_reltol(1.e-4), - m_abstols(1.e-10), - m_hmax(0.0), - m_maxord(0), - m_time_step_num(0), - m_time_step_attempts(0), - m_max_time_step_attempts(11000000), - m_numInitialConstantDeltaTSteps(0), - m_failure_counter(0), - m_min_newt_its(0), - m_printSolnStepInterval(1), - m_printSolnNumberToTout(1), - m_printSolnFirstSteps(0), - m_dumpJacobians(false), - m_neq(0), - m_t0(0.0), - m_time_final(0.0), - time_n(0.0), - time_nm1(0.0), - time_nm2(0.0), - delta_t_n(0.0), - delta_t_nm1(0.0), - delta_t_nm2(0.0), - delta_t_np1(1.0E-8), - delta_t_max(1.0E300), - m_func(0), - tdjac_ptr(0), - m_print_flag(3), - m_nfe(0), - m_nJacEval(0), - m_numTotalNewtIts(0), - m_numTotalLinearSolves(0), - m_numTotalConvFails(0), - m_numTotalTruncFails(0), - num_failures(0) -{ - warn_deprecated("class BEulerInt", "To be removed after Cantera 2.2."); -} - -BEulerInt::~BEulerInt() -{ - delete tdjac_ptr; -} - -void BEulerInt::setTolerances(double reltol, size_t n, double* abstol) -{ - m_itol = 1; - m_abstol.resize(m_neq); - if (static_cast(n) != m_neq) { - printf("ERROR n is wrong\n"); - exit(-1); - } - for (int i = 0; i < m_neq; i++) { - m_abstol[i] = abstol[i]; - } - m_reltol = reltol; -} - -void BEulerInt::setTolerances(double reltol, double abstol) -{ - m_itol = 0; - m_reltol = reltol; - m_abstols = abstol; -} - -void BEulerInt::setProblemType(int jacFormMethod) -{ - m_jacFormMethod = jacFormMethod; -} - -void BEulerInt::setMethodBEMT(BEulerMethodType t) -{ - m_method = t; -} - -void BEulerInt::setMaxStep(doublereal hmax) -{ - m_hmax = hmax; -} - -void BEulerInt::setMaxNumTimeSteps(int maxNumTimeSteps) -{ - m_max_time_step_attempts = maxNumTimeSteps; -} - -void BEulerInt::setNumInitialConstantDeltaTSteps(int num) -{ - m_numInitialConstantDeltaTSteps = num; -} - -void BEulerInt::setPrintSolnOptions(int printSolnStepInterval, - int printSolnNumberToTout, - int printSolnFirstSteps, - bool dumpJacobians) -{ - m_printSolnStepInterval = printSolnStepInterval; - m_printSolnNumberToTout = printSolnNumberToTout; - m_printSolnFirstSteps = printSolnFirstSteps; - m_dumpJacobians = dumpJacobians; -} - -void BEulerInt::setIterator(IterType t) -{ - m_iter = t; -} - -void BEulerInt::setNonLinOptions(int min_newt_its, bool matrixConditioning, - bool colScaling, bool rowScaling) -{ - m_min_newt_its = min_newt_its; - m_matrixConditioning = matrixConditioning; - m_colScaling = colScaling; - m_rowScaling = rowScaling; - if (m_colScaling && m_colScales.empty()) { - m_colScales.assign(m_neq, 1.0); - } - if (m_rowScaling && m_rowScales.empty()) { - m_rowScales.assign(m_neq, 1.0); - } -} - -void BEulerInt::setInitialTimeStep(double deltaT) -{ - delta_t_np1 = deltaT; -} - -void BEulerInt::setPrintFlag(int print_flag) -{ - m_print_flag = print_flag; -} - -void BEulerInt::initializeRJE(double t0, ResidJacEval& func) -{ - m_neq = func.nEquations(); - m_t0 = t0; - internalMalloc(); - - /* - * Get the initial conditions. - */ - func.getInitialConditions(m_t0, &m_y_n[0], &m_ydot_n[0]); - - // Store a pointer to the residual routine in the object - m_func = &func; - - /* - * Initialize the various time counters in the object - */ - time_n = t0; - time_nm1 = time_n; - time_nm2 = time_nm1; - delta_t_n = 0.0; - delta_t_nm1 = 0.0; -} - -void BEulerInt::reinitializeRJE(double t0, ResidJacEval& func) -{ - m_neq = func.nEquations(); - m_t0 = t0; - internalMalloc(); - /* - * At the initial time, get the initial conditions and time and store - * them into internal storage in the object, my[]. - */ - m_t0 = t0; - func.getInitialConditions(m_t0, &m_y_n[0], &m_ydot_n[0]); - /** - * Set up the internal weights that are used for testing convergence - */ - setSolnWeights(); - - // Store a pointer to the function - m_func = &func; - -} - -double BEulerInt::getPrintTime(double time_current) -{ - double tnext; - if (m_printSolnNumberToTout > 0) { - double dt = (m_time_final - m_t0) / m_printSolnNumberToTout; - for (int i = 0; i <= m_printSolnNumberToTout; i++) { - tnext = m_t0 + dt * i; - if (tnext >= time_current) { - return tnext; - } - } - } - return 1.0E300; -} - -int BEulerInt::nEvals() const -{ - return m_nfe; -} - -void BEulerInt::internalMalloc() -{ - m_ewt.assign(m_neq, 0.0); - m_y_n.assign(m_neq, 0.0); - m_y_nm1.assign(m_neq, 0.0); - m_y_pred_n.assign(m_neq, 0.0); - m_ydot_n.assign(m_neq, 0.0); - m_ydot_nm1.assign(m_neq, 0.0); - m_resid.assign(m_neq, 0.0); - m_residWts.assign(m_neq, 0.0); - m_wksp.assign(m_neq, 0.0); - if (m_rowScaling) { - m_rowScales.assign(m_neq, 1.0); - } - if (m_colScaling) { - m_colScales.assign(m_neq, 1.0); - } - tdjac_ptr = new SquareMatrix(m_neq); -} - -void BEulerInt::setSolnWeights() -{ - int i; - if (m_itol == 1) { - for (i = 0; i < m_neq; i++) { - m_ewt[i] = m_abstol[i] + m_reltol * 0.5 * - (fabs(m_y_n[i]) + fabs(m_y_pred_n[i])); - } - } else { - for (i = 0; i < m_neq; i++) { - m_ewt[i] = m_abstols + m_reltol * 0.5 * - (fabs(m_y_n[i]) + fabs(m_y_pred_n[i])); - } - } -} - -void BEulerInt::setColumnScales() -{ - m_func->calcSolnScales(time_n, &m_y_n[0], &m_y_nm1[0], &m_colScales[0]); -} - -void BEulerInt::computeResidWts(GeneralMatrix& jac) -{ - /* - * We compute residual weights here, which we define as the L_0 norm - * of the Jacobian Matrix, weighted by the solution weights. - * This is the proper way to guage the magnitude of residuals. However, - * it does need the evaluation of the Jacobian, and the implementation - * below is slow, but doesn't take up much memory. - * - * Here a small weighting indicates that the change in solution is - * very sensitive to that equation. - */ - int i, j; - double* data = &(*(jac.begin())); - double value; - for (i = 0; i < m_neq; i++) { - m_residWts[i] = fabs(data[i] * m_ewt[0]); - for (j = 1; j < m_neq; j++) { - value = fabs(data[j*m_neq + i] * m_ewt[j]); - m_residWts[i] = std::max(m_residWts[i], value); - } - } -} - -double BEulerInt::filterNewStep(double timeCurrent, double* y_current, double* ydot_current) -{ - return 0.0; -} - -/* - * Print out for relevant time step information - */ -static void print_time_step1(int order, int n_time_step, double time, - double delta_t_n, double delta_t_nm1, - bool step_failed, int num_failures) -{ - const char* string = 0; - if (order == 0) { - string = "Backward Euler"; - } else if (order == 1) { - string = "Forward/Backward Euler"; - } else if (order == 2) { - string = "Adams-Bashforth/TR"; - } - writeline('=', 80, true, true); - printf("\nStart of Time Step: %5d Time_n = %9.5g Time_nm1 = %9.5g\n", - n_time_step, time, time - delta_t_n); - printf("\tIntegration method = %s\n", string); - if (step_failed) { - printf("\tPreviously attempted step was a failure\n"); - } - if (delta_t_n > delta_t_nm1) { - string = "(Increased from previous iteration)"; - } else if (delta_t_n < delta_t_nm1) { - string = "(Decreased from previous iteration)"; - } else { - string = "(same as previous iteration)"; - } - printf("\tdelta_t_n = %8.5e %s", delta_t_n, string); - if (num_failures > 0) { - printf("\t(Bad_History Failure Counter = %d)", num_failures); - } - printf("\n\tdelta_t_nm1 = %8.5e\n", delta_t_nm1); -} - -/* - * Print out for relevant time step information - */ -static void print_time_step2(int time_step_num, int order, - double time, double time_error_factor, - double delta_t_n, double delta_t_np1) -{ - printf("\tTime Step Number %5d was a success: time = %10g\n", time_step_num, - time); - printf("\t\tEstimated Error\n"); - printf("\t\t-------------------- = %8.5e\n", time_error_factor); - printf("\t\tTolerated Error\n\n"); - printf("\t- Recommended next delta_t (not counting history) = %g\n", - delta_t_np1); - writeline('=', 80, true, true); -} - -/* - * Print Out descriptive information on why the current step failed - */ -static void print_time_fail(bool convFailure, int time_step_num, - double time, double delta_t_n, - double delta_t_np1, double time_error_factor) -{ - writeline('=', 80, true, true); - if (convFailure) { - printf("\tTime Step Number %5d experienced a convergence " - "failure\n", time_step_num); - printf("\tin the non-linear or linear solver\n"); - printf("\t\tValue of time at failed step = %g\n", time); - printf("\t\tdelta_t of the failed step = %g\n", - delta_t_n); - printf("\t\tSuggested value of delta_t to try next = %g\n", - delta_t_np1); - } else { - printf("\tTime Step Number %5d experienced a truncation error " - "failure!\n", time_step_num); - printf("\t\tValue of time at failed step = %g\n", time); - printf("\t\tdelta_t of the failed step = %g\n", - delta_t_n); - printf("\t\tSuggested value of delta_t to try next = %g\n", - delta_t_np1); - printf("\t\tCalculated truncation error factor = %g\n", - time_error_factor); - } - writeline('=', 80, true, true); -} - -/* - * Print out the final results and counters - */ -static void print_final(double time, int step_failed, - int time_step_num, int num_newt_its, - int total_linear_solves, int numConvFails, - int numTruncFails, int nfe, int nJacEval) -{ - writeline('=', 80, true, true); - printf("TIME INTEGRATION ROUTINE HAS FINISHED: "); - if (step_failed) { - printf(" IT WAS A FAILURE\n"); - } else { - printf(" IT WAS A SUCCESS\n"); - } - printf("\tEnding time = %g\n", time); - printf("\tNumber of time steps = %d\n", time_step_num); - printf("\tNumber of newt its = %d\n", num_newt_its); - printf("\tNumber of linear solves = %d\n", total_linear_solves); - printf("\tNumber of convergence failures= %d\n", numConvFails); - printf("\tNumber of TimeTruncErr fails = %d\n", numTruncFails); - printf("\tNumber of Function evals = %d\n", nfe); - printf("\tNumber of Jacobian evals/solvs= %d\n", nJacEval); - writeline('=', 80, true, true); -} - -/* - * Header info for one line comment about a time step - */ -static void print_lvl1_Header(int nTimes) -{ - printf("\n"); - if (nTimes) { - writeline('-', 80); - } - printf("time Time Time Time "); - if (nTimes == 0) { - printf(" START"); - } else { - printf(" (continued)"); - } - printf("\n"); - - printf("step (sec) step Newt Aztc bktr trunc "); - printf("\n"); - - printf(" No. Rslt size Its Its stps error |"); - printf(" comment"); - writeline('-', 80, true); -} - -/* - * One line entry about time step - * rslt -> 4 letter code - */ -static void print_lvl1_summary( - int time_step_num, double time, const char* rslt, double delta_t_n, - int newt_its, int aztec_its, int bktr_stps, double time_error_factor, - const char* comment) -{ - printf("%6d %11.6g %4s %10.4g %4d %4d %4d %11.4g", - time_step_num, time, rslt, delta_t_n, newt_its, aztec_its, - bktr_stps, time_error_factor); - if (comment) { - printf(" | %s", comment); - } - printf("\n"); -} - -/* - * This routine subtracts 2 numbers. If the difference is less - * than 1.0E-14 times the magnitude of the smallest number, - * then diff returns an exact zero. - * It also returns an exact zero if the difference is less than - * 1.0E-300. - * - * returns: a - b - * - * This routine is used in numerical differencing schemes in order - * to avoid roundoff errors resulting in creating Jacobian terms. - * Note: This is a slow routine. However, Jacobian errors may cause - * loss of convergence. Therefore, in practice this routine - * has proved cost-effective. - */ -double subtractRD(double a, double b) -{ - double diff = a - b; - double d = std::min(fabs(a), fabs(b)); - d *= 1.0E-14; - double ad = fabs(diff); - if (ad < 1.0E-300) { - diff = 0.0; - } - if (ad < d) { - diff = 0.0; - } - return diff; -} - -void BEulerInt::beuler_jac(GeneralMatrix& J, double* const f, - double time_curr, double CJ, - double* const y, - double* const ydot, - int num_newt_its) -{ - int i, j; - double* col_j; - double ysave, ydotsave, dy; - /** - * Clear the factor flag - */ - J.clearFactorFlag(); - - - if (m_jacFormMethod & BEULER_JAC_ANAL) { - /******************************************************************** - * Call the function to get a Jacobian. - */ - m_func->evalJacobian(time_curr, delta_t_n, CJ, y, ydot, J, f); - m_nJacEval++; - m_nfe++; - } else { - /******************************************************************* - * Generic algorithm to calculate a numerical Jacobian - */ - /* - * Calculate the current value of the RHS given the - * current conditions. - */ - - m_func->evalResidNJ(time_curr, delta_t_n, y, ydot, f, JacBase_ResidEval); - m_nfe++; - m_nJacEval++; - - - /* - * Malloc a vector and call the function object to return a set of - * deltaY's that are appropriate for calculating the numerical - * derivative. - */ - vector_fp dyVector(m_neq); - m_func->calcDeltaSolnVariables(time_curr, y, &m_y_nm1[0], &dyVector[0], - &m_ewt[0]); -#ifdef DEBUG_HKM - bool print_NumJac = false; - if (print_NumJac) { - FILE* idy = fopen("NumJac.csv", "w"); - fprintf(idy, "Unk m_ewt y " - "dyVector ResN\n"); - for (int iii = 0; iii < m_neq; iii++) { - fprintf(idy, " %4d %16.8e %16.8e %16.8e %16.8e \n", - iii, m_ewt[iii], y[iii], dyVector[iii], f[iii]); - } - fclose(idy); - } -#endif - /* - * Loop over the variables, formulating a numerical derivative - * of the dense matrix. - * For the delta in the variable, we will use a variety of approaches - * The original approach was to use the error tolerance amount. - * This may not be the best approach, as it could be overly large in - * some instances and overly small in others. - * We will first protect from being overly small, by using the usual - * sqrt of machine precision approach, i.e., 1.0E-7, - * to bound the lower limit of the delta. - */ - for (j = 0; j < m_neq; j++) { - - - /* - * Get a pointer into the column of the matrix - */ - - - col_j = (double*) J.ptrColumn(j); - ysave = y[j]; - dy = dyVector[j]; - - y[j] = ysave + dy; - dy = y[j] - ysave; - ydotsave = ydot[j]; - ydot[j] += dy * CJ; - /* - * Call the functon - */ - - - m_func->evalResidNJ(time_curr, delta_t_n, y, ydot, &m_wksp[0], - JacDelta_ResidEval, j, dy); - m_nfe++; - double diff; - for (i = 0; i < m_neq; i++) { - diff = subtractRD(m_wksp[i], f[i]); - col_j[i] = diff / dy; - } - - y[j] = ysave; - ydot[j] = ydotsave; - - } - } - - -} - -void BEulerInt::calc_y_pred(int order) -{ - int i; - double c1, c2; - switch (order) { - case 0: - case 1: - c1 = delta_t_n; - for (i = 0; i < m_neq; i++) { - m_y_pred_n[i] = m_y_n[i] + c1 * m_ydot_n[i]; - } - break; - case 2: - c1 = delta_t_n * (2.0 + delta_t_n / delta_t_nm1) / 2.0; - c2 = (delta_t_n * delta_t_n) / (delta_t_nm1 * 2.0); - for (i = 0; i < m_neq; i++) { - m_y_pred_n[i] = m_y_n[i] + c1 * m_ydot_n[i] - c2 * m_ydot_nm1[i]; - } - break; - } - - /* - * Filter the predictions. - */ - m_func->filterSolnPrediction(time_n, &m_y_pred_n[0]); - -} - -void BEulerInt::calc_ydot(int order, double* y_curr, double* ydot_curr) -{ - int i; - double c1; - switch (order) { - case 0: - case 1: /* First order forward Euler/backward Euler */ - c1 = 1.0 / delta_t_n; - for (i = 0; i < m_neq; i++) { - ydot_curr[i] = c1 * (y_curr[i] - m_y_nm1[i]); - } - return; - case 2: /* Second order Adams-Bashforth / Trapezoidal Rule */ - c1 = 2.0 / delta_t_n; - for (i = 0; i < m_neq; i++) { - ydot_curr[i] = c1 * (y_curr[i] - m_y_nm1[i]) - m_ydot_nm1[i]; - } - return; - } -} - -double BEulerInt::time_error_norm() -{ - int i; - double rel_norm, error; -#ifdef DEBUG_HKM -#define NUM_ENTRIES 5 - if (m_print_flag > 2) { - int imax[NUM_ENTRIES], j, jnum; - double dmax; - bool used; - printf("\t\ttime step truncation error contributors:\n"); - printf("\t\t I entry actual predicted " - " weight ydot\n"); - printf("\t\t"); - writeline('-', 70); - for (j = 0; j < NUM_ENTRIES; j++) { - imax[j] = -1; - } - for (jnum = 0; jnum < NUM_ENTRIES; jnum++) { - dmax = -1.0; - for (i = 0; i < m_neq; i++) { - used = false; - for (j = 0; j < jnum; j++) { - if (imax[j] == i) { - used = true; - } - } - if (!used) { - error = (m_y_n[i] - m_y_pred_n[i]) / m_ewt[i]; - rel_norm = sqrt(error * error); - if (rel_norm > dmax) { - imax[jnum] = i; - dmax = rel_norm; - } - } - } - if (imax[jnum] >= 0) { - i = imax[jnum]; - printf("\t\t%4d %12.4e %12.4e %12.4e %12.4e %12.4e\n", - i, dmax, m_y_n[i], m_y_pred_n[i], m_ewt[i], m_ydot_n[i]); - } - } - printf("\t\t"); - writeline('-', 70); - } -#endif - rel_norm = 0.0; - for (i = 0; i < m_neq; i++) { - error = (m_y_n[i] - m_y_pred_n[i]) / m_ewt[i]; - rel_norm += (error * error); - } - return sqrt(rel_norm / m_neq); -} - -double BEulerInt::time_step_control(int order, double time_error_factor) -{ - double factor = 0.0, power = 0.0, delta_t; - const char* yo = "time_step_control"; - - /* - * Special case time_error_factor so that zeroes don't cause a problem. - */ - time_error_factor = std::max(1.0E-50, time_error_factor); - - /* - * Calculate the factor for the change in magnitude of time step. - */ - switch (order) { - case 1: - factor = 1.0/(2.0 *(time_error_factor)); - power = 0.5; - break; - case 2: - factor = 1.0/(3.0 * (1.0 + delta_t_nm1 / delta_t_n) - * (time_error_factor)); - power = 0.3333333333333333; - } - factor = pow(factor, power); - if (factor < 0.5) { - if (m_print_flag > 1) { - printf("\t%s: WARNING - Current time step will be chucked\n", yo); - printf("\t\tdue to a time step truncation error failure.\n"); - } - delta_t = - 0.5 * delta_t_n; - } else { - factor = std::min(factor, 1.5); - delta_t = factor * delta_t_n; - } - return delta_t; -} - -double BEulerInt::integrateRJE(double tout, double time_init) -{ - double time_current; - bool weAreNotFinished = true; - m_time_final = tout; - int flag = SUCCESS; - /** - * Initialize the time step number to zero. step will increment so that - * the first time step is number 1 - */ - m_time_step_num = 0; - - - /* - * Do the integration a step at a time - */ - int istep = 0; - int printStep = 0; - bool doPrintSoln = false; - time_current = time_init; - time_n = time_init; - time_nm1 = time_init; - time_nm2 = time_init; - m_func->evalTimeTrackingEqns(time_current, 0.0, &m_y_n[0], &m_ydot_n[0]); - double print_time = getPrintTime(time_current); - if (print_time == time_current) { - m_func->writeSolution(4, time_current, delta_t_n, - istep, &m_y_n[0], &m_ydot_n[0]); - } - /* - * We print out column headers here for the case of - */ - if (m_print_flag == 1) { - print_lvl1_Header(0); - } - /* - * Call a different user routine at the end of each step, - * that will probably print to a file. - */ - m_func->user_out2(0, time_current, 0.0, &m_y_n[0], &m_ydot_n[0]); - - do { - - print_time = getPrintTime(time_current); - if (print_time >= tout) { - print_time = tout; - } - - /************************************************************ - * Step the solution - */ - time_current = step(tout); - istep++; - printStep++; - /***********************************************************/ - if (time_current < 0.0) { - if (time_current == -1234.) { - time_current = 0.0; - } else { - time_current = -time_current; - } - flag = FAILURE; - } - - if (flag != FAILURE) { - bool retn = - m_func->evalStoppingCritera(time_current, delta_t_n, - &m_y_n[0], &m_ydot_n[0]); - if (retn) { - weAreNotFinished = false; - doPrintSoln = true; - } - } - - /* - * determine conditional printing of soln - */ - if (time_current >= print_time) { - doPrintSoln = true; - } - if (m_printSolnStepInterval == printStep) { - doPrintSoln = true; - } - if (m_printSolnFirstSteps > istep) { - doPrintSoln = true; - } - - /* - * Evaluate time integrated quantities that are calculated at the - * end of every successful time step. - */ - if (flag != FAILURE) { - m_func->evalTimeTrackingEqns(time_current, delta_t_n, - &m_y_n[0], &m_ydot_n[0]); - } - - /* - * Call the printout routine. - */ - if (doPrintSoln) { - m_func->writeSolution(1, time_current, delta_t_n, - istep, &m_y_n[0], &m_ydot_n[0]); - printStep = 0; - doPrintSoln = false; - if (m_print_flag == 1) { - print_lvl1_Header(1); - } - } - /* - * Call a different user routine at the end of each step, - * that will probably print to a file. - */ - if (flag == FAILURE) { - m_func->user_out2(-1, time_current, delta_t_n, &m_y_n[0], &m_ydot_n[0]); - } else { - m_func->user_out2(1, time_current, delta_t_n, &m_y_n[0], &m_ydot_n[0]); - } - - } while (time_current < tout && - m_time_step_attempts < m_max_time_step_attempts && - flag == SUCCESS && weAreNotFinished); - - /* - * Check current time against the max solution time. - */ - if (time_current >= tout) { - printf("Simulation completed time integration in %d time steps\n", - m_time_step_num); - printf("Final Time: %e\n\n", time_current); - } else if (m_time_step_attempts >= m_max_time_step_attempts) { - printf("Simulation ran into time step attempt limit in" - "%d time steps\n", - m_time_step_num); - printf("Final Time: %e\n\n", time_current); - } else if (flag == FAILURE) { - printf("ERROR: time stepper failed at time = %g\n", time_current); - } - - /* - * Print out the final results and counters. - */ - print_final(time_n, flag, m_time_step_num, m_numTotalNewtIts, - m_numTotalLinearSolves, m_numTotalConvFails, - m_numTotalTruncFails, m_nfe, m_nJacEval); - - /* - * Call a different user routine at the end of each step, - * that will probably print to a file. - */ - m_func->user_out2(2, time_current, delta_t_n, &m_y_n[0], &m_ydot_n[0]); - - - if (flag != SUCCESS) { - throw BEulerErr(" BEuler error encountered."); - } - return time_current; -} - -double BEulerInt::step(double t_max) -{ - double CJ; - bool step_failed = false; - bool giveUp = false; - bool convFailure = false; - const char* rslt; - double time_error_factor = 0.0; - double normFilter = 0.0; - int numTSFailures = 0; - int bktr_stps = 0; - int nonlinearloglevel = m_print_flag; - int num_newt_its = 0; - int aztec_its = 0; - string comment; - /* - * Increment the time counter - May have to be taken back, - * if time step is found to be faulty. - */ - m_time_step_num++; - - /** - * Loop here until we achieve a successful step or we set the giveUp - * flag indicating that repeated errors have occurred. - */ - do { - m_time_step_attempts++; - comment.clear(); - - /* - * Possibly adjust the delta_t_n value for this time step from the - * recommended delta_t_np1 value determined in the previous step - * due to maximum time step constraints or other occurences, - * known to happen at a given time. - */ - if ((time_n + delta_t_np1) >= t_max) { - delta_t_np1 =t_max - time_n; - } - - if (delta_t_np1 >= delta_t_max) { - delta_t_np1 = delta_t_max; - } - - /* - * Increment the delta_t counters and the time for the current - * time step. - */ - - delta_t_nm2 = delta_t_nm1; - delta_t_nm1 = delta_t_n; - delta_t_n = delta_t_np1; - time_n += delta_t_n; - - /* - * Determine the integration order of the current step. - * - * Special case for start-up of time integration procedure - * First time step = Do a predictor step as we - * have recently added an initial - * ydot input option. And, setting ydot=0 - * is equivalent to not doing a - * predictor step. - * Second step = If 2nd order method, do a first order - * step for this time-step, only. - * - * If 2nd order method with a constant time step, the - * first and second steps are 1/10 the specified step, and - * the third step is 8/10 the specified step. This reduces - * the error asociated with using lower order - * integration on the first two steps. (RCS 11-6-97) - * - * If the previous time step failed for one reason or another, - * do a linear step. It's more robust. - */ - if (m_time_step_num == 1) { - m_order = 1; /* Backward Euler */ - } else if (m_time_step_num == 2) { - m_order = 1; /* Forward/Backward Euler */ - } else if (step_failed) { - m_order = 1; /* Forward/Backward Euler */ - } else if (m_time_step_num > 2) { - m_order = 1; /* Specified - Predictor/Corrector - - not implemented */ - } - - /* - * Print out an initial statement about the step. - */ - if (m_print_flag > 1) { - print_time_step1(m_order, m_time_step_num, time_n, delta_t_n, - delta_t_nm1, step_failed, m_failure_counter); - } - - /* - * Calculate the predicted solution, m_y_pred_n, for the current - * time step. - */ - calc_y_pred(m_order); - - /* - * HKM - Commented this out. I may need it for particles later. - * If Solution bounds checking is turned on, we need to crop the - * predicted solution to make sure bounds are enforced - * - * - * cropNorm = 0.0; - * if (Cur_Realm->Realm_Nonlinear.Constraint_Backtracking_Flag == - * Constraint_Backtrack_Enable) { - * cropNorm = cropPredictor(mesh, x_pred_n, abs_time_error, - * m_reltol); - */ - - /* - * Save the old solution, before overwriting with the new solution - * - use - */ - m_y_nm1 = m_y_n; - - /* - * Use the predicted value as the initial guess for the corrector - * loop, for - * every step other than the first step. - */ - if (m_order > 0) { - m_y_n = m_y_pred_n; - } - - /* - * Save the old time derivative, if necessary, before it is - * overwritten. - * This overwrites ydot_nm1, losing information from the previous time - * step. - */ - m_ydot_nm1 = m_ydot_n; - - /* - * Calculate the new time derivative, ydot_n, that is consistent - * with the - * initial guess for the corrected solution vector. - * - */ - calc_ydot(m_order, &m_y_n[0], &m_ydot_n[0]); - - /* - * Calculate CJ, the coefficient for the Jacobian corresponding to the - * derivative of the residual wrt to the acceleration vector. - */ - if (m_order < 2) { - CJ = 1.0 / delta_t_n; - } else { - CJ = 2.0 / delta_t_n; - } - - /* - * Calculate a new Solution Error Weighting vector - */ - setSolnWeights(); - - /* - * Solve the system of equations at the current time step. - * Note - x_corr_n and x_dot_n are considered to be updated, - * on return from this solution. - */ - int ierror = solve_nonlinear_problem(&m_y_n[0], &m_ydot_n[0], - CJ, time_n, *tdjac_ptr, num_newt_its, - aztec_its, bktr_stps, - nonlinearloglevel); - /* - * Set the appropriate flags if a convergence failure is detected. - */ - if (ierror < 0) { /* Step failed */ - convFailure = true; - step_failed = true; - rslt = "fail"; - m_numTotalConvFails++; - m_failure_counter +=3; - if (m_print_flag > 1) { - printf("\tStep is Rejected, nonlinear problem didn't converge," - "ierror = %d\n", ierror); - } - } else { /* Step succeeded */ - convFailure = false; - step_failed = false; - rslt = "done"; - - /* - * Apply a filter to a new successful step - */ - normFilter = filterNewStep(time_n, &m_y_n[0], &m_ydot_n[0]); - if (normFilter > 1.0) { - convFailure = true; - step_failed = true; - rslt = "filt"; - if (m_print_flag > 1) { - printf("\tStep is Rejected, too large filter adjustment = %g\n", - normFilter); - } - } else if (normFilter > 0.0) { - if (normFilter > 0.3) { - if (m_print_flag > 1) { - printf("\tStep was filtered, norm = %g, next " - "time step adjusted\n", normFilter); - } - } else { - if (m_print_flag > 1) { - printf("\tStep was filtered, norm = %g\n", normFilter); - } - } - } - } - - /* - * Calculate the time step truncation error for the current step. - */ - if (!step_failed) { - time_error_factor = time_error_norm(); - } else { - time_error_factor = 1000.; - } - - /* - * Dynamic time step control- delta_t_n, delta_t_nm1 are set here. - */ - if (step_failed) { - /* - * For convergence failures, decrease the step-size by a factor of - * 4 and try again. - */ - delta_t_np1 = 0.25 * delta_t_n; - } else if (m_method == BEulerVarStep) { - - /* - * If we are doing a predictor/corrector method, and we are - * past a certain number of time steps given by the input file - * then either correct the DeltaT for the next time step or - * - */ - if ((m_order > 0) && - (m_time_step_num > m_numInitialConstantDeltaTSteps)) { - delta_t_np1 = time_step_control(m_order, time_error_factor); - if (normFilter > 0.1) { - if (delta_t_np1 > delta_t_n) { - delta_t_np1 = delta_t_n; - } - } - - /* - * Check for Current time step failing due to violation of - * time step - * truncation bounds. - */ - if (delta_t_np1 < 0.0) { - m_numTotalTruncFails++; - step_failed = true; - delta_t_np1 = -delta_t_np1; - m_failure_counter += 2; - comment += "TIME TRUNC FAILURE"; - rslt = "TRNC"; - } - - /* - * Prevent churning of the time step by not increasing the - * time step, - * if the recent "History" of the time step behavior is still bad - */ - else if (m_failure_counter > 0) { - delta_t_np1 = std::min(delta_t_np1, delta_t_n); - } - } else { - delta_t_np1 = delta_t_n; - } - - /* Decrease time step if a lot of Newton Iterations are - * taken. - * The idea being if more or less Newton iteration are taken - * than the target number of iterations, then adjust the time - * step downwards so that the target number of iterations or lower - * is achieved. This - * should prevent step failure by too many Newton iterations because - * the time step becomes too large. CCO - * hkm -> put in num_new_its min of 3 because the time step - * was being altered even when num_newt_its == 1 - */ - int max_Newton_steps = 10000; - int target_num_iter = 5; - if (num_newt_its > 3000 && !step_failed) { - if (max_Newton_steps != target_num_iter) { - double iter_diff = num_newt_its - target_num_iter; - double iter_adjust_zone = max_Newton_steps - target_num_iter; - double target_time_step = delta_t_n - *(1.0 - iter_diff*fabs(iter_diff)/ - ((2.0*iter_adjust_zone*iter_adjust_zone))); - target_time_step = std::max(0.5*delta_t_n, target_time_step); - if (target_time_step < delta_t_np1) { - printf("\tNext time step will be decreased from %g to %g" - " because of new its restraint\n", - delta_t_np1, target_time_step); - delta_t_np1 = target_time_step; - } - } - } - - - } - - /* - * The final loop in the time stepping algorithm depends on whether the - * current step was a success or not. - */ - if (step_failed) { - /* - * Increment the counter indicating the number of consecutive - * failures - */ - numTSFailures++; - /* - * Print out a statement about the failure of the time step. - */ - if (m_print_flag > 1) { - print_time_fail(convFailure, m_time_step_num, time_n, delta_t_n, - delta_t_np1, time_error_factor); - } else if (m_print_flag == 1) { - print_lvl1_summary(m_time_step_num, time_n, rslt, delta_t_n, - num_newt_its, aztec_its, bktr_stps, - time_error_factor, - comment.c_str()); - } - - /* - * Change time step counters back to the previous step before - * the failed - * time step occurred. - */ - time_n -= delta_t_n; - delta_t_n = delta_t_nm1; - delta_t_nm1 = delta_t_nm2; - - /* - * Replace old solution vector and time derivative solution vector. - */ - m_y_n = m_y_nm1; - m_ydot_n = m_ydot_nm1; - /* - * Decide whether to bail on the whole loop - */ - if (numTSFailures > 35) { - giveUp = true; - } - } - - /* - * Do processing for a successful step. - */ - else { - - /* - * Decrement the number of consequative failure counter. - */ - m_failure_counter = std::max(0, m_failure_counter-1); - - /* - * Print out final results of a successfull time step. - */ - if (m_print_flag > 1) { - print_time_step2(m_time_step_num, m_order, time_n, time_error_factor, - delta_t_n, delta_t_np1); - } else if (m_print_flag == 1) { - print_lvl1_summary(m_time_step_num, time_n, " ", delta_t_n, - num_newt_its, aztec_its, bktr_stps, time_error_factor, - comment.c_str()); - } - - /* - * Output information at the end of every successful time step, if - * requested. - * - * fill in - */ - - - } - } while (step_failed && !giveUp); - - /* - * Send back the overall result of the time step. - */ - if (step_failed) { - if (time_n == 0.0) { - return -1234.0; - } - return -time_n; - } - return time_n; -} - -//----------------------------------------------------------- -// Constants -//----------------------------------------------------------- - -const double DampFactor = 4; -const int NDAMP = 10; - -//----------------------------------------------------------- -// MultiNewton methods -//----------------------------------------------------------- - -double BEulerInt::soln_error_norm(const double* const delta_y, - bool printLargest) -{ - int i; - double sum_norm = 0.0, error; - for (i = 0; i < m_neq; i++) { - error = delta_y[i] / m_ewt[i]; - sum_norm += (error * error); - } - sum_norm = sqrt(sum_norm / m_neq); - if (printLargest) { - const int num_entries = 8; - double dmax1, normContrib; - int j; - vector_int imax(num_entries, -1); - printf("\t\tPrintout of Largest Contributors to norm " - "of value (%g)\n", sum_norm); - printf("\t\t I ysoln deltaY weightY " - "Error_Norm**2\n"); - printf("\t\t "); - writeline('-', 80); - for (int jnum = 0; jnum < num_entries; jnum++) { - dmax1 = -1.0; - for (i = 0; i < m_neq; i++) { - bool used = false; - for (j = 0; j < jnum; j++) { - if (imax[j] == i) { - used = true; - } - } - if (!used) { - error = delta_y[i] / m_ewt[i]; - normContrib = sqrt(error * error); - if (normContrib > dmax1) { - imax[jnum] = i; - dmax1 = normContrib; - } - } - } - i = imax[jnum]; - if (i >= 0) { - printf("\t\t %4d %12.4e %12.4e %12.4e %12.4e\n", - i, m_y_n[i], delta_y[i], m_ewt[i], dmax1); - } - } - printf("\t\t "); - writeline('-', 80); - } - return sum_norm; -} -#ifdef DEBUG_HKM_JAC -SquareMatrix jacBack(); -#endif - -void BEulerInt::doNewtonSolve(double time_curr, double* y_curr, - double* ydot_curr, double* delta_y, - GeneralMatrix& jac, int loglevel) -{ - int irow, jcol; - - m_func->evalResidNJ(time_curr, delta_t_n, y_curr, - ydot_curr, delta_y, Base_ResidEval); - m_nfe++; - int sz = m_func->nEquations(); - for (int n = 0; n < sz; n++) { - delta_y[n] = -delta_y[n]; - } - - - /* - * Column scaling -> We scale the columns of the Jacobian - * by the nominal important change in the solution vector - */ - if (m_colScaling) { - if (!jac.factored()) { - /* - * Go get new scales - */ - setColumnScales(); - - /* - * Scale the new Jacobian - */ - double* jptr = &(*(jac.begin())); - for (jcol = 0; jcol < m_neq; jcol++) { - for (irow = 0; irow < m_neq; irow++) { - *jptr *= m_colScales[jcol]; - jptr++; - } - } - } - } - - if (m_matrixConditioning) { - if (jac.factored()) { - m_func->matrixConditioning(0, sz, delta_y); - } else { - double* jptr = &(*(jac.begin())); - m_func->matrixConditioning(jptr, sz, delta_y); - } - } - - /* - * row sum scaling -> Note, this is an unequivocal success - * at keeping the small numbers well balanced and - * nonnegative. - */ - if (m_rowScaling) { - if (! jac.factored()) { - /* - * Ok, this is ugly. jac.begin() returns an vector iterator - * to the first data location. - * Then &(*()) reverts it to a double *. - */ - double* jptr = &(*(jac.begin())); - for (irow = 0; irow < m_neq; irow++) { - m_rowScales[irow] = 0.0; - } - for (jcol = 0; jcol < m_neq; jcol++) { - for (irow = 0; irow < m_neq; irow++) { - m_rowScales[irow] += fabs(*jptr); - jptr++; - } - } - - jptr = &(*(jac.begin())); - for (jcol = 0; jcol < m_neq; jcol++) { - for (irow = 0; irow < m_neq; irow++) { - *jptr /= m_rowScales[irow]; - jptr++; - } - } - } - for (irow = 0; irow < m_neq; irow++) { - delta_y[irow] /= m_rowScales[irow]; - } - } - -#ifdef DEBUG_HKM_JAC - bool printJacContributions = false; - if (m_time_step_num > 304) { - printJacContributions = false; - } - int focusRow = 10; - int numRows = 2; - double RRow[2]; - bool freshJac = true; - RRow[0] = delta_y[focusRow]; - RRow[1] = delta_y[focusRow+1]; - double Pcutoff = 1.0E-70; - if (!jac.factored()) { - jacBack = jac; - } else { - freshJac = false; - } -#endif - /* - * Solve the system -> This also involves inverting the - * matrix - */ - (void) jac.solve(delta_y); - - - /* - * reverse the column scaling if there was any. - */ - if (m_colScaling) { - for (irow = 0; irow < m_neq; irow++) { - delta_y[irow] *= m_colScales[irow]; - } - } - -#ifdef DEBUG_HKM_JAC - if (printJacContributions) { - for (int iNum = 0; iNum < numRows; iNum++) { - if (iNum > 0) { - focusRow++; - } - double dsum = 0.0; - vector_fp& Jdata = jacBack.data(); - double dRow = Jdata[m_neq * focusRow + focusRow]; - printf("\n Details on delta_Y for row %d \n", focusRow); - printf(" Value before = %15.5e, delta = %15.5e," - "value after = %15.5e\n", y_curr[focusRow], - delta_y[focusRow], - y_curr[focusRow] + delta_y[focusRow]); - if (!freshJac) { - printf(" Old Jacobian\n"); - } - printf(" col delta_y aij " - "contrib \n"); - printf("--------------------------------------------------" - "---------------------------------------------\n"); - printf(" Res(%d) %15.5e %15.5e %15.5e (Res = %g)\n", - focusRow, delta_y[focusRow], - dRow, RRow[iNum] / dRow, RRow[iNum]); - dsum += RRow[iNum] / dRow; - for (int ii = 0; ii < m_neq; ii++) { - if (ii != focusRow) { - double aij = Jdata[m_neq * ii + focusRow]; - double contrib = aij * delta_y[ii] * (-1.0) / dRow; - dsum += contrib; - if (fabs(contrib) > Pcutoff) { - printf("%6d %15.5e %15.5e %15.5e\n", ii, - delta_y[ii] , aij, contrib); - } - } - } - printf("--------------------------------------------------" - "---------------------------------------------\n"); - printf(" %15.5e %15.5e\n", - delta_y[focusRow], dsum); - } - } - -#endif - - m_numTotalLinearSolves++; -} - -double BEulerInt::boundStep(const double* const y, - const double* const step0, int loglevel) -{ - int i, i_lower = -1, ifbd = 0, i_fbd = 0; - double fbound = 1.0, f_lowbounds = 1.0, f_delta_bounds = 1.0; - double ff, y_new, ff_alt; - for (i = 0; i < m_neq; i++) { - y_new = y[i] + step0[i]; - if ((y_new < (-0.01 * m_ewt[i])) && y[i] >= 0.0) { - ff = 0.9 * (y[i] / (y[i] - y_new)); - if (ff < f_lowbounds) { - f_lowbounds = ff; - i_lower = i; - } - } - /* - * Now do a delta bounds - * Increase variables by a factor of 2 only - * decrease variables by a factor of 5 only - */ - ff = 1.0; - if ((fabs(y_new) > 2.0 * fabs(y[i])) && - (fabs(y_new-y[i]) > m_ewt[i])) { - ff = fabs(y[i]/(y_new - y[i])); - ff_alt = fabs(m_ewt[i] / (y_new - y[i])); - ff = std::max(ff, ff_alt); - ifbd = 1; - } - if ((fabs(5.0 * y_new) < fabs(y[i])) && - (fabs(y_new - y[i]) > m_ewt[i])) { - ff = y[i]/(y_new-y[i]) * (1.0 - 5.0)/5.0; - ff_alt = fabs(m_ewt[i] / (y_new - y[i])); - ff = std::max(ff, ff_alt); - ifbd = 0; - } - if (ff < f_delta_bounds) { - f_delta_bounds = ff; - i_fbd = ifbd; - } - f_delta_bounds = std::min(f_delta_bounds, ff); - } - fbound = std::min(f_lowbounds, f_delta_bounds); - /* - * Report on any corrections - */ - if (loglevel > 1) { - if (fbound != 1.0) { - if (f_lowbounds < f_delta_bounds) { - printf("\t\tboundStep: Variable %d causing lower bounds " - "damping of %g\n", - i_lower, f_lowbounds); - } else { - if (ifbd) { - printf("\t\tboundStep: Decrease of Variable %d causing " - "delta damping of %g\n", - i_fbd, f_delta_bounds); - } else { - printf("\t\tboundStep: Increase of variable %d causing" - "delta damping of %g\n", - i_fbd, f_delta_bounds); - } - } - } - } - return fbound; -} - -int BEulerInt::dampStep(double time_curr, const double* y0, - const double* ydot0, const double* step0, - double* y1, double* ydot1, double* step1, - double& s1, GeneralMatrix& jac, - int& loglevel, bool writetitle, - int& num_backtracks) -{ - // Compute the weighted norm of the undamped step size step0 - double s0 = soln_error_norm(step0); - - // Compute the multiplier to keep all components in bounds - // A value of one indicates that there is no limitation - // on the current step size in the nonlinear method due to - // bounds constraints (either negative values of delta - // bounds constraints. - double fbound = boundStep(y0, step0, loglevel); - - // if fbound is very small, then y0 is already close to the - // boundary and step0 points out of the allowed domain. In - // this case, the Newton algorithm fails, so return an error - // condition. - if (fbound < 1.e-10) { - if (loglevel > 1) { - printf("\t\t\tdampStep: At limits.\n"); - } - return -3; - } - - //-------------------------------------------- - // Attempt damped step - //-------------------------------------------- - - // damping coefficient starts at 1.0 - double damp = 1.0; - int j, m; - double ff; - num_backtracks = 0; - for (m = 0; m < NDAMP; m++) { - - ff = fbound*damp; - - // step the solution by the damped step size - /* - * Whenever we update the solution, we must also always - * update the time derivative. - */ - for (j = 0; j < m_neq; j++) { - y1[j] = y0[j] + ff*step0[j]; - } - calc_ydot(m_order, y1, ydot1); - - // compute the next undamped step, step1[], that would result - // if y1[] were accepted. - - doNewtonSolve(time_curr, y1, ydot1, step1, jac, loglevel); - -#ifdef DEBUG_HKM - for (j = 0; j < m_neq; j++) { - checkFinite(step1[j]); - checkFinite(y1[j]); - } -#endif - // compute the weighted norm of step1 - s1 = soln_error_norm(step1); - - // write log information - if (loglevel > 3) { - print_solnDelta_norm_contrib((const double*) step0, - "DeltaSolnTrial", - (const double*) step1, - "DeltaSolnTrialTest", - "dampNewt: Important Entries for " - "Weighted Soln Updates:", - y0, y1, ff, 5); - } - if (loglevel > 1) { - printf("\t\t\tdampNewt: s0 = %g, s1 = %g, fbound = %g," - "damp = %g\n", s0, s1, fbound, damp); - } -#ifdef DEBUG_HKM - if (loglevel > 2) { - if (s1 > 1.00000001 * s0 && s1 > 1.0E-5) { - printf("WARNING: Possible Jacobian Problem " - "-> turning on more debugging for this step!!!\n"); - print_solnDelta_norm_contrib((const double*) step0, - "DeltaSolnTrial", - (const double*) step1, - "DeltaSolnTrialTest", - "dampNewt: Important Entries for " - "Weighted Soln Updates:", - y0, y1, ff, 5); - loglevel = 4; - } - } -#endif - - // if the norm of s1 is less than the norm of s0, then - // accept this damping coefficient. Also accept it if this - // step would result in a converged solution. Otherwise, - // decrease the damping coefficient and try again. - - if (s1 < 1.0E-5 || s1 < s0) { - if (loglevel > 2) { - if (s1 > s0) { - if (s1 > 1.0) { - printf("\t\t\tdampStep: current trial step and damping" - " coefficient accepted because test step < 1\n"); - printf("\t\t\t s1 = %g, s0 = %g\n", s1, s0); - } - } - } - break; - } else { - if (loglevel > 1) { - printf("\t\t\tdampStep: current step rejected: (s1 = %g > " - "s0 = %g)", s1, s0); - if (m < (NDAMP-1)) { - printf(" Decreasing damping factor and retrying"); - } else { - printf(" Giving up!!!"); - } - printf("\n"); - } - } - num_backtracks++; - damp /= DampFactor; - } - - // If a damping coefficient was found, return 1 if the - // solution after stepping by the damped step would represent - // a converged solution, and return 0 otherwise. If no damping - // coefficient could be found, return -2. - if (m < NDAMP) { - if (s1 > 1.0) { - return 0; - } else { - return 1; - } - } else { - if (s1 < 0.5 && (s0 < 0.5)) { - return 1; - } - if (s1 < 1.0) { - return 0; - } - return -2; - } -} - -int BEulerInt::solve_nonlinear_problem(double* const y_comm, - double* const ydot_comm, double CJ, - double time_curr, - GeneralMatrix& jac, - int& num_newt_its, - int& num_linear_solves, - int& num_backtracks, - int loglevel) -{ - int m = 0; - bool forceNewJac = false; - double s1=1.e30; - - vector_fp y_curr(y_comm, y_comm + m_neq); - vector_fp ydot_curr(ydot_comm, ydot_comm + m_neq); - vector_fp stp(m_neq, 0.0); - vector_fp stp1(m_neq, 0.0); - vector_fp y_new(m_neq, 0.0); - vector_fp ydot_new(m_neq, 0.0); - - bool frst = true; - num_newt_its = 0; - num_linear_solves = - m_numTotalLinearSolves; - num_backtracks = 0; - int i_backtracks; - - while (1 > 0) { - - /* - * Increment Newton Solve counter - */ - m_numTotalNewtIts++; - num_newt_its++; - - - if (loglevel > 1) { - printf("\t\tSolve_Nonlinear_Problem: iteration %d:\n", - num_newt_its); - } - - // Check whether the Jacobian should be re-evaluated. - - forceNewJac = true; - - if (forceNewJac) { - if (loglevel > 1) { - printf("\t\t\tGetting a new Jacobian and solving system\n"); - } - beuler_jac(jac, &m_resid[0], time_curr, CJ, &y_curr[0], &ydot_curr[0], - num_newt_its); - } else { - if (loglevel > 1) { - printf("\t\t\tSolving system with old Jacobian\n"); - } - } - - // compute the undamped Newton step - doNewtonSolve(time_curr, &y_curr[0], &ydot_curr[0], &stp[0], jac, loglevel); - - // damp the Newton step - m = dampStep(time_curr, &y_curr[0], &ydot_curr[0], &stp[0], &y_new[0], &ydot_new[0], - &stp1[0], s1, jac, loglevel, frst, i_backtracks); - frst = false; - num_backtracks += i_backtracks; - - /* - * Impose the minimum number of Newton iterations critera - */ - if (num_newt_its < m_min_newt_its) { - if (m == 1) { - m = 0; - } - } - /* - * Impose max Newton iteration - */ - if (num_newt_its > 20) { - m = -1; - if (loglevel > 1) { - printf("\t\t\tDampnewton unsuccessful (max newts exceeded) sfinal = %g\n", s1); - } - } - - if (loglevel > 1) { - if (m == 1) { - printf("\t\t\tDampNewton iteration successful, nonlin " - "converged sfinal = %g\n", s1); - } else if (m == 0) { - printf("\t\t\tDampNewton iteration successful, get new" - "direction, sfinal = %g\n", s1); - } else { - printf("\t\t\tDampnewton unsuccessful sfinal = %g\n", s1); - } - } - - bool m_filterIntermediate = false; - if (m_filterIntermediate) { - if (m == 0) { - (void) filterNewStep(time_n, &y_new[0], &ydot_new[0]); - } - } - // Exchange new for curr solutions - if (m == 0 || m == 1) { - y_curr = y_new; - calc_ydot(m_order, &y_curr[0], &ydot_curr[0]); - } - - // convergence - if (m == 1) { - goto done; - } - - // If dampStep fails, first try a new Jacobian if an old - // one was being used. If it was a new Jacobian, then - // return -1 to signify failure. - else if (m < 0) { - goto done; - } - } - -done: - // Copy into the return vectors - copy(y_curr.begin(), y_curr.end(), y_comm); - copy(ydot_curr.begin(), ydot_curr.end(), ydot_comm); - // Increment counters - num_linear_solves += m_numTotalLinearSolves; - - double time_elapsed = 0.0; - if (loglevel > 1) { - if (m == 1) { - printf("\t\tNonlinear problem solved successfully in " - "%d its, time elapsed = %g sec\n", - num_newt_its, time_elapsed); - } - } - return m; -} - -void BEulerInt::print_solnDelta_norm_contrib(const double* const solnDelta0, - const char* const s0, - const double* const solnDelta1, - const char* const s1, - const char* const title, - const double* const y0, - const double* const y1, - double damp, - int num_entries) -{ - int i, j, jnum; - bool used; - double dmax0, dmax1, error, rel_norm; - printf("\t\t%s currentDamp = %g\n", title, damp); - printf("\t\t I ysoln %10s ysolnTrial " - "%10s weight relSoln0 relSoln1\n", s0, s1); - vector_int imax(num_entries, -1); - printf("\t\t "); - writeline('-', 90); - for (jnum = 0; jnum < num_entries; jnum++) { - dmax1 = -1.0; - for (i = 0; i < m_neq; i++) { - used = false; - for (j = 0; j < jnum; j++) { - if (imax[j] == i) { - used = true; - } - } - if (!used) { - error = solnDelta0[i] / m_ewt[i]; - rel_norm = sqrt(error * error); - error = solnDelta1[i] / m_ewt[i]; - rel_norm += sqrt(error * error); - if (rel_norm > dmax1) { - imax[jnum] = i; - dmax1 = rel_norm; - } - } - } - if (imax[jnum] >= 0) { - i = imax[jnum]; - error = solnDelta0[i] / m_ewt[i]; - dmax0 = sqrt(error * error); - error = solnDelta1[i] / m_ewt[i]; - dmax1 = sqrt(error * error); - printf("\t\t %4d %12.4e %12.4e %12.4e %12.4e " - "%12.4e %12.4e %12.4e\n", - i, y0[i], solnDelta0[i], y1[i], - solnDelta1[i], m_ewt[i], dmax0, dmax1); - } - } - printf("\t\t "); - writeline('-', 90); -} - -} // End of namespace Cantera diff --git a/src/numerics/BandMatrix.cpp b/src/numerics/BandMatrix.cpp index 6f52c6255..7b00fdc8e 100644 --- a/src/numerics/BandMatrix.cpp +++ b/src/numerics/BandMatrix.cpp @@ -423,15 +423,6 @@ doublereal* const* BandMatrix::colPts() return &(m_colPtrs[0]); } -void BandMatrix::copyData(const GeneralMatrix& y) -{ - warn_deprecated("BandMatrix::copyData", "To be removed after Cantera 2.2."); - m_factored = false; - size_t n = sizeof(doublereal) * m_n * (2 *m_kl + m_ku + 1); - GeneralMatrix* yyPtr = const_cast(&y); - (void) memcpy(DATA_PTR(data), yyPtr->ptrColumn(0), n); -} - void BandMatrix::useFactorAlgorithm(int fAlgorithm) { // useQR_ = fAlgorithm; diff --git a/src/numerics/NonlinearSolver.cpp b/src/numerics/NonlinearSolver.cpp deleted file mode 100644 index b83b86959..000000000 --- a/src/numerics/NonlinearSolver.cpp +++ /dev/null @@ -1,3647 +0,0 @@ -/** - * @file NonlinearSolver.cpp Damped Newton solver for 0D and 1D problems - */ - -/* - * Copyright 2004 Sandia Corporation. Under the terms of Contract - * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government - * retains certain rights in this software. - * See file License.txt for licensing information. - */ - -#include "cantera/numerics/NonlinearSolver.h" -#include "cantera/numerics/ctlapack.h" - -#include "cantera/base/clockWC.h" -#include "cantera/base/stringUtils.h" - -#include - -using namespace std; - -namespace Cantera -{ - -//----------------------------------------------------------- -// Constants -//----------------------------------------------------------- -//! Dampfactor is the factor by which the damping factor is reduced by when a -//! reduction in step length is warranted -const doublereal DampFactor = 4.0; -//! Number of damping steps that are carried out before the solution is deemed -//! a failure -const int NDAMP = 7; - -bool NonlinearSolver::s_TurnOffTiming(false); - -#ifdef DEBUG_NUMJAC -bool NonlinearSolver::s_print_NumJac(true); -#else -bool NonlinearSolver::s_print_NumJac(false); -#endif - -// Turn off printing of dogleg information -bool NonlinearSolver::s_print_DogLeg(false); - -// Turn off solving the system twice and comparing the answer. -/* - * Turn this on if you want to compare the Hessian and Newton solve results. - */ -bool NonlinearSolver::s_doBothSolvesAndCompare(false); - -// This toggle turns off the use of the Hessian when it is warranted by the condition number. -/* - * This is a debugging option. - */ -bool NonlinearSolver::s_alwaysAssumeNewtonGood(false); - -NonlinearSolver::NonlinearSolver(ResidJacEval* func) : - m_func(func), - solnType_(NSOLN_TYPE_STEADY_STATE), - neq_(0), - m_manualDeltaStepSet(0), - m_normResid_0(0.0), - m_normResid_Bound(0.0), - m_normResid_1(0.0), - m_normDeltaSoln_Newton(0.0), - m_normDeltaSoln_CP(0.0), - m_normResidTrial(0.0), - m_resid_scaled(false), - m_dampBound(1.0), - m_dampRes(1.0), - delta_t_n(-1.0), - m_nfe(0), - m_colScaling(0), - m_rowScaling(0), - m_numTotalLinearSolves(0), - m_numTotalNewtIts(0), - m_min_newt_its(0), - maxNewtIts_(100), - m_jacFormMethod(NSOLN_JAC_NUM), - m_nJacEval(0), - time_n(0.0), - m_matrixConditioning(0), - m_order(1), - rtol_(1.0E-3), - atolBase_(1.0E-10), - userResidRtol_(1.0E-3), - checkUserResidualTols_(0), - m_print_flag(0), - m_ScaleSolnNormToResNorm(0.001), - jacCopyPtr_(0), - HessianPtr_(0), - residNorm2Cauchy_(0.0), - dogLegID_(0), - dogLegAlpha_(1.0), - RJd_norm_(0.0), - lambdaStar_(0.0), - Jd_(0), - deltaX_trust_(0), - norm_deltaX_trust_(0.0), - trustDelta_(1.0), - trustRegionInitializationMethod_(2), - trustRegionInitializationFactor_(1.0), - Nuu_(0.0), - dist_R0_(0.0), - dist_R1_(0.0), - dist_R2_(0.0), - dist_Total_(0.0), - JdJd_norm_(0.0), - normTrust_Newton_(0.0), - normTrust_CP_(0.0), - doDogLeg_(0), - doAffineSolve_(0) , - CurrentTrustFactor_(1.0), - NextTrustFactor_(1.0), - ResidWtsReevaluated_(false), - ResidDecreaseSDExp_(0.0), - ResidDecreaseSD_(0.0), - ResidDecreaseNewtExp_(0.0), - ResidDecreaseNewt_(0.0) -{ - warn_deprecated("class NonlinearSolver", "To be removed after Cantera 2.2."); - neq_ = m_func->nEquations(); - - m_ewt.resize(neq_, rtol_); - m_deltaStepMinimum.resize(neq_, 0.001); - m_deltaStepMaximum.resize(neq_, 1.0E10); - m_y_n_curr.resize(neq_, 0.0); - m_ydot_n_curr.resize(neq_, 0.0); - m_y_nm1.resize(neq_, 0.0); - m_ydot_nm1.resize(neq_, 0.0); - m_y_n_trial.resize(neq_, 0.0); - m_ydot_trial.resize(neq_, 0.0); - m_colScales.resize(neq_, 1.0); - m_rowScales.resize(neq_, 1.0); - m_rowWtScales.resize(neq_, 1.0); - m_resid.resize(neq_, 0.0); - m_wksp.resize(neq_, 0.0); - m_wksp_2.resize(neq_, 0.0); - m_residWts.resize(neq_, 0.0); - atolk_.resize(neq_, atolBase_); - deltaX_Newton_.resize(neq_, 0.0); - m_step_1.resize(neq_, 0.0); - m_y_n_trial.resize(neq_, 0.0); - doublereal hb = std::numeric_limits::max(); - m_y_high_bounds.resize(neq_, hb); - m_y_low_bounds.resize(neq_, -hb); - - for (size_t i = 0; i < neq_; i++) { - atolk_[i] = atolBase_; - m_ewt[i] = atolk_[i]; - } - - deltaX_CP_.resize(neq_, 0.0); - Jd_.resize(neq_, 0.0); - deltaX_trust_.resize(neq_, 1.0); -} - -NonlinearSolver::NonlinearSolver(const NonlinearSolver& right) : - m_func(right.m_func), - solnType_(NSOLN_TYPE_STEADY_STATE), - neq_(0), - m_manualDeltaStepSet(0), - m_normResid_0(0.0), - m_normResid_Bound(0.0), - m_normResid_1(0.0), - m_normDeltaSoln_Newton(0.0), - m_normDeltaSoln_CP(0.0), - m_normResidTrial(0.0), - m_resid_scaled(false), - m_dampBound(1.0), - m_dampRes(1.0), - delta_t_n(-1.0), - m_nfe(0), - m_colScaling(0), - m_rowScaling(0), - m_numTotalLinearSolves(0), - m_numTotalNewtIts(0), - m_min_newt_its(0), - maxNewtIts_(100), - m_jacFormMethod(NSOLN_JAC_NUM), - m_nJacEval(0), - time_n(0.0), - m_matrixConditioning(0), - m_order(1), - rtol_(1.0E-3), - atolBase_(1.0E-10), - userResidRtol_(1.0E-3), - checkUserResidualTols_(0), - m_print_flag(0), - m_ScaleSolnNormToResNorm(0.001), - jacCopyPtr_(0), - HessianPtr_(0), - residNorm2Cauchy_(0.0), - dogLegID_(0), - dogLegAlpha_(1.0), - RJd_norm_(0.0), - lambdaStar_(0.0), - norm_deltaX_trust_(0.0), - trustDelta_(1.0), - trustRegionInitializationMethod_(2), - trustRegionInitializationFactor_(1.0), - Nuu_(0.0), - dist_R0_(0.0), - dist_R1_(0.0), - dist_R2_(0.0), - dist_Total_(0.0), - JdJd_norm_(0.0), - normTrust_Newton_(0.0), - normTrust_CP_(0.0), - doDogLeg_(0), - doAffineSolve_(0), - CurrentTrustFactor_(1.0), - NextTrustFactor_(1.0), - ResidWtsReevaluated_(false), - ResidDecreaseSDExp_(0.0), - ResidDecreaseSD_(0.0), - ResidDecreaseNewtExp_(0.0), - ResidDecreaseNewt_(0.0) -{ - *this =operator=(right); -} - -NonlinearSolver::~NonlinearSolver() -{ - delete jacCopyPtr_; - delete HessianPtr_; -} - -NonlinearSolver& NonlinearSolver::operator=(const NonlinearSolver& right) -{ - if (this == &right) { - return *this; - } - // rely on the ResidJacEval duplMyselfAsresidJacEval() function to - // create a deep copy - m_func = right.m_func->duplMyselfAsResidJacEval(); - - solnType_ = right.solnType_; - neq_ = right.neq_; - m_ewt = right.m_ewt; - m_manualDeltaStepSet = right.m_manualDeltaStepSet; - m_deltaStepMinimum = right.m_deltaStepMinimum; - m_y_n_curr = right.m_y_n_curr; - m_ydot_n_curr = right.m_ydot_n_curr; - m_y_nm1 = right.m_y_nm1; - m_ydot_nm1 = right.m_ydot_nm1; - m_y_n_trial = right.m_y_n_trial; - m_ydot_trial = right.m_ydot_trial; - m_step_1 = right.m_step_1; - m_colScales = right.m_colScales; - m_rowScales = right.m_rowScales; - m_rowWtScales = right.m_rowWtScales; - m_resid = right.m_resid; - m_wksp = right.m_wksp; - m_wksp_2 = right.m_wksp_2; - m_residWts = right.m_residWts; - m_normResid_0 = right.m_normResid_0; - m_normResid_Bound = right.m_normResid_Bound; - m_normResid_1 = right.m_normResid_1; - m_normDeltaSoln_Newton = right.m_normDeltaSoln_Newton; - m_normDeltaSoln_CP = right.m_normDeltaSoln_CP; - m_normResidTrial = right.m_normResidTrial; - m_resid_scaled = right.m_resid_scaled; - m_y_high_bounds = right.m_y_high_bounds; - m_y_low_bounds = right.m_y_low_bounds; - m_dampBound = right.m_dampBound; - m_dampRes = right.m_dampRes; - delta_t_n = right.delta_t_n; - m_nfe = right.m_nfe; - m_colScaling = right.m_colScaling; - m_rowScaling = right.m_rowScaling; - m_numTotalLinearSolves = right.m_numTotalLinearSolves; - m_numTotalNewtIts = right.m_numTotalNewtIts; - m_min_newt_its = right.m_min_newt_its; - maxNewtIts_ = right.maxNewtIts_; - m_jacFormMethod = right.m_jacFormMethod; - m_nJacEval = right.m_nJacEval; - time_n = right.time_n; - m_matrixConditioning = right.m_matrixConditioning; - m_order = right.m_order; - rtol_ = right.rtol_; - atolBase_ = right.atolBase_; - atolk_ = right.atolk_; - userResidAtol_ = right.userResidAtol_; - userResidRtol_ = right.userResidRtol_; - checkUserResidualTols_ = right.checkUserResidualTols_; - m_print_flag = right.m_print_flag; - m_ScaleSolnNormToResNorm = right.m_ScaleSolnNormToResNorm; - - delete jacCopyPtr_; - jacCopyPtr_ = (right.jacCopyPtr_)->duplMyselfAsGeneralMatrix(); - delete HessianPtr_; - HessianPtr_ = (right.HessianPtr_)->duplMyselfAsGeneralMatrix(); - - deltaX_CP_ = right.deltaX_CP_; - deltaX_Newton_ = right.deltaX_Newton_; - residNorm2Cauchy_ = right.residNorm2Cauchy_; - dogLegID_ = right.dogLegID_; - dogLegAlpha_ = right.dogLegAlpha_; - RJd_norm_ = right.RJd_norm_; - lambdaStar_ = right.lambdaStar_; - Jd_ = right.Jd_; - deltaX_trust_ = right.deltaX_trust_; - norm_deltaX_trust_ = right.norm_deltaX_trust_; - trustDelta_ = right.trustDelta_; - trustRegionInitializationMethod_ = right.trustRegionInitializationMethod_; - trustRegionInitializationFactor_ = right.trustRegionInitializationFactor_; - Nuu_ = right.Nuu_; - dist_R0_ = right.dist_R0_; - dist_R1_ = right.dist_R1_; - dist_R2_ = right.dist_R2_; - dist_Total_ = right.dist_Total_; - JdJd_norm_ = right.JdJd_norm_; - normTrust_Newton_ = right.normTrust_Newton_; - normTrust_CP_ = right.normTrust_CP_; - doDogLeg_ = right.doDogLeg_; - doAffineSolve_ = right.doAffineSolve_; - CurrentTrustFactor_ = right.CurrentTrustFactor_; - NextTrustFactor_ = right.NextTrustFactor_; - - ResidWtsReevaluated_ = right.ResidWtsReevaluated_; - ResidDecreaseSDExp_ = right.ResidDecreaseSDExp_; - ResidDecreaseSD_ = right.ResidDecreaseSD_; - ResidDecreaseNewtExp_ = right.ResidDecreaseNewtExp_; - ResidDecreaseNewt_ = right.ResidDecreaseNewt_; - - return *this; -} - -void NonlinearSolver::createSolnWeights(const doublereal* const y) -{ - for (size_t i = 0; i < neq_; i++) { - m_ewt[i] = rtol_ * fabs(y[i]) + atolk_[i]; - if (DEBUG_MODE_ENABLED && m_ewt[i] <= 0.0) { - throw CanteraError(" NonlinearSolver::createSolnWeights()", "ewts <= 0.0"); - } - } -} - -void NonlinearSolver::setBoundsConstraints(const doublereal* const y_low_bounds, - const doublereal* const y_high_bounds) -{ - for (size_t i = 0; i < neq_; i++) { - m_y_low_bounds[i] = y_low_bounds[i]; - m_y_high_bounds[i] = y_high_bounds[i]; - } -} - -void NonlinearSolver::setSolverScheme(int doDogLeg, int doAffineSolve) -{ - doDogLeg_ = doDogLeg; - doAffineSolve_ = doAffineSolve; -} - -std::vector & NonlinearSolver::lowBoundsConstraintVector() -{ - return m_y_low_bounds; -} - -std::vector & NonlinearSolver::highBoundsConstraintVector() -{ - return m_y_high_bounds; -} - -doublereal NonlinearSolver::solnErrorNorm(const doublereal* const delta_y, const char* title, int printLargest, - const doublereal dampFactor) const -{ - doublereal sum_norm = 0.0, error; - for (size_t i = 0; i < neq_; i++) { - error = delta_y[i] / m_ewt[i]; - sum_norm += (error * error); - } - sum_norm = sqrt(sum_norm / neq_); - if (printLargest) { - if ((printLargest == 1) || (m_print_flag >= 4 && m_print_flag <= 5)) { - - printf("\t\t solnErrorNorm(): "); - if (title) { - printf("%s", title); - } else { - printf(" Delta soln norm "); - } - printf(" = %-11.4E\n", sum_norm); - } else if (m_print_flag >= 6) { - - - - const int num_entries = printLargest; - printf("\t\t "); - writeline('-', 90); - printf("\t\t solnErrorNorm(): "); - if (title) { - printf("%s", title); - } else { - printf(" Delta soln norm "); - } - printf(" = %-11.4E\n", sum_norm); - - doublereal dmax1, normContrib; - int j; - std::vector imax(num_entries, npos); - printf("\t\t Printout of Largest Contributors: (damp = %g)\n", dampFactor); - printf("\t\t I weightdeltaY/sqtN| deltaY " - "ysolnOld ysolnNew Soln_Weights\n"); - printf("\t\t "); - writeline('-', 88); - - for (int jnum = 0; jnum < num_entries; jnum++) { - dmax1 = -1.0; - for (size_t i = 0; i < neq_; i++) { - bool used = false; - for (j = 0; j < jnum; j++) { - if (imax[j] == i) { - used = true; - } - } - if (!used) { - error = delta_y[i] / m_ewt[i]; - normContrib = sqrt(error * error); - if (normContrib > dmax1) { - imax[jnum] = i; - dmax1 = normContrib; - } - } - } - size_t i = imax[jnum]; - if (i != npos) { - error = delta_y[i] / m_ewt[i]; - normContrib = sqrt(error * error); - printf("\t\t %4s %12.4e | %12.4e %12.4e %12.4e %12.4e\n", int2str(i).c_str(), normContrib/sqrt((double)neq_), - delta_y[i], m_y_n_curr[i], m_y_n_curr[i] + dampFactor * delta_y[i], m_ewt[i]); - - } - } - printf("\t\t "); - writeline('-', 90); - } - } - return sum_norm; -} - -doublereal NonlinearSolver::residErrorNorm(const doublereal* const resid, const char* title, const int printLargest, - const doublereal* const y) const -{ - doublereal sum_norm = 0.0, error; - - for (size_t i = 0; i < neq_; i++) { - if (DEBUG_MODE_ENABLED) { - checkFinite(resid[i]); - } - error = resid[i] / m_residWts[i]; - if (DEBUG_MODE_ENABLED) { - checkFinite(error); - } - sum_norm += (error * error); - } - sum_norm = sqrt(sum_norm / neq_); - if (DEBUG_MODE_ENABLED) { - checkFinite(sum_norm); - } - if (printLargest) { - const int num_entries = printLargest; - doublereal dmax1, normContrib; - int j; - std::vector imax(num_entries, npos); - - if (m_print_flag >= 4 && m_print_flag <= 5) { - printf("\t\t residErrorNorm():"); - if (title) { - printf(" %s ", title); - } else { - printf(" residual L2 norm "); - } - printf("= %12.4E\n", sum_norm); - } - if (m_print_flag >= 6) { - printf("\t\t "); - writeline('-', 90); - printf("\t\t residErrorNorm(): "); - if (title) { - printf(" %s ", title); - } else { - printf(" residual L2 norm "); - } - printf("= %12.4E\n", sum_norm); - printf("\t\t Printout of Largest Contributors to norm:\n"); - printf("\t\t I |Resid/ResWt| UnsclRes ResWt | y_curr\n"); - printf("\t\t "); - writeline('-', 88); - for (int jnum = 0; jnum < num_entries; jnum++) { - dmax1 = -1.0; - for (size_t i = 0; i < neq_; i++) { - bool used = false; - for (j = 0; j < jnum; j++) { - if (imax[j] == i) { - used = true; - } - } - if (!used) { - error = resid[i] / m_residWts[i]; - normContrib = sqrt(error * error); - if (normContrib > dmax1) { - imax[jnum] = i; - dmax1 = normContrib; - } - } - } - size_t i = imax[jnum]; - if (i != npos) { - error = resid[i] / m_residWts[i]; - normContrib = sqrt(error * error); - printf("\t\t %4s %12.4e %12.4e %12.4e | %12.4e\n", int2str(i).c_str(), normContrib, resid[i], m_residWts[i], y[i]); - } - } - - printf("\t\t "); - writeline('-', 90); - } - } - return sum_norm; -} - -void NonlinearSolver::setColumnScaling(bool useColScaling, const double* const scaleFactors) -{ - if (useColScaling) { - if (scaleFactors) { - m_colScaling = 2; - for (size_t i = 0; i < neq_; i++) { - m_colScales[i] = scaleFactors[i]; - if (m_colScales[i] <= 1.0E-200) { - throw CanteraError("NonlinearSolver::setColumnScaling() ERROR", "Bad column scale factor"); - } - } - } else { - m_colScaling = 1; - } - } else { - m_colScaling = 0; - } -} - -void NonlinearSolver::setRowScaling(bool useRowScaling) -{ - m_rowScaling = useRowScaling; -} - -void NonlinearSolver::calcColumnScales() -{ - if (m_colScaling == 1) { - for (size_t i = 0; i < neq_; i++) { - m_colScales[i] = m_ewt[i]; - } - } else { - for (size_t i = 0; i < neq_; i++) { - m_colScales[i] = 1.0; - } - } - if (m_colScaling) { - m_func->calcSolnScales(time_n, DATA_PTR(m_y_n_curr), DATA_PTR(m_y_nm1), DATA_PTR(m_colScales)); - } -} - -int NonlinearSolver::doResidualCalc(const doublereal time_curr, const int typeCalc, const doublereal* const y_curr, - const doublereal* const ydot_curr, const ResidEval_Type_Enum evalType) const -{ - int retn = m_func->evalResidNJ(time_curr, delta_t_n, y_curr, ydot_curr, DATA_PTR(m_resid), evalType); - m_nfe++; - m_resid_scaled = false; - return retn; -} - -void NonlinearSolver::scaleMatrix(GeneralMatrix& jac, doublereal* const y_comm, doublereal* const ydot_comm, - doublereal time_curr, int num_newt_its) -{ - int irow, jcol; - size_t ivec[2]; - jac.nRowsAndStruct(ivec); - double* colP_j; - - /* - * Column scaling -> We scale the columns of the Jacobian - * by the nominal important change in the solution vector - */ - if (m_colScaling) { - if (!jac.factored()) { - if (jac.matrixType_ == 0) { - /* - * Go get new scales -> Took this out of this inner loop. - * Needs to be done at a larger scale. - */ - // setColumnScales(); - - /* - * Scale the new Jacobian - */ - doublereal* jptr = &(*(jac.begin())); - for (jcol = 0; jcol < (int) neq_; jcol++) { - for (irow = 0; irow < (int) neq_; irow++) { - *jptr *= m_colScales[jcol]; - jptr++; - } - } - } else if (jac.matrixType_ == 1) { - int kl = static_cast(ivec[0]); - int ku = static_cast(ivec[1]); - for (jcol = 0; jcol < (int) neq_; jcol++) { - colP_j = (doublereal*) jac.ptrColumn(jcol); - for (irow = jcol - ku; irow <= jcol + kl; irow++) { - if (irow >= 0 && irow < (int) neq_) { - colP_j[kl + ku + irow - jcol] *= m_colScales[jcol]; - } - } - } - } - } - } - /* - * row sum scaling -> Note, this is an unequivocal success - * at keeping the small numbers well balanced and nonnegative. - */ - if (! jac.factored()) { - /* - * Ok, this is ugly. jac.begin() returns an vector iterator - * to the first data location. - * Then &(*()) reverts it to a doublereal *. - */ - doublereal* jptr = &(*(jac.begin())); - for (irow = 0; irow < (int) neq_; irow++) { - m_rowScales[irow] = 0.0; - m_rowWtScales[irow] = 0.0; - } - if (jac.matrixType_ == 0) { - for (jcol = 0; jcol < (int) neq_; jcol++) { - for (irow = 0; irow < (int) neq_; irow++) { - if (m_rowScaling) { - m_rowScales[irow] += fabs(*jptr); - } - if (m_colScaling) { - // This is needed in order to mitgate the change in J_ij carried out just above this loop. - // Alternatively, we could move this loop up to the top - m_rowWtScales[irow] += fabs(*jptr) * m_ewt[jcol] / m_colScales[jcol]; - } else { - m_rowWtScales[irow] += fabs(*jptr) * m_ewt[jcol]; - } - if (DEBUG_MODE_ENABLED) { - checkFinite(m_rowWtScales[irow]); - } - jptr++; - } - } - } else if (jac.matrixType_ == 1) { - int kl = static_cast(ivec[0]); - int ku = static_cast(ivec[1]); - for (jcol = 0; jcol < (int) neq_; jcol++) { - colP_j = (doublereal*) jac.ptrColumn(jcol); - for (irow = jcol - ku; irow <= jcol + kl; irow++) { - if (irow >= 0 && irow < (int) neq_) { - double vv = fabs(colP_j[kl + ku + irow - jcol]); - if (m_rowScaling) { - m_rowScales[irow] += vv; - } - if (m_colScaling) { - // This is needed in order to mitgate the change in J_ij carried out just above this loop. - // Alternatively, we could move this loop up to the top - m_rowWtScales[irow] += vv * m_ewt[jcol] / m_colScales[jcol]; - } else { - m_rowWtScales[irow] += vv * m_ewt[jcol]; - } - if (DEBUG_MODE_ENABLED) { - checkFinite(m_rowWtScales[irow]); - } - } - } - } - } - if (m_rowScaling) { - for (irow = 0; irow < (int) neq_; irow++) { - m_rowScales[irow] = 1.0/m_rowScales[irow]; - } - } else { - for (irow = 0; irow < (int) neq_; irow++) { - m_rowScales[irow] = 1.0; - } - } - // What we have defined is a maximum value that the residual can be and still pass. - // This isn't sufficient. - - if (m_rowScaling) { - if (jac.matrixType_ == 0) { - jptr = &(*(jac.begin())); - for (jcol = 0; jcol < (int) neq_; jcol++) { - for (irow = 0; irow < (int) neq_; irow++) { - *jptr *= m_rowScales[irow]; - jptr++; - } - } - } else if (jac.matrixType_ == 1) { - int kl = static_cast(ivec[0]); - int ku = static_cast(ivec[1]); - for (jcol = 0; jcol < (int) neq_; jcol++) { - colP_j = (doublereal*) jac.ptrColumn(jcol); - for (irow = jcol - ku; irow <= jcol + kl; irow++) { - if (irow >= 0 && irow < (int) neq_) { - colP_j[kl + ku + irow - jcol] *= m_rowScales[irow]; - } - } - } - } - } - - if (num_newt_its % 5 == 1) { - computeResidWts(); - } - - } -} - -void NonlinearSolver::calcSolnToResNormVector() -{ - if (! jacCopyPtr_->factored()) { - - if (checkUserResidualTols_ != 1) { - doublereal sum = 0.0; - for (size_t irow = 0; irow < neq_; irow++) { - m_residWts[irow] = m_rowWtScales[irow] / neq_; - sum += m_residWts[irow]; - } - sum /= neq_; - for (size_t irow = 0; irow < neq_; irow++) { - m_residWts[irow] = (m_residWts[irow] + atolBase_ * atolBase_ * sum); - } - if (checkUserResidualTols_ == 2) { - for (size_t irow = 0; irow < neq_; irow++) { - m_residWts[irow] = std::min(m_residWts[irow], userResidAtol_[irow] + userResidRtol_ * m_rowWtScales[irow] / neq_); - } - } - } else { - for (size_t irow = 0; irow < neq_; irow++) { - m_residWts[irow] = userResidAtol_[irow] + userResidRtol_ * m_rowWtScales[irow] / neq_; - } - } - - - for (size_t irow = 0; irow < neq_; irow++) { - m_wksp[irow] = 0.0; - } - doublereal* jptr = &((*jacCopyPtr_)(0,0)); - for (size_t jcol = 0; jcol < neq_; jcol++) { - for (size_t irow = 0; irow < neq_; irow++) { - m_wksp[irow] += (*jptr) * m_ewt[jcol]; - jptr++; - } - } - doublereal resNormOld = 0.0; - doublereal error; - - for (size_t irow = 0; irow < neq_; irow++) { - error = m_wksp[irow] / m_residWts[irow]; - resNormOld += error * error; - } - resNormOld = sqrt(resNormOld / neq_); - - if (resNormOld > 0.0) { - m_ScaleSolnNormToResNorm = resNormOld; - } - m_ScaleSolnNormToResNorm = std::max(m_ScaleSolnNormToResNorm, 1e-8); - - // Recalculate the residual weights now that we know the value of m_ScaleSolnNormToResNorm - computeResidWts(); - } else { - throw CanteraError("NonlinearSolver::calcSolnToResNormVector()" , "Logic error"); - } -} - -int NonlinearSolver::doNewtonSolve(const doublereal time_curr, const doublereal* const y_curr, - const doublereal* const ydot_curr, doublereal* const delta_y, - GeneralMatrix& jac) -{ - // multiply the residual by -1 - if (m_rowScaling && !m_resid_scaled) { - for (size_t n = 0; n < neq_; n++) { - delta_y[n] = -m_rowScales[n] * m_resid[n]; - } - m_resid_scaled = true; - } else { - for (size_t n = 0; n < neq_; n++) { - delta_y[n] = -m_resid[n]; - } - } - - - - /* - * Solve the system -> This also involves inverting the - * matrix - */ - int info = jac.solve(DATA_PTR(delta_y)); - - - /* - * reverse the column scaling if there was any. - */ - if (m_colScaling) { - for (size_t irow = 0; irow < neq_; irow++) { - delta_y[irow] = delta_y[irow] * m_colScales[irow]; - } - } - -#ifdef DEBUG_JAC - if (printJacContributions) { - for (size_t iNum = 0; iNum < numRows; iNum++) { - if (iNum > 0) { - focusRow++; - } - doublereal dsum = 0.0; - vector_fp& Jdata = jacBack.data(); - doublereal dRow = Jdata[neq_ * focusRow + focusRow]; - printf("\n Details on delta_Y for row %d \n", focusRow); - printf(" Value before = %15.5e, delta = %15.5e," - "value after = %15.5e\n", y_curr[focusRow], - delta_y[focusRow], y_curr[focusRow] + delta_y[focusRow]); - if (!freshJac) { - printf(" Old Jacobian\n"); - } - printf(" col delta_y aij " - "contrib \n"); - printf("--------------------------------------------------" - "---------------------------------------------\n"); - printf(" Res(%d) %15.5e %15.5e %15.5e (Res = %g)\n", - focusRow, delta_y[focusRow], - dRow, RRow[iNum] / dRow, RRow[iNum]); - dsum += RRow[iNum] / dRow; - for (size_t ii = 0; ii < neq_; ii++) { - if (ii != focusRow) { - doublereal aij = Jdata[neq_ * ii + focusRow]; - doublereal contrib = aij * delta_y[ii] * (-1.0) / dRow; - dsum += contrib; - if (fabs(contrib) > Pcutoff) { - printf("%6d %15.5e %15.5e %15.5e\n", ii, - delta_y[ii] , aij, contrib); - } - } - } - printf("--------------------------------------------------" - "---------------------------------------------\n"); - printf(" %15.5e %15.5e\n", - delta_y[focusRow], dsum); - } - } - -#endif - - m_numTotalLinearSolves++; - m_numLocalLinearSolves++; - return info; -} - -int NonlinearSolver::doAffineNewtonSolve(const doublereal* const y_curr, const doublereal* const ydot_curr, - doublereal* const delta_y, GeneralMatrix& jac) -{ - /* - * Notes on banded Hessian solve: The matrix for jT j has a larger band - * width. Both the top and bottom band widths are doubled, going from KU - * to KU+KL and KL to KU+KL in size. This is not an impossible increase - * in cost, but has to be considered. - */ - bool newtonGood = true; - // We can default to QR here ( or not ) - jac.useFactorAlgorithm(1); - int useQR = jac.factorAlgorithm(); - // multiply the residual by -1 - // Scale the residual if there is row scaling. Note, the matrix has already been scaled - if (m_rowScaling && !m_resid_scaled) { - for (size_t n = 0; n < neq_; n++) { - delta_y[n] = -m_rowScales[n] * m_resid[n]; - } - m_resid_scaled = true; - } else { - for (size_t n = 0; n < neq_; n++) { - delta_y[n] = -m_resid[n]; - } - } - - // Factor the matrix using a standard Newton solve - m_conditionNumber = 1.0E300; - int info = 0; - if (!jac.factored()) { - if (useQR) { - info = jac.factorQR(); - } else { - info = jac.factor(); - } - } - /* - * Find the condition number of the matrix - * If we have failed to factor, we will fall back to calculating and factoring a modified Hessian - */ - if (info == 0) { - doublereal rcond = 0.0; - if (useQR) { - rcond = jac.rcondQR(); - } else { - doublereal a1norm = jac.oneNorm(); - rcond = jac.rcond(a1norm); - } - if (rcond > 0.0) { - m_conditionNumber = 1.0 / rcond; - } - } else { - m_conditionNumber = 1.0E300; - newtonGood = false; - if (m_print_flag >= 1) { - printf("\t\t doAffineNewtonSolve: "); - if (useQR) { - printf("factorQR()"); - } else { - printf("factor()"); - } - printf(" returned with info = %d, indicating a zero row or column\n", info); - } - } - bool doHessian = false; - if (s_doBothSolvesAndCompare) { - doHessian = true; - } - if (m_conditionNumber < 1.0E7) { - if (m_print_flag >= 4) { - printf("\t\t doAffineNewtonSolve: Condition number = %g during regular solve\n", m_conditionNumber); - } - - /* - * Solve the system -> This also involves inverting the matrix - */ - int info = jac.solve(DATA_PTR(delta_y)); - if (info) { - if (m_print_flag >= 2) { - printf("\t\t doAffineNewtonSolve() ERROR: QRSolve returned INFO = %d. Switching to Hessian solve\n", info); - } - doHessian = true; - newtonGood = false; - } - /* - * reverse the column scaling if there was any on a successful solve - */ - if (m_colScaling) { - for (size_t irow = 0; irow < neq_; irow++) { - delta_y[irow] = delta_y[irow] * m_colScales[irow]; - } - } - - } else { - if (jac.matrixType_ == 1) { - newtonGood = true; - if (m_print_flag >= 3) { - printf("\t\t doAffineNewtonSolve() WARNING: Condition number too large, %g, But Banded Hessian solve " - "not implemented yet \n", m_conditionNumber); - } - } else { - doHessian = true; - newtonGood = false; - if (m_print_flag >= 3) { - printf("\t\t doAffineNewtonSolve() WARNING: Condition number too large, %g. Doing a Hessian solve \n", m_conditionNumber); - } - } - } - - if (doHessian) { - // Store the old value for later comparison - vector_fp delyNewton(neq_); - for (size_t irow = 0; irow < neq_; irow++) { - delyNewton[irow] = delta_y[irow]; - } - - // Get memory if not done before - if (HessianPtr_ == 0) { - HessianPtr_ = jac.duplMyselfAsGeneralMatrix(); - } - - /* - * Calculate the symmetric Hessian - */ - GeneralMatrix& hessian = *HessianPtr_; - GeneralMatrix& jacCopy = *jacCopyPtr_; - hessian.zero(); - if (m_rowScaling) { - for (size_t i = 0; i < neq_; i++) { - for (size_t j = i; j < neq_; j++) { - for (size_t k = 0; k < neq_; k++) { - hessian(i,j) += jacCopy(k,i) * jacCopy(k,j) * m_rowScales[k] * m_rowScales[k]; - } - hessian(j,i) = hessian(i,j); - } - } - } else { - for (size_t i = 0; i < neq_; i++) { - for (size_t j = i; j < neq_; j++) { - for (size_t k = 0; k < neq_; k++) { - hessian(i,j) += jacCopy(k,i) * jacCopy(k,j); - } - hessian(j,i) = hessian(i,j); - } - } - } - - /* - * Calculate the matrix norm of the Hessian - */ - doublereal hnorm = 0.0; - doublereal hcol = 0.0; - if (m_colScaling) { - for (size_t i = 0; i < neq_; i++) { - for (size_t j = i; j < neq_; j++) { - hcol += fabs(hessian(j,i)) * m_colScales[j]; - } - for (size_t j = i+1; j < neq_; j++) { - hcol += fabs(hessian(i,j)) * m_colScales[j]; - } - hcol *= m_colScales[i]; - if (hcol > hnorm) { - hnorm = hcol; - } - } - } else { - for (size_t i = 0; i < neq_; i++) { - for (size_t j = i; j < neq_; j++) { - hcol += fabs(hessian(j,i)); - } - for (size_t j = i+1; j < neq_; j++) { - hcol += fabs(hessian(i,j)); - } - if (hcol > hnorm) { - hnorm = hcol; - } - } - } - /* - * Add junk to the Hessian diagonal - * -> Note, testing indicates that this will get too big for ill-conditioned systems. - */ - hcol = sqrt(static_cast(neq_)) * 1.0E-7 * hnorm; -#ifdef DEBUG_HKM_NOT - if (hcol > 1.0) { - hcol = 1.0E1; - } -#endif - if (m_colScaling) { - for (size_t i = 0; i < neq_; i++) { - hessian(i,i) += hcol / (m_colScales[i] * m_colScales[i]); - } - } else { - for (size_t i = 0; i < neq_; i++) { - hessian(i,i) += hcol; - } - } - - /* - * Factor the Hessian - */ - int info = 0; - ct_dpotrf(ctlapack::UpperTriangular, neq_, &(*(HessianPtr_->begin())), neq_, info); - if (info) { - if (m_print_flag >= 2) { - printf("\t\t doAffineNewtonSolve() ERROR: Hessian isn't positive definite DPOTRF returned INFO = %d\n", info); - } - return info; - } - - vector_fp delyH(neq_); - // First recalculate the scaled residual. It got wiped out doing the Newton solve - if (m_rowScaling) { - for (size_t n = 0; n < neq_; n++) { - delyH[n] = -m_rowScales[n] * m_resid[n]; - } - } else { - for (size_t n = 0; n < neq_; n++) { - delyH[n] = -m_resid[n]; - } - } - - if (m_rowScaling) { - for (size_t j = 0; j < neq_; j++) { - delta_y[j] = 0.0; - for (size_t i = 0; i < neq_; i++) { - delta_y[j] += delyH[i] * jacCopy(i,j) * m_rowScales[i]; - } - } - } else { - for (size_t j = 0; j < neq_; j++) { - delta_y[j] = 0.0; - for (size_t i = 0; i < neq_; i++) { - delta_y[j] += delyH[i] * jacCopy(i,j); - } - } - } - - - /* - * Solve the factored Hessian System - */ - ct_dpotrs(ctlapack::UpperTriangular, neq_, 1,&(*(hessian.begin())), neq_, delta_y, neq_, info); - if (info) { - if (m_print_flag >= 2) { - printf("\t\t NonlinearSolver::doAffineNewtonSolve() ERROR: DPOTRS returned INFO = %d\n", info); - } - return info; - } - /* - * reverse the column scaling if there was any. - */ - if (m_colScaling) { - for (size_t irow = 0; irow < neq_; irow++) { - delta_y[irow] = delta_y[irow] * m_colScales[irow]; - } - } - - - if (doDogLeg_ && m_print_flag > 7) { - double normNewt = solnErrorNorm(&delyNewton[0]); - double normHess = solnErrorNorm(delta_y); - printf("\t\t doAffineNewtonSolve(): Printout Comparison between Hessian deltaX and Newton deltaX\n"); - - printf("\t\t I Hessian+Junk Newton"); - if (newtonGood || s_alwaysAssumeNewtonGood) { - printf(" (USING NEWTON DIRECTION)\n"); - } else { - printf(" (USING HESSIAN DIRECTION)\n"); - } - printf("\t\t Norm: %12.4E %12.4E\n", normHess, normNewt); - - printf("\t\t --------------------------------------------------------\n"); - for (size_t i = 0; i < neq_; i++) { - printf("\t\t %3s %13.5E %13.5E\n", int2str(i).c_str(), delta_y[i], delyNewton[i]); - } - printf("\t\t --------------------------------------------------------\n"); - } else if (doDogLeg_ && m_print_flag >= 4) { - double normNewt = solnErrorNorm(&delyNewton[0]); - double normHess = solnErrorNorm(delta_y); - printf("\t\t doAffineNewtonSolve(): Hessian update norm = %12.4E \n" - "\t\t Newton update norm = %12.4E \n", normHess, normNewt); - if (newtonGood || s_alwaysAssumeNewtonGood) { - printf("\t\t (USING NEWTON DIRECTION)\n"); - } else { - printf("\t\t (USING HESSIAN DIRECTION)\n"); - } - } - - /* - * Choose the delta_y to use - */ - if (newtonGood || s_alwaysAssumeNewtonGood) { - copy(delyNewton.begin(), delyNewton.end(), delta_y); - } - } - -#ifdef DEBUG_JAC - if (printJacContributions) { - for (int iNum = 0; iNum < numRows; iNum++) { - if (iNum > 0) { - focusRow++; - } - doublereal dsum = 0.0; - vector_fp& Jdata = jacBack.data(); - doublereal dRow = Jdata[neq_ * focusRow + focusRow]; - printf("\n Details on delta_Y for row %d \n", focusRow); - printf(" Value before = %15.5e, delta = %15.5e," - "value after = %15.5e\n", y_curr[focusRow], - delta_y[focusRow], y_curr[focusRow] + delta_y[focusRow]); - if (!freshJac) { - printf(" Old Jacobian\n"); - } - printf(" col delta_y aij " - "contrib \n"); - printf("-----------------------------------------------------------------------------------------------\n"); - printf(" Res(%d) %15.5e %15.5e %15.5e (Res = %g)\n", - focusRow, delta_y[focusRow], - dRow, RRow[iNum] / dRow, RRow[iNum]); - dsum += RRow[iNum] / dRow; - for (int ii = 0; ii < neq_; ii++) { - if (ii != focusRow) { - doublereal aij = Jdata[neq_ * ii + focusRow]; - doublereal contrib = aij * delta_y[ii] * (-1.0) / dRow; - dsum += contrib; - if (fabs(contrib) > Pcutoff) { - printf("%6d %15.5e %15.5e %15.5e\n", ii, - delta_y[ii] , aij, contrib); - } - } - } - printf("-----------------------------------------------------------------------------------------------\n"); - printf(" %15.5e %15.5e\n", - delta_y[focusRow], dsum); - } - } - -#endif - - m_numTotalLinearSolves++; - m_numLocalLinearSolves++; - return info; - -} - -doublereal NonlinearSolver::doCauchyPointSolve(GeneralMatrix& jac) -{ - doublereal rowFac = 1.0; - doublereal colFac = 1.0; - doublereal normSoln; - // Calculate the descent direction - /* - * For confirmation of the scaling factors, see Dennis and Schnabel p, 152, p, 156 and my notes - * - * The colFac and rowFac values are used to eliminate the scaling of the matrix from the - * actual equation - * - * Here we calculate the steepest descent direction. This is equation (11) in the notes. It is - * stored in deltaX_CP_[].The value corresponds to d_descent[]. - */ - for (size_t j = 0; j < neq_; j++) { - deltaX_CP_[j] = 0.0; - if (m_colScaling) { - colFac = 1.0 / m_colScales[j]; - } - for (size_t i = 0; i < neq_; i++) { - if (m_rowScaling) { - rowFac = 1.0 / m_rowScales[i]; - } - deltaX_CP_[j] -= m_resid[i] * jac(i,j) * colFac * rowFac * m_ewt[j] * m_ewt[j] - / (m_residWts[i] * m_residWts[i]); - if (DEBUG_MODE_ENABLED) { - checkFinite(deltaX_CP_[j]); - } - } - } - - /* - * Calculate J_hat d_y_descent. This is formula 18 in the notes. - */ - for (size_t i = 0; i < neq_; i++) { - Jd_[i] = 0.0; - if (m_rowScaling) { - rowFac = 1.0 / m_rowScales[i]; - } else { - rowFac = 1.0; - } - for (size_t j = 0; j < neq_; j++) { - if (m_colScaling) { - colFac = 1.0 / m_colScales[j]; - } - Jd_[i] += deltaX_CP_[j] * jac(i,j) * rowFac * colFac / m_residWts[i]; - } - } - - /* - * Calculate the distance along the steepest descent until the Cauchy point - * This is Eqn. 17 in the notes. - */ - RJd_norm_ = 0.0; - JdJd_norm_ = 0.0; - for (size_t i = 0; i < neq_; i++) { - RJd_norm_ += m_resid[i] * Jd_[i] / m_residWts[i]; - JdJd_norm_ += Jd_[i] * Jd_[i]; - } - if (fabs(JdJd_norm_) < 1.0E-290) { - if (fabs(RJd_norm_) < 1.0E-300) { - lambdaStar_ = 0.0; - } else { - throw CanteraError("NonlinearSolver::doCauchyPointSolve()", "Unexpected condition: norms are zero"); - } - } else { - lambdaStar_ = - RJd_norm_ / (JdJd_norm_); - } - - /* - * Now we modify the steepest descent vector such that its length is equal to the - * Cauchy distance. From now on, if we want to recreate the descent vector, we have - * to unnormalize it by dividing by lambdaStar_. - */ - for (size_t i = 0; i < neq_; i++) { - deltaX_CP_[i] *= lambdaStar_; - } - - - doublereal normResid02 = m_normResid_0 * m_normResid_0 * neq_; - - /* - * Calculate the expected square of the risdual at the Cauchy point if the linear model is correct - */ - if (fabs(JdJd_norm_) < 1.0E-290) { - residNorm2Cauchy_ = normResid02; - } else { - residNorm2Cauchy_ = normResid02 - RJd_norm_ * RJd_norm_ / (JdJd_norm_); - } - - - // Extra printout section - if (m_print_flag > 2) { - // Calculate the expected residual at the Cauchy point if the linear model is correct - doublereal residCauchy = 0.0; - if (residNorm2Cauchy_ > 0.0) { - residCauchy = sqrt(residNorm2Cauchy_ / neq_); - } else { - if (fabs(JdJd_norm_) < 1.0E-290) { - residCauchy = m_normResid_0; - } else { - residCauchy = m_normResid_0 - sqrt(RJd_norm_ * RJd_norm_ / (JdJd_norm_)); - } - } - // Compute the weighted norm of the undamped step size descentDir_[] - if ((s_print_DogLeg || doDogLeg_) && m_print_flag >= 6) { - normSoln = solnErrorNorm(DATA_PTR(deltaX_CP_), "SteepestDescentDir", 10); - } else { - normSoln = solnErrorNorm(DATA_PTR(deltaX_CP_), "SteepestDescentDir", 0); - } - if ((s_print_DogLeg || doDogLeg_) && m_print_flag >= 5) { - printf("\t\t doCauchyPointSolve: Steepest descent to Cauchy point: \n"); - printf("\t\t\t R0 = %g \n", m_normResid_0); - printf("\t\t\t Rpred = %g\n", residCauchy); - printf("\t\t\t Rjd = %g\n", RJd_norm_); - printf("\t\t\t JdJd = %g\n", JdJd_norm_); - printf("\t\t\t deltaX = %g\n", normSoln); - printf("\t\t\t lambda = %g\n", lambdaStar_); - } - } else { - // Calculate the norm of the Cauchy solution update in any case - normSoln = solnErrorNorm(DATA_PTR(deltaX_CP_), "SteepestDescentDir", 0); - } - return normSoln; -} - -void NonlinearSolver::descentComparison(doublereal time_curr, doublereal* ydot0, doublereal* ydot1, int& numTrials) -{ - doublereal ff = 1.0E-5; - doublereal ffNewt = 1.0E-5; - doublereal* y_n_1 = DATA_PTR(m_wksp); - doublereal cauchyDistanceNorm = solnErrorNorm(DATA_PTR(deltaX_CP_)); - if (cauchyDistanceNorm < 1.0E-2) { - ff = 1.0E-9 / cauchyDistanceNorm; - if (ff > 1.0E-2) { - ff = 1.0E-2; - } - } - for (size_t i = 0; i < neq_; i++) { - y_n_1[i] = m_y_n_curr[i] + ff * deltaX_CP_[i]; - } - /* - * Calculate the residual that would result if y1[] were the new solution vector - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - doResidualCalc(time_curr, solnType_, y_n_1, ydot1, Base_LaggedSolutionComponents); - } else { - doResidualCalc(time_curr, solnType_, y_n_1, ydot0, Base_LaggedSolutionComponents); - } - - doublereal normResid02 = m_normResid_0 * m_normResid_0 * neq_; - doublereal residSteep = residErrorNorm(DATA_PTR(m_resid)); - doublereal residSteep2 = residSteep * residSteep * neq_; - doublereal funcDecreaseSD = 0.5 * (residSteep2 - normResid02) / (ff * cauchyDistanceNorm); - - doublereal sNewt = solnErrorNorm(DATA_PTR(deltaX_Newton_)); - if (sNewt > 1.0) { - ffNewt = ffNewt / sNewt; - } - for (size_t i = 0; i < neq_; i++) { - y_n_1[i] = m_y_n_curr[i] + ffNewt * deltaX_Newton_[i]; - } - /* - * Calculate the residual that would result if y1[] were the new solution vector. - * Here we use the lagged solution components in the residual calculation as well. We are - * interested in the linear model and its agreement with the nonlinear model. - * - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - doResidualCalc(time_curr, solnType_, y_n_1, ydot1, Base_LaggedSolutionComponents); - } else { - doResidualCalc(time_curr, solnType_, y_n_1, ydot0, Base_LaggedSolutionComponents); - } - doublereal residNewt = residErrorNorm(DATA_PTR(m_resid)); - doublereal residNewt2 = residNewt * residNewt * neq_; - - doublereal funcDecreaseNewt2 = 0.5 * (residNewt2 - normResid02) / (ffNewt * sNewt); - - // This is the expected initial rate of decrease in the Cauchy direction. - // -> This is Eqn. 29 = Rhat dot Jhat dy / || d || - doublereal funcDecreaseSDExp = RJd_norm_ / cauchyDistanceNorm * lambdaStar_; - - doublereal funcDecreaseNewtExp2 = - normResid02 / sNewt; - - if (m_normResid_0 > 1.0E-100) { - ResidDecreaseSDExp_ = funcDecreaseSDExp / neq_ / m_normResid_0; - ResidDecreaseSD_ = funcDecreaseSD / neq_ / m_normResid_0; - ResidDecreaseNewtExp_ = funcDecreaseNewtExp2 / neq_ / m_normResid_0; - ResidDecreaseNewt_ = funcDecreaseNewt2 / neq_ / m_normResid_0; - } else { - ResidDecreaseSDExp_ = 0.0; - ResidDecreaseSD_ = funcDecreaseSD / neq_; - ResidDecreaseNewtExp_ = 0.0; - ResidDecreaseNewt_ = funcDecreaseNewt2 / neq_; - } - numTrials += 2; - - /* - * HKM These have been shown to exactly match up. - * The steepest direction is always largest even when there are variable solution weights - * - * HKM When a Hessian is used with junk on the diagonal, funcDecreaseNewtExp2 is no longer accurate as the - * direction gets significantly shorter with increasing condition number. This suggests an algorithm where the - * Newton step from the Hessian should be increased so as to match funcDecreaseNewtExp2 = funcDecreaseNewt2. - * This roughly equals the ratio of the norms of the Hessian and Newton steps. This increased Newton step can - * then be used with the trust region double dogleg algorithm. - */ - if ((s_print_DogLeg && m_print_flag >= 3) || (doDogLeg_ && m_print_flag >= 5)) { - printf("\t\t descentComparison: initial rate of decrease of func in Cauchy dir (expected) = %g\n", funcDecreaseSDExp); - printf("\t\t descentComparison: initial rate of decrease of func in Cauchy dir = %g\n", funcDecreaseSD); - printf("\t\t descentComparison: initial rate of decrease of func in Newton dir (expected) = %g\n", funcDecreaseNewtExp2); - printf("\t\t descentComparison: initial rate of decrease of func in Newton dir = %g\n", funcDecreaseNewt2); - } - if ((s_print_DogLeg && m_print_flag >= 3) || (doDogLeg_ && m_print_flag >= 4)) { - printf("\t\t descentComparison: initial rate of decrease of Resid in Cauchy dir (expected) = %g\n", ResidDecreaseSDExp_); - printf("\t\t descentComparison: initial rate of decrease of Resid in Cauchy dir = %g\n", ResidDecreaseSD_); - printf("\t\t descentComparison: initial rate of decrease of Resid in Newton dir (expected) = %g\n", ResidDecreaseNewtExp_); - printf("\t\t descentComparison: initial rate of decrease of Resid in Newton dir = %g\n", ResidDecreaseNewt_); - } - - if ((s_print_DogLeg && m_print_flag >= 5) || (doDogLeg_ && m_print_flag >= 5)) { - if (funcDecreaseNewt2 >= 0.0) { - printf("\t\t %13.5E %22.16E\n", funcDecreaseNewtExp2, m_normResid_0); - double ff = ffNewt * 1.0E-5; - for (int ii = 0; ii < 13; ii++) { - ff *= 10.; - if (ii == 12) { - ff = ffNewt; - } - for (size_t i = 0; i < neq_; i++) { - y_n_1[i] = m_y_n_curr[i] + ff * deltaX_Newton_[i]; - } - numTrials += 1; - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - doResidualCalc(time_curr, solnType_, y_n_1, ydot1, Base_LaggedSolutionComponents); - } else { - doResidualCalc(time_curr, solnType_, y_n_1, ydot0, Base_LaggedSolutionComponents); - } - residNewt = residErrorNorm(DATA_PTR(m_resid)); - residNewt2 = residNewt * residNewt * neq_; - funcDecreaseNewt2 = 0.5 * (residNewt2 - normResid02) / (ff * sNewt); - printf("\t\t %10.3E %13.5E %22.16E\n", ff, funcDecreaseNewt2, residNewt); - } - } - } -} - -void NonlinearSolver::setupDoubleDogleg() -{ - /* - * Gamma = ||grad f ||**4 - * --------------------------------------------- - * (grad f)T H (grad f) (grad f)T H-1 (grad f) - */ - /* - * This hasn't worked. so will do it heuristically. One issue is that the Newton - * direction is not the inverse of the Hessian times the gradient. The Hessian - * is the matrix squared. Until I have the inverse of the Hessian from QR factorization - * I may not be able to do it this way. - */ - - /* - * Heuristic algorithm - Find out where on the Newton line the residual is the same - * as the residual at the Cauchy point. Then, go halfway to - * the Newton point and call that Nuu. - * Maybe we need to check that the linearized residual is - * monotonic along that line. However, we haven't needed to yet. - */ - doublereal residSteepLin = expectedResidLeg(0, 1.0); - doublereal Nres2CP = residSteepLin * residSteepLin * neq_; - doublereal Nres2_o = m_normResid_0 * m_normResid_0 * neq_; - doublereal a = Nres2CP / Nres2_o; - doublereal betaEqual = (2.0 - sqrt(4.0 - 4 * (1.0 - a))) / 2.0; - doublereal beta = (1.0 + betaEqual) / 2.0; - - - Nuu_ = beta; - - dist_R0_ = m_normDeltaSoln_CP; - for (size_t i = 0; i < neq_; i++) { - m_wksp[i] = Nuu_ * deltaX_Newton_[i] - deltaX_CP_[i]; - } - dist_R1_ = solnErrorNorm(DATA_PTR(m_wksp)); - dist_R2_ = (1.0 - Nuu_) * m_normDeltaSoln_Newton; - dist_Total_ = dist_R0_ + dist_R1_ + dist_R2_; - - /* - * Calculate the trust distances - */ - normTrust_Newton_ = calcTrustDistance(deltaX_Newton_); - normTrust_CP_ = calcTrustDistance(deltaX_CP_); -} - -int NonlinearSolver::lambdaToLeg(const doublereal lambda, doublereal& alpha) const -{ - - if (lambda < dist_R0_ / dist_Total_) { - alpha = lambda * dist_Total_ / dist_R0_; - return 0; - } else if (lambda < ((dist_R0_ + dist_R1_)/ dist_Total_)) { - alpha = (lambda * dist_Total_ - dist_R0_) / dist_R1_; - return 1; - } - alpha = (lambda * dist_Total_ - dist_R0_ - dist_R1_) / dist_R2_; - return 2; -} - -doublereal NonlinearSolver::expectedResidLeg(int leg, doublereal alpha) const -{ - doublereal resD2, res2, resNorm; - doublereal normResid02 = m_normResid_0 * m_normResid_0 * neq_; - - if (leg == 0) { - /* - * We are on the steepest descent line - * along that line - * R2 = R2 + 2 lambda R dot Jd + lambda**2 Jd dot Jd - */ - - doublereal tmp = - 2.0 * alpha + alpha * alpha; - doublereal tmp2 = - RJd_norm_ * lambdaStar_; - resD2 = tmp2 * tmp; - - } else if (leg == 1) { - - /* - * Same formula as above for lambda=1. - */ - doublereal tmp2 = - RJd_norm_ * lambdaStar_; - doublereal RdotJS = - tmp2; - doublereal JsJs = tmp2; - - - doublereal res0_2 = m_normResid_0 * m_normResid_0 * neq_; - - res2 = res0_2 + (1.0 - alpha) * 2 * RdotJS - 2 * alpha * Nuu_ * res0_2 - + (1.0 - alpha) * (1.0 - alpha) * JsJs - + alpha * alpha * Nuu_ * Nuu_ * res0_2 - - 2 * alpha * Nuu_ * (1.0 - alpha) * RdotJS; - - return sqrt(res2 / neq_); - - } else { - doublereal beta = Nuu_ + alpha * (1.0 - Nuu_); - doublereal tmp2 = normResid02; - doublereal tmp = 1.0 - 2.0 * beta + 1.0 * beta * beta - 1.0; - resD2 = tmp * tmp2; - } - - res2 = m_normResid_0 * m_normResid_0 * neq_ + resD2; - if (res2 < 0.0) { - resNorm = m_normResid_0 - sqrt(resD2/neq_); - } else { - resNorm = sqrt(res2 / neq_); - } - - return resNorm; - -} - -void NonlinearSolver::residualComparisonLeg(const doublereal time_curr, const doublereal* const ydot0, int& legBest, - doublereal& alphaBest) const -{ - doublereal* y1 = DATA_PTR(m_wksp); - doublereal* ydot1 = DATA_PTR(m_wksp_2); - doublereal sLen; - doublereal alpha = 0; - - doublereal residSteepBest = 1.0E300; - doublereal residSteepLinBest = 0.0; - if (s_print_DogLeg || (doDogLeg_ && m_print_flag > 6)) { - printf("\t\t residualComparisonLeg() \n"); - printf("\t\t Point StepLen Residual_Actual Residual_Linear RelativeMatch\n"); - } - // First compare at 1/4 along SD curve - std::vector alphaT; - alphaT.push_back(0.00); - alphaT.push_back(0.01); - alphaT.push_back(0.1); - alphaT.push_back(0.25); - alphaT.push_back(0.50); - alphaT.push_back(0.75); - alphaT.push_back(1.0); - for (size_t iteration = 0; iteration < alphaT.size(); iteration++) { - alpha = alphaT[iteration]; - for (size_t i = 0; i < neq_; i++) { - y1[i] = m_y_n_curr[i] + alpha * deltaX_CP_[i]; - } - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, y1, ydot1); - } - sLen = alpha * solnErrorNorm(DATA_PTR(deltaX_CP_)); - /* - * Calculate the residual that would result if y1[] were the new solution vector - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - doResidualCalc(time_curr, solnType_, y1, ydot1, Base_LaggedSolutionComponents); - } else { - doResidualCalc(time_curr, solnType_, y1, ydot0, Base_LaggedSolutionComponents); - } - - - doublereal residSteep = residErrorNorm(DATA_PTR(m_resid)); - doublereal residSteepLin = expectedResidLeg(0, alpha); - if (residSteep < residSteepBest) { - legBest = 0; - alphaBest = alpha; - residSteepBest = residSteep; - residSteepLinBest = residSteepLin; - } - - doublereal relFit = (residSteep - residSteepLin) / (fabs(residSteepLin) + 1.0E-10); - if (s_print_DogLeg || (doDogLeg_ && m_print_flag > 6)) { - printf("\t\t (%2d - % 10.3g) % 15.8E % 15.8E % 15.8E % 15.8E\n", 0, alpha, sLen, residSteep, residSteepLin , relFit); - } - } - - for (size_t iteration = 0; iteration < alphaT.size(); iteration++) { - doublereal alpha = alphaT[iteration]; - for (size_t i = 0; i < neq_; i++) { - y1[i] = m_y_n_curr[i] + (1.0 - alpha) * deltaX_CP_[i]; - y1[i] += alpha * Nuu_ * deltaX_Newton_[i]; - } - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, y1, ydot1); - } - /* - * Calculate the residual that would result if y1[] were the new solution vector - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - doResidualCalc(time_curr, solnType_, y1, ydot1, Base_LaggedSolutionComponents); - } else { - doResidualCalc(time_curr, solnType_, y1, ydot0, Base_LaggedSolutionComponents); - } - - for (size_t i = 0; i < neq_; i++) { - y1[i] -= m_y_n_curr[i]; - } - sLen = solnErrorNorm(DATA_PTR(y1)); - - doublereal residSteep = residErrorNorm(DATA_PTR(m_resid)); - doublereal residSteepLin = expectedResidLeg(1, alpha); - if (residSteep < residSteepBest) { - legBest = 1; - alphaBest = alpha; - residSteepBest = residSteep; - residSteepLinBest = residSteepLin; - } - - doublereal relFit = (residSteep - residSteepLin) / (fabs(residSteepLin) + 1.0E-10); - if (s_print_DogLeg || (doDogLeg_ && m_print_flag > 6)) { - printf("\t\t (%2d - % 10.3g) % 15.8E % 15.8E % 15.8E % 15.8E\n", 1, alpha, sLen, residSteep, residSteepLin , relFit); - } - } - - for (size_t iteration = 0; iteration < alphaT.size(); iteration++) { - doublereal alpha = alphaT[iteration]; - for (size_t i = 0; i < neq_; i++) { - y1[i] = m_y_n_curr[i] + (Nuu_ + alpha * (1.0 - Nuu_))* deltaX_Newton_[i]; - } - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, y1, ydot1); - } - sLen = (Nuu_ + alpha * (1.0 - Nuu_)) * solnErrorNorm(DATA_PTR(deltaX_Newton_)); - /* - * Calculate the residual that would result if y1[] were the new solution vector - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - doResidualCalc(time_curr, solnType_, y1, ydot1, Base_LaggedSolutionComponents); - } else { - doResidualCalc(time_curr, solnType_, y1, ydot0, Base_LaggedSolutionComponents); - } - - - - doublereal residSteep = residErrorNorm(DATA_PTR(m_resid)); - doublereal residSteepLin = expectedResidLeg(2, alpha); - if (residSteep < residSteepBest) { - legBest = 2; - alphaBest = alpha; - residSteepBest = residSteep; - residSteepLinBest = residSteepLin; - } - doublereal relFit = (residSteep - residSteepLin) / (fabs(residSteepLin) + 1.0E-10); - if (s_print_DogLeg || (doDogLeg_ && m_print_flag > 6)) { - printf("\t\t (%2d - % 10.3g) % 15.8E % 15.8E % 15.8E % 15.8E\n", 2, alpha, sLen, residSteep, residSteepLin , relFit); - } - } - if (s_print_DogLeg || (doDogLeg_ && m_print_flag > 6)) { - printf("\t\t Best Result: \n"); - doublereal relFit = (residSteepBest - residSteepLinBest) / (fabs(residSteepLinBest) + 1.0E-10); - if (m_print_flag <= 6) { - printf("\t\t Leg %2d alpha %5g: NonlinResid = %g LinResid = %g, relfit = %g\n", - legBest, alphaBest, residSteepBest, residSteepLinBest, relFit); - } else { - if (legBest == 0) { - sLen = alpha * solnErrorNorm(DATA_PTR(deltaX_CP_)); - } else if (legBest == 1) { - for (size_t i = 0; i < neq_; i++) { - y1[i] = (1.0 - alphaBest) * deltaX_CP_[i]; - y1[i] += alphaBest * Nuu_ * deltaX_Newton_[i]; - } - sLen = solnErrorNorm(DATA_PTR(y1)); - } else { - sLen = (Nuu_ + alpha * (1.0 - Nuu_)) * solnErrorNorm(DATA_PTR(deltaX_Newton_)); - } - printf("\t\t (%2d - % 10.3g) % 15.8E % 15.8E % 15.8E % 15.8E\n", legBest, alphaBest, sLen, - residSteepBest, residSteepLinBest , relFit); - } - } - -} - -doublereal NonlinearSolver::trustRegionLength() const -{ - norm_deltaX_trust_ = solnErrorNorm(DATA_PTR(deltaX_trust_)); - return trustDelta_ * norm_deltaX_trust_; -} - -void NonlinearSolver::setDefaultDeltaBoundsMagnitudes() -{ - for (size_t i = 0; i < neq_; i++) { - m_deltaStepMinimum[i] = 1000. * atolk_[i]; - m_deltaStepMinimum[i] = std::max(m_deltaStepMinimum[i], 0.1 * fabs(m_y_n_curr[i])); - } -} - -void NonlinearSolver::adjustUpStepMinimums() -{ - for (size_t i = 0; i < neq_; i++) { - doublereal goodVal = deltaX_trust_[i] * trustDelta_; - if (deltaX_trust_[i] * trustDelta_ > m_deltaStepMinimum[i]) { - m_deltaStepMinimum[i] = 1.1 * goodVal; - } - - } -} - -void NonlinearSolver::setDeltaBoundsMagnitudes(const doublereal* const deltaStepMinimum) -{ - for (size_t i = 0; i < neq_; i++) { - m_deltaStepMinimum[i] = deltaStepMinimum[i]; - } - m_manualDeltaStepSet = 1; -} - -double -NonlinearSolver::deltaBoundStep(const doublereal* const y_n_curr, const doublereal* const step_1) -{ - size_t i_fbounds = 0; - int ifbd = 0; - int i_fbd = 0; - doublereal UPFAC = 2.0; - - doublereal sameSign = 0.0; - doublereal ff; - doublereal f_delta_bounds = 1.0; - doublereal ff_alt; - for (size_t i = 0; i < neq_; i++) { - doublereal y_new = y_n_curr[i] + step_1[i]; - sameSign = y_new * y_n_curr[i]; - - /* - * Now do a delta bounds - * Increase variables by a factor of UPFAC only - * decrease variables by a factor of 2 only - */ - ff = 1.0; - - - if (sameSign >= 0.0) { - if ((fabs(y_new) > UPFAC * fabs(y_n_curr[i])) && - (fabs(y_new - y_n_curr[i]) > m_deltaStepMinimum[i])) { - ff = (UPFAC - 1.0) * fabs(y_n_curr[i]/(y_new - y_n_curr[i])); - ff_alt = fabs(m_deltaStepMinimum[i] / (y_new - y_n_curr[i])); - ff = std::max(ff, ff_alt); - ifbd = 1; - } - if ((fabs(2.0 * y_new) < fabs(y_n_curr[i])) && - (fabs(y_new - y_n_curr[i]) > m_deltaStepMinimum[i])) { - ff = y_n_curr[i]/(y_new - y_n_curr[i]) * (1.0 - 2.0)/2.0; - ff_alt = fabs(m_deltaStepMinimum[i] / (y_new - y_n_curr[i])); - ff = std::max(ff, ff_alt); - ifbd = 0; - } - } else { - /* - * This handles the case where the value crosses the origin. - * - First we don't let it cross the origin until its shrunk to the size of m_deltaStepMinimum[i] - */ - if (fabs(y_n_curr[i]) > m_deltaStepMinimum[i]) { - ff = y_n_curr[i]/(y_new - y_n_curr[i]) * (1.0 - 2.0)/2.0; - ff_alt = fabs(m_deltaStepMinimum[i] / (y_new - y_n_curr[i])); - ff = std::max(ff, ff_alt); - if (y_n_curr[i] >= 0.0) { - ifbd = 0; - } else { - ifbd = 1; - } - } - /* - * Second when it does cross the origin, we make sure that its magnitude is only 50% of the previous value. - */ - else if (fabs(y_new) > 0.5 * fabs(y_n_curr[i])) { - ff = y_n_curr[i]/(y_new - y_n_curr[i]) * (-1.5); - ff_alt = fabs(m_deltaStepMinimum[i] / (y_new - y_n_curr[i])); - ff = std::max(ff, ff_alt); - ifbd = 0; - } - } - - if (ff < f_delta_bounds) { - f_delta_bounds = ff; - i_fbounds = i; - i_fbd = ifbd; - } - - - } - - - /* - * Report on any corrections - */ - if (m_print_flag >= 3) { - if (f_delta_bounds < 1.0) { - if (i_fbd) { - printf("\t\tdeltaBoundStep: Increase of Variable %s causing " - "delta damping of %g: origVal = %10.3g, undampedNew = %10.3g, dampedNew = %10.3g\n", - int2str(i_fbounds).c_str(), f_delta_bounds, y_n_curr[i_fbounds], y_n_curr[i_fbounds] + step_1[i_fbounds], - y_n_curr[i_fbounds] + f_delta_bounds * step_1[i_fbounds]); - } else { - printf("\t\tdeltaBoundStep: Decrease of variable %s causing" - "delta damping of %g: origVal = %10.3g, undampedNew = %10.3g, dampedNew = %10.3g\n", - int2str(i_fbounds).c_str(), f_delta_bounds, y_n_curr[i_fbounds], y_n_curr[i_fbounds] + step_1[i_fbounds], - y_n_curr[i_fbounds] + f_delta_bounds * step_1[i_fbounds]); - } - } - } - - - return f_delta_bounds; -} - -void NonlinearSolver::readjustTrustVector() -{ - doublereal trustDeltaOld = trustDelta_; - doublereal wtSum = 0.0; - for (size_t i = 0; i < neq_; i++) { - wtSum += m_ewt[i]; - } - wtSum /= neq_; - doublereal trustNorm = solnErrorNorm(DATA_PTR(deltaX_trust_)); - doublereal deltaXSizeOld = trustNorm; - doublereal trustNormGoal = trustNorm * trustDelta_; - - doublereal oldVal; - doublereal fabsy; - // we use the old value of the trust region as an indicator - for (size_t i = 0; i < neq_; i++) { - oldVal = deltaX_trust_[i]; - fabsy = fabs(m_y_n_curr[i]); - // First off make sure that each trust region vector is 1/2 the size of each variable or smaller - // unless overridden by the deltaStepMininum value. - doublereal newValue = trustNormGoal * m_ewt[i]; - if (newValue > 0.5 * fabsy) { - if (fabsy * 0.5 > m_deltaStepMinimum[i]) { - deltaX_trust_[i] = 0.5 * fabsy; - } else { - deltaX_trust_[i] = m_deltaStepMinimum[i]; - } - } else { - if (newValue > 4.0 * oldVal) { - newValue = 4.0 * oldVal; - } else if (newValue < 0.25 * oldVal) { - newValue = 0.25 * oldVal; - if (deltaX_trust_[i] < m_deltaStepMinimum[i]) { - newValue = m_deltaStepMinimum[i]; - } - } - deltaX_trust_[i] = newValue; - if (deltaX_trust_[i] > 0.75 * m_deltaStepMaximum[i]) { - deltaX_trust_[i] = 0.75 * m_deltaStepMaximum[i]; - } - } - } - - - // Final renormalization. - norm_deltaX_trust_ = solnErrorNorm(DATA_PTR(deltaX_trust_)); - doublereal sum = trustNormGoal / trustNorm; - for (size_t i = 0; i < neq_; i++) { - deltaX_trust_[i] = deltaX_trust_[i] * sum; - } - norm_deltaX_trust_ = solnErrorNorm(DATA_PTR(deltaX_trust_)); - trustDelta_ = trustNormGoal / norm_deltaX_trust_; - - if (doDogLeg_ && m_print_flag >= 4) { - printf("\t\t reajustTrustVector(): Trust size = %11.3E: Old deltaX size = %11.3E trustDelta_ = %11.3E\n" - "\t\t new deltaX size = %11.3E trustdelta_ = %11.3E\n", - trustNormGoal, deltaXSizeOld, trustDeltaOld, norm_deltaX_trust_, trustDelta_); - } -} - -void NonlinearSolver::initializeTrustRegion() -{ - if (trustRegionInitializationMethod_ == 0) { - return; - } - if (trustRegionInitializationMethod_ == 1) { - for (size_t i = 0; i < neq_; i++) { - deltaX_trust_[i] = m_ewt[i] * trustRegionInitializationFactor_; - } - trustDelta_ = 1.0; - } - if (trustRegionInitializationMethod_ == 2) { - for (size_t i = 0; i < neq_; i++) { - deltaX_trust_[i] = m_ewt[i] * m_normDeltaSoln_CP * trustRegionInitializationFactor_; - } - doublereal cpd = calcTrustDistance(deltaX_CP_); - if ((doDogLeg_ && m_print_flag >= 4)) { - printf("\t\t initializeTrustRegion(): Relative Distance of Cauchy Vector wrt Trust Vector = %g\n", cpd); - } - trustDelta_ = trustDelta_ * cpd * trustRegionInitializationFactor_; - readjustTrustVector(); - cpd = calcTrustDistance(deltaX_CP_); - if ((doDogLeg_ && m_print_flag >= 4)) { - printf("\t\t initializeTrustRegion(): Relative Distance of Cauchy Vector wrt Trust Vector = %g\n", cpd); - } - } - if (trustRegionInitializationMethod_ == 3) { - for (size_t i = 0; i < neq_; i++) { - deltaX_trust_[i] = m_ewt[i] * m_normDeltaSoln_Newton * trustRegionInitializationFactor_; - } - doublereal cpd = calcTrustDistance(deltaX_Newton_); - if ((doDogLeg_ && m_print_flag >= 4)) { - printf("\t\t initializeTrustRegion(): Relative Distance of Newton Vector wrt Trust Vector = %g\n", cpd); - } - trustDelta_ = trustDelta_ * cpd; - readjustTrustVector(); - cpd = calcTrustDistance(deltaX_Newton_); - if ((doDogLeg_ && m_print_flag >= 4)) { - printf("\t\t initializeTrustRegion(): Relative Distance of Newton Vector wrt Trust Vector = %g\n", cpd); - } - } -} - -void NonlinearSolver::fillDogLegStep(int leg, doublereal alpha, std::vector & deltaX) const -{ - if (leg == 0) { - for (size_t i = 0; i < neq_; i++) { - deltaX[i] = alpha * deltaX_CP_[i]; - } - } else if (leg == 2) { - for (size_t i = 0; i < neq_; i++) { - deltaX[i] = (alpha + (1.0 - alpha) * Nuu_) * deltaX_Newton_[i]; - } - } else { - for (size_t i = 0; i < neq_; i++) { - deltaX[i] = deltaX_CP_[i] * (1.0 - alpha) + alpha * Nuu_ * deltaX_Newton_[i]; - } - } -} - -doublereal NonlinearSolver::calcTrustDistance(std::vector const& deltaX) const -{ - doublereal sum = 0.0; - doublereal tmp = 0.0; - for (size_t i = 0; i < neq_; i++) { - tmp = deltaX[i] / deltaX_trust_[i]; - sum += tmp * tmp; - } - return sqrt(sum / neq_) / trustDelta_; -} - -int NonlinearSolver::calcTrustIntersection(doublereal trustDelta, doublereal& lambda, doublereal& alpha) const -{ - doublereal dist; - if (normTrust_Newton_ < trustDelta) { - lambda = 1.0; - alpha = 1.0; - return 2; - } - - if (normTrust_Newton_ * Nuu_ < trustDelta) { - alpha = (trustDelta - normTrust_Newton_ * Nuu_) / (normTrust_Newton_ - normTrust_Newton_ * Nuu_); - dist = dist_R0_ + dist_R1_ + alpha * dist_R2_; - lambda = dist / dist_Total_; - return 2; - } - if (normTrust_CP_ > trustDelta) { - lambda = 1.0; - dist = dist_R0_ * trustDelta / normTrust_CP_; - lambda = dist / dist_Total_; - alpha = trustDelta / normTrust_CP_; - return 0; - } - doublereal sumv = 0.0; - for (size_t i = 0; i < neq_; i++) { - sumv += (deltaX_Newton_[i] / deltaX_trust_[i]) * (deltaX_CP_[i] / deltaX_trust_[i]); - } - - doublereal a = normTrust_Newton_ * normTrust_Newton_ * Nuu_ * Nuu_; - doublereal b = 2.0 * Nuu_ * sumv; - doublereal c = normTrust_CP_ * normTrust_CP_ - trustDelta * trustDelta; - - alpha =(-b + sqrt(b * b - 4.0 * a * c)) / (2.0 * a); - - - dist = dist_R0_ + alpha * dist_R1_; - lambda = dist / dist_Total_; - return 1; -} - -doublereal NonlinearSolver::boundStep(const doublereal* const y, const doublereal* const step0) -{ - size_t i_lower = npos; - doublereal f_bounds = 1.0; - doublereal ff, y_new; - - for (size_t i = 0; i < neq_; i++) { - y_new = y[i] + step0[i]; - /* - * Force the step to only take 80% a step towards the lower bounds - */ - if (step0[i] < 0.0) { - if (y_new < (y[i] + 0.8 * (m_y_low_bounds[i] - y[i]))) { - doublereal legalDelta = 0.8*(m_y_low_bounds[i] - y[i]); - ff = legalDelta / step0[i]; - if (ff < f_bounds) { - f_bounds = ff; - i_lower = i; - } - } - } - /* - * Force the step to only take 80% a step towards the high bounds - */ - if (step0[i] > 0.0) { - if (y_new > (y[i] + 0.8 * (m_y_high_bounds[i] - y[i]))) { - doublereal legalDelta = 0.8*(m_y_high_bounds[i] - y[i]); - ff = legalDelta / step0[i]; - if (ff < f_bounds) { - f_bounds = ff; - i_lower = i; - } - } - } - - } - - /* - * Report on any corrections - */ - if (m_print_flag >= 3) { - if (f_bounds != 1.0) { - printf("\t\tboundStep: Variable %s causing bounds damping of %g\n", int2str(i_lower).c_str(), f_bounds); - } - } - - doublereal f_delta_bounds = deltaBoundStep(y, step0); - return std::min(f_bounds, f_delta_bounds); -} - -int NonlinearSolver::dampStep(const doublereal time_curr, const doublereal* const y_n_curr, - const doublereal* const ydot_n_curr, doublereal* const step_1, - doublereal* const y_n_1, doublereal* const ydot_n_1, doublereal* const step_2, - doublereal& stepNorm_2, GeneralMatrix& jac, bool writetitle, int& num_backtracks) -{ - int m; - int info = 0; - int retnTrial = NSOLN_RETN_FAIL_DAMPSTEP; - // Compute the weighted norm of the undamped step size step_1 - doublereal stepNorm_1 = solnErrorNorm(step_1); - - doublereal* step_1_orig = DATA_PTR(m_wksp); - for (size_t j = 0; j < neq_; j++) { - step_1_orig[j] = step_1[j]; - } - - - // Compute the multiplier to keep all components in bounds.A value of one indicates that there is no limitation - // on the current step size in the nonlinear method due to bounds constraints (either negative values of delta - // bounds constraints. - m_dampBound = boundStep(y_n_curr, step_1); - - // If fbound is very small, then y0 is already close to the boundary and step0 points out of the allowed domain. In - // this case, the Newton algorithm fails, so return an error condition. - if (m_dampBound < 1.e-30) { - if (m_print_flag > 1) { - printf("\t\t\tdampStep(): At limits.\n"); - } - return -3; - } - - //-------------------------------------------- - // Attempt damped step - //-------------------------------------------- - - // damping coefficient starts at 1.0 - m_dampRes = 1.0; - - doublereal ff = m_dampBound; - num_backtracks = 0; - for (m = 0; m < NDAMP; m++) { - - ff = m_dampBound * m_dampRes; - - // step the solution by the damped step size - /* - * Whenever we update the solution, we must also always - * update the time derivative. - */ - for (size_t j = 0; j < neq_; j++) { - step_1[j] = ff * step_1_orig[j]; - y_n_1[j] = y_n_curr[j] + step_1[j]; - } - - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, y_n_1, ydot_n_1); - } - /* - * Calculate the residual that would result if y1[] were the new solution vector - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - info = doResidualCalc(time_curr, solnType_, y_n_1, ydot_n_1, Base_LaggedSolutionComponents); - } else { - info = doResidualCalc(time_curr, solnType_, y_n_1, ydot_n_curr, Base_LaggedSolutionComponents); - } - if (info != 1) { - if (m_print_flag > 0) { - printf("\t\t\tdampStep(): current trial step and damping led to Residual Calc ERROR %d. Bailing\n", info); - } - return -1; - } - m_normResidTrial = residErrorNorm(DATA_PTR(m_resid)); - m_normResid_1 = m_normResidTrial; - if (m == 0) { - m_normResid_Bound = m_normResidTrial; - } - - bool steepEnough = (m_normResidTrial < m_normResid_0 * (0.9 * (1.0 - ff) * (1.0 - ff)* (1.0 - ff) + 0.1)); - - if (m_normResidTrial < 1.0 || steepEnough) { - if (m_print_flag >= 5) { - if (m_normResidTrial < 1.0) { - printf("\t dampStep(): Current trial step and damping" - " coefficient accepted because residTrial test step < 1:\n"); - printf("\t resid0 = %g, residTrial = %g\n", m_normResid_0, m_normResidTrial); - } else if (steepEnough) { - printf("\t dampStep(): Current trial step and damping" - " coefficient accepted because resid0 > residTrial and steep enough:\n"); - printf("\t resid0 = %g, residTrial = %g\n", m_normResid_0, m_normResidTrial); - } else { - printf("\t dampStep(): Current trial step and damping" - " coefficient accepted because residual solution damping is turned off:\n"); - printf("\t resid0 = %g, residTrial = %g\n", m_normResid_0, m_normResidTrial); - } - } - /* - * We aren't going to solve the system if we don't need to. Therefore, return an estimate - * of the next solution update based on the ratio of the residual reduction. - */ - if (m_normResid_0 > 0.0) { - stepNorm_2 = stepNorm_1 * m_normResidTrial / m_normResid_0; - } else { - stepNorm_2 = 0; - } - if (m_normResidTrial < 1.0) { - retnTrial = 3; - } else { - retnTrial = 4; - } - break; - } - - // Compute the next undamped step, step1[], that would result if y1[] were accepted. - // We now have two steps that we have calculated step0[] and step1[] - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - info = doNewtonSolve(time_curr, y_n_1, ydot_n_1, step_2, jac); - } else { - info = doNewtonSolve(time_curr, y_n_1, ydot_n_curr, step_2, jac); - } - if (info) { - if (m_print_flag > 0) { - printf("\t\t\tdampStep: current trial step and damping led to LAPACK ERROR %d. Bailing\n", info); - } - return -1; - } - - // compute the weighted norm of step1 - stepNorm_2 = solnErrorNorm(step_2); - - // write log information - if (m_print_flag >= 5) { - print_solnDelta_norm_contrib((const doublereal*) step_1_orig, "DeltaSoln", - (const doublereal*) step_2, "DeltaSolnTrial", - "dampNewt: Important Entries for Weighted Soln Updates:", - y_n_curr, y_n_1, ff, 5); - } - if (m_print_flag >= 4) { - printf("\t\t\tdampStep(): s1 = %g, s2 = %g, dampBound = %g," - "dampRes = %g\n", stepNorm_1, stepNorm_2, m_dampBound, m_dampRes); - } - - - // if the norm of s1 is less than the norm of s0, then - // accept this damping coefficient. Also accept it if this - // step would result in a converged solution. Otherwise, - // decrease the damping coefficient and try again. - - if (stepNorm_2 < 0.8 || stepNorm_2 < stepNorm_1) { - if (stepNorm_2 < 1.0) { - if (m_print_flag >= 3) { - if (stepNorm_2 < 1.0) { - printf("\t\t\tdampStep: current trial step and damping coefficient accepted because test step < 1\n"); - printf("\t\t\t s2 = %g, s1 = %g\n", stepNorm_2, stepNorm_1); - } - } - retnTrial = 2; - } else { - retnTrial = 1; - } - break; - } else { - if (m_print_flag > 1) { - printf("\t\t\tdampStep: current step rejected: (s1 = %g > " - "s0 = %g)", stepNorm_2, stepNorm_1); - if (m < (NDAMP-1)) { - printf(" Decreasing damping factor and retrying"); - } else { - printf(" Giving up!!!"); - } - printf("\n"); - } - } - num_backtracks++; - m_dampRes /= DampFactor; - } - - // If a damping coefficient was found, return 1 if the - // solution after stepping by the damped step would represent - // a converged solution, and return 0 otherwise. If no damping - // coefficient could be found, return NSOLN_RETN_FAIL_DAMPSTEP. - if (m < NDAMP) { - if (m_print_flag >= 4) { - printf("\t dampStep(): current trial step accepted retnTrial = %d, its = %d, damp = %g\n", retnTrial, m+1, ff); - } - return retnTrial; - } else { - if (stepNorm_2 < 0.5 && (stepNorm_1 < 0.5)) { - if (m_print_flag >= 4) { - printf("\t dampStep(): current trial step accepted kindof retnTrial = %d, its = %d, damp = %g\n", 2, m+1, ff); - } - return 2; - } - if (stepNorm_2 < 1.0) { - if (m_print_flag >= 4) { - printf("\t dampStep(): current trial step accepted and soln converged retnTrial =" - "%d, its = %d, damp = %g\n", 0, m+1, ff); - } - return 0; - } - } - if (m_print_flag >= 4) { - printf("\t dampStep(): current direction is rejected! retnTrial = %d, its = %d, damp = %g\n", - NSOLN_RETN_FAIL_DAMPSTEP, m+1, ff); - } - return NSOLN_RETN_FAIL_DAMPSTEP; -} - -int NonlinearSolver::dampDogLeg(const doublereal time_curr, const doublereal* y_n_curr, - const doublereal* ydot_n_curr, std::vector & step_1, - doublereal* const y_n_1, doublereal* const ydot_n_1, - doublereal& stepNorm_1, doublereal& stepNorm_2, GeneralMatrix& jac, int& numTrials) -{ - doublereal lambda; - int info; - - bool success = false; - bool haveASuccess = false; - doublereal trustDeltaOld = trustDelta_; - doublereal* stepLastGood = DATA_PTR(m_wksp); - //-------------------------------------------- - // Attempt damped step - //-------------------------------------------- - - // damping coefficient starts at 1.0 - m_dampRes = 1.0; - int m; - doublereal tlen; - - - for (m = 0; m < NDAMP; m++) { - numTrials++; - /* - * Find the initial value of lambda that satisfies the trust distance, trustDelta_ - */ - dogLegID_ = calcTrustIntersection(trustDelta_, lambda, dogLegAlpha_); - if (m_print_flag >= 4) { - tlen = trustRegionLength(); - printf("\t\t dampDogLeg: trust region with length %13.5E has intersection at leg = %d, alpha = %g, lambda = %g\n", - tlen, dogLegID_, dogLegAlpha_, lambda); - } - /* - * Figure out the new step vector, step_1, based on (leg, alpha). Here we are using the - * intersection of the trust oval with the dog-leg curve. - */ - fillDogLegStep(dogLegID_, dogLegAlpha_, step_1); - - /* - * OK, now that we have step0, Bound the step - */ - m_dampBound = boundStep(y_n_curr, DATA_PTR(step_1)); - /* - * Decrease the step length if we are bound - */ - if (m_dampBound < 1.0) { - for (size_t j = 0; j < neq_; j++) { - step_1[j] = step_1[j] * m_dampBound; - } - } - /* - * Calculate the new solution value y1[] given the step size - */ - for (size_t j = 0; j < neq_; j++) { - y_n_1[j] = y_n_curr[j] + step_1[j]; - } - /* - * Calculate the new solution time derivative given the step size - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, y_n_1, ydot_n_1); - } - /* - * OK, we have the step0. Now, ask the question whether it satisfies the acceptance criteria - * as a good step. The overall outcome is returned in the variable info. - */ - info = decideStep(time_curr, dogLegID_, dogLegAlpha_, y_n_curr, ydot_n_curr, step_1, - y_n_1, ydot_n_1, trustDeltaOld); - m_normResid_Bound = m_normResid_1; - - /* - * The algorithm failed to find a solution vector sufficiently different than the current point - */ - if (info == -1) { - - if (m_print_flag >= 1) { - doublereal stepNorm = solnErrorNorm(DATA_PTR(step_1)); - printf("\t\t dampDogLeg: Current direction rejected, update became too small %g\n", stepNorm); - success = false; - break; - } - } - if (info == -2) { - if (m_print_flag >= 1) { - printf("\t\t dampDogLeg: current trial step and damping led to LAPACK ERROR %d. Bailing\n", info); - success = false; - break; - } - } - if (info == 0) { - success = true; - break; - } - if (info == 3) { - - haveASuccess = true; - // Store the good results in stepLastGood - copy(step_1.begin(), step_1.end(), stepLastGood); - // Within the program decideStep(), we have already increased the value of trustDelta_. We store the - // value of step0 in step1, recalculate a larger step0 in the next fillDogLegStep(), - // and then attempt to see if the larger step works in the next iteration - } - if (info == 2) { - // Step was a failure. If we had a previous success with a smaller stepsize, haveASuccess is true - // and we execute the next block and break. If we didn't have a previous success, trustDelta_ has - // already been decreased in the decideStep() routine. We go back and try another iteration with - // a smaller trust region. - if (haveASuccess) { - copy(stepLastGood, stepLastGood+neq_, step_1.begin()); - for (size_t j = 0; j < neq_; j++) { - y_n_1[j] = y_n_curr[j] + step_1[j]; - } - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, y_n_1, ydot_n_1); - } - success = true; - break; - } else { - - } - } - } - - /* - * Estimate s1, the norm after the next step - */ - stepNorm_1 = solnErrorNorm(DATA_PTR(step_1)); - stepNorm_2 = stepNorm_1; - if (m_dampBound < 1.0) { - stepNorm_2 /= m_dampBound; - } - stepNorm_2 /= lambda; - stepNorm_2 *= m_normResidTrial / m_normResid_0; - - - if (success) { - if (m_normResidTrial < 1.0) { - if (normTrust_Newton_ < trustDelta_ && m_dampBound == 1.0) { - return 1; - } else { - return 0; - } - } - return 0; - } - return NSOLN_RETN_FAIL_DAMPSTEP; -} - -int NonlinearSolver::decideStep(const doublereal time_curr, int leg, doublereal alpha, - const doublereal* const y_n_curr, - const doublereal* const ydot_n_curr, const std::vector & step_1, - const doublereal* const y_n_1, const doublereal* const ydot_n_1, - doublereal trustDeltaOld) -{ - int retn = 2; - int info; - doublereal ll; - // Calculate the solution step length - doublereal stepNorm = solnErrorNorm(DATA_PTR(step_1)); - - // Calculate the initial (R**2 * neq) value for the old function - doublereal normResid0_2 = m_normResid_0 * m_normResid_0 * neq_; - - // Calculate the distance to the Cauchy point - doublereal cauchyDistanceNorm = solnErrorNorm(DATA_PTR(deltaX_CP_)); - - // This is the expected initial rate of decrease in the Cauchy direction. - // -> This is Eqn. 29 = Rhat dot Jhat dy / || d || - doublereal funcDecreaseSDExp = RJd_norm_ / cauchyDistanceNorm * lambdaStar_; - if (funcDecreaseSDExp > 0.0) { - if (m_print_flag >= 5) { - printf("\t\tdecideStep(): Unexpected condition -> Cauchy slope is positive\n"); - } - } - - /* - * Calculate the residual that would result if y1[] were the new solution vector. - * The Lagged solution components are kept lagged here. Unfortunately, it just doesn't work in some cases to use a - * Jacobian from a lagged state and then use a residual from an unlagged condition. The linear model doesn't - * agree with the nonlinear model. - * -> m_resid[] contains the result of the residual calculation - */ - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - info = doResidualCalc(time_curr, solnType_, y_n_1, ydot_n_1, Base_LaggedSolutionComponents); - } else { - info = doResidualCalc(time_curr, solnType_, y_n_1, ydot_n_curr, Base_LaggedSolutionComponents); - } - - if (info != 1) { - if (m_print_flag >= 2) { - printf("\t\tdecideStep: current trial step and damping led to Residual Calc ERROR %d. Bailing\n", info); - } - return -2; - } - /* - * Ok we have a successful new residual. Calculate the normalized residual value and store it in - * m_normResidTrial - */ - m_normResidTrial = residErrorNorm(DATA_PTR(m_resid)); - doublereal normResidTrial_2 = neq_ * m_normResidTrial * m_normResidTrial; - - /* - * We have a minimal acceptance test for passage. deltaf < 1.0E-4 (CauchySlope) (deltS) - * This is the condition that D&S use in 6.4.5 - */ - doublereal funcDecrease = 0.5 * (normResidTrial_2 - normResid0_2); - doublereal acceptableDelF = funcDecreaseSDExp * stepNorm * 1.0E-4; - if (funcDecrease < acceptableDelF) { - m_normResid_1 = m_normResidTrial; - m_normResid_1 = m_normResidTrial; - retn = 0; - if (m_print_flag >= 4) { - printf("\t\t decideStep: Norm Residual(leg=%1d, alpha=%10.2E) = %11.4E passes\n", - dogLegID_, dogLegAlpha_, m_normResidTrial); - } - } else { - if (m_print_flag >= 4) { - printf("\t\t decideStep: Norm Residual(leg=%1d, alpha=%10.2E) = %11.4E failes\n", - dogLegID_, dogLegAlpha_, m_normResidTrial); - } - trustDelta_ *= 0.33; - CurrentTrustFactor_ *= 0.33; - retn = 2; - // error condition if step is getting too small - if (rtol_ * stepNorm < 1.0E-6) { - retn = -1; - } - return retn; - } - /* - * Figure out the next trust region. We are here iff retn = 0 - * - * If we had to bounds delta the update, decrease the trust region - */ - if (m_dampBound >= 1.0) { - retn = 0; - /* - * Calculate the expected residual from the quadratic model - */ - doublereal expectedNormRes = expectedResidLeg(leg, alpha); - doublereal expectedFuncDecrease = 0.5 * (neq_ * expectedNormRes * expectedNormRes - normResid0_2); - if (funcDecrease > 0.1 * expectedFuncDecrease) { - if ((m_normResidTrial > 0.5 * m_normResid_0) && (m_normResidTrial > 0.1)) { - trustDelta_ *= 0.5; - NextTrustFactor_ *= 0.5; - ll = trustRegionLength(); - if (m_print_flag >= 4) { - printf("\t\t decideStep: Trust region decreased from %g to %g due to bad quad approximation\n", - ll*2, ll); - } - } - } else { - /* - * If we are doing well, consider increasing the trust region and recalculating - */ - if (funcDecrease < 0.8 * expectedFuncDecrease || (m_normResidTrial < 0.33 * m_normResid_0)) { - if (trustDelta_ <= trustDeltaOld && (leg != 2 || alpha < 0.75)) { - trustDelta_ *= 2.0; - CurrentTrustFactor_ *= 2; - adjustUpStepMinimums(); - ll = trustRegionLength(); - if (m_print_flag >= 4) { - if (m_normResidTrial < 0.33 * m_normResid_0) { - printf("\t\t decideStep: Redo line search with trust region increased from %g to %g due to good nonlinear behavior\n", - ll*0.5, ll); - } else { - printf("\t\t decideStep: Redi line search with trust region increased from %g to %g due to good linear model approximation\n", - ll*0.5, ll); - } - } - retn = 3; - } else { - /* - * Increase the size of the trust region for the next calculation - */ - if (m_normResidTrial < 0.99 * expectedNormRes || (m_normResidTrial < 0.20 * m_normResid_0) || - (funcDecrease < -1.0E-50 && (funcDecrease < 0.9 *expectedFuncDecrease))) { - if (leg == 2 && alpha == 1.0) { - ll = trustRegionLength(); - if (ll < 2.0 * m_normDeltaSoln_Newton) { - trustDelta_ *= 2.0; - NextTrustFactor_ *= 2.0; - adjustUpStepMinimums(); - ll = trustRegionLength(); - if (m_print_flag >= 4) { - printf("\t\t decideStep: Trust region further increased from %g to %g next step due to good linear model behavior\n", - ll*0.5, ll); - } - } - } else { - ll = trustRegionLength(); - trustDelta_ *= 2.0; - NextTrustFactor_ *= 2.0; - adjustUpStepMinimums(); - ll = trustRegionLength(); - if (m_print_flag >= 4) { - printf("\t\t decideStep: Trust region further increased from %g to %g next step due to good linear model behavior\n", - ll*0.5, ll); - } - } - } - } - } - } - } - return retn; -} - -int NonlinearSolver::solve_nonlinear_problem(int SolnType, doublereal* const y_comm, doublereal* const ydot_comm, - doublereal CJ, doublereal time_curr, GeneralMatrix& jac, - int& num_newt_its, int& num_linear_solves, - int& num_backtracks, int loglevelInput) -{ - clockWC wc; - int convRes = 0; - solnType_ = SolnType; - int info = 0; - if (neq_ <= 0) { - return 1; - } - - num_linear_solves -= m_numTotalLinearSolves; - int retnDamp = 0; - int retnCode = 0; - bool forceNewJac = false; - - delete jacCopyPtr_; - jacCopyPtr_ = jac.duplMyselfAsGeneralMatrix(); - - doublereal stepNorm_1; - doublereal stepNorm_2; - int legBest; - doublereal alphaBest; - bool trInit = false; - - copy(y_comm, y_comm + neq_, m_y_n_curr.begin()); - - if (SolnType != NSOLN_TYPE_STEADY_STATE || ydot_comm) { - copy(ydot_comm, ydot_comm + neq_, m_ydot_n_curr.begin()); - copy(ydot_comm, ydot_comm + neq_, m_ydot_trial.begin()); - } - // Redo the solution weights every time we enter the function - createSolnWeights(DATA_PTR(m_y_n_curr)); - m_normDeltaSoln_Newton = 1.0E1; - bool frst = true; - num_newt_its = 0; - num_backtracks = 0; - int i_numTrials; - m_print_flag = loglevelInput; - - if (trustRegionInitializationMethod_ == 0) { - trInit = true; - } else if (trustRegionInitializationMethod_ == 1) { - trInit = true; - initializeTrustRegion(); - } else { - deltaX_trust_.assign(neq_, 1.0); - trustDelta_ = 1.0; - } - - if (m_print_flag == 2 || m_print_flag == 3) { - printf("\tsolve_nonlinear_problem():\n\n"); - if (doDogLeg_) { - printf("\tWt Iter Resid NewJac log(CN)| dRdS_CDexp dRdS_CD dRdS_Newtexp dRdS_Newt |" - "DS_Cauchy DS_Newton DS_Trust | legID legAlpha Fbound | CTF NTF | nTr|" - "DS_Final ResidLag ResidFull\n"); - printf("\t---------------------------------------------------------------------------------------------------" - "--------------------------------------------------------------------------------\n"); - } else { - printf("\t Wt Iter Resid NewJac | Fbound ResidBound | DampIts Fdamp DS_Step1 DS_Step2" - "ResidLag | DS_Damp DS_Newton ResidFull\n"); - printf("\t--------------------------------------------------------------------------------------------------" - "----------------------------------\n"); - } - } - - while (1 > 0) { - - CurrentTrustFactor_ = 1.0; - NextTrustFactor_ = 1.0; - ResidWtsReevaluated_ = false; - i_numTrials = 0; - /* - * Increment Newton Solve counter - */ - m_numTotalNewtIts++; - num_newt_its++; - m_numLocalLinearSolves = 0; - - if (m_print_flag > 3) { - printf("\t"); - writeline('=', 119); - printf("\tsolve_nonlinear_problem(): iteration %d:\n", - num_newt_its); - } - /* - * If we are far enough away from the solution, redo the solution weights and the trust vectors. - */ - if (m_normDeltaSoln_Newton > 1.0E2 || (num_newt_its % 5) == 1) { - createSolnWeights(DATA_PTR(m_y_n_curr)); - if (trInit && (DEBUG_MODE_ENABLED || doDogLeg_)) { - readjustTrustVector(); - } - } - - /* - * Set default values of Delta bounds constraints - */ - if (!m_manualDeltaStepSet) { - setDefaultDeltaBoundsMagnitudes(); - } - - // Check whether the Jacobian should be re-evaluated. - - forceNewJac = true; - - if (forceNewJac) { - if (m_print_flag > 3) { - printf("\t solve_nonlinear_problem(): Getting a new Jacobian\n"); - } - info = beuler_jac(jac, DATA_PTR(m_resid), time_curr, CJ, DATA_PTR(m_y_n_curr), - DATA_PTR(m_ydot_n_curr), num_newt_its); - if (info != 1) { - if (m_print_flag > 0) { - printf("\t solve_nonlinear_problem(): Jacobian Formation Error: %d Bailing\n", info); - } - retnDamp = NSOLN_RETN_JACOBIANFORMATIONERROR ; - goto done; - } - } else { - if (m_print_flag > 1) { - printf("\t solve_nonlinear_problem(): Solving system with old Jacobian\n"); - } - } - /* - * Go get new scales - */ - calcColumnScales(); - - - /* - * Calculate the base residual - */ - if (m_print_flag >= 6) { - printf("\t solve_nonlinear_problem(): Calculate the base residual\n"); - } - info = doResidualCalc(time_curr, NSOLN_TYPE_STEADY_STATE, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr)); - if (info != 1) { - if (m_print_flag > 0) { - printf("\t solve_nonlinear_problem(): Residual Calc ERROR %d. Bailing\n", info); - } - retnDamp = NSOLN_RETN_RESIDUALFORMATIONERROR; - goto done; - } - - /* - * Scale the matrix and the RHS, if they aren't already scaled - * Figure out and store the residual scaling factors. - */ - scaleMatrix(jac, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr), time_curr, num_newt_its); - - - /* - * Optional print out the initial residual - */ - if (m_print_flag >= 6) { - m_normResid_0 = residErrorNorm(DATA_PTR(m_resid), "Initial norm of the residual", 10, DATA_PTR(m_y_n_curr)); - } else { - m_normResid_0 = residErrorNorm(DATA_PTR(m_resid), "Initial norm of the residual", 0, DATA_PTR(m_y_n_curr)); - if (m_print_flag == 4 || m_print_flag == 5) { - printf("\t solve_nonlinear_problem(): Initial Residual Norm = %13.4E\n", m_normResid_0); - } - } - - if (DEBUG_MODE_ENABLED || doDogLeg_) { - if (m_print_flag > 3) { - printf("\t solve_nonlinear_problem(): Calculate the steepest descent direction and Cauchy Point\n"); - } - m_normDeltaSoln_CP = doCauchyPointSolve(jac); - } - - // compute the undamped Newton step - if (doAffineSolve_) { - if (m_print_flag >= 4) { - printf("\t solve_nonlinear_problem(): Calculate the Newton direction via an Affine solve\n"); - } - info = doAffineNewtonSolve(DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr), DATA_PTR(deltaX_Newton_), jac); - } else { - if (m_print_flag >= 4) { - printf("\t solve_nonlinear_problem(): Calculate the Newton direction via a Newton solve\n"); - } - info = doNewtonSolve(time_curr, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr), DATA_PTR(deltaX_Newton_), jac); - } - - if (info) { - retnDamp = NSOLN_RETN_MATRIXINVERSIONERROR; - if (m_print_flag > 0) { - printf("\t solve_nonlinear_problem(): Matrix Inversion Error: %d Bailing\n", info); - } - goto done; - } - m_step_1 = deltaX_Newton_; - - if (m_print_flag >= 6) { - m_normDeltaSoln_Newton = solnErrorNorm(DATA_PTR(deltaX_Newton_), "Initial Undamped Newton Step of the iteration", 10); - } else { - m_normDeltaSoln_Newton = solnErrorNorm(DATA_PTR(deltaX_Newton_), "Initial Undamped Newton Step of the iteration", 0); - } - - if (m_numTotalNewtIts == 1) { - if (trustRegionInitializationMethod_ == 2 || trustRegionInitializationMethod_ == 3) { - if (m_print_flag > 3) { - if (trustRegionInitializationMethod_ == 2) { - printf("\t solve_nonlinear_problem(): Initialize the trust region size as the length of the Cauchy Vector times %f\n", - trustRegionInitializationFactor_); - } else { - printf("\t solve_nonlinear_problem(): Initialize the trust region size as the length of the Newton Vector times %f\n", - trustRegionInitializationFactor_); - } - } - initializeTrustRegion(); - trInit = true; - } - } - - if (DEBUG_MODE_ENABLED && doDogLeg_ && m_print_flag >= 4) { - doublereal trustD = calcTrustDistance(m_step_1); - if (trustD > trustDelta_) { - printf("\t\t Newton's method step size, %g trustVectorUnits, larger than trust region, %g trustVectorUnits\n", - trustD, trustDelta_); - printf("\t\t Newton's method step size, %g trustVectorUnits, larger than trust region, %g trustVectorUnits\n", - trustD, trustDelta_); - } else { - printf("\t\t Newton's method step size, %g trustVectorUnits, smaller than trust region, %g trustVectorUnits\n", - trustD, trustDelta_); - } - } - - /* - * Filter out bad directions - */ - filterNewStep(time_curr, DATA_PTR(m_y_n_curr), DATA_PTR(m_step_1)); - - - - if (s_print_DogLeg && m_print_flag >= 4) { - printf("\t solve_nonlinear_problem(): Compare descent rates for Cauchy and Newton directions\n"); - descentComparison(time_curr, DATA_PTR(m_ydot_n_curr), DATA_PTR(m_ydot_trial), i_numTrials); - } else { - if (doDogLeg_) { - descentComparison(time_curr, DATA_PTR(m_ydot_n_curr), DATA_PTR(m_ydot_trial), i_numTrials); - } - } - - - - if (doDogLeg_) { - setupDoubleDogleg(); - if (DEBUG_MODE_ENABLED && s_print_DogLeg && m_print_flag >= 5) { - printf("\t solve_nonlinear_problem(): Compare Linear and nonlinear residuals along double dog-leg path\n"); - residualComparisonLeg(time_curr, DATA_PTR(m_ydot_n_curr), legBest, alphaBest); - } - if (m_print_flag >= 4) { - printf("\t solve_nonlinear_problem(): Calculate damping along dog-leg path to ensure residual decrease\n"); - } - retnDamp = dampDogLeg(time_curr, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr), - m_step_1, DATA_PTR(m_y_n_trial), DATA_PTR(m_ydot_trial), stepNorm_1, stepNorm_2, jac, i_numTrials); - } else if (DEBUG_MODE_ENABLED && s_print_DogLeg && m_print_flag >= 5) { - printf("\t solve_nonlinear_problem(): Compare Linear and nonlinear residuals along double dog-leg path\n"); - residualComparisonLeg(time_curr, DATA_PTR(m_ydot_n_curr), legBest, alphaBest); - } - - // Damp the Newton step - /* - * On return the recommended new solution and derivatives is located in: - * y_new - * y_dot_new - * The update delta vector is located in - * stp1 - * The estimate of the solution update norm for the next step is located in - * s1 - */ - if (!doDogLeg_) { - retnDamp = dampStep(time_curr, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr), - DATA_PTR(m_step_1), DATA_PTR(m_y_n_trial), DATA_PTR(m_ydot_trial), - DATA_PTR(m_wksp_2), stepNorm_2, jac, frst, i_numTrials); - frst = false; - num_backtracks += i_numTrials; - stepNorm_1 = solnErrorNorm(DATA_PTR(m_step_1)); - } - - - /* - * Impose the minimum number of Newton iterations criteria - */ - if (num_newt_its < m_min_newt_its) { - if (retnDamp > NSOLN_RETN_CONTINUE) { - if (m_print_flag > 2) { - printf("\t solve_nonlinear_problem(): Damped Newton successful (m=%d) but minimum Newton" - "iterations not attained. Resolving ...\n", retnDamp); - } - retnDamp = NSOLN_RETN_CONTINUE; - } - } - - /* - * Impose max Newton iteration - */ - if (num_newt_its > maxNewtIts_) { - retnDamp = NSOLN_RETN_MAXIMUMITERATIONSEXCEEDED; - if (m_print_flag > 1) { - printf("\t solve_nonlinear_problem(): Damped Newton unsuccessful (max newts exceeded) sfinal = %g\n", - stepNorm_1); - } - } - - /* - * Do a full residual calculation with the unlagged solution components. - * Then get the norm of the residual - */ - info = doResidualCalc(time_curr, NSOLN_TYPE_STEADY_STATE, DATA_PTR(m_y_n_trial), DATA_PTR(m_ydot_trial)); - if (info != 1) { - if (m_print_flag > 0) { - printf("\t solve_nonlinear_problem(): current trial step and damping led to Residual Calc " - "ERROR %d. Bailing\n", info); - } - retnDamp = NSOLN_RETN_RESIDUALFORMATIONERROR; - goto done; - } - if (m_print_flag >= 4) { - m_normResid_full = residErrorNorm(DATA_PTR(m_resid), " Resulting full residual norm", 10, DATA_PTR(m_y_n_trial)); - if (fabs(m_normResid_full - m_normResid_1) > 1.0E-3 * (m_normResid_1 + m_normResid_full + 1.0E-4)) { - if (m_print_flag >= 4) { - printf("\t solve_nonlinear_problem(): Full residual norm changed from %g to %g due to " - "lagging of components\n", m_normResid_1, m_normResid_full); - } - } - } else { - m_normResid_full = residErrorNorm(DATA_PTR(m_resid)); - } - - /* - * Check the convergence criteria - */ - convRes = 0; - if (retnDamp > NSOLN_RETN_CONTINUE) { - convRes = convergenceCheck(retnDamp, stepNorm_1); - } - - - - - bool m_filterIntermediate = false; - if (m_filterIntermediate) { - if (retnDamp == NSOLN_RETN_CONTINUE) { - (void) filterNewSolution(time_n, DATA_PTR(m_y_n_trial), DATA_PTR(m_ydot_trial)); - } - } - - // Exchange new for curr solutions - if (retnDamp >= NSOLN_RETN_CONTINUE) { - m_y_n_curr = m_y_n_trial; - - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - calc_ydot(m_order, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr)); - } - } - - if (m_print_flag == 2 || m_print_flag == 3) { - if (ResidWtsReevaluated_) { - printf("\t*"); - } else { - printf("\t "); - } - printf(" %3d %11.3E", num_newt_its, m_normResid_0); - bool m_jacAge = false; - if (!m_jacAge) { - printf(" Y "); - } else { - printf(" N "); - } - if (doDogLeg_) { - printf("%5.1F |", log10(m_conditionNumber)); - // printf("\t Iter Resid NewJac | DS_Cauchy DS_Newton DS_Trust | legID legAlpha Fbound | | DS_F ResidFinal \n"); - printf("%10.3E %10.3E %10.3E %10.3E|", ResidDecreaseSDExp_, ResidDecreaseSD_, - ResidDecreaseNewtExp_, ResidDecreaseNewt_); - printf("%10.3E %10.3E %10.3E|", m_normDeltaSoln_CP , m_normDeltaSoln_Newton, norm_deltaX_trust_ * trustDelta_); - printf("%2d %10.2E %10.2E", dogLegID_ , dogLegAlpha_, m_dampBound); - printf("| %3.2f %3.2f |", CurrentTrustFactor_, NextTrustFactor_); - printf(" %2d ", i_numTrials); - printf("| %10.3E %10.3E %10.3E", stepNorm_1, m_normResid_1, m_normResid_full); - } else { - printf(" |"); - printf("%10.2E %10.3E |", m_dampBound, m_normResid_Bound); - printf("%2d %10.2E %10.3E %10.3E %10.3E", i_numTrials + 1, m_dampRes, - stepNorm_1 / (m_dampRes * m_dampBound), stepNorm_2, m_normResid_1); - printf("| %10.3E %10.3E %10.3E", stepNorm_1, m_normDeltaSoln_Newton, m_normResid_full); - } - printf("\n"); - - } - if (m_print_flag >= 4) { - if (doDogLeg_) { - if (convRes > 0) { - printf("\t solve_nonlinear_problem(): Problem Converged, stepNorm = %11.3E, reduction of res from %11.3E to %11.3E\n", - stepNorm_1, m_normResid_0, m_normResid_full); - printf("\t"); - writeline('=', 119); - } else { - printf("\t solve_nonlinear_problem(): Successfull step taken with stepNorm = %11.3E, reduction of res from %11.3E to %11.3E\n", - stepNorm_1, m_normResid_0, m_normResid_full); - } - } else { - if (convRes > 0) { - printf("\t solve_nonlinear_problem(): Damped Newton iteration successful, nonlin " - "converged, final estimate of the next solution update norm = %-12.4E\n", stepNorm_2); - printf("\t"); - writeline('=', 119); - } else if (retnDamp >= NSOLN_RETN_CONTINUE) { - printf("\t solve_nonlinear_problem(): Damped Newton iteration successful, " - "estimate of the next solution update norm = %-12.4E\n", stepNorm_2); - } else { - printf("\t solve_nonlinear_problem(): Damped Newton unsuccessful, final estimate " - "of the next solution update norm = %-12.4E\n", stepNorm_2); - } - } - } - - /* - * Do a full residual calculation with the unlagged solution components calling ShowSolution to perhaps print out the solution. - */ - if (m_print_flag >= 4) { - if (convRes > 0 || m_print_flag >= 6) { - info = doResidualCalc(time_curr, NSOLN_TYPE_STEADY_STATE, DATA_PTR(m_y_n_curr), DATA_PTR(m_ydot_n_curr), Base_ShowSolution); - if (info != 1) { - if (m_print_flag > 0) { - printf("\t solve_nonlinear_problem(): Final ShowSolution residual eval returned an error! " - "ERROR %d. Bailing\n", info); - } - retnDamp = NSOLN_RETN_RESIDUALFORMATIONERROR; - goto done; - } - } - } - - // convergence - if (convRes) { - goto done; - } - - // If dampStep fails, first try a new Jacobian if an old - // one was being used. If it was a new Jacobian, then - // return -1 to signify failure. - else if (retnDamp < NSOLN_RETN_CONTINUE) { - goto done; - } - } - -done: - - - if (m_print_flag == 2 || m_print_flag == 3) { - if (convRes > 0) { - if (doDogLeg_) { - if (convRes == 3) { - printf("\t | | " - " | | converged = 3 |(%11.3E) \n", stepNorm_2); - } else { - printf("\t | | " - " | | converged = %1d | %10.3E %10.3E\n", convRes, - stepNorm_2, m_normResidTrial); - } - printf("\t-----------------------------------------------------------------------------------------------------" - "------------------------------------------------------------------------------\n"); - } else { - if (convRes == 3) { - printf("\t | " - " | converged = 3 | (%11.3E) \n", stepNorm_2); - } else { - printf("\t | " - " | converged = %1d | %10.3E %10.3E\n", convRes, - stepNorm_2, m_normResidTrial); - } - printf("\t------------------------------------------------------------------------------------" - "-----------------------------------------------\n"); - } - } - - - - } - - copy(m_y_n_curr.begin(), m_y_n_curr.end(), y_comm); - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - copy(m_ydot_n_curr.begin(), m_ydot_n_curr.end(), ydot_comm); - } - - num_linear_solves += m_numTotalLinearSolves; - - doublereal time_elapsed = wc.secondsWC(); - if (m_print_flag > 1) { - if (retnDamp > 0) { - if (NonlinearSolver::s_TurnOffTiming) { - printf("\tNonlinear problem solved successfully in %d its\n", - num_newt_its); - } else { - printf("\tNonlinear problem solved successfully in %d its, time elapsed = %g sec\n", - num_newt_its, time_elapsed); - } - } else { - printf("\tNonlinear problem failed to solve after %d its\n", num_newt_its); - } - } - retnCode = retnDamp; - if (retnDamp > 0) { - retnCode = NSOLN_RETN_SUCCESS; - } - - - return retnCode; -} - -void NonlinearSolver::setPreviousTimeStep(const std::vector& y_nm1, - const std::vector& ydot_nm1) -{ - m_y_nm1 = y_nm1; - m_ydot_nm1 = ydot_nm1; -} - -void NonlinearSolver::print_solnDelta_norm_contrib(const doublereal* const step_1, - const char* const stepNorm_1, - const doublereal* const step_2, - const char* const stepNorm_2, - const char* const title, - const doublereal* const y_n_curr, - const doublereal* const y_n_1, - doublereal damp, - size_t num_entries) -{ - bool used; - doublereal dmax0, dmax1, error, rel_norm; - printf("\t\t%s currentDamp = %g\n", title, damp); - printf("\t\t I ysolnOld %13s ysolnNewRaw | ysolnNewTrial " - "%10s ysolnNewTrialRaw | solnWeight wtDelSoln wtDelSolnTrial\n", stepNorm_1, stepNorm_2); - std::vector imax(num_entries, npos); - printf("\t\t "); - writeline('-', 125); - for (size_t jnum = 0; jnum < num_entries; jnum++) { - dmax1 = -1.0; - for (size_t i = 0; i < neq_; i++) { - used = false; - for (size_t j = 0; j < jnum; j++) { - if (imax[j] == i) { - used = true; - } - } - if (!used) { - error = step_1[i] / m_ewt[i]; - rel_norm = sqrt(error * error); - error = step_2[i] / m_ewt[i]; - rel_norm += sqrt(error * error); - if (rel_norm > dmax1) { - imax[jnum] = i; - dmax1 = rel_norm; - } - } - } - if (imax[jnum] != npos) { - size_t i = imax[jnum]; - error = step_1[i] / m_ewt[i]; - dmax0 = sqrt(error * error); - error = step_2[i] / m_ewt[i]; - dmax1 = sqrt(error * error); - printf("\t\t %4s %12.4e %12.4e %12.4e | %12.4e %12.4e %12.4e |%12.4e %12.4e %12.4e\n", - int2str(i).c_str(), y_n_curr[i], step_1[i], y_n_curr[i] + step_1[i], y_n_1[i], - step_2[i], y_n_1[i]+ step_2[i], m_ewt[i], dmax0, dmax1); - } - } - printf("\t\t "); - writeline('-', 125); -} - -//! This routine subtracts two numbers for one another -/*! - * This routine subtracts 2 numbers. If the difference is less - * than 1.0E-14 times the magnitude of the smallest number, then diff returns an exact zero. - * It also returns an exact zero if the difference is less than - * 1.0E-300. - * - * returns: a - b - * - * This routine is used in numerical differencing schemes in order - * to avoid roundoff errors resulting in creating Jacobian terms. - * Note: This is a slow routine. However, Jacobian errors may cause - * loss of convergence. Therefore, in practice this routine has proved cost-effective. - * - * @param a Value of a - * @param b value of b - * - * @return returns the difference between a and b - */ -static inline doublereal subtractRD(doublereal a, doublereal b) -{ - doublereal diff = a - b; - doublereal d = std::min(fabs(a), fabs(b)); - d *= 1.0E-14; - doublereal ad = fabs(diff); - if (ad < 1.0E-300) { - diff = 0.0; - } - if (ad < d) { - diff = 0.0; - } - return diff; -} - -int NonlinearSolver::beuler_jac(GeneralMatrix& J, doublereal* const f, - doublereal time_curr, doublereal CJ, - doublereal* const y, doublereal* const ydot, - int num_newt_its) -{ - double* col_j; - int info; - doublereal ysave, dy; - doublereal ydotsave = 0; - int retn = 1; - - /* - * Clear the factor flag - */ - J.clearFactorFlag(); - if (m_jacFormMethod == NSOLN_JAC_ANAL) { - /******************************************************************** - * Call the function to get a Jacobian. - */ - info = m_func->evalJacobian(time_curr, delta_t_n, CJ, y, ydot, J, f); - m_nJacEval++; - m_nfe++; - if (info != 1) { - return info; - } - } else { - if (J.matrixType_ == 0) { - /******************************************************************* - * Generic algorithm to calculate a numerical Jacobian - */ - /* - * Calculate the current value of the RHS given the - * current conditions. - */ - - info = m_func->evalResidNJ(time_curr, delta_t_n, y, ydot, f, JacBase_ResidEval); - m_nfe++; - if (info != 1) { - return info; - } - m_nJacEval++; - if (DEBUG_MODE_ENABLED) { - for (size_t ii = 0; ii < neq_; ii++) { - checkFinite(f[ii]); - } - } - - /* - * Malloc a vector and call the function object to return a set of - * deltaY's that are appropriate for calculating the numerical - * derivative. - */ - vector_fp dyVector(neq_); - retn = m_func->calcDeltaSolnVariables(time_curr, y, ydot, &dyVector[0], DATA_PTR(m_ewt)); - if (s_print_NumJac) { - if (m_print_flag >= 7) { - if (retn != 1) { - printf("\t\t beuler_jac ERROR! calcDeltaSolnVariables() returned an error flag\n"); - printf("\t\t We will bail from the nonlinear solver after calculating the Jacobian"); - } - if (neq_ < 20) { - printf("\t\tUnk m_ewt y dyVector ResN\n"); - for (size_t iii = 0; iii < neq_; iii++) { - printf("\t\t %4s %16.8e %16.8e %16.8e %16.8e \n", - int2str(iii).c_str(), m_ewt[iii], y[iii], dyVector[iii], f[iii]); - } - } - } - } - - /* - * Loop over the variables, formulating a numerical derivative - * of the dense matrix. - * For the delta in the variable, we will use a variety of approaches - * The original approach was to use the error tolerance amount. - * This may not be the best approach, as it could be overly large in - * some instances and overly small in others. - * We will first protect from being overly small, by using the usual - * sqrt of machine precision approach, i.e., 1.0E-7, - * to bound the lower limit of the delta. - */ - for (size_t j = 0; j < neq_; j++) { - - - /* - * Get a pointer into the column of the matrix - */ - - - col_j = (doublereal*) J.ptrColumn(j); - ysave = y[j]; - dy = dyVector[j]; - - y[j] = ysave + dy; - dy = y[j] - ysave; - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - ydotsave = ydot[j]; - ydot[j] += dy * CJ; - } - /* - * Call the function - */ - - - info = m_func->evalResidNJ(time_curr, delta_t_n, y, ydot, DATA_PTR(m_wksp), - JacDelta_ResidEval, static_cast(j), dy); - m_nfe++; - - if (DEBUG_MODE_ENABLED) { - if (fabs(dy) < 1.0E-300) { - throw CanteraError("NonlinearSolver::beuler_jac", "dy is equal to zero"); - } - for (size_t ii = 0; ii < neq_; ii++) { - checkFinite(m_wksp[ii]); - } - } - - if (info != 1) { - return info; - } - - doublereal diff; - for (size_t i = 0; i < neq_; i++) { - diff = subtractRD(m_wksp[i], f[i]); - col_j[i] = diff / dy; - } - y[j] = ysave; - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - ydot[j] = ydotsave; - } - - } - } else if (J.matrixType_ == 1) { - int ku, kl; - size_t ivec[2]; - size_t n = J.nRowsAndStruct(ivec); - kl = static_cast(ivec[0]); - ku = static_cast(ivec[1]); - if (n != neq_) { - printf("we have probs\n"); - exit(-1); - } - - // --------------------------------- BANDED MATRIX BRAIN DEAD --------------------------------------------------- - info = m_func->evalResidNJ(time_curr, delta_t_n, y, ydot, f, JacBase_ResidEval); - m_nfe++; - if (info != 1) { - return info; - } - m_nJacEval++; - - - vector_fp dyVector(neq_); - retn = m_func->calcDeltaSolnVariables(time_curr, y, ydot, &dyVector[0], DATA_PTR(m_ewt)); - if (s_print_NumJac) { - if (m_print_flag >= 7) { - if (retn != 1) { - printf("\t\t beuler_jac ERROR! calcDeltaSolnVariables() returned an error flag\n"); - printf("\t\t We will bail from the nonlinear solver after calculating the Jacobian"); - } - if (neq_ < 20) { - printf("\t\tUnk m_ewt y dyVector ResN\n"); - for (size_t iii = 0; iii < neq_; iii++) { - printf("\t\t %4s %16.8e %16.8e %16.8e %16.8e \n", - int2str(iii).c_str(), m_ewt[iii], y[iii], dyVector[iii], f[iii]); - } - } - } - } - - - for (size_t j = 0; j < neq_; j++) { - - - col_j = (doublereal*) J.ptrColumn(j); - ysave = y[j]; - dy = dyVector[j]; - - - y[j] = ysave + dy; - dy = y[j] - ysave; - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - ydotsave = ydot[j]; - ydot[j] += dy * CJ; - } - - info = m_func->evalResidNJ(time_curr, delta_t_n, y, ydot, DATA_PTR(m_wksp), JacDelta_ResidEval, static_cast(j), dy); - m_nfe++; - if (DEBUG_MODE_ENABLED) { - if (fabs(dy) < 1.0E-300) { - throw CanteraError("NonlinearSolver::beuler_jac", "dy is equal to zero"); - } - for (size_t ii = 0; ii < neq_; ii++) { - checkFinite(m_wksp[ii]); - } - } - if (info != 1) { - return info; - } - - doublereal diff; - - - - for (int i = (int) j - ku; i <= (int) j + kl; i++) { - if (i >= 0 && i < (int) neq_) { - diff = subtractRD(m_wksp[i], f[i]); - col_j[kl + ku + i - j] = diff / dy; - } - } - y[j] = ysave; - if (solnType_ != NSOLN_TYPE_STEADY_STATE) { - ydot[j] = ydotsave; - } - - } - - double vSmall; - size_t ismall = J.checkRows(vSmall); - if (vSmall < 1.0E-100) { - printf("WE have a zero row, %s\n", int2str(ismall).c_str()); - exit(-1); - } - ismall = J.checkColumns(vSmall); - if (vSmall < 1.0E-100) { - printf("WE have a zero column, %s\n", int2str(ismall).c_str()); - exit(-1); - } - - // ---------------------BANDED MATRIX BRAIN DEAD ----------------------- - } - } - - if (m_print_flag >= 7 && s_print_NumJac) { - if (neq_ < 30) { - printf("\t\tCurrent Matrix and Residual:\n"); - printf("\t\t I,J | "); - for (size_t j = 0; j < neq_; j++) { - printf(" %5s ", int2str(j).c_str()); - } - printf("| Residual \n"); - printf("\t\t --"); - for (size_t j = 0; j < neq_; j++) { - printf("------------"); - } - printf("| -----------\n"); - - - for (size_t i = 0; i < neq_; i++) { - printf("\t\t %4s |", int2str(i).c_str()); - for (size_t j = 0; j < neq_; j++) { - printf(" % 11.4E", J(i,j)); - } - printf(" | % 11.4E\n", f[i]); - } - - printf("\t\t --"); - for (size_t j = 0; j < neq_; j++) { - printf("------------"); - } - printf("--------------\n"); - } - } - /* - * Make a copy of the data. Note, this Jacobian copy occurs before any matrix scaling operations. - * It's the raw matrix producted by this routine. - */ - *jacCopyPtr_ = J; - - return retn; -} - -void NonlinearSolver::calc_ydot(const int order, - const doublereal* const y_curr, - doublereal* const ydot_curr) const -{ - if (!ydot_curr) { - return; - } - doublereal c1; - switch (order) { - case 0: - case 1: /* First order forward Euler/backward Euler */ - c1 = 1.0 / delta_t_n; - for (size_t i = 0; i < neq_; i++) { - ydot_curr[i] = c1 * (y_curr[i] - m_y_nm1[i]); - } - return; - case 2: /* Second order Adams-Bashforth / Trapezoidal Rule */ - c1 = 2.0 / delta_t_n; - for (size_t i = 0; i < neq_; i++) { - ydot_curr[i] = c1 * (y_curr[i] - m_y_nm1[i]) - m_ydot_nm1[i]; - } - - return; - default: - throw CanteraError("calc_ydot()", "Case not covered"); - } -} - -doublereal NonlinearSolver::filterNewStep(const doublereal timeCurrent, - const doublereal* const ybase, doublereal* const step0) -{ - return m_func->filterNewStep(timeCurrent, ybase, step0); -} - -doublereal NonlinearSolver::filterNewSolution(const doublereal timeCurrent, - doublereal* const y_current, doublereal* const ydot_current) -{ - return m_func->filterSolnPrediction(timeCurrent, y_current); -} - -void NonlinearSolver::computeResidWts() -{ - ResidWtsReevaluated_ = true; - if (checkUserResidualTols_ == 1) { - for (size_t i = 0; i < neq_; i++) { - m_residWts[i] = userResidAtol_[i] + userResidRtol_ * m_rowWtScales[i] / rtol_; - if (DEBUG_MODE_ENABLED) { - checkFinite(m_residWts[i]); - } - } - } else { - doublereal sum = 0.0; - for (size_t i = 0; i < neq_; i++) { - m_residWts[i] = m_rowWtScales[i]; - if (DEBUG_MODE_ENABLED) { - checkFinite(m_residWts[i]); - } - sum += m_residWts[i]; - } - sum /= neq_; - for (size_t i = 0; i < neq_; i++) { - m_residWts[i] = m_ScaleSolnNormToResNorm * (m_residWts[i] + atolBase_ * atolBase_ * sum); - } - if (checkUserResidualTols_ == 2) { - for (size_t i = 0; i < neq_; i++) { - double uR = userResidAtol_[i] + userResidRtol_ * m_rowWtScales[i] / rtol_; - m_residWts[i] = std::min(m_residWts[i], uR); - } - } - } -} - -void NonlinearSolver::getResidWts(doublereal* const residWts) const -{ - for (size_t i = 0; i < neq_; i++) { - residWts[i] = (m_residWts)[i]; - } -} - -int NonlinearSolver::convergenceCheck(int dampCode, doublereal s1) -{ - int retn = 0; - if (m_dampBound < 0.9999) { - return retn; - } - if (m_dampRes < 0.9999) { - return retn; - } - if (dampCode <= 0) { - return retn; - } - if (dampCode == 3) { - if (s1 < 1.0E-2) { - if (m_normResid_full < 1.0E-1) { - return 3; - } - } - if (s1 < 0.8) { - if (m_normDeltaSoln_Newton < 1.0) { - if (m_normResid_full < 1.0E-1) { - return 2; - } - } - } - } - if (dampCode == 4) { - if (s1 < 1.0E-2) { - if (m_normResid_full < 1.0E-1) { - return 3; - } - } - } - - if (s1 < 0.8) { - if (m_normDeltaSoln_Newton < 1.0) { - if (m_normResid_full < 1.0E-1) { - return 2; - } - } - } - if (dampCode == 1 || dampCode == 2) { - if (s1 < 1.0) { - if (m_normResid_full < 1.0E-1) { - return 1; - } - } - } - return retn; -} - -void NonlinearSolver::setAtol(const doublereal* const atol) -{ - for (size_t i = 0; i < neq_; i++) { - if (atol[i] <= 0.0) { - throw CanteraError("NonlinearSolver::setAtol()", - "Atol is less than or equal to zero"); - } - atolk_[i]= atol[i]; - } -} - -void NonlinearSolver::setRtol(const doublereal rtol) -{ - if (rtol <= 0.0) { - throw CanteraError("NonlinearSolver::setRtol()", - "Rtol is <= zero"); - } - rtol_ = rtol; -} - -void NonlinearSolver::setResidualTols(double residRtol, double* residATol, int residNormHandling) -{ - if (residNormHandling < 0 || residNormHandling > 2) { - throw CanteraError("NonlinearSolver::setResidualTols()", - "Unknown int for residNormHandling"); - } - checkUserResidualTols_ = residNormHandling; - userResidRtol_ = residRtol; - if (residATol) { - userResidAtol_.resize(neq_); - for (size_t i = 0; i < neq_; i++) { - userResidAtol_[i] = residATol[i]; - } - } else { - if (residNormHandling ==1 || residNormHandling == 2) { - throw CanteraError("NonlinearSolver::setResidualTols()", - "Must set residATol vector"); - } - } -} - -void NonlinearSolver::setPrintLvl(int printLvl) -{ - m_print_flag = printLvl; -} - -} diff --git a/src/numerics/SquareMatrix.cpp b/src/numerics/SquareMatrix.cpp index c3fca4271..d8d97a9ae 100644 --- a/src/numerics/SquareMatrix.cpp +++ b/src/numerics/SquareMatrix.cpp @@ -306,12 +306,6 @@ doublereal* SquareMatrix::ptrColumn(size_t j) return Array2D::ptrColumn(j); } -void SquareMatrix::copyData(const GeneralMatrix& y) -{ - const SquareMatrix* yy_ptr = dynamic_cast(& y); - Array2D::copyData(*yy_ptr); -} - size_t SquareMatrix::nRows() const { return m_nrows; diff --git a/src/numerics/solveProb.cpp b/src/numerics/solveProb.cpp deleted file mode 100644 index 781e10181..000000000 --- a/src/numerics/solveProb.cpp +++ /dev/null @@ -1,915 +0,0 @@ -/** - * @file: solveProb.cpp Implicit solver for nonlinear problems - */ - -/* - * Copyright 2004 Sandia Corporation. Under the terms of Contract - * DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government - * retains certain rights in this software. - * See file License.txt for licensing information. - */ - -#include "cantera/numerics/solveProb.h" -#include "cantera/base/clockWC.h" -#include "cantera/base/stringUtils.h" -#include "cantera/base/global.h" - -using namespace std; -namespace Cantera -{ - -/*************************************************************************** - * STATIC ROUTINES DEFINED IN THIS FILE - ***************************************************************************/ - -static doublereal calcWeightedNorm(const doublereal [], const doublereal dx[], size_t); - -solveProb::solveProb(ResidEval* resid) : - m_residFunc(resid), - m_neq(0), - m_atol(0), - m_rtol(1.0E-4), - m_maxstep(1000), - m_ioflag(0) -{ - warn_deprecated("class solveProb", "To be removed after Cantera 2.2."); - m_neq = m_residFunc->nEquations(); - - // Dimension solution vector - size_t dim1 = std::max(1, m_neq); - - m_atol.resize(dim1, 1.0E-9); - m_netProductionRatesSave.resize(dim1, 0.0); - m_numEqn1.resize(dim1, 0.0); - m_numEqn2.resize(dim1, 0.0); - m_CSolnSave.resize(dim1, 0.0); - m_CSolnSP.resize(dim1, 0.0); - m_CSolnSPInit.resize(dim1, 0.0); - m_CSolnSPOld.resize(dim1, 0.0); - m_wtResid.resize(dim1, 0.0); - m_wtSpecies.resize(dim1, 0.0); - m_resid.resize(dim1, 0.0); - m_topBounds.resize(dim1, 1.0); - m_botBounds.resize(dim1, 0.0); - - m_Jac.resize(dim1, dim1, 0.0); - m_JacCol.resize(dim1, 0); - for (size_t k = 0; k < dim1; k++) { - m_JacCol[k] = m_Jac.ptrColumn(k); - } - -} - -int solveProb::solve(int ifunc, doublereal time_scale, - doublereal reltol) -{ - /* - * The following calculation is a Newton's method to get the surface fractions - * of the surface and bulk species by requiring that the surface species - * production rate = 0 and that the bulk fractions are proportional to their - * production rates. - */ - doublereal EXTRA_ACCURACY = 0.001; - if (ifunc == SOLVEPROB_JACOBIAN) { - EXTRA_ACCURACY *= 0.001; - } - int info = 0; - size_t label_t = npos; /* Species IDs for time control */ - size_t label_d; /* Species IDs for damping control */ - size_t label_t_old = npos; - doublereal label_factor = 1.0; - int iter=0; // iteration number on numlinear solver - int iter_max=1000; // maximum number of nonlinear iterations - doublereal deltaT = 1.0E-10; // Delta time step - doublereal damp=1.0, tmp; - // Weighted L2 norm of the residual. Currently, this is only - // used for IO purposes. It doesn't control convergence. - // Therefore, it is turned off when DEBUG_SOLVEPROB isn't defined. - doublereal resid_norm; - doublereal inv_t = 0.0; - doublereal t_real = 0.0, update_norm = 1.0E6; - - bool do_time = false, not_converged = true; - -#ifdef DEBUG_SOLVEPROB -#ifdef DEBUG_SOLVEPROB_TIME - doublereal t1; -#endif -#else - if (m_ioflag > 1) { - m_ioflag = 1; - } -#endif - -#ifdef DEBUG_SOLVEPROB -#ifdef DEBUG_SOLVEPROB_TIME - clockWC wc; - if (m_ioflag) { - t1 = wc.secondsWC(); - } -#endif -#endif - - /* - * Set the initial value of the do_time parameter - */ - if (ifunc == SOLVEPROB_INITIALIZE || ifunc == SOLVEPROB_TRANSIENT) { - do_time = true; - } - - /* - * upload the initial conditions - */ - m_residFunc->getInitialConditions(t_real, DATA_PTR(m_CSolnSP), DATA_PTR(m_numEqn1)); - - /* - * Store the initial guess in the soln vector, - * CSolnSP, and in an separate vector CSolnSPInit. - */ - std::copy(m_CSolnSP.begin(), m_CSolnSP.end(), m_CSolnSPInit.begin()); - - - - if (m_ioflag) { - print_header(m_ioflag, ifunc, time_scale, reltol, - DATA_PTR(m_netProductionRatesSave)); - } - - /* - * Quick return when there isn't a surface problem to solve - */ - if (m_neq == 0) { - not_converged = false; - update_norm = 0.0; - } - - /* ------------------------------------------------------------------ - * Start of Newton's method - * ------------------------------------------------------------------ - */ - while (not_converged && iter < iter_max) { - iter++; - /* - * Store previous iteration's solution in the old solution vector - */ - std::copy(m_CSolnSP.begin(), m_CSolnSP.end(), m_CSolnSPOld.begin()); - - /* - * Calculate the value of the time step - * - heuristics to stop large oscillations in deltaT - */ - if (do_time) { - /* don't hurry increase in time step at the same time as damping */ - if (damp < 1.0) { - label_factor = 1.0; - } - tmp = calc_t(DATA_PTR(m_netProductionRatesSave), DATA_PTR(m_CSolnSP), - &label_t, &label_t_old, &label_factor, m_ioflag); - if (iter < 10) { - inv_t = tmp; - } else if (tmp > 2.0*inv_t) { - inv_t = 2.0*inv_t; - } else { - inv_t = tmp; - } - - /* - * Check end condition - */ - - if (ifunc == SOLVEPROB_TRANSIENT) { - tmp = t_real + 1.0/inv_t; - if (tmp > time_scale) { - inv_t = 1.0/(time_scale - t_real); - } - } - } else { - /* make steady state calc a step of 1 million seconds to - prevent singular Jacobians for some pathological cases */ - inv_t = 1.0e-6; - } - deltaT = 1.0/inv_t; - - /* - * Call the routine to numerically evaluation the Jacobian - * and residual for the current iteration. - */ - resjac_eval(m_JacCol, DATA_PTR(m_resid), DATA_PTR(m_CSolnSP), - DATA_PTR(m_CSolnSPOld), do_time, deltaT); - - /* - * Calculate the weights. Make sure the calculation is carried - * out on the first iteration. - */ - if (iter%4 == 1) { - calcWeights(DATA_PTR(m_wtSpecies), DATA_PTR(m_wtResid), - DATA_PTR(m_CSolnSP)); - } - - /* - * Find the weighted norm of the residual - */ - resid_norm = calcWeightedNorm(DATA_PTR(m_wtResid), DATA_PTR(m_resid), m_neq); - -#ifdef DEBUG_SOLVEPROB - if (m_ioflag > 1) { - printIterationHeader(m_ioflag, damp, inv_t, t_real, iter, do_time); - /* - * Print out the residual and Jacobian - */ - printResJac(m_ioflag, m_neq, m_Jac, DATA_PTR(m_resid), - DATA_PTR(m_wtResid), resid_norm); - } -#endif - - /* - * Solve Linear system (with LAPACK). The solution is in resid[] - */ - info = m_Jac.factor(); - if (info==0) { - m_Jac.solve(&m_resid[0]); - } - /* - * Force convergence if residual is small to avoid - * "nan" results from the linear solve. - */ - else { - if (m_ioflag) { - printf("solveSurfSS: Zero pivot, assuming converged: %g (%d)\n", - resid_norm, info); - } - for (size_t jcol = 0; jcol < m_neq; jcol++) { - m_resid[jcol] = 0.0; - } - - /* print out some helpful info */ - if (m_ioflag > 1) { - printf("-----\n"); - printf("solveSurfProb: iter %d t_real %g delta_t %g\n\n", - iter,t_real, 1.0/inv_t); - printf("solveSurfProb: init guess, current concentration," - "and prod rate:\n"); - - printf("-----\n"); - } - if (do_time) { - t_real += time_scale; - } -#ifdef DEBUG_SOLVEPROB - if (m_ioflag) { - printf("\nResidual is small, forcing convergence!\n"); - } -#endif - } - - /* - * Calculate the Damping factor needed to keep all unknowns - * between 0 and 1, and not allow too large a change (factor of 2) - * in any unknown. - */ - - - damp = calc_damping(DATA_PTR(m_CSolnSP), DATA_PTR(m_resid), m_neq, &label_d); - - - /* - * Calculate the weighted norm of the update vector - * Here, resid is the delta of the solution, in concentration - * units. - */ - update_norm = calcWeightedNorm(DATA_PTR(m_wtSpecies), - DATA_PTR(m_resid), m_neq); - /* - * Update the solution vector and real time - * Crop the concentrations to zero. - */ - for (size_t irow = 0; irow < m_neq; irow++) { - m_CSolnSP[irow] -= damp * m_resid[irow]; - } - - - if (do_time) { - t_real += damp/inv_t; - } - - if (m_ioflag) { - printIteration(m_ioflag, damp, label_d, label_t, inv_t, t_real, iter, - update_norm, resid_norm, - DATA_PTR(m_netProductionRatesSave), - DATA_PTR(m_CSolnSP), DATA_PTR(m_resid), - DATA_PTR(m_wtSpecies), m_neq, do_time); - } - - if (ifunc == SOLVEPROB_TRANSIENT) { - not_converged = (t_real < time_scale); - } else { - if (do_time) { - if (t_real > time_scale || - (resid_norm < 1.0e-7 && - update_norm*time_scale/t_real < EXTRA_ACCURACY)) { - do_time = false; -#ifdef DEBUG_SOLVEPROB - if (m_ioflag > 1) { - printf("\t\tSwitching to steady solve.\n"); - } -#endif - } - } else { - not_converged = ((update_norm > EXTRA_ACCURACY) || - (resid_norm > EXTRA_ACCURACY)); - } - } - } /* End of Newton's Method while statement */ - - /* - * End Newton's method. If not converged, print error message and - * recalculate sdot's at equal site fractions. - */ - if (not_converged) { - if (m_ioflag) { - printf("#$#$#$# Error in solveProb $#$#$#$ \n"); - printf("Newton iter on surface species did not converge, " - "update_norm = %e \n", update_norm); - printf("Continuing anyway\n"); - } - } -#ifdef DEBUG_SOLVEPROB -#ifdef DEBUG_SOLVEPROB_TIME - if (m_ioflag) { - printf("\nEnd of solve, time used: %e\n", wc.secondsWC()-t1); - } -#endif -#endif - - /* - * Decide on what to return in the solution vector - * - right now, will always return the last solution - * no matter how bad - */ - if (m_ioflag) { - fun_eval(DATA_PTR(m_resid), DATA_PTR(m_CSolnSP), DATA_PTR(m_CSolnSPOld), - false, deltaT); - resid_norm = calcWeightedNorm(DATA_PTR(m_wtResid), - DATA_PTR(m_resid), m_neq); - printFinal(m_ioflag, damp, label_d, label_t, inv_t, t_real, iter, - update_norm, resid_norm, DATA_PTR(m_netProductionRatesSave), - DATA_PTR(m_CSolnSP), DATA_PTR(m_resid), - DATA_PTR(m_wtSpecies), - DATA_PTR(m_wtResid), m_neq, do_time); - } - - /* - * Return with the appropriate flag - */ - if (update_norm > 1.0) { - return -1; - } - return 0; -} - -void solveProb::reportState(doublereal* const CSolnSP) const -{ - std::copy(m_CSolnSP.begin(), m_CSolnSP.end(), CSolnSP); -} - -void solveProb::fun_eval(doublereal* const resid, const doublereal* const CSoln, - const doublereal* const CSolnOld, const bool do_time, - const doublereal deltaT) -{ - /* - * This routine uses the m_numEqn1 and m_netProductionRatesSave vectors - * as temporary internal storage. - */ - if (do_time) { - m_residFunc->evalSimpleTD(0.0, CSoln, CSolnOld, deltaT, resid); - } else { - m_residFunc->evalSS(0.0, CSoln, resid); - } -} - -void solveProb::resjac_eval(std::vector &JacCol, - doublereal resid[], doublereal CSoln[], - const doublereal CSolnOld[], const bool do_time, - const doublereal deltaT) -{ - doublereal dc, cSave, sd; - doublereal* col_j; - /* - * Calculate the residual - */ - fun_eval(resid, CSoln, CSolnOld, do_time, deltaT); - /* - * Now we will look over the columns perturbing each unknown. - */ - - for (size_t kCol = 0; kCol < m_neq; kCol++) { - cSave = CSoln[kCol]; - sd = fabs(cSave) + fabs(CSoln[kCol]) + m_atol[kCol] * 1.0E6; - if (sd < 1.0E-200) { - sd = 1.0E-4; - } - dc = std::max(1.0E-11 * sd, fabs(cSave) * 1.0E-6); - CSoln[kCol] += dc; - // Use the m_numEqn2 vector as temporary internal storage. - fun_eval(DATA_PTR(m_numEqn2), CSoln, CSolnOld, do_time, deltaT); - col_j = JacCol[kCol]; - for (size_t i = 0; i < m_neq; i++) { - col_j[i] = (m_numEqn2[i] - resid[i])/dc; - } - CSoln[kCol] = cSave; - } - -} - -doublereal solveProb::calc_damping(doublereal x[], doublereal dxneg[], size_t dim, size_t* label) -{ - const doublereal APPROACH = 0.50; - doublereal damp = 1.0, xnew, xtop, xbot; - static doublereal damp_old = 1.0; - *label = npos; - - for (size_t i = 0; i < dim; i++) { - doublereal topBounds = m_topBounds[i]; - doublereal botBounds = m_botBounds[i]; - /* - * Calculate the new suggested new value of x[i] - */ - double delta_x = - dxneg[i]; - xnew = x[i] - damp * dxneg[i]; - - /* - * Calculate the allowed maximum and minimum values of x[i] - * - Only going to allow x[i] to converge to the top and bottom bounds by a - * single order of magnitude at one time - */ - bool canCrossOrigin = false; - if (topBounds > 0.0 && botBounds < 0.0) { - canCrossOrigin = true; - } - - xtop = topBounds - 0.1 * fabs(topBounds - x[i]); - - xbot = botBounds + 0.1 * fabs(x[i] - botBounds); - - if (xnew > xtop) { - damp = - APPROACH * (xtop - x[i]) / dxneg[i]; - *label = i; - } else if (xnew < xbot) { - damp = APPROACH * (x[i] - xbot) / dxneg[i]; - *label = i; - } - double denom = fabs(x[i]) + 1.0E5 * m_atol[i]; - if ((fabs(delta_x) / denom) > 0.3) { - double newdamp = 0.3 * denom / fabs(delta_x); - if (canCrossOrigin) { - if (xnew * x[i] < 0.0) { - if (fabs(x[i]) < 1.0E8 * m_atol[i]) { - newdamp = 2.0 * fabs(x[i]) / fabs(delta_x); - } - } - } - damp = std::min(damp, newdamp); - } - - } - - /* - * Only allow the damping parameter to increase by a factor of three each - * iteration. Heuristic to avoid oscillations in the value of damp - */ - if (damp > damp_old*3) { - damp = damp_old*3; - *label = npos; - } - - /* - * Save old value of the damping parameter for use - * in subsequent calls. - */ - damp_old = damp; - return damp; - -} - -/* - * This function calculates the norm of an update, dx[], - * based on the weighted values of x. - */ -static doublereal calcWeightedNorm(const doublereal wtX[], const doublereal dx[], size_t dim) -{ - doublereal norm = 0.0; - doublereal tmp; - if (dim == 0) { - return 0.0; - } - for (size_t i = 0; i < dim; i++) { - tmp = dx[i] / wtX[i]; - norm += tmp * tmp; - } - return sqrt(norm/dim); -} - -void solveProb::calcWeights(doublereal wtSpecies[], doublereal wtResid[], - const doublereal CSoln[]) -{ - /* - * First calculate the weighting factor - */ - - for (size_t k = 0; k < m_neq; k++) { - wtSpecies[k] = m_atol[k] + m_rtol * fabs(CSoln[k]); - } - /* - * Now do the residual Weights. Since we have the Jacobian, we - * will use it to generate a number based on the what a significant - * change in a solution variable does to each residual. - * This is a row sum scale operation. - */ - for (size_t k = 0; k < m_neq; k++) { - wtResid[k] = 0.0; - for (size_t jcol = 0; jcol < m_neq; jcol++) { - wtResid[k] += fabs(m_Jac(k,jcol) * wtSpecies[jcol]); - } - } -} - -doublereal solveProb::calc_t(doublereal netProdRateSolnSP[], doublereal Csoln[], - size_t* label, size_t* label_old, - doublereal* label_factor, int ioflag) -{ - doublereal tmp, inv_timeScale=0.0; - for (size_t k = 0; k < m_neq; k++) { - if (Csoln[k] <= 1.0E-10) { - tmp = 1.0E-10; - } else { - tmp = Csoln[k]; - } - tmp = fabs(netProdRateSolnSP[k]/ tmp); - - - if (netProdRateSolnSP[k]> 0.0) { - tmp /= 100.; - } - if (tmp > inv_timeScale) { - inv_timeScale = tmp; - *label = k; - } - } - - /* - * Increase time step exponentially as same species repeatedly - * controls time step - */ - if (*label == *label_old) { - *label_factor *= 1.5; - } else { - *label_old = *label; - *label_factor = 1.0; - } - inv_timeScale = inv_timeScale / *label_factor; -#ifdef DEBUG_SOLVEPROB - if (ioflag > 1) { - if (*label_factor > 1.0) { - printf("Delta_t increase due to repeated controlling species = %e\n", - *label_factor); - } - int kkin = m_kinSpecIndex[*label]; - - string sn = " " - printf("calc_t: spec=%d(%s) sf=%e pr=%e dt=%e\n", - *label, sn.c_str(), XMolSolnSP[*label], - netProdRateSolnSP[*label], 1.0/inv_timeScale); - } -#endif - - return inv_timeScale; - -} - -void solveProb::setBounds(const doublereal botBounds[], const doublereal topBounds[]) -{ - for (size_t k = 0; k < m_neq; k++) { - m_botBounds[k] = botBounds[k]; - m_topBounds[k] = topBounds[k]; - } -} - -#ifdef DEBUG_SOLVEPROB -void solveProb::printResJac(int ioflag, int neq, const Array2D& Jac, - doublereal resid[], doublereal wtRes[], - doublereal norm) -{ - -} -#endif - -void solveProb::print_header(int ioflag, int ifunc, doublereal time_scale, - doublereal reltol, - doublereal netProdRate[]) -{ - int damping = 1; - if (ioflag) { - printf("\n================================ SOLVEPROB CALL SETUP " - "========================================\n"); - if (ifunc == SOLVEPROB_INITIALIZE) { - printf("\n SOLVEPROB Called with Initialization turned on\n"); - printf(" Time scale input = %9.3e\n", time_scale); - } else if (ifunc == SOLVEPROB_RESIDUAL) { - printf("\n SOLVEPROB Called to calculate steady state residual\n"); - printf(" from a good initial guess\n"); - } else if (ifunc == SOLVEPROB_JACOBIAN) { - printf("\n SOLVEPROB Called to calculate steady state Jacobian\n"); - printf(" from a good initial guess\n"); - } else if (ifunc == SOLVEPROB_TRANSIENT) { - printf("\n SOLVEPROB Called to integrate surface in time\n"); - printf(" for a total of %9.3e sec\n", time_scale); - } else { - throw CanteraError("solveProb::print_header", - "Unknown ifunc flag = " + int2str(ifunc)); - } - - - - if (damping) { - printf(" Damping is ON \n"); - } else { - printf(" Damping is OFF \n"); - } - - printf(" Reltol = %9.3e, Abstol = %9.3e\n", reltol, m_atol[0]); - } - - /* - * Print out the initial guess - */ -#ifdef DEBUG_SOLVEPROB - if (ioflag > 1) { - printf("\n================================ INITIAL GUESS " - "========================================\n"); - int kindexSP = 0; - for (int isp = 0; isp < m_numSurfPhases; isp++) { - InterfaceKinetics* m_kin = m_objects[isp]; - int surfIndex = m_kin->surfacePhaseIndex(); - int nPhases = m_kin->nPhases(); - m_kin->getNetProductionRates(netProdRate); - updateMFKinSpecies(XMolKinSpecies, isp); - - printf("\n IntefaceKinetics Object # %d\n\n", isp); - - printf("\t Number of Phases = %d\n", nPhases); - printf("\t Phase:SpecName Prod_Rate MoleFraction kindexSP\n"); - printf("\t -------------------------------------------------------" - "----------\n"); - - int kspindex = 0; - bool inSurfacePhase = false; - for (int ip = 0; ip < nPhases; ip++) { - if (ip == surfIndex) { - inSurfacePhase = true; - } else { - inSurfacePhase = false; - } - ThermoPhase& THref = m_kin->thermo(ip); - int nsp = THref.nSpecies(); - string pname = THref.id(); - for (int k = 0; k < nsp; k++) { - string sname = THref.speciesName(k); - string cname = pname + ":" + sname; - if (inSurfacePhase) { - printf("\t %-24s %10.3e %10.3e %d\n", cname.c_str(), - netProdRate[kspindex], XMolKinSpecies[kspindex], - kindexSP); - kindexSP++; - } else { - printf("\t %-24s %10.3e %10.3e\n", cname.c_str(), - netProdRate[kspindex], XMolKinSpecies[kspindex]); - } - kspindex++; - } - } - printf("==========================================================" - "=================================\n"); - } - } -#endif - if (ioflag == 1) { - printf("\n\n\t Iter Time Del_t Damp DelX " - " Resid Name-Time Name-Damp\n"); - printf("\t -----------------------------------------------" - "------------------------------------\n"); - } -} - -void solveProb::printIteration(int ioflag, doublereal damp, size_t label_d, - size_t label_t, - doublereal inv_t, doublereal t_real, int iter, - doublereal update_norm, doublereal resid_norm, - doublereal netProdRate[], doublereal CSolnSP[], - doublereal resid[], - doublereal wtSpecies[], size_t dim, bool do_time) -{ - size_t i, k; - string nm; - if (ioflag == 1) { - - printf("\t%6d ", iter); - if (do_time) { - printf("%9.4e %9.4e ", t_real, 1.0/inv_t); - } else - for (i = 0; i < 22; i++) { - printf(" "); - } - if (damp < 1.0) { - printf("%9.4e ", damp); - } else - for (i = 0; i < 11; i++) { - printf(" "); - } - printf("%9.4e %9.4e", update_norm, resid_norm); - if (do_time) { - k = label_t; - printf(" %s", int2str(k).c_str()); - } else { - for (i = 0; i < 16; i++) { - printf(" "); - } - } - if (label_d != npos) { - k = label_d; - printf(" %s", int2str(k).c_str()); - } - printf("\n"); - } -#ifdef DEBUG_SOLVEPROB - else if (ioflag > 1) { - - updateMFSolnSP(XMolSolnSP); - printf("\n\t Weighted norm of update = %10.4e\n", update_norm); - - printf("\t Name Prod_Rate XMol Conc " - " Conc_Old wtConc"); - if (damp < 1.0) { - printf(" UnDamped_Conc"); - } - printf("\n"); - printf("\t---------------------------------------------------------" - "-----------------------------\n"); - int kindexSP = 0; - for (int isp = 0; isp < m_numSurfPhases; isp++) { - int nsp = m_nSpeciesSurfPhase[isp]; - InterfaceKinetics* m_kin = m_objects[isp]; - m_kin->getNetProductionRates(DATA_PTR(m_numEqn1)); - for (int k = 0; k < nsp; k++, kindexSP++) { - int kspIndex = m_kinSpecIndex[kindexSP]; - nm = m_kin->kineticsSpeciesName(kspIndex); - printf("\t%-16s %10.3e %10.3e %10.3e %10.3e %10.3e ", - nm.c_str(), - m_numEqn1[kspIndex], - XMolSolnSP[kindexSP], - CSolnSP[kindexSP], CSolnSP[kindexSP]+damp*resid[kindexSP], - wtSpecies[kindexSP]); - if (damp < 1.0) { - printf("%10.4e ", CSolnSP[kindexSP]+(damp-1.0)*resid[kindexSP]); - if (label_d == kindexSP) { - printf(" Damp "); - } - } - if (label_t == kindexSP) { - printf(" Tctrl"); - } - printf("\n"); - } - - } - - printf("\t--------------------------------------------------------" - "------------------------------\n"); - } -#endif -} - -void solveProb::printFinal(int ioflag, doublereal damp, size_t label_d, size_t label_t, - doublereal inv_t, doublereal t_real, int iter, - doublereal update_norm, doublereal resid_norm, - doublereal netProdRateKinSpecies[], const doublereal CSolnSP[], - const doublereal resid[], - const doublereal wtSpecies[], const doublereal wtRes[], - size_t dim, bool do_time) -{ - size_t i, k; - string nm; - if (ioflag == 1) { - - printf("\tFIN%3d ", iter); - if (do_time) { - printf("%9.4e %9.4e ", t_real, 1.0/inv_t); - } else - for (i = 0; i < 22; i++) { - printf(" "); - } - if (damp < 1.0) { - printf("%9.4e ", damp); - } else - for (i = 0; i < 11; i++) { - printf(" "); - } - printf("%9.4e %9.4e", update_norm, resid_norm); - if (do_time) { - k = label_t; - printf(" %s", int2str(k).c_str()); - } else { - for (i = 0; i < 16; i++) { - printf(" "); - } - } - if (label_d != npos) { - k = label_d; - - printf(" %s", int2str(k).c_str()); - } - printf(" -- success\n"); - } -#ifdef DEBUG_SOLVEPROB - else if (ioflag > 1) { - printf("\n================================== FINAL RESULT =========" - "==================================================\n"); - - printf("\n Weighted norm of solution update = %10.4e\n", update_norm); - printf(" Weighted norm of residual update = %10.4e\n\n", resid_norm); - - printf(" Name Prod_Rate XMol Conc " - " wtConc Resid Resid/wtResid wtResid"); - if (damp < 1.0) { - printf(" UnDamped_Conc"); - } - printf("\n"); - printf("---------------------------------------------------------------" - "---------------------------------------------\n"); - - for (int k = 0; k < m_neq; k++, k++) { - printf("%-16s %10.3e %10.3e %10.3e %10.3e %10.3e %10.3e %10.3e", - nm.c_str(), - m_numEqn1[k], - XMolSolnSP[k], - CSolnSP[k], - wtSpecies[k], - resid[k], - resid[k]/wtRes[k], wtRes[k]); - if (damp < 1.0) { - printf("%10.4e ", CSolnSP[k]+(damp-1.0)*resid[k]); - if (label_d == k) { - printf(" Damp "); - } - } - if (label_t == k) { - printf(" Tctrl"); - } - printf("\n"); - } - - printf("\n"); - printf("===============================================================" - "============================================\n\n"); - } -#endif -} - -#ifdef DEBUG_SOLVEPROB -void solveProb::printIterationHeader(int ioflag, doublereal damp, - doublereal inv_t, doublereal t_real, - int iter, bool do_time) -{ - if (ioflag > 1) { - printf("\n===============================Iteration %5d " - "=================================\n", iter); - if (do_time) { - printf(" Transient step with: Real Time_n-1 = %10.4e sec,", t_real); - printf(" Time_n = %10.4e sec\n", t_real + 1.0/inv_t); - printf(" Delta t = %10.4e sec", 1.0/inv_t); - } else { - printf(" Steady Solve "); - } - if (damp < 1.0) { - printf(", Damping value = %10.4e\n", damp); - } else { - printf("\n"); - } - } -} -#endif - -void solveProb::setAtol(const doublereal atol[]) -{ - for (size_t k = 0; k < m_neq; k++, k++) { - m_atol[k] = atol[k]; - } -} - -void solveProb::setAtolConst(const doublereal atolconst) -{ - for (size_t k = 0; k < m_neq; k++, k++) { - m_atol[k] = atolconst; - } -} - -} diff --git a/src/oneD/MultiNewton.cpp b/src/oneD/MultiNewton.cpp index d2d860949..58e92b2d8 100644 --- a/src/oneD/MultiNewton.cpp +++ b/src/oneD/MultiNewton.cpp @@ -7,7 +7,7 @@ */ #include "cantera/oneD/MultiNewton.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" #include #include diff --git a/src/oneD/StFlow.cpp b/src/oneD/StFlow.cpp index 6750d6369..740d3853e 100644 --- a/src/oneD/StFlow.cpp +++ b/src/oneD/StFlow.cpp @@ -123,8 +123,6 @@ void StFlow::resize(size_t ncomponents, size_t points) m_wdot.resize(m_nsp,m_points, 0.0); m_do_energy.resize(m_points,false); m_qdotRadiation.resize(m_points, 0.0); - - m_fixedy.resize(m_nsp, m_points); m_fixedtemp.resize(m_points); m_dz.resize(m_points-1); @@ -203,7 +201,7 @@ void StFlow::setGasAtMidpoint(const doublereal* x, size_t j) void StFlow::_finalize(const doublereal* x) { - size_t k, j; + size_t j; doublereal zz, tt; size_t nz = m_zfix.size(); bool e = m_do_energy[0]; @@ -215,9 +213,6 @@ void StFlow::_finalize(const doublereal* x) tt = linearInterp(zz, m_zfix, m_tfix); m_fixedtemp[j] = tt; } - for (k = 0; k < m_nsp; k++) { - setMassFraction(j, k, Y(x, k, j)); - } } if (e) { solveEnergyEqn(); diff --git a/src/thermo/DebyeHuckel.cpp b/src/thermo/DebyeHuckel.cpp index 4aef6632f..1597d0504 100644 --- a/src/thermo/DebyeHuckel.cpp +++ b/src/thermo/DebyeHuckel.cpp @@ -320,32 +320,6 @@ doublereal DebyeHuckel::standardConcentration(size_t k) const return 1.0 / mvSolvent; } -void DebyeHuckel::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("DebyeHuckel::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } -} - void DebyeHuckel::getActivities(doublereal* ac) const { _updateStandardStateThermo(); diff --git a/src/thermo/FixedChemPotSSTP.cpp b/src/thermo/FixedChemPotSSTP.cpp index 362c5ae87..08b9cf10d 100644 --- a/src/thermo/FixedChemPotSSTP.cpp +++ b/src/thermo/FixedChemPotSSTP.cpp @@ -186,16 +186,6 @@ doublereal FixedChemPotSSTP::logStandardConc(size_t k) const return 0.0; } -void FixedChemPotSSTP::getUnitsStandardConc(doublereal* uA, int k, - int sizeUA) const -{ - warn_deprecated("FixedChemPotSSTP::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - for (int i = 0; i < 6; i++) { - uA[i] = 0; - } -} - /* * ---- Partial Molar Properties of the Solution ---- */ diff --git a/src/thermo/GibbsExcessVPSSTP.cpp b/src/thermo/GibbsExcessVPSSTP.cpp index b80adf50c..9a99afd87 100644 --- a/src/thermo/GibbsExcessVPSSTP.cpp +++ b/src/thermo/GibbsExcessVPSSTP.cpp @@ -151,47 +151,14 @@ void GibbsExcessVPSSTP::getActivities(doublereal* ac) const void GibbsExcessVPSSTP::getActivityCoefficients(doublereal* const ac) const { getLnActivityCoefficients(ac); - // - // Protect against or inform about roundoff when taking exponentials - // - if ((DEBUG_MODE_ENABLED && realNumberRangeBehavior_ == THROWON_OVERFLOW_DEBUGMODEONLY_CTRB) || - (realNumberRangeBehavior_ == THROWON_OVERFLOW_CTRB)) { - for (size_t k = 0; k < m_kk; k++) { - if (ac[k] > 700.) { - throw CanteraError("GibbsExcessVPSSTP::getActivityCoefficients()", - "activity coefficient for " + int2str(k) + " is overflowing: ln(ac) = " + fp2str(ac[k])); - } else if (ac[k] < -700.) { - throw CanteraError("GibbsExcessVPSSTP::getActivityCoefficients()", - "activity coefficient for " + int2str(k) + " is underflowing: ln(ac) = " + fp2str(ac[k])); - } else { - ac[k] = exp(ac[k]); - } - } - } else if (realNumberRangeBehavior_ == CHANGE_OVERFLOW_CTRB) { - for (size_t k = 0; k < m_kk; k++) { - if (ac[k] > 700.) { - ac[k] = exp(700.0); - } else if (ac[k] < -700.) { - ac[k] = exp(-700.0); - } else { - ac[k] = exp(ac[k]); - } - } - } else { - for (size_t k = 0; k < m_kk; k++) { + for (size_t k = 0; k < m_kk; k++) { + if (ac[k] > 700.) { + ac[k] = exp(700.0); + } else if (ac[k] < -700.) { + ac[k] = exp(-700.0); + } else { ac[k] = exp(ac[k]); } - if (realNumberRangeBehavior_ == FENV_CHECK_CTRB) { -#ifdef HAVE_FENV_H - if (check_FENV_OverUnder_Flow()) { - throw CanteraError("GibbsExcessVPSSTP::getActivityCoefficients()", - "activity coefficient is over/underflowing"); - } -#else - throw CanteraError("GibbsExcessVPSSTP::getActivityCoefficients()", - "realNumberRangeBehavior_ == FENV_CHECK_CTRB not supported by compiler"); -#endif - } } } @@ -230,36 +197,6 @@ double GibbsExcessVPSSTP::checkMFSum(const doublereal* const x) const return norm; } -void GibbsExcessVPSSTP::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("GibbsExcessVPSSTP::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - // - // We assume here that the units of the standard concentration is unitless. In other words activities are - // used unchanged in kinetics expressions. This may be changed in implementations of child classes. - // - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 0.0; - } - if (i == 1) { - uA[1] = 0.0; - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } -} - void GibbsExcessVPSSTP::initThermo() { initLengths(); diff --git a/src/thermo/HMWSoln.cpp b/src/thermo/HMWSoln.cpp index e36670a5e..2464ccb20 100644 --- a/src/thermo/HMWSoln.cpp +++ b/src/thermo/HMWSoln.cpp @@ -624,32 +624,6 @@ doublereal HMWSoln::standardConcentration(size_t k) const return 1.0 / mvSolvent; } -void HMWSoln::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("HMWSoln::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } -} - void HMWSoln::getActivities(doublereal* ac) const { updateStandardStateThermo(); diff --git a/src/thermo/IdealGasPhase.cpp b/src/thermo/IdealGasPhase.cpp index 43aea6a95..82ea38bbd 100644 --- a/src/thermo/IdealGasPhase.cpp +++ b/src/thermo/IdealGasPhase.cpp @@ -6,7 +6,7 @@ */ #include "cantera/thermo/IdealGasPhase.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" using namespace std; @@ -82,64 +82,6 @@ doublereal IdealGasPhase::cv_mole() const return cp_mole() - GasConstant; } -doublereal IdealGasPhase::cv_tr(doublereal atomicity) const -{ - warn_deprecated("IdealGasPhase::cv_tr", "To be removed after Cantera 2.2."); - // k is the species number - int dum = 0; - int type = m_spthermo->reportType(); - doublereal c[12]; - doublereal minTemp_; - doublereal maxTemp_; - doublereal refPressure_; - - if (type != 111) { - throw CanteraError("Error in IdealGasPhase.cpp", "cv_tr only supported for StatMech!. \n\n"); - } - - m_spthermo->reportParams(dum, type, c, minTemp_, maxTemp_, refPressure_); - - // see reportParameters for specific details - return c[3]; -} - -doublereal IdealGasPhase::cv_trans() const -{ - warn_deprecated("IdealGasPhase::cv_trans", "To be removed after Cantera 2.2."); - return 1.5 * GasConstant; -} - -doublereal IdealGasPhase::cv_rot(double atom) const -{ - warn_deprecated("IdealGasPhase::cv_rot", "To be removed after Cantera 2.2."); - return std::max(cv_tr(atom) - cv_trans(), 0.); -} - -doublereal IdealGasPhase::cv_vib(const int k, const doublereal T) const -{ - warn_deprecated("IdealGasPhase::cv_vib", "To be removed after Cantera 2.2."); - // k is the species number - int dum = 0; - int type = m_spthermo->reportType(); - doublereal c[12]; - doublereal minTemp_; - doublereal maxTemp_; - doublereal refPressure_; - - c[0] = temperature(); - - // basic sanity check - if (type != 111) { - throw CanteraError("Error in IdealGasPhase.cpp", "cv_vib only supported for StatMech!. \n\n"); - } - - m_spthermo->reportParams(dum, type, c, minTemp_, maxTemp_, refPressure_); - - // see reportParameters for specific details - return c[4]; - -} - doublereal IdealGasPhase::standardConcentration(size_t k) const { return pressure() / (GasConstant * temperature()); diff --git a/src/thermo/IdealMolalSoln.cpp b/src/thermo/IdealMolalSoln.cpp index 9f49d6ef6..443c01c7b 100644 --- a/src/thermo/IdealMolalSoln.cpp +++ b/src/thermo/IdealMolalSoln.cpp @@ -263,40 +263,6 @@ doublereal IdealMolalSoln::standardConcentration(size_t k) const return c0; } -void IdealMolalSoln::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("IdealMolalSoln::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - - int eos = eosType(); - if (eos == 0) { - for (int i = 0; i < sizeUA; i++) { - uA[i] = 0.0; - } - } else { - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } - } -} - void IdealMolalSoln::getActivities(doublereal* ac) const { _updateStandardStateThermo(); diff --git a/src/thermo/IdealSolidSolnPhase.cpp b/src/thermo/IdealSolidSolnPhase.cpp index 74b7746f1..b974ca172 100644 --- a/src/thermo/IdealSolidSolnPhase.cpp +++ b/src/thermo/IdealSolidSolnPhase.cpp @@ -14,7 +14,7 @@ #include "cantera/thermo/ThermoFactory.h" #include "cantera/base/stringUtils.h" #include "cantera/base/ctml.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" using namespace std; @@ -282,39 +282,6 @@ doublereal IdealSolidSolnPhase::logStandardConc(size_t k) const return res; } -void IdealSolidSolnPhase::getUnitsStandardConc(double* uA, int, int sizeUA) const -{ - warn_deprecated("IdealSolidSolnPhase::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - int eos = eosType(); - if (eos == cIdealSolidSolnPhase0) { - for (int i = 0; i < sizeUA; i++) { - uA[i] = 0.0; - } - } else { - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } - } -} - void IdealSolidSolnPhase::getActivityCoefficients(doublereal* ac) const { for (size_t k = 0; k < m_kk; k++) { diff --git a/src/thermo/IdealSolnGasVPSS.cpp b/src/thermo/IdealSolnGasVPSS.cpp index 1d3783588..dfe4e110b 100644 --- a/src/thermo/IdealSolnGasVPSS.cpp +++ b/src/thermo/IdealSolnGasVPSS.cpp @@ -16,7 +16,7 @@ #include "cantera/thermo/PDSS.h" #include "cantera/thermo/ThermoFactory.h" #include "cantera/base/stringUtils.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" using namespace std; @@ -195,39 +195,6 @@ doublereal IdealSolnGasVPSS::standardConcentration(size_t k) const } } -void IdealSolnGasVPSS::getUnitsStandardConc(double* uA, int, int sizeUA) const -{ - warn_deprecated("IdealSolnGasVPSS::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - - if (eosType() == cIdealSolnGasPhase0) { - for (int i = 0; i < sizeUA; i++) { - uA[i] = 0.0; - } - } else { - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } - } -} - void IdealSolnGasVPSS::getActivityCoefficients(doublereal* ac) const { for (size_t k = 0; k < m_kk; k++) { diff --git a/src/thermo/LatticePhase.cpp b/src/thermo/LatticePhase.cpp index 4f591a3d3..ca0da0210 100644 --- a/src/thermo/LatticePhase.cpp +++ b/src/thermo/LatticePhase.cpp @@ -11,7 +11,7 @@ #include "cantera/thermo/ThermoFactory.h" #include "cantera/base/stringUtils.h" #include "cantera/base/ctml.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" namespace Cantera { diff --git a/src/thermo/MetalSHEelectrons.cpp b/src/thermo/MetalSHEelectrons.cpp index 5c3e1c1c5..96b576780 100644 --- a/src/thermo/MetalSHEelectrons.cpp +++ b/src/thermo/MetalSHEelectrons.cpp @@ -156,17 +156,6 @@ doublereal MetalSHEelectrons::logStandardConc(size_t k) const return 0.0; } -void MetalSHEelectrons::getUnitsStandardConc(doublereal* uA, int k, - int sizeUA) const -{ - warn_deprecated("MetalSHEelectrons::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - - for (int i = 0; i < 6; i++) { - uA[i] = 0; - } -} - /* * Properties of the Standard State of the Species in the Solution */ diff --git a/src/thermo/MineralEQ3.cpp b/src/thermo/MineralEQ3.cpp index 762c9ac17..7a56d7e0f 100644 --- a/src/thermo/MineralEQ3.cpp +++ b/src/thermo/MineralEQ3.cpp @@ -144,16 +144,6 @@ doublereal MineralEQ3::logStandardConc(size_t k) const return 0.0; } -void MineralEQ3::getUnitsStandardConc(doublereal* uA, int k, int sizeUA) const -{ - warn_deprecated("MineralEQ3::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - - for (int i = 0; i < 6; i++) { - uA[i] = 0; - } -} - /* * Properties of the Standard State of the Species in the Solution */ diff --git a/src/thermo/MixedSolventElectrolyte.cpp b/src/thermo/MixedSolventElectrolyte.cpp index 86a19fbf0..a1611bbe1 100644 --- a/src/thermo/MixedSolventElectrolyte.cpp +++ b/src/thermo/MixedSolventElectrolyte.cpp @@ -86,66 +86,6 @@ MixedSolventElectrolyte::duplMyselfAsThermoPhase() const return new MixedSolventElectrolyte(*this); } -MixedSolventElectrolyte::MixedSolventElectrolyte(int testProb) : - MolarityIonicVPSSTP(), - numBinaryInteractions_(0), - formMargules_(0), - formTempModel_(0) -{ - warn_deprecated("MixedSolventElectrolyte::MixedSolventElectrolyte(int testProb)", - "To be removed after Cantera 2.2"); - - initThermoFile("LiKCl_liquid.xml", ""); - - - numBinaryInteractions_ = 1; - - m_HE_b_ij.resize(1); - m_HE_c_ij.resize(1); - m_HE_d_ij.resize(1); - - m_SE_b_ij.resize(1); - m_SE_c_ij.resize(1); - m_SE_d_ij.resize(1); - - m_VHE_b_ij.resize(1); - m_VHE_c_ij.resize(1); - m_VHE_d_ij.resize(1); - - m_VSE_b_ij.resize(1); - m_VSE_c_ij.resize(1); - m_VSE_d_ij.resize(1); - - m_pSpecies_A_ij.resize(1); - m_pSpecies_B_ij.resize(1); - - - - m_HE_b_ij[0] = -17570E3; - m_HE_c_ij[0] = -377.0E3; - m_HE_d_ij[0] = 0.0; - - m_SE_b_ij[0] = -7.627E3; - m_SE_c_ij[0] = 4.958E3; - m_SE_d_ij[0] = 0.0; - - - size_t iLiCl = speciesIndex("LiCl(L)"); - if (iLiCl == npos) { - throw CanteraError("MixedSolventElectrolyte test1 constructor", - "Unable to find LiCl(L)"); - } - m_pSpecies_B_ij[0] = iLiCl; - - - size_t iKCl = speciesIndex("KCl(L)"); - if (iKCl == npos) { - throw CanteraError("MixedSolventElectrolyte test1 constructor", - "Unable to find KCl(L)"); - } - m_pSpecies_A_ij[0] = iKCl; -} - /* * - Activities, Standard States, Activity Concentrations ----------- */ diff --git a/src/thermo/MixtureFugacityTP.cpp b/src/thermo/MixtureFugacityTP.cpp index f64f2730a..675ac924d 100644 --- a/src/thermo/MixtureFugacityTP.cpp +++ b/src/thermo/MixtureFugacityTP.cpp @@ -13,7 +13,6 @@ #include "cantera/thermo/MixtureFugacityTP.h" #include "cantera/base/stringUtils.h" #include "cantera/base/ctml.h" -#include "cantera/base/vec_functions.h" using namespace std; diff --git a/src/thermo/MolalityVPSSTP.cpp b/src/thermo/MolalityVPSSTP.cpp index 5ce18b733..ad7957d4b 100644 --- a/src/thermo/MolalityVPSSTP.cpp +++ b/src/thermo/MolalityVPSSTP.cpp @@ -329,33 +329,6 @@ void MolalityVPSSTP::getElectrochemPotentials(doublereal* mu) const } } -void MolalityVPSSTP::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("MolalityVPSSTP::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } -} - void MolalityVPSSTP::setToEquilState(const doublereal* lambda_RT) { updateStandardStateThermo(); diff --git a/src/thermo/Phase.cpp b/src/thermo/Phase.cpp index 2a22b6285..9ff1e6711 100644 --- a/src/thermo/Phase.cpp +++ b/src/thermo/Phase.cpp @@ -6,7 +6,7 @@ // Copyright 2001 California Institute of Technology #include "cantera/thermo/Phase.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" #include "cantera/base/stringUtils.h" #include "cantera/base/ctml.h" #include "cantera/thermo/ThermoFactory.h" @@ -27,8 +27,7 @@ Phase::Phase() : m_mmw(0.0), m_stateNum(-1), m_mm(0), - m_elem_type(0), - realNumberRangeBehavior_(THROWON_OVERFLOW_DEBUGMODEONLY_CTRB) + m_elem_type(0) { } @@ -43,8 +42,7 @@ Phase::Phase(const Phase& right) : m_mmw(0.0), m_stateNum(-1), m_mm(0), - m_elem_type(0), - realNumberRangeBehavior_(THROWON_OVERFLOW_DEBUGMODEONLY_CTRB) + m_elem_type(0) { // Use the assignment operator to do the actual copying operator=(right); @@ -106,8 +104,6 @@ Phase& Phase::operator=(const Phase& right) } m_id = right.m_id; m_name = right.m_name; - realNumberRangeBehavior_ = right.realNumberRangeBehavior_; - return *this; } @@ -692,23 +688,11 @@ doublereal Phase::mean_X(const vector_fp& Q) const return m_mmw*std::inner_product(m_ym.begin(), m_ym.end(), Q.begin(), 0.0); } -doublereal Phase::mean_Y(const doublereal* const Q) const -{ - warn_deprecated("Phase::mean_Y", "To be removed after Cantera 2.2."); - return dot(m_y.begin(), m_y.end(), Q); -} - doublereal Phase::sum_xlogx() const { return m_mmw* Cantera::sum_xlogx(m_ym.begin(), m_ym.end()) + log(m_mmw); } -doublereal Phase::sum_xlogQ(doublereal* Q) const -{ - warn_deprecated("Phase::sum_xlogQ", "To be removed after Cantera 2.2."); - return m_mmw * Cantera::sum_xlogQ(m_ym.begin(), m_ym.end(), Q); -} - size_t Phase::addElement(const std::string& symbol, doublereal weight, int atomic_number, doublereal entropy298, int elem_type) diff --git a/src/thermo/PhaseCombo_Interaction.cpp b/src/thermo/PhaseCombo_Interaction.cpp index a6d3b1673..d5595372b 100644 --- a/src/thermo/PhaseCombo_Interaction.cpp +++ b/src/thermo/PhaseCombo_Interaction.cpp @@ -81,67 +81,6 @@ PhaseCombo_Interaction::duplMyselfAsThermoPhase() const return new PhaseCombo_Interaction(*this); } -PhaseCombo_Interaction::PhaseCombo_Interaction(int testProb) : - GibbsExcessVPSSTP(), - numBinaryInteractions_(0), - formMargules_(0), - formTempModel_(0) -{ - warn_deprecated("PhaseCombo_Interaction::PhaseCombo_Interaction(int testProb)", - "To be removed after Cantera 2.2"); - - initThermoFile("PhaseCombo_Interaction.xml", ""); - - - numBinaryInteractions_ = 1; - - m_HE_b_ij.resize(1); - m_HE_c_ij.resize(1); - m_HE_d_ij.resize(1); - - m_SE_b_ij.resize(1); - m_SE_c_ij.resize(1); - m_SE_d_ij.resize(1); - - m_VHE_b_ij.resize(1); - m_VHE_c_ij.resize(1); - m_VHE_d_ij.resize(1); - - m_VSE_b_ij.resize(1); - m_VSE_c_ij.resize(1); - m_VSE_d_ij.resize(1); - - m_pSpecies_A_ij.resize(1); - m_pSpecies_B_ij.resize(1); - - - - m_HE_b_ij[0] = -17570E3; - m_HE_c_ij[0] = -377.0E3; - m_HE_d_ij[0] = 0.0; - - m_SE_b_ij[0] = -7.627E3; - m_SE_c_ij[0] = 4.958E3; - m_SE_d_ij[0] = 0.0; - - - size_t iLiT = speciesIndex("LiTFe1S2(S)"); - if (iLiT == npos) { - throw CanteraError("PhaseCombo_Interaction test1 constructor", - "Unable to find LiTFe1S2(S)"); - } - m_pSpecies_A_ij[0] = iLiT; - - - size_t iLi2 = speciesIndex("Li2Fe1S2(S)"); - if (iLi2 == npos) { - throw CanteraError("PhaseCombo_Interaction test1 constructor", - "Unable to find Li2Fe1S2(S)"); - } - m_pSpecies_B_ij[0] = iLi2; - throw CanteraError("PhaseCombo_Interaction test1 constructor", "unimplemented"); -} - /* * -------------- Utilities ------------------------------- */ diff --git a/src/thermo/PseudoBinaryVPSSTP.cpp b/src/thermo/PseudoBinaryVPSSTP.cpp deleted file mode 100644 index ab06fed17..000000000 --- a/src/thermo/PseudoBinaryVPSSTP.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/** - * @file PseudoBinaryVPSSTP.cpp - * Definitions for intermediate ThermoPhase object for phases which - * employ excess Gibbs free energy formulations - * (see \ref thermoprops - * and class \link Cantera::PseudoBinaryVPSSTP PseudoBinaryVPSSTP\endlink). - * - * Header file for a derived class of ThermoPhase that handles - * variable pressure standard state methods for calculating - * thermodynamic properties that are further based upon expressions - * for the excess Gibbs free energy expressed as a function of - * the mole fractions. - */ -/* - * Copyright (2009) Sandia Corporation. Under the terms of - * Contract DE-AC04-94AL85000 with Sandia Corporation, the - * U.S. Government retains certain rights in this software. - */ -#include "cantera/thermo/PseudoBinaryVPSSTP.h" -#include "cantera/base/stringUtils.h" - -#include - -using namespace std; - -namespace Cantera -{ -PseudoBinaryVPSSTP::PseudoBinaryVPSSTP() : - PBType_(PBTYPE_PASSTHROUGH), - numPBSpecies_(m_kk), - indexSpecialSpecies_(npos), - numCationSpecies_(0), - numAnionSpecies_(0), - numPassThroughSpecies_(0), - neutralPBindexStart(0), - cationPhase_(0), - anionPhase_(0) -{ - warn_deprecated("Class PseudoBinaryVPSSTP", - "To be removed after Cantera 2.2."); -} - -PseudoBinaryVPSSTP::PseudoBinaryVPSSTP(const PseudoBinaryVPSSTP& b) : - PBType_(PBTYPE_PASSTHROUGH), - numPBSpecies_(m_kk), - indexSpecialSpecies_(npos), - numCationSpecies_(0), - numAnionSpecies_(0), - numPassThroughSpecies_(0), - neutralPBindexStart(0), - cationPhase_(0), - anionPhase_(0) -{ - *this = b; -} - -PseudoBinaryVPSSTP& PseudoBinaryVPSSTP::operator=(const PseudoBinaryVPSSTP& b) -{ - if (&b != this) { - GibbsExcessVPSSTP::operator=(b); - } - - PBType_ = b.PBType_; - numPBSpecies_ = b.numPBSpecies_; - indexSpecialSpecies_ = b.indexSpecialSpecies_; - PBMoleFractions_ = b.PBMoleFractions_; - cationList_ = b.cationList_; - numCationSpecies_ = b.numCationSpecies_; - anionList_ = b.anionList_; - numAnionSpecies_ = b.numAnionSpecies_; - passThroughList_ = b.passThroughList_; - numPassThroughSpecies_ = b.numPassThroughSpecies_; - neutralPBindexStart = b.neutralPBindexStart; - cationPhase_ = b.cationPhase_; - anionPhase_ = b.anionPhase_; - moleFractionsTmp_ = b.moleFractionsTmp_; - - return *this; -} - -ThermoPhase* -PseudoBinaryVPSSTP::duplMyselfAsThermoPhase() const -{ - return new PseudoBinaryVPSSTP(*this); -} - -doublereal PseudoBinaryVPSSTP::standardConcentration(size_t k) const -{ - throw NotImplementedError("PseudoBinaryVPSSTP::standardConcentration"); -} - -void PseudoBinaryVPSSTP::getElectrochemPotentials(doublereal* mu) const -{ - getChemPotentials(mu); - double ve = Faraday * electricPotential(); - for (size_t k = 0; k < m_kk; k++) { - mu[k] += ve*charge(k); - } -} - -void PseudoBinaryVPSSTP::calcPseudoBinaryMoleFractions() const -{ - switch (PBType_) { - case PBTYPE_PASSTHROUGH: - for (size_t k = 0; k < m_kk; k++) { - PBMoleFractions_[k] = moleFractions_[k]; - } - break; - case PBTYPE_SINGLEANION: - { - double sumCat = 0.0; - double sumAnion = 0.0; - for (size_t k = 0; k < m_kk; k++) { - moleFractionsTmp_[k] = moleFractions_[k]; - } - for (size_t k = 0; k < cationList_.size(); k++) { - sumCat += moleFractions_[cationList_[k]]; - } - sumAnion = moleFractions_[anionList_[0]]; - PBMoleFractions_[0] = sumCat -sumAnion; - moleFractionsTmp_[indexSpecialSpecies_] -= PBMoleFractions_[0]; - - - for (size_t k = 0; k < numCationSpecies_; k++) { - PBMoleFractions_[1+k] = moleFractionsTmp_[cationList_[k]]; - } - - for (size_t k = 0; k < numPassThroughSpecies_; k++) { - PBMoleFractions_[neutralPBindexStart + k] = - moleFractions_[cationList_[k]]; - } - - double sum = std::max(0.0, PBMoleFractions_[0]); - for (size_t k = 1; k < numPBSpecies_; k++) { - sum += PBMoleFractions_[k]; - } - for (size_t k = 0; k < numPBSpecies_; k++) { - PBMoleFractions_[k] /= sum; - } - break; - } - case PBTYPE_SINGLECATION: - throw CanteraError("eosType", "Unknown type"); - - break; - - case PBTYPE_MULTICATIONANION: - throw CanteraError("eosType", "Unknown type"); - - break; - default: - throw CanteraError("eosType", "Unknown type"); - break; - - } -} - -void PseudoBinaryVPSSTP::initThermo() -{ - initLengths(); - GibbsExcessVPSSTP::initThermo(); -} - -void PseudoBinaryVPSSTP::initLengths() -{ - moleFractions_.resize(m_kk); -} - -void PseudoBinaryVPSSTP::initThermoXML(XML_Node& phaseNode, const std::string& id_) -{ - GibbsExcessVPSSTP::initThermoXML(phaseNode, id_); -} - -std::string PseudoBinaryVPSSTP::report(bool show_thermo, doublereal threshold) const -{ - char p[800]; - string s = ""; - try { - if (name() != "") { - sprintf(p, " \n %s:\n", name().c_str()); - s += p; - } - sprintf(p, " \n temperature %12.6g K\n", temperature()); - s += p; - sprintf(p, " pressure %12.6g Pa\n", pressure()); - s += p; - sprintf(p, " density %12.6g kg/m^3\n", density()); - s += p; - sprintf(p, " mean mol. weight %12.6g amu\n", meanMolecularWeight()); - s += p; - - doublereal phi = electricPotential(); - sprintf(p, " potential %12.6g V\n", phi); - s += p; - - vector_fp x(m_kk); - vector_fp molal(m_kk); - vector_fp mu(m_kk); - vector_fp muss(m_kk); - vector_fp acMolal(m_kk); - vector_fp actMolal(m_kk); - getMoleFractions(&x[0]); - - getChemPotentials(&mu[0]); - getStandardChemPotentials(&muss[0]); - getActivities(&actMolal[0]); - - - if (show_thermo) { - sprintf(p, " \n"); - s += p; - sprintf(p, " 1 kg 1 kmol\n"); - s += p; - sprintf(p, " ----------- ------------\n"); - s += p; - sprintf(p, " enthalpy %12.6g %12.4g J\n", - enthalpy_mass(), enthalpy_mole()); - s += p; - sprintf(p, " internal energy %12.6g %12.4g J\n", - intEnergy_mass(), intEnergy_mole()); - s += p; - sprintf(p, " entropy %12.6g %12.4g J/K\n", - entropy_mass(), entropy_mole()); - s += p; - sprintf(p, " Gibbs function %12.6g %12.4g J\n", - gibbs_mass(), gibbs_mole()); - s += p; - sprintf(p, " heat capacity c_p %12.6g %12.4g J/K\n", - cp_mass(), cp_mole()); - s += p; - try { - sprintf(p, " heat capacity c_v %12.6g %12.4g J/K\n", - cv_mass(), cv_mole()); - s += p; - } catch (CanteraError& e) { - e.save(); - sprintf(p, " heat capacity c_v \n"); - s += p; - } - } - - } catch (CanteraError& e) { - e.save(); - } - return s; -} - -} diff --git a/src/thermo/RedlichKisterVPSSTP.cpp b/src/thermo/RedlichKisterVPSSTP.cpp index 6d76d85e4..45527cadf 100644 --- a/src/thermo/RedlichKisterVPSSTP.cpp +++ b/src/thermo/RedlichKisterVPSSTP.cpp @@ -46,49 +46,6 @@ RedlichKisterVPSSTP::RedlichKisterVPSSTP(XML_Node& phaseRoot, importPhase(*findXMLPhase(&phaseRoot, id_), this); } -RedlichKisterVPSSTP::RedlichKisterVPSSTP(int testProb) : - numBinaryInteractions_(0), - formRedlichKister_(0), - formTempModel_(0) -{ - warn_deprecated("RedlichKisterVPSSTP::RedlichKisterVPSSTP(int testProb)", - "To be removed after Cantera 2.2"); - - initThermoFile("LiKCl_liquid.xml", ""); - numBinaryInteractions_ = 1; - - m_HE_m_ij.resize(0); - m_SE_m_ij.resize(0); - - vector_fp he(2); - he[0] = 0.0; - he[1] = 0.0; - vector_fp se(2); - se[0] = 0.0; - se[1] = 0.0; - - m_HE_m_ij.push_back(he); - m_SE_m_ij.push_back(se); - m_N_ij.push_back(1); - m_pSpecies_A_ij.resize(1); - m_pSpecies_B_ij.resize(1); - - size_t iLiLi = speciesIndex("LiLi"); - if (iLiLi == npos) { - throw CanteraError("RedlichKisterVPSSTP test1 constructor", - "Unable to find LiLi"); - } - m_pSpecies_A_ij[0] = iLiLi; - - - size_t iVLi = speciesIndex("VLi"); - if (iVLi == npos) { - throw CanteraError("RedlichKisterVPSSTP test1 constructor", - "Unable to find VLi"); - } - m_pSpecies_B_ij[0] = iVLi; -} - RedlichKisterVPSSTP::RedlichKisterVPSSTP(const RedlichKisterVPSSTP& b) : numBinaryInteractions_(0), formRedlichKister_(0), diff --git a/src/thermo/RedlichKwongMFTP.cpp b/src/thermo/RedlichKwongMFTP.cpp index af0a19560..f657e3c47 100644 --- a/src/thermo/RedlichKwongMFTP.cpp +++ b/src/thermo/RedlichKwongMFTP.cpp @@ -86,37 +86,6 @@ RedlichKwongMFTP::RedlichKwongMFTP(XML_Node& phaseRefRoot, const std::string& id importPhase(*xphase, this); } -RedlichKwongMFTP::RedlichKwongMFTP(int testProb) : - m_standardMixingRules(0), - m_formTempParam(0), - m_b_current(0.0), - m_a_current(0.0), - NSolns_(0), - dpdV_(0.0), - dpdT_(0.0) -{ - warn_deprecated("RedlichKwongMFTP::RedlichKwongMFTP(int testProb)", - "To be removed after Cantera 2.2"); - std::string infile = "co2_redlichkwong.xml"; - std::string id_; - if (testProb == 1) { - infile = "co2_redlichkwong.xml"; - id_ = "carbondioxide"; - } else { - throw CanteraError("RedlichKwongMFTP::RedlichKwongMFTP(int testProb)", - "test prob = 1 only"); - } - XML_Node* root = get_XML_File(infile); - if (id_ == "-") { - id_ = ""; - } - XML_Node* xphase = get_XML_NameID("phase", std::string("#")+id_, root); - if (!xphase) { - throw CanteraError("newPhase", "Couldn't find phase named \"" + id_ + "\" in file, " + infile); - } - importPhase(*xphase, this); -} - RedlichKwongMFTP::RedlichKwongMFTP(const RedlichKwongMFTP& b) : m_standardMixingRules(0), m_formTempParam(0), @@ -311,36 +280,6 @@ doublereal RedlichKwongMFTP::standardConcentration(size_t k) const return 1.0 / m_tmpV[k]; } -void RedlichKwongMFTP::getUnitsStandardConc(double* uA, int, int sizeUA) const -{ - warn_deprecated("RedlichKwongMFTP::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - - //int eos = eosType(); - - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -static_cast(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } - -} - void RedlichKwongMFTP::getActivityCoefficients(doublereal* ac) const { doublereal TKelvin = temperature(); diff --git a/src/thermo/SpeciesThermoFactory.cpp b/src/thermo/SpeciesThermoFactory.cpp index 49fe191df..c44db0436 100644 --- a/src/thermo/SpeciesThermoFactory.cpp +++ b/src/thermo/SpeciesThermoFactory.cpp @@ -12,7 +12,6 @@ #include "cantera/thermo/Mu0Poly.h" #include "cantera/thermo/Nasa9PolyMultiTempRegion.h" #include "cantera/thermo/Nasa9Poly1.h" -#include "cantera/thermo/StatMech.h" #include "cantera/thermo/NasaPoly2.h" #include "cantera/thermo/ShomatePoly.h" #include "cantera/thermo/ConstCpPoly.h" @@ -350,29 +349,6 @@ static SpeciesThermoInterpType* newNasa9ThermoFromXML( } } -/** - * Create a stat mech based property solver for a species - * @deprecated - */ -static StatMech* newStatMechThermoFromXML(XML_Node& f) -{ - doublereal tmin = fpValue(f["Tmin"]); - doublereal tmax = fpValue(f["Tmax"]); - doublereal pref = OneAtm; - if (f.hasAttrib("P0")) { - pref = fpValue(f["P0"]); - } - if (f.hasAttrib("Pref")) { - pref = fpValue(f["Pref"]); - } - - // set properties - tmin = 0.1; - vector_fp coeffs(1); - coeffs[0] = 0.0; - return new StatMech(0, tmin, tmax, pref, &coeffs[0], ""); -} - //! Create an Adsorbate polynomial thermodynamic property parameterization for a //! species /*! @@ -457,8 +433,6 @@ SpeciesThermoInterpType* newSpeciesThermoInterpType(const XML_Node& thermo) return newNasa9ThermoFromXML(tp); } else if (thermoType == "adsorbate") { return newAdsorbateThermoFromXML(*tp[0]); - } else if (thermoType == "statmech") { - return newStatMechThermoFromXML(*tp[0]); } else if (model == "hkft" || model == "ionfromneutral") { // Some PDSS species use the 'thermo' node, but don't specify a // SpeciesThermoInterpType parameterization. This function needs to just diff --git a/src/thermo/StatMech.cpp b/src/thermo/StatMech.cpp deleted file mode 100644 index 59291d314..000000000 --- a/src/thermo/StatMech.cpp +++ /dev/null @@ -1,656 +0,0 @@ -/** - * @file StatMech.cpp - * \link Cantera::SpeciesThermoInterpType SpeciesThermoInterpType\endlink - */ - -// Copyright 2007 Sandia National Laboratories - -#include "cantera/thermo/StatMech.h" -#include "cantera/base/ctexceptions.h" -#include - -namespace Cantera -{ -StatMech::StatMech() { - warn_deprecated("class StatMech", "To be removed after Cantera 2.2"); -} - -StatMech::StatMech(int n, doublereal tlow, doublereal thigh, - doublereal pref, - const doublereal* coeffs, - const std::string& my_name) : - SpeciesThermoInterpType(tlow, thigh, pref), - sp_name(my_name) -{ - // should error on zero -- cannot take ln(0) - if (m_lowT <= 0.0) { - throw CanteraError("Error in StatMech.cpp", - " Cannot take 0 tmin as input. \n\n"); - } - buildmap(); -} - -StatMech::StatMech(const StatMech& b) : - SpeciesThermoInterpType(b) -{ -} - -StatMech& StatMech::operator=(const StatMech& b) -{ - if (&b != this) { - SpeciesThermoInterpType::operator=(b); - } - return *this; -} - -SpeciesThermoInterpType* -StatMech::duplMyselfAsSpeciesThermoInterpType() const -{ - return new StatMech(*this); -} - -int StatMech::reportType() const -{ - return STAT; -} - -int StatMech::buildmap() -{ - - // build vector of strings - std::vector SS; - - // now just iterate over name map to place each - // string in a key - - SS.push_back("Air"); - SS.push_back("CPAir"); - SS.push_back("Ar"); - SS.push_back("Ar+"); - SS.push_back("C"); - SS.push_back("C+"); - SS.push_back("C2"); - SS.push_back("C2H"); - SS.push_back("C2H2"); - SS.push_back("C3"); - SS.push_back("CF"); - SS.push_back("CF2"); - SS.push_back("CF3"); - SS.push_back("CF4"); - SS.push_back("CH"); - SS.push_back("CH2"); - SS.push_back("CH3"); - SS.push_back("CH4"); - SS.push_back("Cl"); - SS.push_back("Cl2"); - SS.push_back("CN"); - SS.push_back("CN+"); - SS.push_back("CO"); - SS.push_back("CO+"); - SS.push_back("CO2"); - SS.push_back("F"); - SS.push_back("F2"); - SS.push_back("H"); - SS.push_back("H+"); - SS.push_back("H2"); - SS.push_back("H2+"); - SS.push_back("H2O"); - SS.push_back("HCl"); - SS.push_back("HCN"); - SS.push_back("He"); - SS.push_back("He+"); - SS.push_back("N"); - SS.push_back("N+"); - SS.push_back("N2"); - SS.push_back("CPN2"); - SS.push_back("N2+"); - SS.push_back("Ne"); - SS.push_back("NCO"); - SS.push_back("NH"); - SS.push_back("NH+"); - SS.push_back("NH2"); - SS.push_back("NH3"); - SS.push_back("NO"); - SS.push_back("NO+"); - SS.push_back("NO2"); - SS.push_back("O"); - SS.push_back("O+"); - SS.push_back("O2"); - SS.push_back("O2+"); - SS.push_back("OH"); - SS.push_back("Si"); - SS.push_back("SiO"); - SS.push_back("e"); - - // now place each species in a map - size_t ii; - for (ii=0; ii < SS.size(); ii++) { - name_map[SS[ii]]=(new species); - - // init to crazy defaults - name_map[SS[ii]]->nvib = -1; - name_map[SS[ii]]->cfs = -1; - name_map[SS[ii]]->mol_weight = -1; - - name_map[SS[ii]]->theta[0] =0.0; - name_map[SS[ii]]->theta[1] =0.0; - name_map[SS[ii]]->theta[2] =0.0; - name_map[SS[ii]]->theta[3] =0.0; - name_map[SS[ii]]->theta[4] =0.0; - } - - // now set all species information - - // build Air - name_map["Air"]->cfs = 2.5; - name_map["Air"]->mol_weight=28.96; - name_map["Air"]->nvib=0; - - // build CPAir - name_map["CPAir"]->cfs = 2.5; - name_map["CPAir"]->mol_weight=28.96; - name_map["CPAir"]->nvib=0; - - // build Ar - name_map["Ar"]->cfs = 1.5; - name_map["Ar"]->mol_weight=39.944; - name_map["Ar"]->nvib=0; - - // build Ar+ - name_map["Ar+"]->cfs = 1.5; - name_map["Ar+"]->mol_weight=39.94345; - name_map["Ar+"]->nvib=0; - - // build C - name_map["C"]->cfs = 1.5; - name_map["C"]->mol_weight=12.011; - name_map["C"]->nvib=0; - - // build C+ - name_map["C+"]->cfs = 1.5; - name_map["C+"]->mol_weight=12.01045; - name_map["C+"]->nvib=0; - - // C2 - name_map["C2"]->cfs=2.5; - name_map["C2"]->mol_weight=24.022; - name_map["C2"]->nvib=1; - name_map["C2"]->theta[0]=2.6687e3; - - // C2H - name_map["C2H"]->cfs=2.5; - name_map["C2H"]->mol_weight=25.03; - name_map["C2H"]->nvib=3; - name_map["C2H"]->theta[0]=5.20100e+03; - name_map["C2H"]->theta[1]=7.20000e+03; - name_map["C2H"]->theta[2]=2.66100e+03; - - // C2H2 - name_map["C2H2"]->cfs=2.5; - name_map["C2H2"]->mol_weight=26.038; - name_map["C2H2"]->nvib=5; - name_map["C2H2"]->theta[0]=4.85290e+03; - name_map["C2H2"]->theta[1]=2.84000e+03; - name_map["C2H2"]->theta[2]=4.72490e+03; - name_map["C2H2"]->theta[3]=8.81830e+02; - name_map["C2H2"]->theta[4]=1.05080e+03; - - // C3 - name_map["C3"]->cfs=2.5; - name_map["C3"]->mol_weight=36.033; - name_map["C3"]->nvib=3; - name_map["C3"]->theta[0]=1.84500e+03; - name_map["C3"]->theta[1]=7.78700e+02; - name_map["C3"]->theta[2]=3.11760e+03; - - // CF - name_map["CF"]->cfs=2.5; - name_map["CF"]->mol_weight=31.00940; - name_map["CF"]->nvib=1; - name_map["CF"]->theta[0]=1.88214e+03; - - // CF2 - name_map["CF2"]->cfs=3; - name_map["CF2"]->mol_weight=50.00780; - name_map["CF2"]->nvib=3; - name_map["CF2"]->theta[0]=1.76120e+03; - name_map["CF2"]->theta[1]=9.56820e+02; - name_map["CF2"]->theta[2]=1.60000e+03; - - // CF3 - name_map["CF3"]->cfs=3; - name_map["CF3"]->mol_weight=69.00620; - name_map["CF3"]->nvib=4; - name_map["CF3"]->theta[0]=1.56800e+03; - name_map["CF3"]->theta[1]=1.00900e+03; - name_map["CF3"]->theta[2]=1.81150e+03; - name_map["CF3"]->theta[3]=7.36680e+02; - - // CF4 - name_map["CF4"]->cfs=3; - name_map["CF4"]->mol_weight=88.00460; - name_map["CF4"]->nvib=4; - name_map["CF4"]->theta[0]=1.30720e+03; - name_map["CF4"]->theta[1]=6.25892e+02; - name_map["CF4"]->theta[2]=1.84540e+03; - name_map["CF4"]->theta[3]=9.08950e+02; - - // CH - name_map["CH"]->cfs=2.5; - name_map["CH"]->mol_weight=13.01900; - name_map["CH"]->nvib=1; - name_map["CH"]->theta[0]=4.11290e+03; - - // CH2 - name_map["CH2"]->cfs=3; - name_map["CH2"]->mol_weight=14.02700; - name_map["CH2"]->nvib=3; - name_map["CH2"]->theta[0]=4.31650e+03; - name_map["CH2"]->theta[1]=1.95972e+03; - name_map["CH2"]->theta[2]=4.60432e+03; - - // CH3 - name_map["CH3"]->cfs=3; - name_map["CH3"]->mol_weight=15.03500; - name_map["CH3"]->nvib=4; - name_map["CH3"]->theta[0]=4.31650e+03; - name_map["CH3"]->theta[1]=8.73370e+02; - name_map["CH3"]->theta[2]=4.54960e+03; - name_map["CH3"]->theta[3]=2.01150e+03; - - // CH4 - name_map["CH4"]->cfs=3; - name_map["CH4"]->mol_weight=16.04300; - name_map["CH4"]->nvib=4; - name_map["CH4"]->theta[0]=4.19660e+03; - name_map["CH4"]->theta[1]=2.20620e+03; - name_map["CH4"]->theta[2]=4.34450e+03; - name_map["CH4"]->theta[3]=1.88600e+03; - - // Cl - name_map["Cl"]->cfs=1.5; - name_map["Cl"]->mol_weight=35.45300; - name_map["Cl"]->nvib=0; - - // Cl2 - name_map["Cl2"]->cfs=2.5; - name_map["Cl2"]->mol_weight=70.96; - name_map["Cl2"]->nvib=1; - name_map["Cl2"]->theta[0]=8.05355e+02; - - // CN - name_map["CN"]->cfs=2.5; - name_map["CN"]->mol_weight=26.01900; - name_map["CN"]->nvib=1; - name_map["CN"]->theta[0]=2.97610e+03; - - // CN+ - name_map["CN+"]->cfs=2.5; - name_map["CN+"]->mol_weight=26.01845; - name_map["CN+"]->nvib=1; - name_map["CN+"]->theta[0]=2.92520e+03; - - // CO - name_map["CO"]->cfs=2.5; - name_map["CO"]->mol_weight=28.01100; - name_map["CO"]->nvib=1; - name_map["CO"]->theta[0]=3.12200e+03; - - // CO+ - name_map["CO+"]->cfs=2.5; - name_map["CO+"]->mol_weight=28.01045; - name_map["CO+"]->nvib=1; - name_map["CO+"]->theta[0]=3.18800e+03; - - // CO2 - name_map["CO2"]->cfs=2.5; - name_map["CO2"]->mol_weight=44.01100; - name_map["CO2"]->nvib=3; - name_map["CO2"]->theta[0]=1.91870e+03; - name_map["CO2"]->theta[1]=9.59660e+02; - name_map["CO2"]->theta[2]=3.38210e+03; - - // F - name_map["F"]->cfs=1.5; - name_map["F"]->mol_weight=18.99840; - name_map["F"]->nvib=0; - - // F2 - name_map["F2"]->cfs=2.5; - name_map["F2"]->mol_weight=37.99680; - name_map["F2"]->nvib=1; - name_map["F2"]->theta[0]=1.32020e+03; - - // H - name_map["H"]->cfs=1.5; - name_map["H"]->mol_weight=1; - name_map["H"]->nvib=0; - - // H+ - name_map["H+"]->cfs=1.5; - name_map["H+"]->mol_weight=1.00745; - name_map["H+"]->nvib=0; - - // H2 - name_map["H2"]->cfs=2.5; - name_map["H2"]->mol_weight=2.01600; - name_map["H2"]->nvib=1; - name_map["H2"]->theta[0]=6.33140e+03; - - // H2+ - name_map["H2+"]->cfs=2.5; - name_map["H2+"]->mol_weight=2.01545; - name_map["H2+"]->nvib=1; - name_map["H2+"]->theta[0]=3.34280e+03; - - // H2O - name_map["H2O"]->cfs=3.0; - name_map["H2O"]->mol_weight=18.01600; - name_map["H2O"]->nvib=3; - name_map["H2O"]->theta[0]=5.26130e+03; - name_map["H2O"]->theta[1]=2.29460e+03; - name_map["H2O"]->theta[2]=5.40395e+03; - - // HCl - name_map["HCl"]->cfs=2.5; - name_map["HCl"]->mol_weight=36.46100; - name_map["HCl"]->nvib=1; - name_map["HCl"]->theta[0]=4.30330e+03; - - // HCN - name_map["HCN"]->cfs=2.5; - name_map["HCN"]->mol_weight=27.02700; - name_map["HCN"]->nvib=3; - name_map["HCN"]->theta[0]=3.01620e+03; - name_map["HCN"]->theta[1]=1.02660e+03; - name_map["HCN"]->theta[2]=4.76450e+03; - - // He - name_map["He"]->cfs=1.5; - name_map["He"]->mol_weight=4.00300; - name_map["He"]->nvib=0; - - // He+ - name_map["He+"]->cfs=1.5; - name_map["He+"]->mol_weight=4.00245; - name_map["He+"]->nvib=0; - - // N - name_map["N"]->cfs=1.5; - name_map["N"]->mol_weight=14.008; - name_map["N"]->nvib=0; - - // Ne - name_map["Ne"]->cfs=1.5; - name_map["Ne"]->mol_weight=20.17900; - name_map["Ne"]->nvib=0; - - // N+ - name_map["N+"]->cfs=1.5; - name_map["N+"]->mol_weight=14.00745; - name_map["N+"]->nvib=0; - - // N2 - name_map["N2"]->cfs=2.5; - name_map["N2"]->mol_weight=28.01600; - name_map["N2"]->nvib=1; - name_map["N2"]->theta[0]=3.39500e+03; - - // N2+ - name_map["N2+"]->cfs=2.5; - name_map["N2+"]->mol_weight=28.01545; - name_map["N2+"]->nvib=1; - name_map["N2+"]->theta[0]=3.17580e+03; - - // CPN2 - name_map["CPN2"]->cfs=2.5; - name_map["CPN2"]->mol_weight=28.01600; - name_map["CPN2"]->nvib=0; - - // NCO - name_map["NCO"]->cfs=2.5; - name_map["NCO"]->mol_weight=42.01900; - name_map["NCO"]->nvib=3; - name_map["NCO"]->theta[0]=1.83600e+03; - name_map["NCO"]->theta[1]=7.67100e+02; - name_map["NCO"]->theta[2]=2.76800e+03; - - // NH - name_map["NH"]->cfs=2.5; - name_map["NH"]->mol_weight=15.01600; - name_map["NH"]->nvib=1; - name_map["NH"]->theta[0]=4.72240e+03; - - // NH+ - name_map["NH+"]->cfs=2.5; - name_map["NH+"]->mol_weight=15.01545; - name_map["NH+"]->nvib=0; - - // NH2 - name_map["NH2"]->cfs=2.5; - name_map["NH2"]->mol_weight=16.02400; - name_map["NH2"]->nvib=0; - - // NH3 - name_map["NH3"]->cfs=2.5; - name_map["NH3"]->mol_weight=17.03200; - name_map["NH3"]->nvib=4; - name_map["NH3"]->theta[0]=4.78100e+03; - name_map["NH3"]->theta[1]=1.47040e+03; - name_map["NH3"]->theta[2]=4.95440e+03; - name_map["NH3"]->theta[3]=2.34070e+03; - - // NO - name_map["NO"]->cfs=2.5; - name_map["NO"]->mol_weight=30.00800; - name_map["NO"]->nvib=1; - name_map["NO"]->theta[0]=2.81700e+03; - - // NO+ - name_map["NO+"]->cfs=2.5; - name_map["NO+"]->mol_weight=30.00745; - name_map["NO+"]->nvib=1; - name_map["NO+"]->theta[0]=3.42100e+03; - - // NO2 - name_map["NO2"]->cfs=3; - name_map["NO2"]->mol_weight=46.00800; - name_map["NO2"]->nvib=3; - name_map["NO2"]->theta[0]=1.07900e+03; - name_map["NO2"]->theta[1]=1.90000e+03; - name_map["NO2"]->theta[2]=2.32700e+03; - - // O - name_map["O"]->cfs=1.5; - name_map["O"]->mol_weight=16.000; - name_map["O"]->nvib=0; - - // O+ - name_map["O+"]->cfs=1.5; - name_map["O+"]->mol_weight=15.99945; - name_map["O+"]->nvib=0; - - // O2 - name_map["O2"]->cfs=2.5; - name_map["O2"]->mol_weight=32.00000; - name_map["O2"]->nvib=1; - name_map["O2"]->theta[0]=2.23900e+03; - - // O2 - name_map["O2+"]->cfs=2.5; - name_map["O2+"]->mol_weight=31.99945; - name_map["O2+"]->nvib=1; - name_map["O2+"]->theta[0]=2.74120e+03; - - // OH - name_map["OH"]->cfs=2.5; - name_map["OH"]->mol_weight=17.00800; - name_map["OH"]->nvib=1; - name_map["OH"]->theta[0]=5.37820e+03; - - // Si - name_map["Si"]->cfs=1.5; - name_map["Si"]->mol_weight=28.08550; - name_map["Si"]->nvib=0; - - // SiO - name_map["SiO"]->cfs=2.5; - name_map["SiO"]->mol_weight=44.08550; - name_map["SiO"]->nvib=1; - name_map["SiO"]->theta[0]=1.78640e+03; - - // electron - name_map["e"]->cfs=1.5; - name_map["e"]->mol_weight=0.00055; - name_map["e"]->nvib=0; - - for (ii=0; ii < SS.size(); ii++) { - // check nvib was initialized for all species - if (name_map[SS[ii]]->nvib == -1) { - std::cout << name_map[SS[ii]]->nvib << std::endl; - throw CanteraError("Error in StatMech.cpp", - "nvib not initialized!. \n\n"); - - } else { - // check that theta is initialized - for (int i=0; invib; i++) { - if (name_map[SS[ii]]->theta[i] <= 0.0) { - throw CanteraError("Error in StatMech.cpp", - "theta not initialized!. \n\n"); - } - } - - // check that no non-zero theta exist - // for any theta larger than nvib! - for (int i=name_map[SS[ii]]->nvib; i<5; i++) { - if (name_map[SS[ii]]->theta[i] != 0.0) { - std::string err = "bad theta value for "+SS[ii]+"\n"; - throw CanteraError("StatMech.cpp",err); - } - } // done with for loop - } - - // check mol weight was initialized for all species - if (name_map[SS[ii]]->mol_weight == -1) { - std::cout << name_map[SS[ii]]->mol_weight << std::endl; - throw CanteraError("Error in StatMech.cpp", - "mol_weight not initialized!. \n\n"); - - } - - // cfs was initialized for all species - if (name_map[SS[ii]]->cfs == -1) { - std::cout << name_map[SS[ii]]->cfs << std::endl; - throw CanteraError("Error in StatMech.cpp", - "cfs not initialized!. \n\n"); - - } - - } // done with sanity checks - - // mark it zero, dude - return 0; -} - -void StatMech::updateProperties(const doublereal* tt, - doublereal* cp_R, doublereal* h_RT, - doublereal* s_R) const -{ - - std::map::iterator it; - - // get species name, to gather species properties - species* s; - - // pointer to map location of particular species - if (name_map.find(sp_name) != name_map.end()) { - s = name_map.find(sp_name)->second; - } else { - throw CanteraError("StatMech.cpp", - "species properties not found!. \n\n"); - } - - // translational + rotational specific heat - doublereal ctr = 0.0; - double theta = 0.0; - - // 5/2 * R for molecules, 3/2 * R for atoms - ctr += GasConstant * s->cfs; - - // vibrational energy - for (int i=0; i< s->nvib; i++) { - theta = s->theta[i]; - ctr += GasConstant * theta * (theta* exp(theta/tt[0])/(tt[0]*tt[0]))/((exp(theta/tt[0])-1) * (exp(theta/tt[0])-1)); - } - - // Cp = Cv + R - doublereal cpdivR = ctr/GasConstant + 1; - - // ACTUNG: fix enthalpy and entropy - doublereal hdivRT = 0.0; - doublereal sdivR = 0.0; - - // return the computed properties in the location in the output - // arrays for this species - *cp_R = cpdivR; - *h_RT = hdivRT; - *s_R = sdivR; -} - -void StatMech::updatePropertiesTemp(const doublereal temp, - doublereal* cp_R, doublereal* h_RT, - doublereal* s_R) const -{ - double tPoly[1]; - tPoly[0] = temp; - updateProperties(tPoly, cp_R, h_RT, s_R); -} - -void StatMech::reportParameters(size_t& n, int& type, - doublereal& tlow, doublereal& thigh, - doublereal& pref, - doublereal* const coeffs) const -{ - species* s; - - n = 0; - type = STAT; - tlow = m_lowT; - thigh = m_highT; - pref = m_Pref; - for (int i = 0; i < 9; i++) { - coeffs[i] = 0.0; - } - doublereal temp = coeffs[0]; - coeffs[1] = m_lowT; - coeffs[2] = m_highT; - - // get species name, to gather species properties - // pointer to map location of particular species - if (name_map.find(sp_name) != name_map.end()) { - s = name_map.find(sp_name)->second; - } else { - throw CanteraError("StatMech.cpp", - "species properties not found!. \n\n"); - } - - double theta = 0.0; - doublereal cvib = 0; - - // vibrational energy - for (int i=0; i< s->nvib; i++) { - theta = s->theta[i]; - cvib += GasConstant * theta * (theta* exp(theta/temp)/(temp*temp))/((exp(theta/temp)-1) * (exp(theta/temp)-1)); - } - - // load vibrational energy - coeffs[3] = GasConstant * s->cfs; - coeffs[4] = cvib; - -} - -void StatMech::modifyParameters(doublereal* coeffs) -{ -} - -} diff --git a/src/thermo/StoichSubstance.cpp b/src/thermo/StoichSubstance.cpp index e615918e6..685498ebe 100644 --- a/src/thermo/StoichSubstance.cpp +++ b/src/thermo/StoichSubstance.cpp @@ -136,15 +136,6 @@ void StoichSubstance::getStandardChemPotentials(doublereal* mu0) const mu0[0] = gibbs_mole(); } -void StoichSubstance::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("StoichSubstance::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - for (int i = 0; i < sizeUA; i++) { - uA[i] = 0.0; - } -} - void StoichSubstance::getChemPotentials_RT(doublereal* mu) const { mu[0] = gibbs_mole() / (GasConstant * temperature()); diff --git a/src/thermo/StoichSubstanceSSTP.cpp b/src/thermo/StoichSubstanceSSTP.cpp index b8e8f44f1..37bf736bd 100644 --- a/src/thermo/StoichSubstanceSSTP.cpp +++ b/src/thermo/StoichSubstanceSSTP.cpp @@ -129,15 +129,6 @@ doublereal StoichSubstanceSSTP::logStandardConc(size_t k) const return 0.0; } -void StoichSubstanceSSTP::getUnitsStandardConc(doublereal* uA, int k, int sizeUA) const -{ - warn_deprecated("StoichSubstanceSSTP::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - for (int i = 0; i < 6; i++) { - uA[i] = 0; - } -} - /* * Properties of the Standard State of the Species in the Solution */ diff --git a/src/thermo/SurfPhase.cpp b/src/thermo/SurfPhase.cpp index ba477ad65..074fbd198 100644 --- a/src/thermo/SurfPhase.cpp +++ b/src/thermo/SurfPhase.cpp @@ -12,7 +12,7 @@ #include "cantera/thermo/ThermoFactory.h" #include "cantera/base/stringUtils.h" #include "cantera/base/ctml.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" using namespace std; diff --git a/src/thermo/ThermoPhase.cpp b/src/thermo/ThermoPhase.cpp index e82e0b7fe..ae29d5c99 100644 --- a/src/thermo/ThermoPhase.cpp +++ b/src/thermo/ThermoPhase.cpp @@ -15,7 +15,6 @@ #include "cantera/equil/ChemEquil.h" #include "cantera/equil/MultiPhase.h" #include "cantera/base/ctml.h" -#include "cantera/base/vec_functions.h" #include #include @@ -620,32 +619,6 @@ void ThermoPhase::setState_SPorSV(doublereal Starget, doublereal p, } } -void ThermoPhase::getUnitsStandardConc(double* uA, int k, int sizeUA) const -{ - warn_deprecated("ThermoPhase::getUnitsStandardConc", - "To be removed after Cantera 2.2."); - for (int i = 0; i < sizeUA; i++) { - if (i == 0) { - uA[0] = 1.0; - } - if (i == 1) { - uA[1] = -int(nDim()); - } - if (i == 2) { - uA[2] = 0.0; - } - if (i == 3) { - uA[3] = 0.0; - } - if (i == 4) { - uA[4] = 0.0; - } - if (i == 5) { - uA[5] = 0.0; - } - } -} - void ThermoPhase::setSpeciesThermo(SpeciesThermo* spthermo) { if (!dynamic_cast(spthermo)) { diff --git a/src/thermo/VPSSMgr.cpp b/src/thermo/VPSSMgr.cpp index e62752b82..025bef238 100644 --- a/src/thermo/VPSSMgr.cpp +++ b/src/thermo/VPSSMgr.cpp @@ -17,7 +17,7 @@ #include "cantera/thermo/SpeciesThermoFactory.h" #include "cantera/thermo/PDSS.h" #include "cantera/thermo/GeneralSpeciesThermo.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" #include "cantera/base/xml.h" using namespace std; diff --git a/src/thermo/VPSSMgr_General.cpp b/src/thermo/VPSSMgr_General.cpp index 5f2ce44e0..fe1c96476 100644 --- a/src/thermo/VPSSMgr_General.cpp +++ b/src/thermo/VPSSMgr_General.cpp @@ -22,7 +22,7 @@ #include "cantera/thermo/PDSS_HKFT.h" #include "cantera/thermo/PDSS_IonsFromNeutral.h" #include "cantera/thermo/GeneralSpeciesThermo.h" -#include "cantera/base/vec_functions.h" +#include "cantera/base/utilities.h" using namespace std; diff --git a/src/transport/AqueousTransport.cpp b/src/transport/AqueousTransport.cpp deleted file mode 100644 index 7ff2b2d59..000000000 --- a/src/transport/AqueousTransport.cpp +++ /dev/null @@ -1,548 +0,0 @@ -/** - * @file AqueousTransport.cpp - * Transport properties for aqueous systems - */ - -#include "cantera/transport/AqueousTransport.h" -#include "cantera/transport/LiquidTransportParams.h" -#include "cantera/base/stringUtils.h" - -#include - -using namespace std; - -namespace Cantera -{ - -AqueousTransport::AqueousTransport() : - m_iStateMF(-1), - m_temp(-1.0), - m_logt(0.0), - m_sqrt_t(-1.0), - m_t14(-1.0), - m_t32(-1.0), - m_sqrt_kbt(-1.0), - m_press(-1.0), - m_lambda(-1.0), - m_viscmix(-1.0), - m_viscmix_ok(false), - m_viscwt_ok(false), - m_spvisc_ok(false), - m_diffmix_ok(false), - m_bindiff_ok(false), - m_spcond_ok(false), - m_condmix_ok(false), - m_mode(-1000), - m_debug(false), - m_nDim(1) -{ - warn_deprecated("class AqueousTransport", - "Non-functional. To be removed after Cantera 2.2."); -} - -bool AqueousTransport::initLiquid(LiquidTransportParams& tr) -{ - // constant substance attributes - m_thermo = tr.thermo; - m_nsp = m_thermo->nSpecies(); - - // make a local copy of the molecular weights - m_mw.resize(m_nsp); - copy(m_thermo->molecularWeights().begin(), - m_thermo->molecularWeights().end(), m_mw.begin()); - - // copy polynomials and parameters into local storage - cout << "In AqueousTransport::initLiquid we need to replace" << endl - << "LiquidTransportParams polynomial coefficients with" << endl - << "those in LiquidTransportData as in SimpleTransport." << endl; - - m_mode = tr.mode_; - - m_phi.resize(m_nsp, m_nsp, 0.0); - - - m_wratjk.resize(m_nsp, m_nsp, 0.0); - m_wratkj1.resize(m_nsp, m_nsp, 0.0); - for (size_t j = 0; j < m_nsp; j++) - for (size_t k = j; k < m_nsp; k++) { - m_wratjk(j,k) = sqrt(m_mw[j]/m_mw[k]); - m_wratjk(k,j) = sqrt(m_wratjk(j,k)); - m_wratkj1(j,k) = sqrt(1.0 + m_mw[k]/m_mw[j]); - } - - m_polytempvec.resize(5); - m_visc.resize(m_nsp); - m_sqvisc.resize(m_nsp); - m_cond.resize(m_nsp); - m_bdiff.resize(m_nsp, m_nsp); - - m_molefracs.resize(m_nsp); - m_spwork.resize(m_nsp); - - // resize the internal gradient variables - m_Grad_X.resize(m_nDim * m_nsp, 0.0); - m_Grad_T.resize(m_nDim, 0.0); - m_Grad_V.resize(m_nDim, 0.0); - m_Grad_mu.resize(m_nDim * m_nsp, 0.0); - - - // set all flags to false - m_viscmix_ok = false; - m_viscwt_ok = false; - m_spvisc_ok = false; - m_spcond_ok = false; - m_condmix_ok = false; - m_spcond_ok = false; - m_diffmix_ok = false; - - return true; -} - -doublereal AqueousTransport::viscosity() -{ - - update_T(); - update_C(); - - if (m_viscmix_ok) { - return m_viscmix; - } - - // update m_visc[] and m_phi[] if necessary - if (!m_viscwt_ok) { - updateViscosity_T(); - } - - multiply(m_phi, DATA_PTR(m_molefracs), DATA_PTR(m_spwork)); - - m_viscmix = 0.0; - for (size_t k = 0; k < m_nsp; k++) { - m_viscmix += m_molefracs[k] * m_visc[k]/m_spwork[k]; //denom; - } - return m_viscmix; -} - -void AqueousTransport::getSpeciesViscosities(doublereal* const visc) -{ - updateViscosity_T(); - copy(m_visc.begin(), m_visc.end(), visc); -} - -void AqueousTransport::getBinaryDiffCoeffs(const size_t ld, doublereal* const d) -{ - update_T(); - - // if necessary, evaluate the binary diffusion coefficients - // from the polynomial fits - if (!m_bindiff_ok) { - updateDiff_T(); - } - doublereal pres = m_thermo->pressure(); - - doublereal rp = 1.0/pres; - for (size_t i = 0; i < m_nsp; i++) - for (size_t j = 0; j < m_nsp; j++) { - d[ld*j + i] = rp * m_bdiff(i,j); - } -} - -void AqueousTransport::getMobilities(doublereal* const mobil) -{ - getMixDiffCoeffs(DATA_PTR(m_spwork)); - doublereal c1 = ElectronCharge / (Boltzmann * m_temp); - for (size_t k = 0; k < m_nsp; k++) { - mobil[k] = c1 * m_spwork[k]; - } -} - -void AqueousTransport::getFluidMobilities(doublereal* const mobil) -{ - getMixDiffCoeffs(DATA_PTR(m_spwork)); - doublereal c1 = 1.0 / (GasConstant * m_temp); - for (size_t k = 0; k < m_nsp; k++) { - mobil[k] = c1 * m_spwork[k]; - } -} - -void AqueousTransport::set_Grad_V(const doublereal* const grad_V) -{ - for (size_t a = 0; a < m_nDim; a++) { - m_Grad_V[a] = grad_V[a]; - } -} - -void AqueousTransport::set_Grad_T(const doublereal* const grad_T) -{ - for (size_t a = 0; a < m_nDim; a++) { - m_Grad_T[a] = grad_T[a]; - } -} - -void AqueousTransport::set_Grad_X(const doublereal* const grad_X) -{ - size_t itop = m_nDim * m_nsp; - for (size_t i = 0; i < itop; i++) { - m_Grad_X[i] = grad_X[i]; - } -} - -doublereal AqueousTransport::thermalConductivity() -{ - update_T(); - update_C(); - - if (!m_spcond_ok) { - updateCond_T(); - } - if (!m_condmix_ok) { - doublereal sum1 = 0.0, sum2 = 0.0; - for (size_t k = 0; k < m_nsp; k++) { - sum1 += m_molefracs[k] * m_cond[k]; - sum2 += m_molefracs[k] / m_cond[k]; - } - m_lambda = 0.5*(sum1 + 1.0/sum2); - } - return m_lambda; -} - -void AqueousTransport::getThermalDiffCoeffs(doublereal* const dt) -{ - for (size_t k = 0; k < m_nsp; k++) { - dt[k] = 0.0; - } -} - -void AqueousTransport::getSpeciesFluxes(size_t ndim, const doublereal* const grad_T, - size_t ldx, const doublereal* const grad_X, - size_t ldf, doublereal* const fluxes) -{ - set_Grad_T(grad_T); - set_Grad_X(grad_X); - getSpeciesFluxesExt(ldf, fluxes); -} - -void AqueousTransport::getSpeciesFluxesExt(size_t ldf, doublereal* const fluxes) -{ - update_T(); - update_C(); - - getMixDiffCoeffs(DATA_PTR(m_spwork)); - - const vector_fp& mw = m_thermo->molecularWeights(); - const doublereal* y = m_thermo->massFractions(); - doublereal rhon = m_thermo->molarDensity(); - // Unroll wrt ndim - vector_fp sum(m_nDim,0.0); - for (size_t n = 0; n < m_nDim; n++) { - for (size_t k = 0; k < m_nsp; k++) { - fluxes[n*ldf + k] = -rhon * mw[k] * m_spwork[k] * m_Grad_X[n*m_nsp + k]; - sum[n] += fluxes[n*ldf + k]; - } - } - // add correction flux to enforce sum to zero - for (size_t n = 0; n < m_nDim; n++) { - for (size_t k = 0; k < m_nsp; k++) { - fluxes[n*ldf + k] -= y[k]*sum[n]; - } - } -} - -void AqueousTransport::getMixDiffCoeffs(doublereal* const d) -{ - update_T(); - update_C(); - - // update the binary diffusion coefficients if necessary - if (!m_bindiff_ok) { - updateDiff_T(); - } - - size_t k, j; - doublereal mmw = m_thermo->meanMolecularWeight(); - doublereal sumxw = 0.0, sum2; - doublereal p = m_press; - if (m_nsp == 1) { - d[0] = m_bdiff(0,0) / p; - } else { - for (k = 0; k < m_nsp; k++) { - sumxw += m_molefracs[k] * m_mw[k]; - } - for (k = 0; k < m_nsp; k++) { - sum2 = 0.0; - for (j = 0; j < m_nsp; j++) { - if (j != k) { - sum2 += m_molefracs[j] / m_bdiff(j,k); - } - } - if (sum2 <= 0.0) { - d[k] = m_bdiff(k,k) / p; - } else { - d[k] = (sumxw - m_molefracs[k] * m_mw[k])/(p * mmw * sum2); - } - } - } -} - -void AqueousTransport::update_T() -{ - doublereal t = m_thermo->temperature(); - if (t == m_temp) { - return; - } - if (t < 0.0) { - throw CanteraError("AqueousTransport::update_T", - "negative temperature "+fp2str(t)); - } - - // Compute various functions of temperature - m_temp = t; - m_logt = log(m_temp); - m_kbt = Boltzmann * m_temp; - m_sqrt_t = sqrt(m_temp); - m_t14 = sqrt(m_sqrt_t); - m_t32 = m_temp * m_sqrt_t; - m_sqrt_kbt = sqrt(Boltzmann*m_temp); - - // compute powers of log(T) - m_polytempvec[0] = 1.0; - m_polytempvec[1] = m_logt; - m_polytempvec[2] = m_logt*m_logt; - m_polytempvec[3] = m_logt*m_logt*m_logt; - m_polytempvec[4] = m_logt*m_logt*m_logt*m_logt; - - // temperature has changed, so polynomial temperature - // interpolations will need to be reevaluated. - // Set all of these flags to false - m_viscmix_ok = false; - m_spvisc_ok = false; - m_viscwt_ok = false; - m_spcond_ok = false; - m_diffmix_ok = false; - m_bindiff_ok = false; - m_condmix_ok = false; - - // For now, for a concentration redo also - m_iStateMF = -1; -} - -void AqueousTransport::update_C() -{ - - doublereal pres = m_thermo->pressure(); - m_press = pres; - - // signal that concentration-dependent quantities will need to - // be recomputed before use, and update the local mole - // fractions. - - m_viscmix_ok = false; - m_diffmix_ok = false; - m_condmix_ok = false; - - m_thermo->getMoleFractions(DATA_PTR(m_molefracs)); - - // add an offset to avoid a pure species condition or - // negative mole fractions. *Tiny* is 1.0E-20, a value - // which is below the additive machine precision of mole fractions. - for (size_t k = 0; k < m_nsp; k++) { - m_molefracs[k] = std::max(Tiny, m_molefracs[k]); - } -} - -void AqueousTransport::updateCond_T() -{ - if (m_mode == CK_Mode) { - for (size_t k = 0; k < m_nsp; k++) { - m_cond[k] = exp(dot4(m_polytempvec, m_condcoeffs[k])); - } - } else { - for (size_t k = 0; k < m_nsp; k++) { - m_cond[k] = m_sqrt_t*dot5(m_polytempvec, m_condcoeffs[k]); - } - } - m_spcond_ok = true; - m_condmix_ok = false; -} - -void AqueousTransport::updateDiff_T() -{ - // evaluate binary diffusion coefficients at unit pressure - size_t ic = 0; - if (m_mode == CK_Mode) { - for (size_t i = 0; i < m_nsp; i++) { - for (size_t j = i; j < m_nsp; j++) { - m_bdiff(i,j) = exp(dot4(m_polytempvec, m_diffcoeffs[ic])); - m_bdiff(j,i) = m_bdiff(i,j); - ic++; - } - } - } else { - for (size_t i = 0; i < m_nsp; i++) { - for (size_t j = i; j < m_nsp; j++) { - m_bdiff(i,j) = m_temp * m_sqrt_t*dot5(m_polytempvec, - m_diffcoeffs[ic]); - m_bdiff(j,i) = m_bdiff(i,j); - ic++; - } - } - } - - m_bindiff_ok = true; - m_diffmix_ok = false; -} - -void AqueousTransport::updateSpeciesViscosities() -{ - if (m_mode == CK_Mode) { - for (size_t k = 0; k < m_nsp; k++) { - m_visc[k] = exp(dot4(m_polytempvec, m_visccoeffs[k])); - m_sqvisc[k] = sqrt(m_visc[k]); - } - } else { - for (size_t k = 0; k < m_nsp; k++) { - // the polynomial fit is done for sqrt(visc/sqrt(T)) - m_sqvisc[k] = m_t14*dot5(m_polytempvec, m_visccoeffs[k]); - m_visc[k] = (m_sqvisc[k]*m_sqvisc[k]); - } - } - m_spvisc_ok = true; -} - -void AqueousTransport::updateViscosity_T() -{ - doublereal vratiokj, wratiojk, factor1; - - if (!m_spvisc_ok) { - updateSpeciesViscosities(); - } - - // see Eq. (9-5.15) of Reid, Prausnitz, and Poling - for (size_t j = 0; j < m_nsp; j++) { - for (size_t k = j; k < m_nsp; k++) { - vratiokj = m_visc[k]/m_visc[j]; - wratiojk = m_mw[j]/m_mw[k]; - - // Note that m_wratjk(k,j) holds the square root of - // m_wratjk(j,k)! - factor1 = 1.0 + (m_sqvisc[k]/m_sqvisc[j]) * m_wratjk(k,j); - m_phi(k,j) = factor1*factor1 / - (sqrt(8.0) * m_wratkj1(j,k)); - m_phi(j,k) = m_phi(k,j)/(vratiokj * wratiojk); - } - } - m_viscwt_ok = true; -} - -LiquidTransportData AqueousTransport::getLiquidTransportData(int kSpecies) -{ - LiquidTransportData td; - td.speciesName = m_thermo->speciesName(kSpecies); - return td; -} - -void AqueousTransport::stefan_maxwell_solve() -{ - size_t VIM = 2; - m_B.resize(m_nsp, VIM); - // grab a local copy of the molecular weights - const vector_fp& M = m_thermo->molecularWeights(); - - m_thermo->getMoleFractions(DATA_PTR(m_molefracs)); - - double T = m_thermo->temperature(); - - - /* electrochemical potential gradient */ - for (size_t i = 0; i < m_nsp; i++) { - for (size_t a = 0; a < VIM; a++) { - m_Grad_mu[a*m_nsp + i] = m_chargeSpecies[i] * Faraday * m_Grad_V[a] - + (GasConstant*T/m_molefracs[i]) * m_Grad_X[a*m_nsp+i]; - } - } - - /* - * Just for Note, m_A(i,j) refers to the ith row and jth column. - * They are still fortran ordered, so that i varies fastest. - */ - switch (VIM) { - case 1: /* 1-D approximation */ - m_B(0,0) = 0.0; - for (size_t j = 0; j < m_nsp; j++) { - m_A(0,j) = 1.0; - } - for (size_t i = 1; i < m_nsp; i++) { - m_B(i,0) = m_concentrations[i] * m_Grad_mu[i] / (GasConstant * T); - for (size_t j = 0; j < m_nsp; j++) { - if (j != i) { - m_A(i,j) = m_molefracs[i] / (M[j] * m_DiffCoeff_StefMax(i,j)); - m_A(i,i) -= m_molefracs[j] / (M[i] * m_DiffCoeff_StefMax(i,j)); - } else if (j == i) { - m_A(i,i) = 0.0; - } - } - } - - //! invert and solve the system Ax = b. Answer is in m_B - solve(m_A, m_B.ptrColumn(0)); - - m_flux = m_B; - - - break; - case 2: /* 2-D approximation */ - m_B(0,0) = 0.0; - m_B(0,1) = 0.0; - for (size_t j = 0; j < m_nsp; j++) { - m_A(0,j) = 1.0; - } - for (size_t i = 1; i < m_nsp; i++) { - m_B(i,0) = m_concentrations[i] * m_Grad_mu[i] / (GasConstant * T); - m_B(i,1) = m_concentrations[i] * m_Grad_mu[m_nsp + i] / (GasConstant * T); - for (size_t j = 0; j < m_nsp; j++) { - if (j != i) { - m_A(i,j) = m_molefracs[i] / (M[j] * m_DiffCoeff_StefMax(i,j)); - m_A(i,i) -= m_molefracs[j] / (M[i] * m_DiffCoeff_StefMax(i,j)); - } else if (j == i) { - m_A(i,i) = 0.0; - } - } - } - - m_flux = m_B; - - - break; - - case 3: /* 3-D approximation */ - m_B(0,0) = 0.0; - m_B(0,1) = 0.0; - m_B(0,2) = 0.0; - for (size_t j = 0; j < m_nsp; j++) { - m_A(0,j) = 1.0; - } - for (size_t i = 1; i < m_nsp; i++) { - m_B(i,0) = m_concentrations[i] * m_Grad_mu[i] / (GasConstant * T); - m_B(i,1) = m_concentrations[i] * m_Grad_mu[m_nsp + i] / (GasConstant * T); - m_B(i,2) = m_concentrations[i] * m_Grad_mu[2*m_nsp + i] / (GasConstant * T); - for (size_t j = 0; j < m_nsp; j++) { - if (j != i) { - m_A(i,j) = m_molefracs[i] / (M[j] * m_DiffCoeff_StefMax(i,j)); - m_A(i,i) -= m_molefracs[j] / (M[i] * m_DiffCoeff_StefMax(i,j)); - } else if (j == i) { - m_A(i,i) = 0.0; - } - } - } - - m_flux = m_B; - - - break; - default: - printf("unimplemented\n"); - throw CanteraError("routine", "not done"); - break; - } -} - -} diff --git a/src/transport/TransportFactory.cpp b/src/transport/TransportFactory.cpp index 0d4ebaec3..875479826 100644 --- a/src/transport/TransportFactory.cpp +++ b/src/transport/TransportFactory.cpp @@ -11,7 +11,6 @@ #include "cantera/transport/DustyGasTransport.h" #include "cantera/transport/SimpleTransport.h" #include "cantera/transport/LiquidTransport.h" -#include "cantera/transport/AqueousTransport.h" #include "cantera/transport/HighPressureGasTransport.h" #include "cantera/transport/TransportFactory.h" #include "cantera/transport/SolidTransportData.h" @@ -54,7 +53,6 @@ TransportFactory::TransportFactory() m_models["CK_Multi"] = CK_Multicomponent; m_models["CK_Mix"] = CK_MixtureAveraged; m_models["Liquid"] = cLiquidTransport; - m_models["Aqueous"] = cAqueousTransport; m_models["Simple"] = cSimpleTransport; m_models["User"] = cUserTransport; m_models["HighP"] = cHighP; @@ -253,11 +251,6 @@ Transport* TransportFactory::newTransport(const std::string& transportModel, initLiquidTransport(tr, phase, log_level); tr->setThermo(*phase); break; - case cAqueousTransport: - tr = new AqueousTransport; - initLiquidTransport(tr, phase, log_level); - tr->setThermo(*phase); - break; default: throw CanteraError("newTransport","unknown transport model: " + transportModel); } diff --git a/test_problems/statmech/output_blessed.txt b/test_problems/statmech/output_blessed.txt deleted file mode 100644 index 4d973a319..000000000 --- a/test_problems/statmech/output_blessed.txt +++ /dev/null @@ -1,23 +0,0 @@ - - -************************************************ - Cantera Error! -************************************************ - - -Procedure: StatMech.cpp -Error: species properties not found!. - - - -Procedure: StatMech.cpp -Error: species properties not found!. - - - -Procedure: StatMech.cpp -Error: species properties not found!. - - - - diff --git a/test_problems/statmech/runtest_stat b/test_problems/statmech/runtest_stat deleted file mode 100755 index 48da88d0c..000000000 --- a/test_problems/statmech/runtest_stat +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# -# -temp_success="1" -/bin/rm -f output.txt outputa.txt -tname="mixGasTransport" -################################################################# -# -################################################################# -CANTERA_DATA=${CANTERA_DATA:=../../data/inputs}; export CANTERA_DATA - -CANTERA_BIN=${CANTERA_BIN:=../../bin} -./statmech_test > output.txt - -exit $? diff --git a/test_problems/statmech/statmech_test_Fe.cpp b/test_problems/statmech/statmech_test_Fe.cpp deleted file mode 100644 index b89e4b7db..000000000 --- a/test_problems/statmech/statmech_test_Fe.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * @file statmech - * test problem for statistical mechanics in cantera - */ - -// Example -// -// Test case to check error thrown if using Fe (not supported species) -// - -#include "cantera/transport.h" -#include "cantera/IdealGasMix.h" -#include "cantera/equil/equil.h" - -using namespace std; -using namespace Cantera; - -int main(int argc, char** argv) -{ - - try { - int k; - IdealGasMix g("test_stat_Fe.xml"); - int nsp = g.nSpecies(); - double pres = 1.0E5; - - vector_fp Xset(nsp, 0.0); - Xset[0] = 0.5 ; - Xset[1] = 0.5; - - g.setState_TPX(1500.0, pres, DATA_PTR(Xset)); - equilibrate(g, "TP", -1); - g.report(); - - vector_fp cp_R(nsp, 0.0); - g.getCp_R(DATA_PTR(cp_R)); - - for (int i=0; i - - - - - - - O H C N Na Cl Fe - - H Fe - - 2.165 - - - - - - - - - - - H:1 - - - - - 2.165 - - - - - Fe:1 - - - - - 2.165 - - - - - diff --git a/test_problems/statmech_properties/output_blessed.txt b/test_problems/statmech_properties/output_blessed.txt deleted file mode 100644 index 147c78b69..000000000 --- a/test_problems/statmech_properties/output_blessed.txt +++ /dev/null @@ -1,4 +0,0 @@ -2.5 -2.5 -2.5 -6.6558 diff --git a/test_problems/statmech_properties/statmech_properties.cpp b/test_problems/statmech_properties/statmech_properties.cpp deleted file mode 100644 index df863dd22..000000000 --- a/test_problems/statmech_properties/statmech_properties.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @file statmech - * test problem for statistical mechanics in cantera - */ - -// Example -// -// Test case for the statistical mechanics in cantera -// - -#include -#include -#include -#include -#include - -using namespace std; - -/*****************************************************************/ -/*****************************************************************/ - -#include "cantera/transport.h" -#include "cantera/IdealGasMix.h" -#include "cantera/equil/equil.h" - -#include "cantera/transport/TransportFactory.h" - -using namespace Cantera; - -int main(int argc, char** argv) -{ - - try { - int k; - IdealGasMix g("test_stat.xml"); - int nsp = g.nSpecies(); - double pres = 1.0E5; - - vector_fp Xset(nsp, 0.0); - Xset[0] = 0.5 ; - Xset[1] = 0.5; - - g.setState_TPX(1500.0, pres, DATA_PTR(Xset)); - equilibrate(g, "TP", -1); - - vector_fp cp_R(nsp, 0.0); - g.getCp_R(DATA_PTR(cp_R)); - - for (size_t i = 0; i < nsp; i++) { - cout << cp_R[i] << std::endl; - } - - } catch (CanteraError) { - showErrors(cout); - return 1; - } - - // Mark it zero! - return 0; - -} diff --git a/test_problems/statmech_properties/test_stat.xml b/test_problems/statmech_properties/test_stat.xml deleted file mode 100644 index 2938c4153..000000000 --- a/test_problems/statmech_properties/test_stat.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - O H C N Na - - H O N NO2 - - 2.165 - - - - - - - - - - - H:1 - - - - - 2.165 - - - - - O:1 - - - - - 2.165 - - - - - N:1 - - - - - 2.165 - - - - - O:2 N:1 - - - - - - - 2.165 - - - - - diff --git a/test_problems/statmech_test/output_blessed.txt b/test_problems/statmech_test/output_blessed.txt deleted file mode 100644 index e69de29bb..000000000 diff --git a/test_problems/statmech_test/runtest_stat b/test_problems/statmech_test/runtest_stat deleted file mode 100755 index 48da88d0c..000000000 --- a/test_problems/statmech_test/runtest_stat +++ /dev/null @@ -1,15 +0,0 @@ -#!/bin/sh -# -# -temp_success="1" -/bin/rm -f output.txt outputa.txt -tname="mixGasTransport" -################################################################# -# -################################################################# -CANTERA_DATA=${CANTERA_DATA:=../../data/inputs}; export CANTERA_DATA - -CANTERA_BIN=${CANTERA_BIN:=../../bin} -./statmech_test > output.txt - -exit $? diff --git a/test_problems/statmech_test/statmech_test.cpp b/test_problems/statmech_test/statmech_test.cpp deleted file mode 100644 index 039db7216..000000000 --- a/test_problems/statmech_test/statmech_test.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/** - * @file statmech - * test problem for statistical mechanics in cantera - */ - -// Example -// -// Test case for the statistical mechanics in cantera -// - -#include "cantera/transport.h" -#include "cantera/IdealGasMix.h" -#include "cantera/equil/equil.h" - -using namespace std; -using namespace Cantera; - -int main(int argc, char** argv) -{ - - try { - int k; - IdealGasMix g("test_stat.xml"); - int nsp = g.nSpecies(); - double pres = 1.0E5; - - vector_fp Xset(nsp, 0.0); - Xset[0] = 0.5 ; - Xset[1] = 0.5; - - g.setState_TPX(1500.0, pres, DATA_PTR(Xset)); - equilibrate(g, "TP", -1); - - vector_fp cp_R(nsp, 0.0); - g.getCp_R(DATA_PTR(cp_R)); - - //for(int i=0;i= tol) { - double diff = cp_R[3]-sol; - std::cout << "Error for Species NO2!\n"; - std::cout << "Diff was: " << diff << "\n"; - return 1; - } - - } catch (CanteraError) { - showErrors(cout); - return 1; - } - - // Mark it zero! - return 0; - -} diff --git a/test_problems/statmech_test/test_stat.xml b/test_problems/statmech_test/test_stat.xml deleted file mode 100644 index 2938c4153..000000000 --- a/test_problems/statmech_test/test_stat.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - O H C N Na - - H O N NO2 - - 2.165 - - - - - - - - - - - H:1 - - - - - 2.165 - - - - - O:1 - - - - - 2.165 - - - - - N:1 - - - - - 2.165 - - - - - O:2 N:1 - - - - - - - 2.165 - - - - - diff --git a/test_problems/statmech_test_poly/output_blessed.txt b/test_problems/statmech_test_poly/output_blessed.txt deleted file mode 100644 index 1fc388107..000000000 --- a/test_problems/statmech_test_poly/output_blessed.txt +++ /dev/null @@ -1,11 +0,0 @@ - - -************************************************ - Cantera Error! -************************************************ - - -Procedure: installStatMechThermoFromXML -Error: Expected no coeff: this is not a polynomial representation - - diff --git a/test_problems/statmech_test_poly/statmech_test_poly.cpp b/test_problems/statmech_test_poly/statmech_test_poly.cpp deleted file mode 100644 index 640613c78..000000000 --- a/test_problems/statmech_test_poly/statmech_test_poly.cpp +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @file statmech - * test problem for statistical mechanics in cantera - */ - -// Example -// -// Test case for the statistical mechanics in cantera -// - -#include "cantera/transport.h" -#include "cantera/IdealGasMix.h" -#include "cantera/equil/equil.h" - -using namespace std; -using namespace Cantera; - -int main(int argc, char** argv) -{ - - try { - int k; - IdealGasMix g("test_stat_err.xml"); - int nsp = g.nSpecies(); - double pres = 1.0E5; - - vector_fp Xset(nsp, 0.0); - Xset[0] = 0.5 ; - Xset[1] = 0.5; - - g.setState_TPX(1500.0, pres, DATA_PTR(Xset)); - equilibrate(g, "TP", -1); - - vector_fp cp_R(nsp, 0.0); - g.getCp_R(DATA_PTR(cp_R)); - - } catch (CanteraError) { - // we wanted to catch an error here for incorrectly trying to use poly methods - // for the statmech species data, so exit successfully - showErrors(cout); - - // Mark it zero! - return 0; - } - - cout << "ERROR" << std::endl; - // something is wrong: we were suppose to catch an error here: paradox! - return 1; - -} diff --git a/test_problems/statmech_test_poly/test_stat_err.xml b/test_problems/statmech_test_poly/test_stat_err.xml deleted file mode 100644 index 5af385f26..000000000 --- a/test_problems/statmech_test_poly/test_stat_err.xml +++ /dev/null @@ -1,47 +0,0 @@ - - - - - - - - - O H C N Na Cl - - H O - - 2.165 - - - - - - - - - - - H:1 - - - - - 2.165 - - - - - O:1 - - - - 2.344331120E+00, 7.980520750E-03, -1.947815100E-05, 2.015720940E-08, - -7.376117610E-12, -9.179351730E+02, 6.830102380E-01 - - - 2.165 - - - - -