Python gekko 方程定义中的换行符

2024-04-08

我目前正在手动实现有限元的伽辽金法,并使用 python gekko 来求解所得的非线性代数方程组。这对于小型系统来说不会产生任何问题并且工作正常。

一旦系统变得更加复杂,涉及长方程和指数项m.exp()对于求解器来说,方程可能不再具有正确的格式。确切的错误消息是@error: Equation Definition Equation without an equality (=) or inequality (>,<).

我通过检查方程m.open_folder() in the model.apm。看来,以某种方式在方程中添加了换行符,从而失去了结果表达式之间的数学关系。这就是求解器无法识别的原因equality (=) or inequality (>,<)在第一个表达式中。 我还发现指数项m.exp(-EA / (R * T))导致断行。替换为np.exp(-EA/(R*T0))修复了该问题。这可能是由于 gekko 在后台缩短了长方程,并且此过程中存在错误。或者我的方程定义有问题。这是我的代码。

生成长而复杂的代数方程的基础

import pandas as pd
import numpy as np
from gekko import GEKKO
from typing import List, Callable
m = GEKKO(remote=False)
# constants
# -------------------------
R = 8.314  # J/mol K
# Rahmenbedingungen
# -------------------------
T0 = 550  # K
p0 = 15 * 10 ** 5 # Pa
# components
# -------------------------
x_bulk = np.array(
    [0.1, 0.08, 0.05]
)  # no unit Ethen, O2, CO2, EO, H2O
# catalyst pellet
# -------------------------
rho_p = 1171.2  # kg / m**3 Dichte eines Pellets
epsilon_p = 0.7  # Poroesitaet
tau = 4  # Tortuositaet
# heat transfer
# -------------------------
lambda_pm = 16  # W/m K Wärmeleitfähigkeit des reinen Katalysatorfestoffes
lambda_p = (1 - epsilon_p) * lambda_pm  # W/m K Wärmeleitfähigkeit des porösen Pellets
# reaction enthalpies
# -------------------------
dh_r1 = -107000  # J/mol
dh_r2 = -1323000  # J/mol
Deff = 5.42773893 * 10 **7

# reaction speeds 
# --------
def r_r1(p: np.array, T: float = T0) -> float:
    n_E = 0.6  # Reaktionsordnung Ethen
    n_O2 = 0.5  # Reaktionsordnung Sauerstoff
    k0 = 6.275 * 10**6  # pre-exponential collision factor [mol / (kg s Pa ** (nE+nO2))]
    EA = 74900 # activation energy [J/mol]
    K0 = 1.985 * 10**2  # pre-exponential adsorption factor [1/Pa]
    Tads = 2400  # adsorption temperature [K]
    r = k0 * m.exp(-EA / (R * T)) * p[0] ** n_E * p[1] ** n_O2 / (1 + K0 * np.exp(Tads / T0) * p[2])
    # this is m.exp() one cause for the quations not being formatted correctly
    # change it to np.exp(-EA/(R*T0)) and the equations are formatted correctly for the solver
    # this may be a mistake in my code or a bug in gekko
    return r

# differential equations 
# --------
def rhs(x: float, y: np.array, dy: np.array) -> np.array:
    # second derivatives of the partial pressures [bar/m**2]
    # use bar instead of Pa to increase numerical precision
    rhs_E   = -2 / x * dy[0] + R * y[-1] * T0 * rho_p / (Deff * p0) * (r_r1(p=y[0:-1] * p0, T=y[-1] * T0))
    rhs_O2  = -2 / x * dy[1] + R * y[-1] * T0 * rho_p / (Deff * p0) * (0.5 * r_r1(p=y[0:-1] * p0, T=y[-1] * T0))
    rhs_CO2 = -2 / x * dy[2] + R * y[-1] * T0 * rho_p / (Deff * p0) * (-2) * r_r1(p=y[0:-1] * p0, T=y[-1] * T0)
    rhs_T   = -2 / x * dy[-1] - rho_p / (lambda_p * T0) * (r_r1(p=y[0:-1] * p0, T=y[-1] * T0) * (-dh_r1))
    return np.array([rhs_E, rhs_O2, rhs_CO2, rhs_T])

# quadrature over the right hand side of the difffereantial equation
# ----------------

