Simulai residuals

simulai.residuals#

Bases: Module

The SymbolicOperatorClass is a class that constructs tensor operators using symbolic expressions written in PyTorch.

Returns:

Name Type Description
object

An instance of the SymbolicOperatorClass.

Source code in simulai/residuals/_pytorch_residuals.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
class SymbolicOperator(torch.nn.Module):
    """The SymbolicOperatorClass is a class that constructs tensor operators using symbolic expressions written in PyTorch.


    Returns:
        object: An instance of the SymbolicOperatorClass.
    """

    def __init__(
        self,
        expressions: List[Union[sympy.Expr, str]] = None,
        input_vars: List[Union[sympy.Symbol, str]] = None,
        output_vars: List[Union[sympy.Symbol, str]] = None,
        function: callable = None,
        gradient: callable = None,
        keys: str = None,
        inputs_key=None,
        constants: dict = None,
        trainable_parameters: dict = None,
        external_functions: dict = dict(),
        processing: str = "serial",
        device: str = "cpu",
        engine: str = "torch",
        auxiliary_expressions: list = None,
    ) -> None:
        if engine == "torch":
            super(SymbolicOperator, self).__init__()
        else:
            pass

        self.engine = importlib.import_module(engine)

        self.constants = constants

        if trainable_parameters is not None:
            self.trainable_parameters = trainable_parameters

        else:
            self.trainable_parameters = dict()

        self.external_functions = external_functions
        self.processing = processing
        self.periodic_bc_protected_key = "periodic"

        self.protected_funcs = ["cos", "sin", "sqrt", "exp"]
        self.protected_operators = ["L", "Div", "Identity", "Kronecker"]

        self.protected_funcs_subs = self._construct_protected_functions()
        self.protected_operators_subs = self._construct_implict_operators()

        # Configuring the device to be used during the fitting process
        if device == "gpu":
            if not torch.cuda.is_available():
                print("Warning: There is no GPU available, using CPU instead.")
                device = "cpu"
            else:
                device = "cuda"
                print("Using GPU.")
        elif device == "cpu":
            print("Using CPU.")
        else:
            raise Exception(f"The device must be cpu or gpu, but received: {device}")

        self.device = device

        self.expressions = [self._parse_expression(expr=expr) for expr in expressions]

        if isinstance(auxiliary_expressions, dict):
            self.auxiliary_expressions = {
                key: self._parse_expression(expr=expr)
                for key, expr in auxiliary_expressions.items()
            }
        else:
            self.auxiliary_expressions = auxiliary_expressions

        self.input_vars = [self._parse_variable(var=var) for var in input_vars]
        self.output_vars = [self._parse_variable(var=var) for var in output_vars]

        self.input_names = [var.name for var in self.input_vars]
        self.output_names = [var.name for var in self.output_vars]
        self.keys = keys

        if inputs_key != None:
            self.inputs_key = self._parse_inputs_key(inputs_key=inputs_key)
        else:
            self.inputs_key = inputs_key

        self.all_vars = self.input_vars + self.output_vars

        if self.inputs_key is not None:
            self.forward = self._forward_dict
        else:
            self.forward = self._forward_tensor

        self.function = function
        self.diff_symbol = D

        self.output = None

        self.f_expressions = list()
        self.g_expressions = dict()

        self.feed_vars = None

        for name in self.output_names:
            setattr(self, name, None)

        # Defining functions for returning each variable of the regression
        # function
        for index, name in enumerate(self.output_names):
            setattr(
                self,
                name,
                lambda data: self.function.forward(input_data=data)[..., index][
                    ..., None
                ],
            )

        # If no external gradient is provided, use the core gradient evaluator
        if gradient is None:
            gradient_function = self.gradient
        else:
            gradient_function = gradient

        subs = {self.diff_symbol.name: gradient_function}
        subs.update(self.external_functions)
        subs.update(self.protected_funcs_subs)

        for expr in self.expressions:
            if not callable(expr):
                f_expr = sympy.lambdify(self.all_vars, expr, subs)
            else:
                f_expr = expr

            self.f_expressions.append(f_expr)

        if self.auxiliary_expressions is not None:
            for key, expr in self.auxiliary_expressions.items():
                if not callable(expr):
                    g_expr = sympy.lambdify(self.all_vars, expr, subs)
                else:
                    g_expr = expr

                self.g_expressions[key] = g_expr

        # Method for executing the expressions evaluation
        if self.processing == "serial":
            self.process_expression = self._process_expression_serial
        else:
            raise Exception(f"Processing case {self.processing} not supported.")

    def _construct_protected_functions(self):
        """This function creates a dictionary of protected functions from the engine object attribute.


        Returns:
            dict: A dictionary of function names and their corresponding function objects.
        """
        protected_funcs = {
            func: getattr(self.engine, func) for func in self.protected_funcs
        }

        return protected_funcs

    def _construct_implict_operators(self):
        """This function creates a dictionary of protected operators from the operators engine module.


        Returns:
            dict: A dictionary of operator names and their corresponding function objects.
        """
        operators_engine = importlib.import_module("simulai.tokens")

        protected_operators = {
            func: getattr(operators_engine, func) for func in self.protected_operators
        }

        return protected_operators

    def _parse_key_interval(self, intv: str) -> List:
        begin, end = intv.split(",")

        end = int(end[:-1])
        begin = int(begin)
        end = int(end + 1)

        return np.arange(begin, end).astype(int).tolist()

    def _parse_inputs_key(self, inputs_key: str = None) -> dict:
        # Sentences separator: '|'
        sep = "|"
        # Index identifier: ':'
        inx = ":"
        # Interval identifier
        intv = "["

        # Removing possible spaces in the inputs_key string
        inputs_key = inputs_key.replace(" ", "")

        try:
            split_components = inputs_key.split(sep)
        except ValueError:
            split_components = inputs_key

        keys_dict = dict()
        for s in split_components:
            try:
                if len(s.split(inx)) > 1:
                    key, index = s.split(inx)

                    if not key in keys_dict:
                        keys_dict[key] = list()
                        keys_dict[key].append(int(index))

                    else:
                        keys_dict[key].append(int(index))

                elif len(s.split(intv)) > 1:
                    key, interval_str = s.split(intv)
                    interval = self._parse_key_interval(interval_str)
                    keys_dict[key] = interval

                else:
                    raise ValueError

            except ValueError:
                keys_dict[s] = -1

        return keys_dict

    def _collect_data_from_inputs_list(self, inputs_list: dict = None) -> list:
        data = list()
        for k, v in self.inputs_key.items():
            if v == -1:
                if inputs_list[k].shape[1] == 1:
                    data_ = [inputs_list[k]]
                else:
                    data_ = list(torch.split(inputs_list[k], 1, dim=1))
            else:
                data_ = [inputs_list[k][:, i : i + 1] for i in v]

            data += data_

        return data

    def _parse_expression(self, expr=Union[sympy.Expr, str]) -> sympy.Expr:
        """Parses the input expression and returns a SymPy expression.

        Args:
            expr (Union[sympy.Expr, str], optional, optional): The expression to parse, by default None. It can either be a SymPy expression or a string.

        Returns:
            sympy.Expr: The parsed SymPy expression.

        Raises:
            Exception: If the `constants` attribute is not defined, and the input expression is a string.


        """
        if isinstance(expr, str):
            try:
                expr_ = sympify(
                    expr, locals=self.protected_operators_subs, evaluate=False
                )

                if self.constants is not None:
                    expr_ = expr_.subs(self.constants)
                if self.trainable_parameters is not None:
                    expr_ = expr_.subs(self.trainable_parameters)
            except ValueError:
                if self.constants is not None:
                    _expr = expr
                    for key, value in self.constants.items():
                        _expr = _expr.replace(key, str(value))

                    expr_ = parse_expr(_expr, evaluate=0)
                else:
                    raise Exception("It is necessary to define a constants dict.")
        elif callable(expr):
            expr_ = expr
        else:
            if self.constants is not None:
                expr_ = expr.subs(self.constants)
            else:
                expr_ = expr

        return expr_

    def _parse_variable(self, var=Union[sympy.Symbol, str]) -> sympy.Symbol:
        """Parse the input variable and return a SymPy Symbol.

        Args:
            var (Union[sympy.Symbol, str], optional, optional): The input variable, either a SymPy Symbol or a string. (Default value = Union[sympy.Symbol, str])

        Returns:
            sympy.Symbol: A SymPy Symbol representing the input variable.

        """
        if isinstance(var, str):
            return sympy.Symbol(var)
        else:
            return var

    def _forward_tensor(self, input_data: torch.Tensor = None) -> torch.Tensor:
        """Forward the input tensor through the function.

        Args:
            input_data (torch.Tensor, optional): The input tensor. (Default value = None)

        Returns:
            torch.Tensor: The output tensor after forward pass.

        """
        return self.function.forward(input_data=input_data)

    def _forward_dict(self, input_data: dict = None) -> torch.Tensor:
        """Forward the input dictionary through the function.

        Args:
            input_data (dict, optional): The input dictionary. (Default value = None)

        Returns:
            torch.Tensor: The output tensor after forward pass.

        """
        return self.function.forward(**input_data)

    def _process_expression_serial(self, feed_vars: dict = None) -> List[torch.Tensor]:
        """Process the expression list serially using the given feed variables.

        Args:
            feed_vars (dict, optional): The feed variables. (Default value = None)

        Returns:
            List[torch.Tensor]: A list of tensors after evaluating the expressions serially.

        """
        return [f(**feed_vars).to(self.device) for f in self.f_expressions]

    def _process_expression_individual(
        self, index: int = None, feed_vars: dict = None
    ) -> torch.Tensor:
        """Evaluates a single expression specified by index from the f_expressions list with given feed variables.

        Args:
            index (int, optional): Index of the expression to be evaluated, by default None
            feed_vars (dict, optional): Dictionary of feed variables, by default None

        Returns:
            torch.Tensor: Result of evaluating the specified expression with given feed variables

        """
        return self.f_expressions[index](**feed_vars).to(self.device)

    def __call__(
        self, inputs_data: Union[np.ndarray, dict] = None
    ) -> List[torch.Tensor]:
        """Evaluate the symbolic expression.

        This function takes either a numpy array or a dictionary of numpy arrays as input.

        Args:
            inputs_data (Union[np.ndarray, dict], optional): Union (Default value = None)

        Returns:
            List[torch.Tensor]: List[torch.Tensor]: A list of tensors containing the evaluated expressions.

            Raises:

        Raises:
            does: not match with the inputs_key attribute

        """
        constructor = MakeTensor(
            input_names=self.input_names, output_names=self.output_names
        )

        inputs_list = constructor(input_data=inputs_data, device=self.device)

        output = self.forward(input_data=inputs_list)

        output = output.to(self.device)  # TODO Check if it is necessary

        outputs_list = torch.split(output, 1, dim=-1)

        outputs = {key: value for key, value in zip(self.output_names, outputs_list)}

        if type(inputs_list) is list:
            inputs = {key: value for key, value in zip(self.input_names, inputs_list)}

        elif type(inputs_list) is dict:
            assert (
                self.inputs_key is not None
            ), "If inputs_list is dict, \
                it is necessary to provide\
                a key."

            inputs_list = self._collect_data_from_inputs_list(inputs_list=inputs_list)

            inputs = {key: value for key, value in zip(self.input_names, inputs_list)}
        else:
            raise Exception(
                f"Format {type(inputs_list)} not supported \
                            for inputs_list"
            )

        feed_vars = {**outputs, **inputs}

        # It returns a list of tensors containing the expressions
        # evaluated over a domain
        return self.process_expression(feed_vars=feed_vars)

    def eval_expression(self, key, inputs_list):
        """This function evaluates an expression stored in the class attribute 'g_expressions' using the inputs in 'inputs_list'. If the expression has a periodic boundary condition, the function evaluates the expression at the lower and upper boundaries and returns the difference. If the inputs are provided as a list, they are split into individual tensors and stored in a dictionary with the keys as the input names. If the inputs are provided as an np.ndarray, they are converted to tensors and split along the second axis. If the inputs are provided as a dict, they are extracted using the 'inputs_key' attribute. The inputs, along with the outputs obtained from running the function, are then passed as arguments to the expression using the 'g(**feed_vars)' syntax.

        Args:
            key (str): the key used to retrieve the expression from the 'g_expressions' attribute
            inputs_list (list): either a list of arrays, an np.ndarray, or a dict containing the inputs to the function

        Returns:
            the result of evaluating the expression using the inputs.:

        """

        try:
            g = self.g_expressions.get(key)
        except:
            raise Exception(f"The expression {key} does not exist.")

        # Periodic boundary conditions
        if self.periodic_bc_protected_key in key:
            assert isinstance(inputs_list, list), (
                "When a periodic boundary expression is used,"
                " the input must be a list of arrays."
            )

            # Lower bound
            constructor = MakeTensor(
                input_names=self.input_names, output_names=self.output_names
            )

            tensors_list = constructor(input_data=inputs_list[0], device=self.device)

            inputs_L = {
                key: value for key, value in zip(self.input_names, tensors_list)
            }

            output = self.function.forward(input_data=tensors_list)

            output = output.to(self.device)  # TODO Check if it is necessary

            outputs_list = torch.split(output, 1, dim=-1)

            outputs_L = {
                key: value for key, value in zip(self.output_names, outputs_list)
            }

            feed_vars_L = {**inputs_L, **outputs_L}

            # Upper bound
            constructor = MakeTensor(
                input_names=self.input_names, output_names=self.output_names
            )

            tensors_list = constructor(input_data=inputs_list[-1], device=self.device)

            inputs_U = {
                key: value for key, value in zip(self.input_names, tensors_list)
            }

            output = self.function.forward(input_data=tensors_list)

            output = output.to(self.device)  # TODO Check if it is necessary

            outputs_list = torch.split(output, 1, dim=-1)

            outputs_U = {
                key: value for key, value in zip(self.output_names, outputs_list)
            }

            feed_vars_U = {**inputs_U, **outputs_U}

            # Evaluating the boundaries equality
            return g(**feed_vars_L) - g(**feed_vars_U)

        # The non-periodic cases
        else:
            constructor = MakeTensor(
                input_names=self.input_names, output_names=self.output_names
            )

            inputs_list = constructor(input_data=inputs_list, device=self.device)

            output = self.function.forward(input_data=inputs_list)

            outputs_list = torch.split(output, 1, dim=-1)

            outputs = {
                key: value for key, value in zip(self.output_names, outputs_list)
            }

            if type(inputs_list) is list:
                inputs = {
                    key: value for key, value in zip(self.input_names, inputs_list)
                }

            elif type(inputs_list) is np.ndarray:
                arrays_list = np.split(inputs_list, inputs_list.shape[1], axis=1)
                tensors_list = [torch.from_numpy(arr) for arr in arrays_list]

                for t in tensors_list:
                    t.requires_grad = True

                inputs = {
                    key: value for key, value in zip(self.input_names, tensors_list)
                }

            elif type(inputs_list) is dict:
                assert (
                    self.inputs_key is not None
                ), "If inputs_list is dict, \
                                                     it is necessary to provide\
                                                     a key."

                inputs = {
                    key: value
                    for key, value in zip(
                        self.input_names, inputs_list[self.inputs_key]
                    )
                }

            else:
                raise Exception(
                    f"Format {type(inputs_list)} not supported \
                                for inputs_list"
                )

            feed_vars = {**inputs, **outputs}

            return g(**feed_vars)

    @staticmethod
    def gradient(feature, param):
        """Calculates the gradient of the given feature with respect to the given parameter.

        Args:
            feature (torch.Tensor): Tensor with the input feature.
            param (torch.Tensor): Tensor with the parameter to calculate the gradient with respect to.

        Returns:
            torch.Tensor: Tensor with the gradient of the feature with respect to the given parameter.
        Example:

            >>> feature = torch.tensor([1, 2, 3], dtype=torch.float32)
            >>> param = torch.tensor([2, 3, 4], dtype=torch.float32)
            >>> gradient(feature, param)
            tensor([1., 1., 1.], grad_fn=<AddBackward0>)
        """
        grad_ = grad(
            feature,
            param,
            grad_outputs=torch.ones_like(feature),
            create_graph=True,
            allow_unused=True,
            retain_graph=True,
        )

        return grad_[0]

    def jac(self, inputs):
        """Calculates the Jacobian of the forward function of the model with respect to its inputs.

        Args:
            inputs (torch.Tensor): Tensor with the input data to the forward function.

        Returns:
            torch.Tensor: Tensor with the Jacobian of the forward function with respect to its inputs.
        Example:

            >>> inputs = torch.tensor([[1, 2, 3], [2, 3, 4]], dtype=torch.float32)
            >>> jac(inputs)
            tensor([[1., 1., 1.],
                    [1., 1., 1.]], grad_fn=<MulBackward0>)
        """

        def inner(inputs):
            return self.forward(input_data=inputs)

        return jacobian(inner, inputs)

