Skip to content

Setting density to invalid values does not return correct error message in language interfaces using Clib #1412

@ssun30

Description

@ssun30

Problem description

Setting density to a negative value in a language interface using Clib does not return the correct error message. Instead, it returns the latest Cantera error thrown by other methods.

Steps to reproduce

  1. In the Matlab interface for Cantera, comment the first three lines in setTemperature.m and setDensity.m so error messages are handled by Cantera not Matlab:
% if (t <= 0)
%     error('The temperature must be positive.');
% end
  1. Using the Matlab interface for Cantera, run the following commands in Matlab command window:
a = Air
setTemperature(a, -100)
setDensity(a, -1)

Behavior

Matlab will report two errors, first for setting an invalid temperautre:

setTemperature(a, -100)
Error using ctmethods

*******************************************************************************
CanteraError thrown by Phase::setTemperature:
temperature must be positive. T = -100
*******************************************************************************

But the second error is the same message instead of setting invalid density:

setDensity(a, -1)
Error using ctmethods

*******************************************************************************
CanteraError thrown by Phase::setTemperature:
temperature must be positive. T = -100
*******************************************************************************

System information

  • Cantera version: 2.6.0
  • OS: Ubuntu 22.04 LTS
  • Python/MATLAB/other software versions: MATLAB R2022b

Additional context

The bug is attributed to the function thermo_setDensity in clib/ct.cpp.

int thermo_setDensity(int n, double rho)
{
    if (rho < 0.0) {
        return -1;
    }
    try {
        ThermoCabinet::item(n).setDensity(rho);
    } catch (...) {
        return handleAllExceptions(-1, ERR);
    }
    return 0;
}

The check for negative density at beginning is redundant since Phase::setDensity already does that:

void Phase::setDensity(const double density_)
{
    assertCompressible("setDensity");
    if (density_ > 0.0) {
        m_dens = density_;
    } else {
        throw CanteraError("Phase::setDensity",
            "density must be positive. density = {}", density_);
    }
}

The same issue is present in thermo_setMolarDensity. After removing the negative density check, the issue is resolved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions