openmdao - 在 OpenMDAO 中重用具有不同参数名称的外部函数
问题描述
我正在尝试从外部规范生成 MDAO 问题。这需要自动创建组、学科和变量。我想重用一些分析函数,但参数不同。我必须假设这些参数的名称在重用实例之间可能不同,因此我正在寻找一种方法来制定分析函数,而函数的字典式输入/输出参数中的键与学科输入和输出之间没有必要的一致性变量。
是否有可能(如果是,如何?)在以下示例中使用以下可重用函数MyReusableFunction
之一MyReusableFunctionAlt
?
import openmdao.api as om
### External information
# I can choose the format of disciplinary functions. Some alternatives:
def MyNonReusableFunction1(inputs, outputs): # <- The way it works
# I have to use keys 'A', 'B', 'C' here
outputs['C'] = inputs['A']*inputs['B']
def MyNonReusableFunction2(inputs, outputs): # <- The way it works
# I have to use keys 'D', 'E', 'F' here
outputs['F'] = inputs['D']*inputs['E']
def MyReusableFunction(x, y): # <- The way I want it to work
return x*y
def MyReusableFunctionAlt(inputs, outputs): # <- This would also be fine
outputs['z'] = inputs['x']*inputs['y']
# Given structure of the problem
disciplines = {
'D1': {
'inputs': ['A', 'B'],
'outputs': ['C'],
'function': MyReusableFunction}, # <- instead of MyNonReusableFunction1
'D2': {
'inputs': ['D', 'E'],
'outputs': ['F'],
'function': MyReusableFunction}, # <- instead of MyNonReusableFunction2
}
connections = [('D2.F', 'D1.B')]
### My script starts here
problem = om.Problem()
for disc_name, disc_data in disciplines.items():
discipine = om.ExplicitComponent()
discipline.compute = disc_data['function']
for param_in in disc_data['inputs']:
discipline.add_input(param_in, 1)
for param_out in disc_data['outputs']:
discipline.add_output(param_out, 1)
problem.add_subsystem(disc_name, discipline)
for connection in connections:
problem.connect(connection[0], connection[1])
解决方案
这感觉像是在 ExecComps 中注册用户定义函数的用例。这是一个全新的功能。
它的使用示例如下:
这将为您处理导数,使用复杂步长或有限差分,具体取决于给定函数是否是复杂安全的。
这是您的代码示例。它并不能完美地复制存储用户函数的字典,但使用这条路径可能更容易获得它们,而不是重新分配计算。
import openmdao.api as om
def MyReusableFunction(x, y): # <- The way I want it to work
return x*y
connections = [('D2.F', 'D1.B')]
problem = om.Problem()
om.ExecComp.register('myfunc', MyReusableFunction, complex_safe=True)
D1 = om.ExecComp('C = myfunc(A, B)')
D2 = om.ExecComp('F = myfunc(D, E)')
problem.model.add_subsystem('D1', D1)
problem.model.add_subsystem('D2', D2)
for connection in connections:
problem.model.connect(connection[0], connection[1])
problem.setup()
problem.run_model()
让我们知道这是否不适用于您的用例。
推荐阅读
- intellij-idea - 无法更改日期样式 intellij IDE
- user-interface - Pharo:魅力浏览器中的可伸缩面板。如何?
- python - 从 Jupyter Notebook 启动 Dash
- git - 具有相同历史记录的 git 和 mercurial 存储库中的提交是否具有相同的哈希?
- c# - c# GetResponse() 超时,但适用于浏览器
- c - C根据带有指针的字符串的输入打印特定的字符
- mapbox - 地图框标记/点的交互性取决于所选的渲染方法
- python - 系列到数据框的列表
- python - 在 Python 中运行 oracle 查询时如何访问 pandas 数据框?
- ios - 我想在 tableView 中显示来自 firebase 的数据