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

Some CLib/sourcegen/dotnet updates #1773

Merged
merged 15 commits into from
Aug 18, 2024
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
17 changes: 5 additions & 12 deletions include/cantera/clib/ct.h
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,9 @@ extern "C" {
CANTERA_CAPI int soln_adjacent(int n, int a);
CANTERA_CAPI int soln_adjacentName(int n, int a, int lennm, char* nm);

CANTERA_CAPI int thermo_newFromFile(const char* filename, const char* phasename); //!< @todo remove from .NET and Fortran interfaces
CANTERA_CAPI int thermo_parent(int n);
CANTERA_CAPI int thermo_size();
CANTERA_CAPI int thermo_del(int n);
CANTERA_CAPI int thermo_del(int n); //!< no-op; object is managed by Solution
CANTERA_CAPI size_t thermo_nElements(int n);
CANTERA_CAPI size_t thermo_nSpecies(int n);
CANTERA_CAPI double thermo_temperature(int n);
Expand Down Expand Up @@ -119,7 +118,7 @@ extern "C" {
CANTERA_CAPI int thermo_set_VH(int n, double* vals);
CANTERA_CAPI int thermo_set_TH(int n, double* vals);
CANTERA_CAPI int thermo_set_SH(int n, double* vals);
CANTERA_CAPI int thermo_equilibrate(int n, const char* XY, int solver,
CANTERA_CAPI int thermo_equilibrate(int n, const char* XY, const char* solver,
double rtol, int maxsteps, int maxiter,
int loglevel);

Expand All @@ -132,12 +131,8 @@ extern "C" {
CANTERA_CAPI int thermo_setState_Psat(int n, double p, double x);
CANTERA_CAPI int thermo_setState_Tsat(int n, double t, double x);

//! @since Starting in %Cantera 3.0, the "phasename" argument should be blank
CANTERA_CAPI int kin_newFromFile(const char* filename, const char* phasename,
int reactingPhase, int neighbor1, int neighbor2,
int neighbor3, int neighbor4); //!< @todo remove from .NET and Fortran interfaces
CANTERA_CAPI int kin_parent(int n);
CANTERA_CAPI int kin_del(int n);
CANTERA_CAPI int kin_del(int n); //!< no-op; object is managed by Solution
CANTERA_CAPI size_t kin_nSpecies(int n);
CANTERA_CAPI size_t kin_nReactions(int n);
CANTERA_CAPI size_t kin_nPhases(int n);
Expand Down Expand Up @@ -165,14 +160,12 @@ extern "C" {
CANTERA_CAPI int kin_isReversible(int n, int i);
CANTERA_CAPI int kin_getType(int n, size_t len, char* name);
CANTERA_CAPI size_t kin_start(int n, int p);
CANTERA_CAPI size_t kin_speciesIndex(int n, const char* nm, const char* ph);
CANTERA_CAPI size_t kin_speciesIndex(int n, const char* nm);
CANTERA_CAPI int kin_advanceCoverages(int n, double tstep);
CANTERA_CAPI size_t kin_phase(int n, size_t i);

CANTERA_CAPI int trans_newDefault(int th, int loglevel); //!< @todo remove from .NET and Fortran interfaces
CANTERA_CAPI int trans_new(const char* model, int th, int loglevel); //!< @todo remove from .NET and Fortran interfaces
CANTERA_CAPI int trans_parent(int n);
CANTERA_CAPI int trans_del(int n);
CANTERA_CAPI int trans_del(int n); //!< no-op; object is managed by Solution
CANTERA_CAPI int trans_transportModel(int n, int lennm, char* nm);
CANTERA_CAPI double trans_viscosity(int n);
CANTERA_CAPI double trans_electricalConductivity(int n);
Expand Down
21 changes: 0 additions & 21 deletions include/cantera/clib/ctonedim.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,8 @@ extern "C" {
CANTERA_CAPI double bdry_massFraction(int i, int k);
CANTERA_CAPI double bdry_mdot(int i);

CANTERA_CAPI int reactingsurf_setkineticsmgr(int i, int j);
CANTERA_CAPI int reactingsurf_enableCoverageEqs(int i, int onoff);

CANTERA_CAPI int inlet_new();
CANTERA_CAPI int outlet_new();
CANTERA_CAPI int outletres_new();
CANTERA_CAPI int symm_new();
CANTERA_CAPI int surf_new();
CANTERA_CAPI int reactingsurf_new();

CANTERA_CAPI int inlet_setSpreadRate(int i, double v);

CANTERA_CAPI int flow1D_new(int iph, int ikin, int itr, int itype);
CANTERA_CAPI int flow1D_setTransport(int i, int itr);
CANTERA_CAPI int flow1D_enableSoret(int i, int iSoret);
CANTERA_CAPI int flow1D_setPressure(int i, double p);
Expand All @@ -70,16 +59,6 @@ extern "C" {
size_t m, const double* temp);
CANTERA_CAPI int flow1D_solveEnergyEqn(int i, int flag);

//! @todo: Remove all functions with `stflow` prefix after %Cantera 3.1
CANTERA_CAPI int stflow_new(int iph, int ikin, int itr, int itype);
CANTERA_CAPI int stflow_setTransport(int i, int itr);
CANTERA_CAPI int stflow_enableSoret(int i, int iSoret);
CANTERA_CAPI int stflow_setPressure(int i, double p);
CANTERA_CAPI double stflow_pressure(int i);
CANTERA_CAPI int stflow_setFixedTempProfile(int i, size_t n, const double* pos,
size_t m, const double* temp);
CANTERA_CAPI int stflow_solveEnergyEqn(int i, int flag);

CANTERA_CAPI int sim1D_new(size_t nd, const int* domains);
CANTERA_CAPI int sim1D_del(int i);
CANTERA_CAPI int sim1D_setValue(int i, int dom, int comp, int localPoint, double value);
Expand Down
7 changes: 2 additions & 5 deletions include/cantera/clib/ctreactor.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,11 @@
extern "C" {
#endif

CANTERA_CAPI int reactor_new(const char* type); //!< @deprecated: remove after 3.1
CANTERA_CAPI int reactor_new3(const char* type, int n, const char* name);
CANTERA_CAPI int reactor_new(const char* type, int n, const char* name);
CANTERA_CAPI int reactor_del(int i);
CANTERA_CAPI int reactor_setInitialVolume(int i, double v);
CANTERA_CAPI int reactor_setChemistry(int i, int cflag);
CANTERA_CAPI int reactor_setEnergy(int i, int eflag);
CANTERA_CAPI int reactor_setThermoMgr(int i, int n); //!< @deprecated: remove after 3.1
CANTERA_CAPI int reactor_setKineticsMgr(int i, int n); //!< @deprecated: remove after 3.1
CANTERA_CAPI int reactor_insert(int i, int n);
CANTERA_CAPI double reactor_mass(int i);
CANTERA_CAPI double reactor_volume(int i);
Expand All @@ -36,7 +33,7 @@ extern "C" {
CANTERA_CAPI double reactor_massFraction(int i, int k);
CANTERA_CAPI size_t reactor_nSensParams(int i);
CANTERA_CAPI int reactor_addSensitivityReaction(int i, int rxn);
CANTERA_CAPI int flowReactor_setMassFlowRate(int i, double mdot);
CANTERA_CAPI int reactor_setMassFlowRate(int i, double mdot);

CANTERA_CAPI int reactornet_new();
CANTERA_CAPI int reactornet_del(int i);
Expand Down
1 change: 1 addition & 0 deletions include/cantera/oneD/Flow1D.h
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ class Flow1D : public Domain1D
//! @name Governing Equations
//! Methods called by eval() to calculate residuals for individual governing
//! equations.
//! @{

/**
* Evaluate the continuity equation residual.
Expand Down
2 changes: 1 addition & 1 deletion include/cantera/thermo/PlasmaPhase.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ namespace Cantera
* changed or removed without notice.
* @todo Implement electron Boltzmann equation solver to solve EEDF.
* https://github.com/Cantera/enhancements/issues/127
* @ingroup phase
* @ingroup thermoprops
*/
class PlasmaPhase: public IdealGasPhase
{
Expand Down
4 changes: 0 additions & 4 deletions interfaces/dotnet/Cantera.Tests/src/EnumsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ public void ThermoPair_ToStringsCorrectly()
}
}

[Fact]
public void EquilibriumSolver_MapsCorrectly() =>
TestInteropEnumInvariants<EquilibriumSolver>(true, -1, 2);

[Fact]
public void LogLevel_MapsCorrectly() =>
TestInteropEnumInvariants<LogLevel>(true, 0, 2);
Expand Down
2 changes: 1 addition & 1 deletion interfaces/dotnet/Cantera.Tests/src/ExceptionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class FooException : Exception { }
[Fact]
public void CanteraException_Thrown()
{
var handle = LibCantera.thermo_newFromFile(".yaml", "");
var handle = LibCantera.soln_newSolution(".yaml", "", "");

Assert.True(handle.IsInvalid);

Expand Down
28 changes: 1 addition & 27 deletions interfaces/dotnet/Cantera/src/Enums.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,33 +101,7 @@ public static string ToInteropString(this ThermoPair thermoPair)
}
}

// the constants MUST match what CLIB is expecting

/// <summary>
/// Determines which algorithm is used to find equilibrium.
/// </summary>
public enum EquilibriumSolver
{
/// <summary>
/// Allow Cantera to determine the optimum algorithm.
/// </summary>
Auto = -1,

/// <summary>
/// Solve by using the element potential algorithm.
/// </summary>
ElementPotential,

/// <summary>
/// Solve by using the general algorithm to minimize Gibbs free energy.
/// </summary>
Gibbs,

/// <summary>
/// Solved by using the VCS algorithm to minimize Gibbs free energy.
/// </summary>
Vcs
}
// the constants MUST match what CLib is expecting

/// <summary>
/// The
Expand Down
15 changes: 9 additions & 6 deletions interfaces/dotnet/Cantera/src/ThermoPhase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@
/// </summary>
public partial class ThermoPhase
{
readonly SolutionHandle _sol;

/// <summary>
/// Represents a func that sets a pair of thermo variables using a pointer
/// to a pair of doubles to stand in for a stack-allocated array with two elements.
/// </summary>
unsafe delegate int SetPairFunc(ThermoPhaseHandle n, (double, double)* values);

/// <summary>
/// Using reflection and the fact that CLIB follows a naming convention for
/// Using reflection and the fact that CLib follows a naming convention for
/// the functions that set the pairs of thermodynamic variables simultaneously
/// </summary>
static readonly Lazy<Dictionary<ThermoPair, SetPairFunc>> s_pairSetters;
Expand Down Expand Up @@ -53,25 +55,26 @@

internal ThermoPhase(string filename, string? phaseName)
{
_handle = LibCantera.thermo_newFromFile(filename, phaseName ?? "");
_sol = LibCantera.soln_newSolution(filename, phaseName ?? "", "none");
_handle = LibCantera.soln_thermo(_sol);
_handle.EnsureValid();

_species = new(() => new SpeciesCollection(_handle));
}

/// <summary>
/// Simulates bringing the phase to thermodynamic equilibrium by holding the
/// specified <see cref="ThermoPair" /> constant and using the algorithm
/// identified by the given <see cref="EquilibriumSolver" />.
/// specified <see cref="ThermoPair" /> constant and using the algorithm(s)
/// identified by the solver string.
/// </summary>
public void Equilibrate(ThermoPair thermoPair,
EquilibriumSolver solver = EquilibriumSolver.Auto,
string solver = "auto",
double tolerance = 1e-9, int maxSteps = 1000,
int maxIterations = 100, int logVerbosity = 0)
{
var interopString = thermoPair.ToInteropString();

var retVal = LibCantera.thermo_equilibrate(_handle, interopString, (int) solver,
var retVal = LibCantera.thermo_equilibrate(_handle, interopString, solver,

Check warning on line 77 in interfaces/dotnet/Cantera/src/ThermoPhase.cs

View check run for this annotation

Codecov / codecov/patch

interfaces/dotnet/Cantera/src/ThermoPhase.cs#L77

Added line #L77 was not covered by tests
tolerance, maxSteps, maxIterations, logVerbosity);

InteropUtil.CheckReturn(retVal);
Expand Down
21 changes: 15 additions & 6 deletions interfaces/dotnet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,21 @@
This directory and its children contain the interface to Cantera for .NET languages
such as C# and F#. It is written in C# and supports .NET Standard 2.0
(for the primary project) and .NET 6 (and newer) on all platforms that support both
.NET and the Cantera C++ library.
.NET and the Cantera C++ library. The .NET interface requires an installation of the
.NET 6.0 SDK.

## Project Layout

The primary C# project is Cantera.csproj. This project uses P/Invoke extensively with
The primary C# project is `Cantera.csproj`. This project uses P/Invoke extensively with
the native Cantera library via the Cantera C interface (CLib), and wraps the low-level
interfaces with classes and concepts familiar to a .NET developer. As part of the build
process, it invokes [sourcegen](/interfaces/sourcegen)
to scaffold the interop code and some of the code for the wrapper objects, such as
simple properties which can mapped directly to CLib getter and setter functions.
Cantera.csproj targets .NET Standard 2.0 and .NET 6. This project will be released as
`Cantera.csproj` targets .NET Standard 2.0 and .NET 6. This project will be released as
a NuGet package.

Cantera.Tests.csproj contains the unit tests for the Cantera .NET library and targets
`Cantera.Tests.csproj` contains the unit tests for the Cantera .NET library and targets
.Net 6.

The examples directory contains separate projects for each Cantera example. These will
Expand All @@ -39,10 +40,18 @@ C# development installed. Visual Studio is _not_ required, and although contribu
may choose to use it, submissions should not depend on Visual Studio or require
the use of Windows.

### Running Tests
### Building the .NET Interface.

After [building the main Cantera library](https://cantera.org/install/compiling-install.html),
switch to this directory and run `dotnet test`.
switch to this directory and run `dotnet build`.

In order to force re-import of generated code from sourcegen, a manual deletion of
`obj` and `bin` folders in `Cantera`, `Cantera.Tests`, `examples/Applications` and
`examples/Soundspeed` may be necessary.

### Running Tests

After building the .NET interface, run `dotnet test`.

### Running Examples

Expand Down
11 changes: 3 additions & 8 deletions interfaces/matlab_experimental/Base/Kinetics.m
Original file line number Diff line number Diff line change
Expand Up @@ -107,22 +107,17 @@

%% Get scalar attributes

function n = kineticsSpeciesIndex(kin, name, phase)
function n = kineticsSpeciesIndex(kin, name)
% Get the species index of a species of a phase in the Kinetics class. ::
%
% >> n = kin.kineticsSpeciesIndex(name, phase)
% >> n = kin.kineticsSpeciesIndex(name)
%
% :param name:
% String name or integer index of the species.
% :param phase:
% String name or integer index of the phase.
% :return:
% Index of the species.

if nargin == 2
phase = '';
end
n = ctFunc('kin_speciesIndex', kin.kinID, name, phase) + 1;
n = ctFunc('kin_speciesIndex', kin.kinID, name) + 1;
end

function n = multiplier(kin, irxn)
Expand Down
13 changes: 6 additions & 7 deletions interfaces/matlab_experimental/Base/ThermoPhase.m
Original file line number Diff line number Diff line change
Expand Up @@ -451,11 +451,10 @@ function display(tp)
% Not all of the properties to be held constant are available with
% all of the solvers.
% :param solver:
% Specifies the equilibrium solver to use. If solver = 0, a fast
% solver using the element potential method will be used. If
% solver = 1, a slower but more robust Gibbs minimization solver
% will be used. If solver >= 2, a version of the VCS algorithm will
% be used. If solver < 0 or is unspecified, the fast solver
% Specifies the equilibrium solver to use. Choices are
% 'element_potential' (fast solver using the element potential method),
% 'gibbs' (slower but more robust Gibbs minimization solver), 'vcs'
% (VCS algorithm). For the default 'auto' setting, the fast solver
ischoegl marked this conversation as resolved.
Show resolved Hide resolved
% will be tried first, then if it fails the Gibbs minimization solver
% will be tried.
% :param rtol:
Expand All @@ -472,7 +471,7 @@ function display(tp)
% generate more detailed information.

if nargin < 3
solver = -1;
solver = 'auto';
end

if nargin < 4
Expand All @@ -492,7 +491,7 @@ function display(tp)
end

ctFunc('thermo_equilibrate', tp.tpID, xy, solver, rtol, ...
maxsteps, maxiter, loglevel);
maxsteps, maxiter, loglevel);
end

%% ThermoPhase inquiry methods
Expand Down
2 changes: 0 additions & 2 deletions interfaces/matlab_experimental/OneDim/ReactingSurface.m
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@
end

s@Boundary1D('reacting-surface', surface_mech, id);

ctFunc('reactingsurf_setkineticsmgr', s.domainID, surface_mech.kinID);
s.coverageEnabled = false;
end

Expand Down
4 changes: 1 addition & 3 deletions interfaces/matlab_experimental/Reactor/Reactor.m
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,7 @@
end

r.type = char(typ);
r.id = ctFunc('reactor_new3', typ, content.solnID, name);


r.id = ctFunc('reactor_new', typ, content.solnID, name);
end

%% Reactor Class Destructor
Expand Down
2 changes: 1 addition & 1 deletion interfaces/matlab_experimental/readme.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Experimental MATLAB Toolbox for Cantera
This experimental Matlab Toolbox for Cantera changes the Matlab interface to the modern
Matlab structure and syntaxes for OOP. It replaces the MEX interface with direct
function calling from Cantera Clib.
function calling from Cantera CLib.

## Installation guide:

Expand Down
7 changes: 6 additions & 1 deletion interfaces/sourcegen/sourcegen/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ def with_unpack_iter(cls: type) -> type:
return cls


def hanging_text(text: str, spaces: int) -> str:
ret = ("\n" + " "*spaces).join(text.split("\n"))
return "\n".join([line.rstrip() for line in ret.split("\n")])


def normalize_indent(code: str) -> str:
code = textwrap.dedent(code).strip()

Expand All @@ -32,4 +37,4 @@ def normalize_indent(code: str) -> str:


def get_preamble() -> str:
return Path(__file__).parent.joinpath("preamble.txt").read_text()
return Path(__file__).parent.joinpath("preamble.txt").read_text("utf-8").strip()
Loading
Loading