simplify kwargs logic for equations

This commit is contained in:
Dario Coscia
2025-09-04 14:55:37 +02:00
committed by Giovanni Canali
parent 684d691b78
commit 7469543499
2 changed files with 18 additions and 12 deletions

View File

@@ -1,5 +1,7 @@
"""Module for the Equation.""" """Module for the Equation."""
import inspect
from .equation_interface import EquationInterface from .equation_interface import EquationInterface
@@ -25,6 +27,9 @@ class Equation(EquationInterface):
"Expected a callable function, got " "Expected a callable function, got "
f"{equation}" f"{equation}"
) )
# compute the signature
sig = inspect.signature(equation)
self.__len_sig = len(sig.parameters)
self.__equation = equation self.__equation = equation
def residual(self, input_, output_, params_=None): def residual(self, input_, output_, params_=None):
@@ -41,9 +46,14 @@ class Equation(EquationInterface):
parameters must be initialized to ``None``. Default is ``None``. parameters must be initialized to ``None``. Default is ``None``.
:return: The computed residual of the equation. :return: The computed residual of the equation.
:rtype: LabelTensor :rtype: LabelTensor
:raises RuntimeError: If the underlying equation signature length is not
2 (direct problem) or 3 (inverse problem).
""" """
if params_ is None: if self.__len_sig == 2:
result = self.__equation(input_, output_) return self.__equation(input_, output_)
else: if self.__len_sig == 3:
result = self.__equation(input_, output_, params_) return self.__equation(input_, output_, params_)
return result raise RuntimeError(
f"Unexpected number of arguments in equation: {self.__len_sig}. "
"Expected either 2 (direct problem) or 3 (inverse problem)."
)

View File

@@ -190,13 +190,9 @@ class PINNInterface(SupervisedSolverInterface, metaclass=ABCMeta):
:return: The residual of the solution of the model. :return: The residual of the solution of the model.
:rtype: LabelTensor :rtype: LabelTensor
""" """
try: residual = equation.residual(
residual = equation.residual(samples, self.forward(samples)) samples, self.forward(samples), self._params
except TypeError: )
# this occurs when the function has three inputs (inverse problem)
residual = equation.residual(
samples, self.forward(samples), self._params
)
return residual return residual
def _residual_loss(self, samples, equation): def _residual_loss(self, samples, equation):