__call__(inputs_data=None) #

Evaluate the symbolic expression.

This function takes either a numpy array or a dictionary of numpy arrays as input.

Parameters:

Name Type Description Default
inputs_data Union[ndarray, dict]

Union (Default value = None)

None

Returns:

Name Type Description
List[Tensor]

List[torch.Tensor]: List[torch.Tensor]: A list of tensors containing the evaluated expressions.

Raises List[Tensor]

Raises:

Type Description
does

not match with the inputs_key attribute

Source code in simulai/residuals/_pytorch_residuals.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
def __call__(
    self, inputs_data: Union[np.ndarray, dict] = None
) -> List[torch.Tensor]:
    """Evaluate the symbolic expression.

    This function takes either a numpy array or a dictionary of numpy arrays as input.

    Args:
        inputs_data (Union[np.ndarray, dict], optional): Union (Default value = None)

    Returns:
        List[torch.Tensor]: List[torch.Tensor]: A list of tensors containing the evaluated expressions.

        Raises:

    Raises:
        does: not match with the inputs_key attribute

    """
    constructor = MakeTensor(
        input_names=self.input_names, output_names=self.output_names
    )

    inputs_list = constructor(input_data=inputs_data, device=self.device)

    output = self.forward(input_data=inputs_list)

    output = output.to(self.device)  # TODO Check if it is necessary

    outputs_list = torch.split(output, 1, dim=-1)

    outputs = {key: value for key, value in zip(self.output_names, outputs_list)}

    if type(inputs_list) is list:
        inputs = {key: value for key, value in zip(self.input_names, inputs_list)}

    elif type(inputs_list) is dict:
        assert (
            self.inputs_key is not None
        ), "If inputs_list is dict, \
            it is necessary to provide\
            a key."

        inputs_list = self._collect_data_from_inputs_list(inputs_list=inputs_list)

        inputs = {key: value for key, value in zip(self.input_names, inputs_list)}
    else:
        raise Exception(
            f"Format {type(inputs_list)} not supported \
                        for inputs_list"
        )

    feed_vars = {**outputs, **inputs}

    # It returns a list of tensors containing the expressions
    # evaluated over a domain
    return self.process_expression(feed_vars=feed_vars)

