質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
最適化

最適化とはメソッドやデザインの最適な処理方法を選択することです。パフォーマンスの向上を目指す為に行われます。プログラミングにおける最適化は、アルゴリズムのスピードアップや、要求されるリソースを減らすことなどを指します。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

22342閲覧

too many indices for array: array is 1-dimensional, but 2 were indexedが解決できません…

kk_nikmann

総合スコア1

最適化

最適化とはメソッドやデザインの最適な処理方法を選択することです。パフォーマンスの向上を目指す為に行われます。プログラミングにおける最適化は、アルゴリズムのスピードアップや、要求されるリソースを減らすことなどを指します。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/02/08 10:10

最小化問題

pyomoでコスト最小化問題を計算しようとしていました。
線形の問題に対して2つの制約条件を設けて計算しようとしましたが、以下のようなエラーが出てしまいました。

発生している問題・エラーメッセージ

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

該当のソースコード

python

1import pyomo.environ as pyo 2from pyomo.opt import SolverFactory 3import numpy as np 4 5# 変数・パラメータの設定 6 7#係数行列の次元 8N = 6 9M = 2 10 11#係数ベクトル、係数行列の作成 12b = np.array([24261,132454,18026,40737,27865,2732], dtype = "float") 13A = np.array([[0.43860,0.29240,0.27911,1,0.27911,0],[1.34575,0.82225,-0.21513,1.18625,1.56975,-1]], dtype = "float") 14B = np.array([0,0,0,0,0,1], dtype = "float") 15c = np.array([510183,0], dtype = "float") 16d = np.array([100000]) 17 18#決定変数の設定 19x = np.zeros(shape=(N), dtype = "float") 20 21#決定変数の初期化用関数 22xx = {i:x[i] for i in range(len(x))} 23def init_x(model,i): 24 return xx[i] 25 26N_index_list = list(range(N)) 27M_index_list = list(range(M)) 28 29#不等式制約 30def const(model,j): 31 tmp = sum(A[j,i]*model.x[i] for i in N_index_list) 32 return tmp == c[j] 33 34def const2(model,j): 35 tmp2 = sum(B[j,i]*model.x[i]for i in N_index_list) 36 return tmp2 <= d[j] 37 38#目的関数 39def func(model): 40 return sum(b[i] * model.x[i] for i in N_index_list) 41 42#モデル 43model = pyo.AbstractModel("LP-sample") 44 45#決定変数をモデルに組み込む 46model.x = pyo.Var(N_index_list, domain=pyo.NonNegativeReals, initialize = init_x) 47 48#目的関数をモデルに組み込む 49model.value = pyo.Objective(rule = func, sense = pyo.minimize) 50 51#制約をモデルに組み込む 52model.const = pyo.Constraint(M_index_list, rule = const) 53model.const2 = pyo.Constraint(M_index_list, rule = const2) 54 55#ソルバーの選択とオプション 56solver_name = "glpk" 57opt = SolverFactory(solver_name) 58 59instance = model.create_instance() 60instance.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT) #双対変数取得用に必要 61results = opt.solve(instance, tee = True) #tee=Trueでログ出力 62instance.load(results) 63results.write() 64

試したこと

補足情報(FW/ツールのバージョンなど)

制約条件を複数設定しましたが、これで本当にいいのかすらわかっていない状態です。
これを参考にしてプログラムは組んでいます。
https://takala.tokyo/takala_wp/2019/02/20/844/

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

meg_

2021/02/08 11:00

エラーが発生した箇所はどこでしょうか?
kk_nikmann

2021/02/09 01:41

このようなエラーが出ておりました ERROR: Rule failed when generating expression for constraint const2 with index 0: IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed ERROR: Constructing component 'const2' from data=None failed: IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-69-8e225d568fd2> in <module> ----> 1 instance = model.create_instance() 2 instance.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT) #双対変数取得用に必要 3 results = opt.solve(instance, tee = True) #tee=Trueでログ出力 4 instance.load(results) 5 results.write() ~\anaconda3\lib\site-packages\pyomo\core\base\PyomoModel.py in create_instance(self, filename, data, name, namespace, namespaces, profile_memory, report_timing, **kwds) 720 _namespaces.append(None) 721 --> 722 instance.load( data, 723 namespaces=_namespaces, 724 profile_memory=profile_memory ) ~\anaconda3\lib\site-packages\pyomo\core\base\PyomoModel.py in load(self, arg, namespaces, profile_memory, report_timing) 777 msg = "Cannot load model model data from with object of type '%s'" 778 raise ValueError(msg % str( type(arg) )) --> 779 self._load_model_data(dp, 780 namespaces, 781 profile_memory=profile_memory) ~\anaconda3\lib\site-packages\pyomo\core\base\PyomoModel.py in _load_model_data(self, modeldata, namespaces, **kwds) 830 continue 831 --> 832 self._initialize_component(modeldata, namespaces, component_name, profile_memory) 833 if False: 834 total_time = time.time() - start_time ~\anaconda3\lib\site-packages\pyomo\core\base\PyomoModel.py in _initialize_component(self, modeldata, namespaces, component_name, profile_memory) 881 declaration.name, _blockName, str(data) ) 882 try: --> 883 declaration.construct(data) 884 except: 885 err = sys.exc_info()[1] ~\anaconda3\lib\site-packages\pyomo\core\base\constraint.py in construct(self, data) 833 for index in self.index_set(): 834 self._setitem_when_not_present( --> 835 index, self.rule(block, index) 836 ) 837 except Exception: ~\anaconda3\lib\site-packages\pyomo\core\base\util.py in __call__(self, parent, idx) 302 return self._fcn(parent, *idx) 303 else: --> 304 return self._fcn(parent, idx) 305 306 <ipython-input-66-d454e3429ed2> in const2(model, j) 5 6 def const2(model,j): ----> 7 tmp2 = sum(B[j,i]*model.x[i]for i in N_index_list) 8 return tmp2 <= d[j] 9 <ipython-input-66-d454e3429ed2> in <genexpr>(.0) 5 6 def const2(model,j): ----> 7 tmp2 = sum(B[j,i]*model.x[i]for i in N_index_list) 8 return tmp2 <= d[j] 9 IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
guest

回答1

0

ベストアンサー

エラーとしては、1次元の配列に、2つのインデックスが指定されているというような内容です。

どこでエラーが発生しているか書いてないですが、const2()の部分がおかしいです。

python

1B = np.array([0,0,0,0,0,1], dtype = "float") 2 3def const2(model,j): 4 tmp2 = sum(B[j,i]*model.x[i]for i in N_index_list) 5 return tmp2 <= d[j]

Bは1次元の配列ですが、B[j, i]と2つのインデックスが渡されています。

投稿2021/02/08 23:34

bsdfan

総合スコア4560

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

kk_nikmann

2021/02/09 01:58

ご指摘ありがとうございます。修正したらうまく回りました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問