从Python导入矩阵到Pyomo [英] Importing a matrix from Python to Pyomo

查看:196
本文介绍了从Python导入矩阵到Pyomo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Python定义的矩阵:(文件名为matrix.py)

I have a matrix defined in Python: (name of the document matrix.py)

N = 4
l = N
k = N


D = np.zeros((l,k))


for i in range(0,l):   
    for j in range(0,k):
        if (i==j):
            D[i,j] = 2
        else:
            D[i,j] = 0
D[0,0] = (2*N**2+1)/6   

D[-1,-1] = -(2*N**2+1)/6  


print(D)

我想在Pyomo中使用它,而我做到了:

I want to use it in Pyomo, and i did:

import matrix 

. .

m.f_x1 = Var(m.N)
def f_x1_definition(model,i):
    for j in m.N:
        return m.f_x1[j] ==sum(D[i,j]*m.x1[j] for j in range(value(m.n)))

m.f_x1_const = Constraint(m.N, rule = f_x1_definition)

但是出现下一个错误: NameError: global name 'D' is not defined

But I get the next error: NameError: global name 'D' is not defined

我该怎么办?

推荐答案

使用语法在python中导入模块时

When you import a module in python using the syntax

import foo

foo模块中定义的所有内容都将在foo名称空间中可用.也就是说,如果foo.py包含:

all the things defined in the foo module will be available within the foo namespace. That is, if foo.py contains:

import numpy as np
a = 5
D = np.zeros((1,5))

使用import foo导入模块时,可以使用以下命令访问aD:

when you import the module with import foo, then you can access a, and D with:

import foo
print(foo.a)
print(foo.D)

如果要将符号从foo直接拉到本地名称空间,则应使用from ... import ...语法:

If you want to pull the symbols from foo directly into your local namespace, you would instead use the from ... import ... syntax:

from foo import a,D
print(a)
print(D)

这篇关于从Python导入矩阵到Pyomo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