eval_expression(key, inputs_list) #

This function evaluates an expression stored in the class attribute 'g_expressions' using the inputs in 'inputs_list'. If the expression has a periodic boundary condition, the function evaluates the expression at the lower and upper boundaries and returns the difference. If the inputs are provided as a list, they are split into individual tensors and stored in a dictionary with the keys as the input names. If the inputs are provided as an np.ndarray, they are converted to tensors and split along the second axis. If the inputs are provided as a dict, they are extracted using the 'inputs_key' attribute. The inputs, along with the outputs obtained from running the function, are then passed as arguments to the expression using the 'g(**feed_vars)' syntax.

Parameters:

Name Type Description Default
key str

the key used to retrieve the expression from the 'g_expressions' attribute

required
inputs_list list

either a list of arrays, an np.ndarray, or a dict containing the inputs to the function

required

Returns:

Type Description

the result of evaluating the expression using the inputs.:

Source code in simulai/residuals/_pytorch_residuals.py
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def eval_expression(self, key, inputs_list):
    """This function evaluates an expression stored in the class attribute 'g_expressions' using the inputs in 'inputs_list'. If the expression has a periodic boundary condition, the function evaluates the expression at the lower and upper boundaries and returns the difference. If the inputs are provided as a list, they are split into individual tensors and stored in a dictionary with the keys as the input names. If the inputs are provided as an np.ndarray, they are converted to tensors and split along the second axis. If the inputs are provided as a dict, they are extracted using the 'inputs_key' attribute. The inputs, along with the outputs obtained from running the function, are then passed as arguments to the expression using the 'g(**feed_vars)' syntax.

    Args:
        key (str): the key used to retrieve the expression from the 'g_expressions' attribute
        inputs_list (list): either a list of arrays, an np.ndarray, or a dict containing the inputs to the function

    Returns:
        the result of evaluating the expression using the inputs.:

    """

    try:
        g = self.g_expressions.get(key)
    except:
        raise Exception(f"The expression {key} does not exist.")

    # Periodic boundary conditions
    if self.periodic_bc_protected_key in key:
        assert isinstance(inputs_list, list), (
            "When a periodic boundary expression is used,"
            " the input must be a list of arrays."
        )

        # Lower bound
        constructor = MakeTensor(
            input_names=self.input_names, output_names=self.output_names
        )

        tensors_list = constructor(input_data=inputs_list[0], device=self.device)

        inputs_L = {
            key: value for key, value in zip(self.input_names, tensors_list)
        }

        output = self.function.forward(input_data=tensors_list)

        output = output.to(self.device)  # TODO Check if it is necessary

        outputs_list = torch.split(output, 1, dim=-1)

        outputs_L = {
            key: value for key, value in zip(self.output_names, outputs_list)
        }

        feed_vars_L = {**inputs_L, **outputs_L}

        # Upper bound
        constructor = MakeTensor(
            input_names=self.input_names, output_names=self.output_names
        )

        tensors_list = constructor(input_data=inputs_list[-1], device=self.device)

        inputs_U = {
            key: value for key, value in zip(self.input_names, tensors_list)
        }

        output = self.function.forward(input_data=tensors_list)

        output = output.to(self.device)  # TODO Check if it is necessary

        outputs_list = torch.split(output, 1, dim=-1)

        outputs_U = {
            key: value for key, value in zip(self.output_names, outputs_list)
        }

        feed_vars_U = {**inputs_U, **outputs_U}

        # Evaluating the boundaries equality
        return g(**feed_vars_L) - g(**feed_vars_U)

    # The non-periodic cases
    else:
        constructor = MakeTensor(
            input_names=self.input_names, output_names=self.output_names
        )

        inputs_list = constructor(input_data=inputs_list, device=self.device)

        output = self.function.forward(input_data=inputs_list)

        outputs_list = torch.split(output, 1, dim=-1)

        outputs = {
            key: value for key, value in zip(self.output_names, outputs_list)
        }

        if type(inputs_list) is list:
            inputs = {
                key: value for key, value in zip(self.input_names, inputs_list)
            }

        elif type(inputs_list) is np.ndarray:
            arrays_list = np.split(inputs_list, inputs_list.shape[1], axis=1)
            tensors_list = [torch.from_numpy(arr) for arr in arrays_list]

            for t in tensors_list:
                t.requires_grad = True

            inputs = {
                key: value for key, value in zip(self.input_names, tensors_list)
            }

        elif type(inputs_list) is dict:
            assert (
                self.inputs_key is not None
            ), "If inputs_list is dict, \
                                                 it is necessary to provide\
                                                 a key."

            inputs = {
                key: value
                for key, value in zip(
                    self.input_names, inputs_list[self.inputs_key]
                )
            }

        else:
            raise Exception(
                f"Format {type(inputs_list)} not supported \
                            for inputs_list"
            )

        feed_vars = {**inputs, **outputs}

        return g(**feed_vars)

