LoginSignup
4
1

M1/M2 macでPython−MIPを動かすには?

Last updated at Posted at 2023-12-01

M1/M2でPython−MIPは動かない?

普通に実行すると、M1/M2 macでは数理最適化のライブラリであるPython−MIPが動きません。
Python 3.12ではPython−MIPの最新版をインストールできないので、Python 3.11を使います。最初に、Python−MIPが動かないことを確かめます。

% python3.11 -V

Python 3.11.6

Python−MIPをインストールします。

% pip3.11 install mip

(中略)
Successfully installed cffi-1.15.1 mip-1.15.0 pycparser-2.21

インストールは成功します。モデルを作ってみましょう。

% python3.11 -c 'import mip; m = mip.Model()'

An error occurred while loading the CBC library:
(中略)'.../lib/python3.11/site-packages/mip/libraries/cbc-c-darwin-x86-64.dylib'
 (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64')),
(中略)
NameError: name 'cbclib' is not defined

エラーになりました。これは、Python−MIPと一緒にインストールされたソルバーのCBCのライブラリがx86_64のバイナリだからです。

M1/M2でPython−MIPを動かす方法

CBCのライブラリを動かすためには、x86_64のエミュレータであるRosetta2が必要です。
Rosetta2を有効にするには、一度だけ次のようにします。

% /usr/sbin/softwareupdate --install-rosetta --agree-to-license

Rosetta2を有効にするとarchというコマンドが使えます。
archを使うと、次のようにしてx86_64のzshを起動できます。

% arch --x86_64 zsh

これだけでは、まだ動きません。さらに仮想環境で作業する必要があります。
仮想環境を作成し、アクティベートしましょう。

% python3.11 -m venv venv
% . venv/bin/activate

Python−MIPをインストールします。

(venv) % pip install mip

(中略)
Successfully installed cffi-1.15.1 mip-1.15.0 pycparser-2.21

ここまですると、次のように動かすことができます。

(venv) % python -c 'import mip; m = mip.Model()'

まとめ

M1/M2 macでPython−MIPを動かすには、次の作業が必要でした。

  • Rosetta2を有効にします。
  • x86_64でzshを起動します。
  • 仮想環境で作業します。

補足

PoetryでPython−MIPを動かしたい場合は、下記を参照してください。

余談

Python−MIPは、CFFIのインターフェースを使っているため、まとめで紹介したような作業が必要でした。
似たようなライブラリであるPuLPは、CBCを外部アプリケーションとして使っているので、Rosetta2を有効にするだけで使えます。

参考:M1/M2でIntel用ライブラリを利用する手順 - PyQドキュメント

以上

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1