def give_quad_expressions(
    rhs: Callable, phi: List[np.poly1d], dphi: List[np.poly1d]
) -> Callable:
    """Creates an expression for the quadrature of the right-hand-side of the
    differential equation that is only dependent on the function values at the
    nodes y_i. It takes the quadrature base points to evaluate the
    base functions phi_i and their derivatives dphi_i to set up the expression.

    Args:
        rhs (Callable): Right hand side of the differential equation.
        Needs to be a function of x, y, and dy
        phi (List[np.poly1d]): List with all base polynomials phi. Mostly, base polynomials of Legendre type.
        dphi (List[np.poly1d]): List with the corresponding derivatives of the base polynomials.

    Returns:
        Callable: Expression for the weighted quadratures of the right-hand-side for each node that is only
        dependent on the unknown function values y_i. It can be called by a solving algorithm.
    """
    # these will be defined during runtime
    number_base_points = 2
    base_points = np.array([0.00021132, 0.00078868])
    weights = np.array([0.0005, 0.0005])

    # evaluate base functions at quadrature base points
    phi_eval = np.zeros(shape=(len(phi), number_base_points))
    dphi_eval = np.zeros(shape=(len(dphi), number_base_points))
    for index, phi_i in enumerate(phi):
        phi_eval[index] = phi_i(base_points)
        dphi_eval[index] = dphi[index](base_points)

    # set up the expression for the quadrature only dependent on the unknown y_i values
    def quad_expressions(y: np.array, model:GEKKO) -> np.array:
        """Variable expressions for the weighted quadratures of the integral of the weighted right-hand-side
        for each node that are only dependend on y.
        The integral is crucial for the Galerkin Method. int(phi_j * rhs(x, y, dy))dx.
        It allows the gekko solver to embed a numpy array y into the quadrature
        that is safed into the gekko model by using 'm.Array(m.Var)' for setting up the algebraic equation system.

        Args:
            y (np.array): Unknown function values that the gekko solver needs to find.

        Returns:
            np.array: Array with the weighted quadratures for each function and node as a function of y_i.
                first index specifies the function, second index the node
        """

        # TODO: Work with numpy arrays instead of lists to enhance speed.
        y_tilde = []
        dy_tilde = []
        # set up the trail functions and their derivatives using the base functions which are already
        # evaluated and the supposed y values at the nodes.
        for eq_l in range(y.shape[0]):
            y_tilde_eq = []
            dy_tilde_eq = []
            for bpoint_iq in range(number_base_points):
                # iterates over quadrature base points
                y_tilde_eq.append(np.dot(y[eq_l], phi_eval[:, bpoint_iq]))
                dy_tilde_eq.append(np.dot(y[eq_l], dphi_eval[:, bpoint_iq]))
            y_tilde.append(y_tilde_eq)
            dy_tilde.append(dy_tilde_eq)
        # evaluate the right-hand-sides with the base points and the supposed trial function values at the base points
        rhsides_evaluated_bpoints = rhs(
            base_points, np.array(y_tilde), np.array(dy_tilde)
        )
        # multiply the right-hand-side with the trial function of each node
        integrals = np.zeros_like(y)
        for eq_l, rhs_eq in enumerate(rhsides_evaluated_bpoints):
            # iterate over the equations
            for node_i in range(y.shape[1]):
                # iterate over the weight function of each node
                # calcualte the quadrature using the weights
                rhs_w_func = rhs_eq * phi_eval[node_i]
                dotp = model.sum(
                    [rhs_w_func[i] * weights[i] for i in range(number_base_points)]
                )
                # dotp = np.dot(
                #     rhs_w_func, self.weights
                # )
                integrals[eq_l, node_i] = dotp  # using the dot product via list comprehension with gekko to allow the model to split long equations
        return integrals

    return quad_expressions

建立方程

phi = [
    np.poly1d([ 2.e+06, -3.e+03,  1.e+00]),
    np.poly1d([-4000000.,     4000.,       -0.]),
    np.poly1d([ 2.e+06, -1.e+03,  0.e+00])
]

dphi = [
    np.poly1d([ 4.e+06, -3.e+03]),
    np.poly1d([-8.e+06,  4.e+03]),
    np.poly1d([ 4.e+06, -1.e+03])
]

