Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent errors due to unsafe math optimizations #1161

Merged
merged 6 commits into from
Dec 22, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,8 @@ jobs:
run: |
scons build extra_inc_dirs=$CONDA_PREFIX/include:$CONDA_PREFIX/include/eigen3 \
extra_lib_dirs=$CONDA_PREFIX/lib system_fmt=y system_eigen=y system_yamlcpp=y \
system_sundials=y blas_lapack_libs='lapack,blas' -j2 VERBOSE=True debug=n
system_sundials=y blas_lapack_libs='lapack,blas' -j2 VERBOSE=True debug=n \
optimize_flags='-O3 -ffast-math -fno-finite-math-only'
- name: Test Cantera
run: scons test show_long_tests=yes verbose_tests=yes

Expand Down
14 changes: 12 additions & 2 deletions SConstruct
Original file line number Diff line number Diff line change
Expand Up @@ -960,8 +960,6 @@ int main(int argc, char** argv) {
context.Result(result)
return result

conf = Configure(env, custom_tests={'CheckStatement': CheckStatement})

# Set up compiler options before running configuration tests
env['CXXFLAGS'] = listify(env['cxx_flags'])
env['CCFLAGS'] = listify(env['cc_flags']) + listify(env['thread_flags'])
Expand Down Expand Up @@ -1007,6 +1005,8 @@ def config_error(message):
print("See 'config.log' for details.")
sys.exit(1)

conf = Configure(env, custom_tests={'CheckStatement': CheckStatement})

# First, a sanity check:
if not conf.CheckCXXHeader('cmath', '<>'):
config_error('The C++ compiler is not correctly configured.')
Expand All @@ -1027,6 +1027,16 @@ def get_expression_value(includes, expression, defines=()):
'}\n'))
return '\n'.join(s)

# Check that NaN is treated correctly
nan_check_source = get_expression_value(["<cmath>"], 'std::isnan(NAN + argc)')
retcode, nan_works = conf.TryRun(nan_check_source, ".cpp")
if nan_works.strip() != "1":
config_error(
"Cantera requires a working implementation of 'std::isnan'.\n"
"If you have specified '-ffast-math' or equivalent as an optimization option,\n"
"either remove this option or add the '-fno-finite-math-only option'."
)

# Check for fmt library and checkout submodule if needed
# Test for 'ostream.h' to ensure that version >= 3.0.0 is available
if env['system_fmt'] in ('y', 'default'):
Expand Down
5 changes: 2 additions & 3 deletions interfaces/cython/cantera/test/test_kinetics.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,7 @@ def test_surface(self):
r2.rate.pre_exponential_factor)
self.assertEqual(r1.rate.temperature_exponent,
r2.rate.temperature_exponent)
self.assertEqual(r1.rate.activation_energy,
r2.rate.activation_energy)
self.assertNear(r1.rate.activation_energy, r2.rate.activation_energy)

self.assertArrayNear(surf1.delta_enthalpy,
surf2.delta_enthalpy)
Expand Down Expand Up @@ -1342,7 +1341,7 @@ def test_Blowers_Masel_change_enthalpy(self):
species.thermo = ct.NasaPoly2(species.thermo.min_temp, species.thermo.max_temp,
species.thermo.reference_pressure, perturbed_coeffs)
gas.modify_species(index, species)
self.assertEqual(deltaH_high, gas.reaction(0).rate.activation_energy(deltaH_high))
self.assertNear(deltaH_high, gas.reaction(0).rate.activation_energy(deltaH_high))
self.assertNear(A*gas.T**b*np.exp(-deltaH_high/ct.gas_constant/gas.T), gas.forward_rate_constants[0])

perturbed_coeffs = species.thermo.coeffs.copy()
Expand Down
6 changes: 3 additions & 3 deletions interfaces/cython/cantera/test/test_reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ def test_from_parts(self):
rate = self.from_parts()
self.assertEqual(self._parts["A"], rate.pre_exponential_factor)
self.assertEqual(self._parts["b"], rate.temperature_exponent)
self.assertEqual(self._parts["Ea"], rate.activation_energy)
self.assertNear(self._parts["Ea"], rate.activation_energy)
self.check_rate(rate)

def test_negative_A(self):
Expand Down Expand Up @@ -273,8 +273,8 @@ def test_from_parts(self):
rate = self.from_parts()
self.assertEqual(self._parts["A"], rate.pre_exponential_factor)
self.assertEqual(self._parts["b"], rate.temperature_exponent)
self.assertEqual(self._parts["Ea0"], rate.intrinsic_activation_energy)
self.assertEqual(self._parts["w"], rate.bond_energy)
self.assertNear(self._parts["Ea0"], rate.intrinsic_activation_energy)
self.assertNear(self._parts["w"], rate.bond_energy)
self.check_rate(rate)

def test_negative_A(self):
Expand Down
20 changes: 3 additions & 17 deletions src/equil/vcs_solve_TP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1943,20 +1943,8 @@ bool VCS_SOLVE::vcs_globStepDamp()
plogf(" --- subroutine FORCE: End Slope = %g\n", s2);
}

if (s1 > 0.0) {
if (m_debug_print_lvl >= 2) {
plogf(" --- subroutine FORCE produced no adjustments,");
if (s1 < 1.0E-40) {
plogf(" s1 positive but really small\n");
} else {
plogf(" failed s1 test\n");
}
}
return false;
}