gradient(feature, param) staticmethod #

Calculates the gradient of the given feature with respect to the given parameter.

Parameters:

Name Type Description Default
feature Tensor

Tensor with the input feature.

required
param Tensor

Tensor with the parameter to calculate the gradient with respect to.

required

Returns:

Type Description

torch.Tensor: Tensor with the gradient of the feature with respect to the given parameter.

Example:

>>> feature = torch.tensor([1, 2, 3], dtype=torch.float32)
>>> param = torch.tensor([2, 3, 4], dtype=torch.float32)
>>> gradient(feature, param)
tensor([1., 1., 1.], grad_fn=<AddBackward0>)
Source code in simulai/residuals/_pytorch_residuals.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
@staticmethod
def gradient(feature, param):
    """Calculates the gradient of the given feature with respect to the given parameter.

    Args:
        feature (torch.Tensor): Tensor with the input feature.
        param (torch.Tensor): Tensor with the parameter to calculate the gradient with respect to.

    Returns:
        torch.Tensor: Tensor with the gradient of the feature with respect to the given parameter.
    Example:

        >>> feature = torch.tensor([1, 2, 3], dtype=torch.float32)
        >>> param = torch.tensor([2, 3, 4], dtype=torch.float32)
        >>> gradient(feature, param)
        tensor([1., 1., 1.], grad_fn=<AddBackward0>)
    """
    grad_ = grad(
        feature,
        param,
        grad_outputs=torch.ones_like(feature),
        create_graph=True,
        allow_unused=True,
        retain_graph=True,
    )

    return grad_[0]

