|
| 1 | +''' |
| 2 | +Copyright 2024 Capgemini |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +''' |
| 16 | +import logging |
| 17 | +from typing import TYPE_CHECKING, Union |
| 18 | + |
| 19 | +from sostrades_core.execution_engine.sos_wrapp import SoSWrapp |
| 20 | + |
| 21 | +if TYPE_CHECKING: |
| 22 | + from sostrades_optimization_plugins.models.differentiable_model import ( |
| 23 | + DifferentiableModel, |
| 24 | + ) |
| 25 | + |
| 26 | + |
| 27 | +class AutodifferentiedDisc(SoSWrapp): |
| 28 | + """Discipline which model is a DifferentiableModel""" |
| 29 | + coupling_inputs = [] # inputs verified during jacobian test |
| 30 | + coupling_outputs = [] # outputs verified during jacobian test |
| 31 | + |
| 32 | + def __init__(self, sos_name, logger: logging.Logger): |
| 33 | + super().__init__(sos_name, logger) |
| 34 | + self.model: Union[DifferentiableModel, None] = None |
| 35 | + |
| 36 | + def run(self): |
| 37 | + |
| 38 | + inputs = self.get_sosdisc_inputs() |
| 39 | + self.model.set_inputs(inputs) |
| 40 | + outputs = self.model.compute() |
| 41 | + self.store_sos_outputs_values(outputs) |
| 42 | + |
| 43 | + def compute_sos_jacobian(self): |
| 44 | + """ |
| 45 | + Compute jacobian for each coupling variable |
| 46 | + """ |
| 47 | + |
| 48 | + gradients = self.model.compute_jacobians_custom(outputs=self.coupling_outputs, inputs=self.coupling_inputs) |
| 49 | + for output_name in gradients: |
| 50 | + for output_col in gradients[output_name]: |
| 51 | + for input_name in gradients[output_name][output_col]: |
| 52 | + for input_col, value in gradients[output_name][output_col][input_name].items(): |
| 53 | + self.set_partial_derivative_for_other_types( |
| 54 | + (output_name, output_col), |
| 55 | + (input_name, input_col), |
| 56 | + value) |
0 commit comments