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 方程定义中的换行符 的相关文章

  • 如何在Jenkins上更改工作空间并建立记录根目录?

    我希望将 Jenkins 的数据写入驱动器 E 因为这是服务器上的大型驱动器 Jenkins 本身安装在 C 上 我怎么做 我看到的默认配置是 工作区根目录 ITEM ROOTDIR 工作区 构建记录根目录 ITEM ROOTDIR 构建
  • 在 selenium webdriver 中打开一个新窗口而不是新选项卡

    当在我的应用程序中手动单击链接时 它会在 Chrome 和 IE 中的新选项卡中打开 但是 当我的脚本运行时 该链接会在 IE 中的新窗口而不是新选项卡中打开 相同的脚本在 Chrome 中按预期运行 知道如何摆脱这个吗 更改 IE 的默认
  • 以 UTF8 而不是 UTF16 输出 DataTable XML

    我有一个 DataTable 我正在使用 WriteXML 创建一个 XML 文件 尽管我在以 UTF 16 编码导出它时遇到问题 并且似乎没有明显的方法来更改它 我了解 NET 在字符串内部使用 UTF 16 这是正确的吗 然后 我通过
  • 正则表达式 - 匹配不包含字符串的模式

    我对正则表达式很陌生 并且一直在寻找方法来做到这一点 但没有成功 给定一个字符串 我想删除以 abc 开头 以 abc 结尾且中间不包含 abc 的任何模式 如果我做 abc abc abc 它将匹配以 b 开头 以 abc 结尾并且中间包
  • Javascript/jQuery 外部高度()

    Does idOfLememt outerHeight 对所有浏览器产生相同的结果 IE7 有什么不同吗 只要去http api jquery com outerHeight http api jquery com outerHeight
  • 我如何用 javascript/jquery 进行两指拖动?

    我正在尝试创建当有两个手指放在 div 上时拖动 div 的功能 我已将 div 绑定到 touchstart 和 touchmove 事件 我只是不确定如何编写这些函数 就像是if event originalEvent targetTo
  • 服务器响应 PASV 命令返回的地址与建立 FTP 连接的地址不同

    System Net WebException 服务器响应 PASV 命令返回的地址与建立 FTP 连接的地址不同 在 System Net FtpWebRequest CheckError 在 System Net FtpWebReque
  • Android 的代码覆盖率[重复]

    这个问题在这里已经有答案了 可能的重复 Android测试代码覆盖率 Eclipse https stackoverflow com questions 3282702 android test code coverage eclipse
  • 关闭扫描仪是否会影响性能

    我正在解决一个竞争问题 在问题中 我正在使用扫描仪获取用户输入 这是 2 个代码段 一个关闭扫描器 一个不关闭扫描器 关闭扫描仪 import java util Scanner public class JImSelection publ
  • UWP 应用程序在与商店关联后崩溃

    我正在为 Windows 创建一个 cordova 应用程序 将应用程序与商店关联后 应用程序起始页变为白色空白 如果应用程序使用包标识名称 com something moretext 则该应用程序可以正常工作 但我的商店包身份名称是 5
  • Swift 中的 quitFirstResponder

    我怎样才能用Apple的新语言实现它 Objective C 代码 void touchesBegan NSSet touches withEvent UIEvent event for UIView view in self view s
  • Maven2继承

    如果我有一个父 pom 并且想将其继承到多个项目 我通常通过添加到项目顶部来做到这一点
  • 文本处理问题:删除其中一列不包含特定值的行

    我有一个制表符分隔的文件 如下所示 input sequence match sequence score receptor group epitope antigen organism ASRPPGGVNEQF ASRPPGGVNEQF
  • 如何用LoaderManager自动重新查询

    我有一个应用程序显示来自 SQLite DB 的数据 并且数据不断变化 所以显然 我认为我应该使用 LoaderManager 来显示数据 我读过一些关于将 LoaderManager 与 SQLite 结合使用的内容 然后看到了亚历克斯
  • 用 Beautiful Soup 进行抓取:为什么 get_text 方法不返回该元素的文本?

    最近我一直在用 python 开发一个项目 其中涉及抓取一些网站的一些代理 我遇到的问题是 当我尝试抓取某个知名代理站点时 当我要求 Beautiful Soup 查找 IP 在代理表中的位置时 它并没有按照我的预期执行操作 我将尝试查找每
  • JavaScript 中“键”的类型是什么?

    当我失去焦点并开始思考一个愚蠢的问题时 我遇到了这样的时刻 var a b value b 的类型是什么 我的意思不是 值 的类型 而是标记为 b 的实际键 背景 当我必须创建一个字符串键时 我开始想知道这一点 var a b value
  • 从 Teradata sql Assistant 将结果导出到 Excel 工作表

    我想通过在 Teradata SQL Assistant 中运行查询将结果导出到 Excel 工作表中 我使用了复制粘贴 但没有用 提前致谢 如果您将答案返回到 SQL Assistant 您应该能够从 文件 菜单中选择 保存答案集 然后
  • RavenDB:为什么我会在此多重映射/归约索引中获得字段空值?

    受到 Ayende 文章的启发https ayende com blog 89089 ravendb multi maps reduce indexes https ayende com blog 89089 ravendb multi m
  • 如何在 Symfony 4 中为测试环境设置数据库

    我对如何在 symfony 4 中为测试环境设置数据库感到困惑 我曾经在配置测试 ymlsymfony 3 及以下版本中的文件 最佳做法是什么 我应该重新创建一个学说 yaml文件输入配置 包 测试 该文档提到如何通过编辑 phpunit
  • GAE 无法部署到 App Engine

    我正在尝试从 Eclipse 发布 Web 应用程序 我在 GAE 上创建了四个项目 可以通过登录我的帐户并查看控制台来查看它们 我已经改变了appengine web xml到项目的应用程序 ID 如果我将其更改为 GAE 上第一个创建的

随机推荐

  • 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 对于求解器来说 方程可能不再具有正确的格