jac(inputs) #

Calculates the Jacobian of the forward function of the model with respect to its inputs.

Parameters:

Name Type Description Default
inputs Tensor

Tensor with the input data to the forward function.

required

Returns:

Type Description

torch.Tensor: Tensor with the Jacobian of the forward function with respect to its inputs.

Example:

>>> inputs = torch.tensor([[1, 2, 3], [2, 3, 4]], dtype=torch.float32)
>>> jac(inputs)
tensor([[1., 1., 1.],
        [1., 1., 1.]], grad_fn=<MulBackward0>)
Source code in simulai/residuals/_pytorch_residuals.py
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def jac(self, inputs):
    """Calculates the Jacobian of the forward function of the model with respect to its inputs.

    Args:
        inputs (torch.Tensor): Tensor with the input data to the forward function.

    Returns:
        torch.Tensor: Tensor with the Jacobian of the forward function with respect to its inputs.
    Example:

        >>> inputs = torch.tensor([[1, 2, 3], [2, 3, 4]], dtype=torch.float32)
        >>> jac(inputs)
        tensor([[1., 1., 1.],
                [1., 1., 1.]], grad_fn=<MulBackward0>)
    """

    def inner(inputs):
        return self.forward(input_data=inputs)

    return jacobian(inner, inputs)