Importing a matrix from Python to Pyomo

好久不见. 提交于 2019-12-25 07:48:27

问题


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)

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)

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

How can I do it?


回答1:


When you import a module in python using the syntax

import foo

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))

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

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

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)


来源:https://stackoverflow.com/questions/41812375/importing-a-matrix-from-python-to-pyomo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!