if (s2 <= 0.0) {
debuglog(" --- subroutine FORCE produced no adjustments, s2 < 0\n", m_debug_print_lvl >= 2);
if (s1 > 0.0 || s2 <= 0.0) {
debuglog(" --- subroutine FORCE produced no adjustments\n", m_debug_print_lvl >= 2);
return false;
}

Expand All @@ -1966,9 +1954,7 @@ bool VCS_SOLVE::vcs_globStepDamp()
al = s1 / (s1 - s2);
}
if (al >= 0.95 || al < 0.0) {
if (m_debug_print_lvl >= 2) {
plogf(" --- subroutine FORCE produced no adjustments (al = %g)\n", al);
}
debuglog(" --- subroutine FORCE produced no adjustments\n", m_debug_print_lvl >= 2);
return false;
}
if (m_debug_print_lvl >= 2) {
Expand Down
8 changes: 4 additions & 4 deletions test/kinetics/kineticsFromYaml.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -494,10 +494,10 @@ class ReactionToYaml : public testing::Test
kin->getRevRateConstants(kr.data());
kin->getFwdRatesOfProgress(ropf.data());
kin->getRevRatesOfProgress(ropr.data());
EXPECT_DOUBLE_EQ(kf[iOld], kf[iNew]);
EXPECT_DOUBLE_EQ(kr[iOld], kr[iNew]);
EXPECT_DOUBLE_EQ(ropf[iOld], ropf[iNew]);
EXPECT_DOUBLE_EQ(ropr[iOld], ropr[iNew]);
EXPECT_NEAR(kf[iOld], kf[iNew], 1e-13 * kf[iOld]);
EXPECT_NEAR(kr[iOld], kr[iNew], 1e-13 * kr[iOld]);
EXPECT_NEAR(ropf[iOld], ropf[iNew], 1e-13 * ropf[iOld]);
EXPECT_NEAR(ropr[iOld], ropr[iNew], 1e-13 * ropr[iOld]);
}

shared_ptr<Solution> soln;
Expand Down
6 changes: 3 additions & 3 deletions test/thermo/PengRobinson_Test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -186,13 +186,13 @@ TEST_F(PengRobinson_Test, setTP)
const double temp = 294 + i*2;
set_r(0.999);
test_phase->setState_TP(temp, 5542027.5);
EXPECT_NEAR(test_phase->density(),rho1[i],1.e-8);
EXPECT_NEAR(test_phase->density(), rho1[i], 1.e-8);

test_phase->setState_TP(temp, 7388370.);
EXPECT_NEAR(test_phase->density(),rho2[i],1.e-8);
EXPECT_NEAR(test_phase->density(), rho2[i], 1.e-7);

test_phase->setState_TP(temp, 9236712.5);
EXPECT_NEAR(test_phase->density(),rho3[i],1.e-8);
EXPECT_NEAR(test_phase->density(), rho3[i], 1.e-8);
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/thermo/water_iapws.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,6 @@ TEST_F(WaterPropsIAPWS_Test, expansion_coeffs)
EXPECT_NEAR(water.coeffThermExp(), alpha[i], 2e-14);
EXPECT_NEAR(water.coeffPresExp(), beta[i], beta[i] * 2e-12);
EXPECT_NEAR(dPdT(TT[i], PP[i]) * 18.015268 / (8.314371E3 * rho),
beta_num[i], 2e-10 * beta_num[i]);
beta_num[i], 4e-10 * beta_num[i]);
}
}
2 changes: 1 addition & 1 deletion test_problems/SConscript
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ Test('cxx-flamespeed', 'cxx_samples', '#build/samples/cxx/flamespeed/flamespeed'
options='0.9 0 0')
Test('cxx-kinetics1', 'cxx_samples', '#build/samples/cxx/kinetics1/kinetics1', None,
comparisons=[('kin1_blessed.csv', 'kin1.csv')],
artifacts=['kin1.dat'], slow=True)
artifacts=['kin1.dat'], slow=True, tolerance=2e-4)
Test('cxx-gas-transport', 'cxx_samples',
'#build/samples/cxx/gas_transport/gas_transport', None, slow=True,
comparisons=[('transport_mix_blessed.csv', 'transport_mix.csv'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ VCS CALCULATION METHOD
--- Total tentative Dimensionless Gibbs Free Energy = -4.1206752525561E+03
--- subroutine FORCE: Beginning Slope = -0.109397
--- subroutine FORCE: End Slope = -0.0989949
--- subroutine FORCE produced no adjustments, s2 < 0
--- subroutine FORCE produced no adjustments
-------------------------------------------------------------------------------------------------------
--- Summary of the Update (all species):
--- Species Status Initial_KMoles Final_KMoles Initial_Mu/RT Mu/RT Init_Del_G/RT Delta_G/RT
Expand Down Expand Up @@ -285,7 +285,7 @@ VCS CALCULATION METHOD
--- Total tentative Dimensionless Gibbs Free Energy = -4.1206857517346E+03
--- subroutine FORCE: Beginning Slope = -0.0109994
--- subroutine FORCE: End Slope = 5.0022e-07
--- subroutine FORCE produced no adjustments (al = 0.999955)
--- subroutine FORCE produced no adjustments
-------------------------------------------------------------------------------------------------------
--- Summary of the Update (all species):
--- Species Status Initial_KMoles Final_KMoles Initial_Mu/RT Mu/RT Init_Del_G/RT Delta_G/RT
Expand Down Expand Up @@ -342,7 +342,7 @@ VCS CALCULATION METHOD
--- Total tentative Dimensionless Gibbs Free Energy = -4.1206857517346E+03
--- subroutine FORCE: Beginning Slope = -1.39826e-19
--- subroutine FORCE: End Slope = 9.31017e-32
--- subroutine FORCE produced no adjustments, s2 < 0
--- subroutine FORCE produced no adjustments
-------------------------------------------------------------------------------------------------------
--- Summary of the Update (all species):
--- Species Status Initial_KMoles Final_KMoles Initial_Mu/RT Mu/RT Init_Del_G/RT Delta_G/RT
Expand Down