diffusion_matrix = np.array(
    [[ 2333.33333333, -2666.66666667,   333.33333333],
    [-2666.66666667,  5333.33333333, -2666.66666667],
    [  333.33333333, -2666.66666667,  2333.33333333]]
)
y = m.Array(m.Var, (4, 3), value=x_bulk[0])

quad_expression = give_quad_expressions(rhs=rhs, phi=phi, dphi=dphi)
rhs_integrals = quad_expression(y=y, model=m)

for j in range(y.shape[0]):
    # iterates over each differential equation
    for i in range(y.shape[1]):
        # iterates over each node
        m.Equation(
            np.dot(
                y[j], (-1) * diffusion_matrix[:, i]
            ) == rhs_integrals[j, i]
        )

for eq in m._equations:
    print(eq)
m.solve()

Error

Exception: @error: Equation Definition

不带等式 (=) 或不等式 (>,(((((((v10)(-0.12200771519999987))+((v11)(0.6666554303999999)))+((v12)(0.4553522848000001))))(550)))))]))))([((((((((v1))(0.4553522848))+((v2)(0.6666554304000001)))+((v3)(-0.1220077152))))(1500000)))^(0.6)) 正在停止...


我发现了这个问题: 方程定义中出现这些换行符的原因是由于错误使用了 gekko 内置函数,例如m.exp(), m.sin(),...这些只能分段评估,而不是像我尝试的那样一次评估整个数组。

所以改变从

rhsides_evaluated_bpoints = rhs(
        base_points, np.array(y_tilde), np.array(dy_tilde)
    )

to

rhs_eval = []
    for i, bpoint in enumerate(base_points):
         rhs_eval.append(
              rhs(
                x=bpoint,
                y=y_tilde[:, i],
                dy=dy_tilde[:, i]
            )  
         )
    rhs_eval = np.array(rhs_eval).transpose()

完成了工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python gekko 方程定义中的换行符 的相关文章

  • 如何防止用户控件表单在 C# 中处理键盘输入(箭头键)

    我的用户控件包含其他可以选择的控件 我想实现使用箭头键导航子控件的方法 问题是家长控制拦截箭头键并使用它来滚动其视图什么是我想避免的事情 我想自己解决控制内容的导航问题 我如何控制由箭头键引起的标准行为 提前致谢 MTH 这通常是通过重写
  • 如何在发布期间复制未版本化的测试资源:执行?

    我的问题与 Maven 在发布时不会复制未跟踪的资源 https stackoverflow com questions 10378708 maven doesnt copy untracked resources while releas
  • CFdump cfcomponent cfscript

    可以在 cfcomponent 中使用 cfdump 吗 可以在 cfscript 中使用 cfdump 吗 我知道 anser 不是 那么如何发出 insde cfcomponent 函数的值 cf脚本 我用的是CF8 可以在 cfcom
  • TIFF 元数据的最大大小是多少?

    TIFF 文件元数据的单个字段中可以合并的元数据数量是否有最大限制 我想在 ImageDescription 字段中存储大文本 最多几 MB 没有具体的最大限制ImageDescription但是 整个 TIFF 文件存在最大文件大小 该最
  • 使用.NET技术录制屏幕视频[关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 有没有一种方法可以使用 NET 技术来录制屏幕 无论是桌面还是窗口 我的目标是免费的 我喜欢小型 低
  • Redis如何存储关联数组?设置、散列还是列表?

    我对 Redis 的所有可用存储选项有点困惑 我想做一些简单的事情 并且不想过度设计它 我正在与phpredis and Redis v2 8 6 我有一个需要存储的简单关联数组 我还需要能够通过其键检索项目并循环遍历所有项目 a arra
  • Vue.js[vuex] 如何从突变中调度?

    我有一个要应用于 json 对象的过滤器列表 我的突变看起来像这样 const mutations setStars state payload state stars payload this dispatch filter setRev
  • CSS溢出文本显示在几行中,没有断字

    我有一些长文本显示在 div 中 该 div 具有固定的宽度和高度 我希望文本显示在几行上 作为 div 高度 并且句子单词不会中断 一行中的单词前缀和下一行中的继续 此外 我想在末尾添加省略号最后一句话 CSS white space n
  • 节拍匹配算法

    我最近开始尝试创建一个移动应用程序 iOS Android 它将自动击败比赛 http en wikipedia org wiki Beatmatching http en wikipedia org wiki Beatmatching 两
  • Spring Boot @ConfigurationProperties 不从环境中检索属性

    我正在使用 Spring Boot 1 2 1 并尝试创建一个 ConfigurationProperties带有验证的bean 如下所示 package com sampleapp import java net URL import j
  • 对来自流读取器的过滤数据执行小计

    编辑问题未得到解答 我有一个基于 1 个标准的过滤输出 前 3 个数字是 110 210 或 310 给出 3 个不同的组 从流阅读器控制台 问题已编辑 因为第一个答案是我给出的具体示例的字面解决方案 我使用的实际字符串长度为 450 个
  • 用于验证目的的动态查找方法

    我正在使用 Ruby on Rails 3 0 7 我想在运行时查找一些记录以进行验证 但为该查找方法传递 设置一个值 也就是说 在我的班级中 我有以下内容 class Group lt lt ActiveRecord Base valid
  • neo4j - python 驱动程序,服务不可用

    我对 neo4j 非常陌生 我正在尝试建立从 python3 6 到 neo4j 的连接 我已经安装了驱动程序 并且刚刚开始执行第一步 导入请求 导入操作系统 导入时间 导入urllib 从 neo4j v1 导入 GraphDatabas
  • rspec 中的模拟方法链

    有一系列方法可以获得user目的 我试图模拟以下内容以返回user in my Factory Girl current user AuthorizeApiRequest call request headers result 我可以模拟该
  • 如何使用 Pycharm 安装 tkinter? [复制]

    这个问题在这里已经有答案了 I used sudo apt get install python3 6 tk而且效果很好 如果我在终端中打开 python Tkinter 就可以工作 但我无法将其安装在我的 Pycharm 项目上 pip
  • NotImplementedError:无法将符号张量 (lstm_2/strided_slice:0) 转换为 numpy 数组。时间

    张量流版本 2 3 1 numpy 版本 1 20 在代码下面 define model model Sequential model add LSTM 50 activation relu input shape n steps n fe
  • Erlang dict的时间复杂度

    我想知道 Erlang OTP 是否dict模块是作为哈希表实现的 在这种情况下它是否能提供这样的性能 平均情况 Search O 1 n k Insert O 1 Delete O 1 n k 最坏的情况下 Search O n Inse
  • 升级到 Rails 6 时是否有一种编程方法可以检测 Zeitwerk::NameError?

    我目前正在将旧的 Rails 应用程序迁移到 Rails 6 好像项目中有些文件和里面定义的类不一致 运行应用程序测试时我没有看到此错误 但部署后我收到如下错误 Zeitwerk NameError expected file app my
  • 如何在react-highcharts中使用图表工具提示格式化程序?

    如何使用图表工具提示格式化程序 我正在使用高图表的反应包装器 我有这样的配置 const CHART CONFIG tooltip formatter tooltip gt var s b this x b each this points
  • 强制 Listview 不重复使用视图(复选框)

    我做了一个定制Listview 没有覆盖getView 方法 Listview 中的每个项目都具有以下布局 联系布局 xml

随机推荐

  • VSCode 显示文件夹 /run/user/1000/doc 中路径的问题

    我最近在更新到 v1 77 3 后在 VSCode 中遇到了一个问题 新项目的路径是错误的 而旧项目的路径是正确的 特别是 新项目在前缀为的文件夹中打开 run user 100 doc 接下来是类似于 sha256 的摘要 每个文件夹都不
  • \ 对非转义字符有何作用?

    I 又问了一个不好的问题 https stackoverflow com questions 4380386 fix escape javascript escape character所以我会问别的事情 根据http www c poin
  • 存储值以便在以后的函数中使用的最佳方法是什么?我听说全局变量很邪恶

    所以我使用的代码位于http jsfiddle net 8j947 10 http jsfiddle net 8j947 10 它为变量 isLive 返回 true 或 false 值 如何在稍后的函数中使用变量 onLive 我在以下位
  • 使用Jackson写yaml?

    我正在使用 Jackson 来读取和修改 yaml 文件 效果很好 不过 我找不到编写 yaml 所需的魔法 ObjectMapper mapper new ObjectMapper new YAMLFactory ObjectNode r
  • 使用 docker-compose 时如何为 mongodb 镜像添加 --auth ?

    我正在使用 docker compose 来运行由 node mongodb nginx 创建的项目 我已经使用构建了该项目docker build 然后我用docker up d nginx开始我的项目 但我还没有找到使用 auth 运行
  • 我应该在 Common Lisp 中使用哪些正则表达式库? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • Python 列表索引效率

    关于内置 python 列表对象的快速问题 假设您有一个包含数字 0 99 的列表 您正在编写一个程序 该程序获取列表中的最后一项并将其用于其他目的 使用list 1 比使用list 99 更有效吗 换句话说 无论哪种情况 python 都
  • Python-从另一个列表中删除一组列表

    array1 1 2 3 4 5 6 7 8 9 array2 1 2 2 2 5 6 6 6 9 temp set array2 array1 remove temp Traceback most recent call last Fil
  • JqG​​rid 搜索字段的多个文本框

    我想知道 JqGrid 高级搜索是否可以为我想要搜索的某些字段显示多个文本框 例如 如果我有一个 电话号码 字段 我希望能够可视化 2 个框 一个用于区号 另一个用于电话号码的其余部分 然后按 查找 后 我希望能够获取两个值并将它们合并或执
  • 将事件分配给事件处理程序的两种不同类型之间的区别

    我在 SO 中看到了这个示例代码 它说一种做法不好 另一种做法很好 但我不明白为什么 事实上 我收到了著名的 RCW COM 对象错误 该帖子说这可能是一个原因 public class SomeClass private Interop
  • 如何在单击项目时检查ListView的复选框?

    如何在单击项目时检查ListView的复选框 我有一个带有复选框 文本视图 按钮的列表视图 这里我想选择ListView的多行 所以使用了CheckBox 如果我点击一行 我想让它对应的CheckBox被选中并获取ListView中被点击项
  • 每个Android的location.Address方法返回什么?

    我试图弄清楚如何使用 Android SDK 和 android location Address 类获取地址组件 有些方法非常简单 其他方法很容易通过示例中的示例来理解文档 http developer android com refer
  • .Net Core - CS0012“对象”在未引用的程序集中定义

    我是 Net Core 的新手 我正在尝试基于它构建一个构建系统 作为该项目的一部分 我创建了一个抽象类 它详细说明了构建任务应实现的内容 并将其填充到共享库中 可执行项目引用该库并扫描项目目录以查找特殊命名的目录 然后检查是否有任何 cs
  • Play Framework Form“折叠”方法命名原理

    Play 框架 2 x 表格类 http www playframework com documentation 2 0 api scala index html play api data Form有一个方法叫做foldwho 的用法表示
  • 所需的后台模式 iOS6 Xcode 4.5

    我注意到在 Xcode 4 5 和 iOS6 中 必需的背景模式 应用程序播放音频 不起作用 有其他人注意到这一点吗 如果是的话 您找到解决办法了吗 Thanks 我相信它可能取决于您为 AVAudioSession 指定的类别类型 确保将
  • 测试递归方法

    我想测试一个方法 public function get key if time this gt driver gt get key if key self LAST UPDATE KEY time new DateTime this gt
  • 保持侧边导航与页面滚动固定

    我有一个客户网站 www stagecraft co uk 他们想要在租用页面 http www stagecraft co uk hire html 较长的页面 http www stagecraft co uk lighting gen
  • Tensorflow 未显示“在本地成功打开某某 CUDA 库”

    我将 TensorFlow 配置为在 GPU GeForce 840M 上支持 CUDA 但程序运行速度相当慢slow与我之前使用的 CPU 相比 还有 我do not收到任何类型的消息某某CUDA库打开成功当我运行程序时 相反 这是我运行
  • 在精确的关键帧处停止故事板

    我为我正在制作的一些游戏制作了一个骰子 在 C 中 它是一个用户控件 它使用故事板来依次显示多个图像 如幻灯片 因此它看起来像一个滚动的 3D 骰子 问题在于在特定关键帧处启动和停止它 为此使用 Pause 和 Resume 似乎是合乎逻辑
  • Python gekko 方程定义中的换行符

    我目前正在手动实现有限元的伽辽金法 并使用 python gekko 来求解所得的非线性代数方程组 这对于小型系统来说不会产生任何问题并且工作正常 一旦系统变得更加复杂 涉及长方程和指数项m exp 对于求解器来说 方程可能不再具有正确的格