goo blog サービス終了のお知らせ 

coLinux日記

coLinuxはフリーソフトを種として、よろずのシステムとぞなれりける。

入門者が、生成AIに Python3 のプログラムを作成してもらい衝撃を受ける。

2025-04-13 22:02:22 | Python
生成AIも進展してプログラミングもできるようになったので、今までのように補助的な使用をしないで Python3 プログラムそのものを作成してもらいました。

今回は Google Gemini を利用して、数独のプログラム作成依頼でプロンプトはこのようになりました。

「python3で数独を解くプログラムを作成したい。動作するコンピュータが遅いのでなるべく高速になるように作成したい。問題はプログラムの入力ではなく、問題の1行を表す要素数9個のリストを9個使用する。以下に、問題の例を示す。  
# Set Puzzle
R1 = [3, 0, 0, 7, 4, 0, 5, 2, 0]
R2 = [0, 2, 8, 9, 0, 0, 0, 0, 0]
R3 = [0, 4, 5, 0, 0, 0, 9, 0, 3]
R4 = [4, 5, 0, 6, 0, 7, 0, 0, 9]
R5 = [9, 0, 0, 0, 2, 3, 0, 0, 1]
R6 = [0, 0, 0, 8, 5, 9, 3, 4, 7]
R7 = [5, 0, 9, 0, 0, 2, 8, 0, 4]
R8 = [1, 0, 0, 0, 0, 8, 0, 0, 0]
R9 = [0, 0, 2, 3, 9, 4, 1, 0, 5]


Gemini の回答は以下の通りです。

ここから======
数独ソルバーを高速化するために、いくつかの最適化手法を取り入れたPython3プログラムを提案します。

**1. 問題の表現**

与えられた問題を効率的に処理するために、NumPy配列を使用します。NumPyは、数値計算に特化したライブラリであり、高速な配列操作を提供します。

```python
import numpy as np

puzzle = np.array([
  [3, 0, 0, 7, 4, 0, 5, 2, 0],
  [0, 2, 8, 9, 0, 0, 0, 0, 0],
  [0, 4, 5, 0, 0, 0, 9, 0, 3],
  [4, 5, 0, 6, 0, 7, 0, 0, 9],
  [9, 0, 0, 0, 2, 3, 0, 0, 1],
  [0, 0, 0, 8, 5, 9, 3, 4, 7],
  [5, 0, 9, 0, 0, 2, 8, 0, 4],
  [1, 0, 0, 0, 0, 8, 0, 0, 0],
  [0, 0, 2, 3, 9, 4, 1, 0, 5]
])
```

**2. 制約条件のチェック**

各セルに数字を配置する際に、行、列、3x3ブロックの制約条件を満たしているかを効率的にチェックする関数を実装します。

```python
def is_valid(puzzle, row, col, num):
  # 行のチェック
  if num in puzzle[row]:
    return False

  # 列のチェック
  if num in puzzle[:, col]:
    return False

  # 3x3ブロックのチェック
  start_row, start_col = 3 * (row // 3), 3 * (col // 3)
  if num in puzzle[start_row:start_row + 3, start_col:start_col + 3]:
    return False

  return True
```

**3. 再帰的なバックトラッキング**

数独を解くために、再帰的なバックトラッキングアルゴリズムを使用します。

```python
def solve_sudoku(puzzle):
  for row in range(9):
    for col in range(9):
      if puzzle[row, col] == 0:
        for num in range(1, 10):
          if is_valid(puzzle, row, col, num):
            puzzle[row, col] = num
            if solve_sudoku(puzzle):
              return True
            else:
              puzzle[row, col] = 0
        return False
  return True
```

**4. 実行と結果の表示**

数独ソルバーを実行し、結果を表示します。

```python
if solve_sudoku(puzzle):
  print(puzzle)
else:
  print("解が見つかりませんでした。")

**高速化のポイント**

* **NumPyの活用:** NumPy配列を使用することで、高速な配列操作が可能になります。
* **制約条件の効率的なチェック:** 制約条件を効率的にチェックすることで、無駄な探索を減らします。
* **バックトラッキングの最適化:** バックトラッキングアルゴリズムを最適化することで、探索時間を短縮します。
(以下省略)
======ここまで


入門者にとって、かなり洗練されたプログラムが提示されました。

・ 配列を扱うために NumPy を使い、 array() で ndarray オブジェクトを生成する。
・ 条件判定に、 if num in ndarryaオブジェクトから抽出したもの を使う。
・ 再帰的呼び出し(バックトラッキングアルゴリズムと説明されている)で数値を埋めていく。

このプログラムは1つ解が見つかったら終了するので、以前作成したプログラムを解が見つかったら exit()で終了するようにして実際に実行してみました。

前のプログラム:
real 0m40.165s
user 0m40.147s
sys 0m0.017s


Geminiが提示したプログラム:
real 0m0.446s
user 0m0.637s
sys 0m0.042s


数独プログラムなので至るところで作成されて公開されているので生成AIが高速化されたプログラムを教えてくれると思いましたが、ここまで高速だったとは「衝撃的」です。

入門者は、すでに行ったように作成を少し助けてもらう事やdocstring などを生成してもらう場合に限定して生成AIを使ったほうが良さそうですね。
今回の場合のように全面的にプログラム作成に使ってしまった場合は、その動きを正しく理解する必要があると思いました。

というわけで、入門者として生成されたプログラムの説明を試みました。

まず、問題を2次元配列として考えるために NumPy を利用していますね。その、array()で生成されるndarrayオブジェクトにより、
・ 配列の行は、puzzle[row]  。
・ 配列の列は、puzzle[ : ,col]  。
・ 3行3列の部分配列の取り出しは、puzzle[row:row+3 , ocl:col+3 ] 。

で得られます。

これによって、is_valid()関数の判定で、
if num in puzzle[....]: が使えるようになり、行、列、3x3ブロックのなかに数値 num があるかどうかの判定ができるので分かりやすくなりますね。
ちなみに、3*(row//3) は切り捨て割り算なので、rowが 0~2 なら 0, 3~5 なら 3, 6-8 なら 6 となり数独のブロックに使えます。

入門者にとって難しいのは、「バックトラッキング」 solve_sudoku(puzzle) です。

まず、大切なのは Pytnon の関数の引数は「参照渡し」であることです。
そのため、puzzle のある要素 puzzle[row,col] の値が 0 の時、
puzzle[row,col] = num  のように値を代入したり、
その値代入が条件を満たさなかった場合に、
puzzle[row,col] = 0 のように値の代入をキャンセルしてもとの値 0 に戻すことができるわけですね。

外側のfor ループでrow(行) が 0から8まで、2番目のfor ループでcol(列) が 0から8まで繰り返して、
puzzle[row,col]の値が 0 でなければなにもしないで次に行き、
0 の場合は、
3番目のfor ループで num に 1から9まで値をpuzzle[row,col]に入れて、その時点で条件がクリア (is_valid()がTrue) できているときに、
puzzle[row,col]にnumを代入して、再帰的に solve_sudoku(puzzle) を呼び出すと、
今度は前に見つかった値が0の場所に仮の値が入っているので、次に値が0になるところまでrow、col を進めて、
同じ事を繰り返すわけです。

最後まで仮の値に矛盾がなければ True で帰って、穴埋め完了になり、矛盾が生まれたら値を 0 に戻して、次の num を試すのですね。

一見、外側の row ループや、2番目の col ループで繰り返すみたいに見えますが、
値をどんどん入れて行ったときに再帰的に呼び出した solve_sudoku() の中で、
すでに値が設定された要素をスキップして、次の値が0の要素を探すためのループと解釈できそうです。

0の所に値をどんどん入れて行って最後のsolve_sudoku() 呼び出しのとき値がすべて 0 でないので最後の行で True で帰るので、
次々に solve_sudoku()が True で帰って 9 行目の return Trueで終了するようです。
最後から2行目の return False は、解が無い場合の保険ですね。
設定する値は必ず 1~9 の中にある(Trueで帰る)前提でプログラムが作られているようです。

初心者なので、再帰的呼び出しが多くなりすぎるので動かないのではと思ってしまいそうなのと、このようなプログラムを作るとかなりの頻度でバグが発生しそうで、しかもバグが発生した場合に修正に困難が予想されるのでこのようなプログラムに辿り着ける可能性はほぼないような気がしました。

気になるのは、どうしてこのように高速になったのかです。
・ solve_sudoku() のアルゴリズム
・ NumPy の ndarray オブジェクトの使用
が考えられます。

そこで、次回 NumPy を使わない場合を試してみることにします。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Raspberry Pi に、Python 3.13.3 をインストールする。

2025-04-09 22:26:30 | Python
予定通り、2025-04-09(日本時間)に Python 3.13.3 がリリースされました。

https://www.python.org/downloads/release/python-3132/
(以下、Google Chromeで翻訳)
ここから======
Python 3.13.3
発売日: 2025年4月8日

これはPython 3.13の3回目のメンテナンスリリースです。
Python 3.13 は Python プログラミング言語の最新のメジャー リリースであり、Python 3.12 と比較して多くの新機能と最適化が含まれています。3.13.3 は最新のメンテナンス リリースであり、3.13.2 以降、約 320 件のバグ修正、ビルドの改善、ドキュメントの変更が含まれています。

======ここまで

ソースはこの中の以下のものです。(XZ圧縮版)
https://www.python.org/ftp/python/3.13.3/Python-3.13.3.tar.xz
https://www.python.org/ftp/python/3.13.3/Python-3.13.3.tar.xz.asc
MD5 8bb5f0b8c9d9d7b87d7d98510e8d58e5

$ wget https://www.python.org/ftp/python/3.13.3/Python-3.13.3.tar.xz
--2025-04-09 00:42:30-- https://www.python.org/ftp/python/3.13.3/Python-3.13.3.tar.xz
Resolving www.python.org (www.python.org)... 2a04:4e42:400::223, 2a04:4e42:600::223, 2a04:4e42::223, ...
Connecting to www.python.org (www.python.org)|2a04:4e42:400::223|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 22654240 (22M) [application/octet-stream]
Saving to: ‘Python-3.13.3.tar.xz’

Python-3.13.3.tar.x 100%[===================>] 21.60M 39.4MB/s in 0.5s

2025-04-09 00:42:31 (39.4 MB/s) - ‘Python-3.13.3.tar.xz’ saved [22654240/22654240]

$

$ wget https://www.python.org/ftp/python/3.13.3/Python-3.13.3.tar.xz.asc
--2025-04-09 00:44:27-- https://www.python.org/ftp/python/3.13.3/Python-3.13.3.tar.xz.asc
Resolving www.python.org (www.python.org)... 2a04:4e42:600::223, 2a04:4e42::223, 2a04:4e42:200::223, ...
Connecting to www.python.org (www.python.org)|2a04:4e42:600::223|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 963 [application/octet-stream]
Saving to: ‘Python-3.13.3.tar.xz.asc’

Python-3.13.3.tar.x 100%[===================>] 963 --.-KB/s in 0s

2025-04-09 00:44:27 (23.3 MB/s) - ‘Python-3.13.3.tar.xz.asc’ saved [963/963]

$

$ gpg --verify Python-3.13.3.tar.xz.asc
gpg: assuming signed data in 'Python-3.13.3.tar.xz'
gpg: Signature made Tue 08 Apr 2025 18:09:21 BST
gpg: using RSA key 7169605F62C751356D054A26A821E680E5FA6305
gpg: Good signature from "Thomas Wouters <thomas@python.org>" [unknown]
gpg: aka "Thomas Wouters <thomas@xs4all.nl>" [unknown]
gpg: aka "Thomas Wouters <twouters@google.com>" [unknown]
gpg: aka "Thomas Wouters <thomas.wouters.prive@gmail.com>" [unknown]
gpg: aka "Thomas Wouters <thomaswout@gmail.com>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 7169 605F 62C7 5135 6D05 4A26 A821 E680 E5FA 6305
$

$ md5sum Python-3.13.3.tar.xz; echo '8bb5f0b8c9d9d7b87d7d98510e8d58e5'
8bb5f0b8c9d9d7b87d7d98510e8d58e5 Python-3.13.3.tar.xz
8bb5f0b8c9d9d7b87d7d98510e8d58e5
$

ダウンロードしたファイルはこのように基本的な確認をすることをお勧めします。

Python3をインストールしている環境を設定します。ここでは、python3.sh でまとめてあります。
$ source python3.sh

早速、インストールしてみましょう。
$ tar xvf Python-3.13.3.tar.xz

$ cd Python-3.13.3

$ ./configure --prefix=/usr/local/python --with-readline --enable-shared --enable-optimizations
checking build system type... aarch64-unknown-linux-gnu
checking host system type... aarch64-unknown-linux-gnu
checking for Python interpreter freezing... ./_bootstrap_python
checking for python3.13... python3.13
checking Python for regen version... Python 3.13.2
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking MACHDEP... "linux"
..................................................
configure: creating ./config.status
config.status: creating Makefile.pre
config.status: creating Misc/python.pc
config.status: creating Misc/python-embed.pc
config.status: creating Misc/python-config.sh
config.status: creating Modules/Setup.bootstrap
config.status: creating Modules/Setup.stdlib
config.status: creating Modules/ld_so_aix
config.status: creating pyconfig.h
configure: creating Modules/Setup.local
configure: creating Makefile
$

$ time make
Running code to generate profile data (this can take a while):
# First, we need to create a clean build with profile generation
# enabled.
make profile-gen-stamp
................................................................................
The necessary bits to build these optional modules were not found:
_dbm
To find the necessary bits, look in configure.ac and config.log.

Checked 112 modules (33 built-in, 77 shared, 1 n/a on linux-aarch64, 0 disabled, 1 missing, 0 failed on import)
make[1]: Leaving directory '/home/espiya/src/Python-3.13.3'

real 51m30.279s
user 49m11.255s
sys 1m35.573s

$

$ su
# make install
.................................................................................
Processing /tmp/tmp194d334c/pip-25.0.1-py3-none-any.whl
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 24.3.1
Uninstalling pip-24.3.1:
Successfully uninstalled pip-24.3.1
Successfully installed pip-25.0.1
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.
#

pip も自動的にアップデートされました。

環境変数も設定済みですので、バージョンの確認を行います。

$ python3 --version
Python 3.13.3
$ python3
Python 3.13.3 (main, Apr 9 2025, 01:53:38) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> quit()
$


今回も無事にインストールできました。こちらのブログでは、今後 Python 3.13.3 を使います。

補足ですが、こちらの環境ではすでに3.13.2 とかインストール済みなので特に問題なくインストールできていますが、初めての場合でうまくできない場合は、

https://blog.goo.ne.jp/espiya/e/fdf200d42183170e14bd374987749a7d

などを参照して必要なライブラリ等を事前にインストールしておく必要があります。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

入門者が、Python プログラムの高速化に挑戦する。

2025-04-02 23:50:35 | Python
以前 Python3 で数独のプログラムを作りました。
https://blog.goo.ne.jp/espiya/e/31cfcafc2c57e4b98612fbe10b9266ad

しかし、Raspberry Piなので非常に実行時間がかかってしまいました。そこで、このプログラムを Cython に直して実行してみることにしました。
Python3 プログラムの中から、関数定義部分を取り出して Cython に変換すると思うのですが、ここで生成AIを利用することにします。

プロンプトは単純で、
「以下のPythonプログラムを高速化するために、Cythonプログラムに変換してください。
 (以下、import itertools と 関数定義をいれました。) 」

Google Gemini と Microsoft Copilot で試してみましたが、うまく行きませんでした。
詳しくは書きませんが、今回のプログラムのように関数の引数にリストを使うと変換されたCythonプログラムが何故かエラーになってしまうのです。

そこで プログラムの中で1から9までの数字が重複無く含まれているかを判定する関数に狙いをつけてPythonプログラムを修正することにしました。

つまり、

def check_list(b):
  """
  リストbの要素が重複なく1から9まで含まれているかを判定する関数
  Args:
    b: 判定対象のリスト
  Returns:
    bool: 条件を満たす場合はTrue、満たさない場合はFalse
"""

  # 要素数が9でない場合、Falseを返す
  if len(b) != 9:
    return False

  # 要素が1から9の範囲に含まれていないか、重複があるかを確認
  return set(b) == set(range(1, 10))

の関数を高速化すれば、プログラムが高速化できそうです。
やはり、set()が遅いのかもしれません。そこで、引数のリストの長さは9に固定なので判定は省略して、
VAL という「タプル」を用意(2のi乗にしてみました。0番目(値が入っていない状態)だけ0にしました。タプルを作るときに括弧で囲っていません。
これで、すべての要素を加えて 511 になるかどうかをチェックすることにしました。
ちょっと怪しいアルゴリズムのような気がしますが、可能性のある解はすべて出力するので、その中で正しいものを選べるので大丈夫です。

def check_list(b):
  VAL = 0, 1, 2, 4, 8, 16, 32, 64, 128, 256
  check_v = VAL[b[0]] + VAL[b[1]] + VAL[b[2]] + VAL[b[3]] + VAL[b[4]] + VAL[b[5]] + VAL[b[6]] + VAL[b[7]] + VAL[b[8]]

  # 要素が1から9の範囲に含まれていないか、重複があるかを確認
  return check_v == 511

プログラムの速度を比較してみます。が、以前の問題は遅いので、もう少し簡単な3分ぐらいで解ける問題を探してそれに変更しました。

$ time python3 sudoku.py
Question:
0 6 0 | 0 9 0 | 0 8 0
3 0 0 | 0 5 0 | 0 9 4
0 9 4 | 0 6 0 | 5 7 0
------+-------+-------
0 0 7 | 0 0 0 | 9 0 0
9 0 0 | 1 0 5 | 0 2 6
0 5 0 | 9 2 0 | 4 0 0
------+-------+-------
7 0 5 | 4 0 9 | 2 0 1
8 2 9 | 0 1 0 | 0 4 7
4 0 0 | 3 7 2 | 0 0 9

.......... 途中省略 ................

5 6 2 | 7 9 4 | 1 8 3
3 7 8 | 2 5 1 | 6 9 4
1 9 4 | 8 6 3 | 5 7 2
------+-------+-------
2 4 7 | 6 3 8 | 9 1 5
9 8 3 | 1 4 5 | 7 2 6
6 5 1 | 9 2 7 | 4 3 8
------+-------+-------
7 3 5 | 4 8 9 | 2 6 1
8 2 9 | 5 1 6 | 3 4 7
4 1 6 | 3 7 2 | 8 5 9
=== END ===

real 2m58.681s
user 2m58.445s
sys 0m0.128s

$ time python3 sudoku-mod.py
Question:
,,,,,,,,,, 途中省略 ,,,,,,,,,,,,,,,,,,,,,,,

------+-------+-------
7 3 5 | 4 8 9 | 2 6 1
8 2 9 | 5 1 6 | 3 4 7
4 1 6 | 3 7 2 | 8 5 9
=== END ===

real 1m12.566s
user 1m12.377s
sys 0m0.093s

大体、2倍ぐらい速くなっています。やはり、縦とブロックが条件を満たしているかの判定が高速化の鍵を握っていますね。
この例では答えも一つで、一応修正はうまくいきました。

Pythonプログラム入門の一環なので、タプルを使ってみることができて良かったです。

まもなく、Python 3.13 のアップデートがあるので、その話題にも触れたいと思います。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Raspberry Pi に、 Python 3.13.2 をインストールする。

2025-02-05 14:50:41 | Python
PEP 719 にあるように、

PEP 719 – Python 3.13 Release Schedule
https://peps.python.org/pep-0719/

2025-02-05(日本時間) に Python 3.13.2 がリリースされました。

https://www.python.org/downloads/release/python-3132/
(以下、Google Chromeで翻訳)
ここから======
Python 3.13.2
発売日: 2025年2月4日

これはPython 3.13の2回目のメンテナンスリリースです。
Python 3.13 は Python プログラミング言語の最新のメジャー リリースであり、Python 3.12 と比較して多くの新機能と最適化が含まれています。3.13.2 は最新のメンテナンス リリースであり、3.13.1 以降、約 250 件のバグ修正、ビルドの改善、ドキュメントの変更が含まれています。

======ここまで

ソースはこの中の以下のものです。

https://www.python.org/ftp/python/3.13.2/Python-3.13.2.tar.xz

早速、Raspberry Pi にソースをダウンロードしてみます。

$ wget https://www.python.org/ftp/python/3.13.2/Python-3.13.2.tar.xz
--2025-02-04 23:55:35-- https://www.python.org/ftp/python/3.13.2/Python-3.13.2.tar.xz
Resolving www.python.org (www.python.org)... 2a04:4e42:8c::223, 146.75.112.223
Connecting to www.python.org (www.python.org)|2a04:4e42:8c::223|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 22621108 (22M) [application/octet-stream]
Saving to: ‘Python-3.13.2.tar.xz’

Python-3.13.2.tar.x 100%[===================>] 21.57M 39.0MB/s in 0.6s

2025-02-04 23:55:35 (39.0 MB/s) - ‘Python-3.13.2.tar.xz’ saved [22621108/22621108]

$ wget https://www.python.org/ftp/python/3.13.2/Python-3.13.2.tar.xz.asc
--2025-02-04 23:55:58-- https://www.python.org/ftp/python/3.13.2/Python-3.13.2.tar.xz.asc
Resolving www.python.org (www.python.org)... 2a04:4e42:8c::223, 146.75.112.223
Connecting to www.python.org (www.python.org)|2a04:4e42:8c::223|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 963 [application/octet-stream]
Saving to: ‘Python-3.13.2.tar.xz.asc’

Python-3.13.2.tar.x 100%[===================>] 963 --.-KB/s in 0s

2025-02-04 23:55:58 (23.0 MB/s) - ‘Python-3.13.2.tar.xz.asc’ saved [963/963]

$

$ gpg --verify Python-3.13.2.tar.xz.asc
gpg: assuming signed data in 'Python-3.13.2.tar.xz'
gpg: Signature made Tue 04 Feb 2025 18:44:53 GMT
gpg: using RSA key 7169605F62C751356D054A26A821E680E5FA6305
gpg: Good signature from "Thomas Wouters <thomas@python.org>" [unknown]
gpg: aka "Thomas Wouters <thomas@xs4all.nl>" [unknown]
gpg: aka "Thomas Wouters <twouters@google.com>" [unknown]
gpg: aka "Thomas Wouters <thomas.wouters.prive@gmail.com>" [unknown]
gpg: aka "Thomas Wouters <thomaswout@gmail.com>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 7169 605F 62C7 5135 6D05 4A26 A821 E680 E5FA 6305
$

スケジュール通りですね。早速インストールしてみましょう。3.13.1 の時と同じようにしてみます。

$ tar xvf ......../Python-3.13.2.tar.xz

$ cd Python-3.13.2
$
$ ./configure --prefix=/usr/local/python --with-readline --enable-shared --enable-optimizations

例によって、Raspberry Piでは時間がかかるので time コマンドで計測します。

$ time make
.............

The necessary bits to build these optional modules were not found:
_dbm
To find the necessary bits, look in configure.ac and config.log.

Checked 112 modules (33 built-in, 77 shared, 1 n/a on linux-aarch64, 0 disabled, 1 missing, 0 failed on import)
make[1]: Leaving directory '......................espiya/src/Python-3.13.2'

real 51m6.586s
user 48m55.436s
sys 1m31.861s
$


やはり、50分以上かかりますね。

$ su

# make install

Python3 を使うための環境変数設定は、ここでは python3.sh にしてあるので、

$ source python3.sh
$ which
/usr/local/python/bin/python3
$
$ python3
Python 3.13.2 (main, Feb 5 2025, 00:55:10) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>


今後は、 Python 3.13.2 を使う事にします。


さて、Python3で for 文とか入れると、
>>> for i in range(3):
... print(i)
...
0
1
2
>>>
のようになりますが、プロンプト >>> で、上矢印キーを押すと

>>> for i in range(3):
... print(i)
のようにいっぺんに出てくるのは、3.13 の特徴です。これは、readline や ncurses を使っていると思われます。

別のところで同様なインストールをしたとき、readline と ncurses でエラーがでてしまいました。
これは、readline と ncurses も事前にソースからインストールしておいて、Python 3.13 をビルドすると途中でエラーになるような現象でした。
そのときは make 時に、readline と ncurses のモジュールがないというメッセージがでていました。
記録していたわけではないのでうろ覚えですが、これにはまると中々抜け出せそうもないので、そんなときはおとなしくシステムのものを使う事をお勧めします。

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Python 3.13.1 で、試しに Cython を使って見る。

2025-01-07 15:40:40 | Python
以前の記事、
https://blog.goo.ne.jp/espiya/e/cf058105a1d29877e483a3bd007b4039

では、インストールした Python 3.13 に Cython をインストールしておきました。Papsberry Pi は遅いので Cython の様な高速化は魅力的です。

Welcome to Cython's Developmentation
https://cython.readthedocs.io/en/stable/index.html

そこで、年末年始の隙間時間を利用して、前回インストールした Cython を使って見ます。
全く使ったことがないので、とりあえず次のものに出ていたプログラムを使います。

Faster code via static typing
https://cython.readthedocs.io/en/latest/src/quickstart/cythonize.html

このページでは、Pure Python と Cython の変更点がわかるようになっています。Pythonは変数の値の型が決まっていないので型変換に時間がかかるという考えから、Cython では型定義をするのが重要な変更点みたいです。

さて、この中の、integrate.py を Cython プログラムに変形したものが integrate_cy.pyx です。
関数の引数はそのまま型定義ができて、内部変数は cdef で定義するのですね。それ以外は変更していません。

$ cat integrate.py
def f(x):
   return x ** 2 - x

def integrate_f(a, b, N):
   s = 0
   dx = (b - a) / N
   for i in range(N):
     s += f(a + i * dx)
   return s * dx
$

$ cat integrate_cy.pyx
def f(double x):
   return x ** 2 - x

def integrate_f(double a, double b, int N):
   cdef int i
   cdef double s
   cdef double dx

   s = 0
   dx = (b - a) / N
   for i in range(N):
     s += f(a + i * dx)
   return s * dx
$


次にコンパイル?するために、setup.py を作ります。色々な所を参考にして適当に作りました。

$ cat setup.py
from distutils.core import setup, Extension
from Cython.Build import cythonize

ext = Extension("integrate", sources=["integrate_cy.pyx"], include_dirs=['.'])
setup(name="integrate", ext_modules=cythonize([ext]))

$

コンパイルします。
$ python3 setup.py build_ext --inplace
省略
$

これによって、

./build/
integrate.cpython-313-aarch64-linux-gnu.so
integrate_cy.c


が作成されました。ディレクトリ build の中身は以下の通りです。

$ ls -R build
build:
lib.linux-aarch64-cpython-313 temp.linux-aarch64-cpython-313

build/lib.linux-aarch64-cpython-313:
integrate.cpython-313-aarch64-linux-gnu.so

build/temp.linux-aarch64-cpython-313:
integrate_cy.o

$

Cython で作成されたライブラリ integrate を使って、以下のプログラム test001.py を動かすことができます。

$ cat test001.py
from integrate import f, integrate_f

if __name__ == "__main__":
   result = integrate_f(0.0, 2.0, 2000000)
   print(result)
$


比較用に、Pythonのプログラム test002.py も用意します。integrate.py の2つの関数を陽に定義しておきました。

$ cat test002.py
def f(x):
   return x ** 2 - x

def integrate_f(a, b, N):
   s = 0
   dx = (b - a) / N
   for i in range(N):
     s += f(a + i * dx)
   return s * dx

result = integrate_f(0.0, 2.0, 2000000)
print(result)
$

2つを実行して速度を比較します。

$ time python3 test001.py
0.6666656666670076

real 0m0.556s
user 0m0.543s
sys 0m0.012s

$ time python3 test002.py
0.6666656666670076

real 0m1.136s
user 0m1.128s
sys 0m0.009s
$


実際に2倍少し早くなっていますね。

今回とりあえず Cython を使ってみました。
必要な修正もあまりないので有用そうなので今後ももう少し調べてみたいと思います。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

スパムメールの傾向をまとめて見る。

2024-12-30 09:30:10 | その他
sendmail を扱っていると、メールのヘッダーが気になります。そんな中で、今スパムメールがどうなっているか気になりました。

年末なので、スパムメールの傾向をまとめてみました。2024-12-28 に、個人的なメールアドレスに来た91通です。

ここに出てくる固有名詞は誘導目的なので実際のものとは何の関係もありません。

スパムメールなので内容はどうでもよく、「ヘッダーFrom」を中心に集めてみました。

スパムメールなので、ヘッダーFromに差出人メールアドレスのドメイン名以外に差出人を表す名前でまとめます。メールアドレスの仕組みが分からないと引っかけるために名前の方が重要ですね。
Subject: の文面抜粋も追記してみます。

改めて分かったのは、次の点です。

・ ヘッダーFrom に改行文字を入れるものもある。
・ ヘッダーDate で +0900 以外のものがほとんど。 特に +0800 が多い。

ヘッダーDate を替えるのは難しいみたいですね。話題になった nintendo.com も多数あり、 +0900 になっています。

以下は、From の名前、メールアドレスのドメイン名、Subject の抜粋、Date 情報、になっています。例によって、空白文字が1文字になるので見にくいのはご容赦ください。

ETC利用紹介サービス accounts.nintendo.com 解約予告のお知らせ Sat. 28 Dec 2024 00:xx:xx +0900
PayPay classi.jp 最大50,000円分のポイントをプレゼント Fri. 27 Dec 2024 23:xx:xx +0800
Amazon guoc.com 支払い方法の承認が必要 Sat. 28 Dec 2024 00:xx:xx +0800
Amazon jojo.net 支払い方法の承認が必要 Sat. 28 Dec 2024 00:xx:xx +0800
PayPya gilt.jp 2025年新年福袋キャンペーン! Sat, 28 Dec 2024 00:xx:xx +0800
佐川急便株式会社 cugs.com 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 01:xx:xx +0800
佐川急便株式会社 xhki.com 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 01:xx:xx +0800
Amazon.co.jp rkpzz.com Amazonから情報を更新 Sat. 28 Dec 2024 01:xx:xx +0800
PayPay creema.jp 最大18万円分のポイント Sat, 28 Dec 2024 01:xx:xx +0800
自動配信 ildl.com ETC利用照会サービスの重要なお知らせ Dec, 28 Dec 2024 02:xx:xx +0800
Amazon bcef.net 支払い方法の承認が必要 Sat. 28 Dec 2024 02:xx:xx +0800
Amazon ab.em-net.ne.jp Amazon重要情報についての通知 Fri, 27 Dec 2024 19:xx:xx GMT
PayPya costcojapan.jp (文字化け) Sat, 28 Dec 2024 03:xx:xx +0800
PayPay classi.jp PayPayで最大100,000円 Sat, 28 Dec 2024 03:xx:xx +0800
エスポカード accounts.nintendo.com 5,000エポスポイント Sat, 28 Dec 2024 04:xx:xx +0900
????? accounts.nintendo.com 口座取引制限のご案内 Sat, 28 Dec 2024 05:xx:xx +0900
????? accounts.nintendo.com 口座取引制限のご案内 Sat, 28 Dec 2024 05:xx:xx +0900
Amazon ab.em-net.ne.jp お支払方法に問題があり Fri, 27 Dec 2024 21:xx:xx GMT
PayPya hyumanet.jp PayPayで最大100,000円 Sat, 28 Dec 2024 06:xx:xx +0800
Amazon za.cyperhome.ne.jp Аmazonアカウントの情報更新 Fri, 27 Dec 2024 22:xx:xx GMT
Amazon cvgrp.com 支払い方法の承認が必要 Sat, 28 Dec 2024 06:xx:xx +0800
えきねっと mhwi.com えきねっとアカウントの自動退会処理 Sat, 28 Dec 2024 06:xx:xx +0800
Amazon ptoi.com 支払い方法の承認が必要 Sat, 28 Dec 2024 06:xx:xx +0800
Amazon wcrap.com 支払い方法の承認が必要 Sat, 28 Dec 2024 06:xx:xx +0800
Amazon udho.com 支払い方法の承認が必要 Sat, 28 Dec 2024 06:xx:xx +0800
Amazon jmeg.com 支払い方法の承認が必要 Sat, 28 Dec 2024 06:xx:xx +0800
PayPay costcojapan.jp 10,000円分のポイント Sat, 28 Dec 2024 06:xx:xx +0800
Amazon grdi.com 支払い方法の承認が必要 Sat, 28 Dec 2024 07:xx:xx +0800
自動配信 equo.com ETC利用照会サービスの重要なお知らせ Dec, 28 Dec 2024 07:xx:xx +0800
ヤマト運輸株式会社 xnow.net お荷物お届けのお知らせ Sat, 28 Dec 2024 07:xx:xx +0800
Amazon za.cyberhome.ne.jp あなたのAmazonアカウントはセキュリティ Fri, 27 Dec 2024 23:xx:xx GMT
PayPay sosekikan.co.jp 最大10,000円分のPayPayポイントバック Sat, 28 Dec 2024 07:xx:xx +0800
ヤマト運輸株式会社 chtah.net お荷物お届けのお知らせ Sat, 28 Dec 2024 07:xx:xx +0800
えきねっと dtie.com えきねっとアカウントの自動退会処理 Sat, 28 Dec 2024 07:xx:xx +0800
国税庁 onjq.com e-Tax税務署からの【未払い税金 Sat, 28 Dec 2024 07:xx:xx +0800
????? accounts.nintendo.com 口座取引制限のお知らせ Sat, 28 Dec 2024 09:xx:xx +0900
????? accounts.nintendo.com Vpass情報更新のご案内: Sat, 28 Dec 2024 09:xx:xx +0900
Amazon zyro.net 支払い方法の承認が必要 Sat, 28 Dec 2024 08:xx:xx +0800
佐川急便株式会社 rrpn.com 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 08:xx:xx +0800
Amazon fyrn.com 支払い方法の承認が必要 Sat, 28 Dec 2024 08:xx:xx +0800
Amazon.ne.jp enil.com 支払い方法の承認が必要 Sat, 28 Dec 2024 08:xx:xx +0800
ユーシーカード株式会社 xiykici.com 年終キャッシュバックのお知らせ Sat, 28 Dec 2024 10:xx:xx +0900
PayPay glaq.com (文字化け) Sat, 28 Dec 2024 09:xx:xx +0800
Amazon.co.jp krtt.net Amazonプライム会費のお支払い方法に問題 Sat, 28 Dec 2024 09:xx:xx +0800
東京電力エナジーパートナー appl.net 未払いの電気料金についてご連絡 Sat, 28 Dec 2024 09:xx:xx +0800
PayPay hyumannet.jp (文字化け) Sat, 28 Dec 2024 09:xx:xx +0800
東京電力エナジーパートナー wvht.net 未払いの電気料金についてご連絡 Sat, 28 Dec 2024 09:xx:xx +0800
株式会社NTTドコモ ewngy.cn ご請求金額確定のご案内 Sat, 28 Dec 2024 09:xx:xx +0800
TS CUBIC CARD service.vrglj.cn お支払い予定金額のご案内 ENEOSカード Sat, 28 Dec 2024 10:xx:xx +0900
Amazon ndix.net 支払い方法の承認が必要 Sat, 28 Dec 2024 10:xx:xx +0800
Apple iwpy.com Appleサポートセンターより、重要な Sat, 28 Dec 2024 10:xx:xx +0800
Amazon qfcl.com 支払い方法の承認が必要 Sat, 28 Dec 2024 10:xx:xx +0800
PayPay hyumanet.jp 最大30,000円分のPayPayポイント Sat, 28 Dec 2024 10:xx:xx +0800
Amazon ycmc.com 支払い方法の承認が必要 Sat, 28 Dec 2024 11:xx:xx +0800
Amazon.co.jp jjce.net 支払い方法の承認が必要 Sat, 28 Dec 2024 11:xx:xx +0800
Amazon glata.net 支払い方法の承認が必要 Sat, 28 Dec 2024 11:xx:xx +0800
Amazon jrbj.com 支払い方法の承認が必要 Sat, 28 Dec 2024 11:xx:xx +0800
PayPay creema.jp 最大100,000円分のポイントをゲット Sat, 28 Dec 2024 11:xx:xx +0800
三井住友カード株式会社 accounts.nintendo.com 口座取引制限のお知らせ: Sat, 28 Dec 2024 13:xx:xx +0900
ヤマト運輸株式会社 blbd.com お荷物お届けのお知らせ Sat, 28 Dec 2024 12:xx:xx +0800
マスター カード zumi.net マスター カード認証通知 Sat, 28 Dec 2024 12:xx:xx +0800
Amazon fundsle.com 支払い方法の承認が必要 Sat, 28 Dec 2024 12:xx:xx +0800
PayPay cbel.com (文字化け) Sat, 28 Dec 2024 12:xx:xx +0800
セゾンカード ntt-finance.co.jp Netアンサーのアカウント確認 Sat, 28 Dec 2024 13:xx:xx +0900
PayPay creema.jp (文字化け) Sat, 28 Dec 2024 13:xx:xx +0800
佐川急便株式会社 xhba.com 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 13:xx:xx +0800
Amazon.co.jp fahn.com ご利用の Amazon アカウントを一時保留 Sat. 28 Dec 2024 14:xx:xx +0800
佐川急便株式会社 voeed.com 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 14:xx:xx +0800
マスター カード hbng.com マスター カード認証通知 Sat, 28 Dec 2024 14:xx:xx +0800
佐川急便株式会社 vgeo.net 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 14:xx:xx +0800
Amazon.co.jp creema.jp Amazonプライム会員のお支払い方法 Sat, 28 Dec 2024 14:xx:xx +0800
Amazon lkok.com 支払い方法の承認が必要 Sat, 28 Dec 2024 14:xx:xx +0800
PayPay costocojapan.jp (文字化け) Sat, 28 Dec 2024 14:xx:xx +0800
Amazon sanc.com 支払い方法の承認が必要 Sat, 28 Dec 2024 14:xx:xx +0800
PayPay glaq.com (文字化け) Sat, 28 Dec 2024 15:xx:xx +0800
ETC利用照会サービス accounts.nintendo.com 解約予告のお知らせ Sat, 28 Dec 2024 16:xx:xx +0900
Amazon poma.com 支払い方法の承認が必要 Sat, 28 Dec 2024 15:xx:xx +0800
Apple pchw.net Appleサポートセンターより、重要な Sat, 28 Dec 2024 16:xx:xx +0800
セゾンカード saisoncard.co.jp セゾンカード ご利用確認のお願い Sat, 28 Dec 2024 17:xx:xx +0800
Amazon ipdl.com 支払い方法の承認が必要 Sat, 28 Dec 2024 18:xx:xx +0800
佐川急便株式会社 avfd.net 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 19:xx:xx +0800
..@docomo.ne.jp docomo.ne.jp 交通系IC suica・高速道路ETC Sat, 28 Dec 2024 05:xx:xx -0700
Amazon wmtw.com 支払い方法の承認が必要 Sat, 28 Dec 2024 20:xx:xx +0800
佐川急便株式会社 apjv.net 【重要】お荷物の配達について重要なお知らせ Sat. 28 Dec 2024 20:xx:xx +0800
ETC利用照会サービス accounts.nintendo.com 解約予告のお知らせ Sat, 28 Dec 2024 22:xx:xx +0900
Amazon wyex.com 支払い方法の承認が必要 Sat, 28 Dec 2024 21:xx:xx +0800
ヤマト運輸株式会社 dftr.com お荷物お届けのお知らせ Sat, 28 Dec 2024 22:xx:xx +0800
Amazon bdry.net 支払い方法の承認が必要 Sat, 28 Dec 2024 22:xx:xx +0800
Amazon glmi.net 支払い方法の承認が必要 Sat, 28 Dec 2024 22:xx:xx +0800
えきねっと igta.net えきねっとアカウントの自動退会処理 Sat, 28 Dec 2024 22:xx:xx +0800
PayPay glaq.com PayPay 新年開運キャンペーン Sat, 28 Dec 2024 23:xx:xx +0800

気になる .jp で Authentication-Results ヘッダーを見ると dmarc=fail でした。

また、期待していた SPF: Sender Policy Framework で送信元アドレスの偽証を検証する Received-SPF ヘッダーは、 SOFTFAIL が多くてもう少し時間がかかりそうな気がしました。

コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Raspberry Pi に Python 3.13.1 をインストールする。

2024-12-05 18:46:25 | Python
Python 3.13.1 がリリースされました。早速アップデートします。これで、Python 3.13 もメンテナンスリリースモードになりました。定期的にアップデートされていくと思います。

https://www.python.org/downloads/release/python-3131/ の冒頭は、以下のようです。

Python 3.13 は Python プログラミング言語の最新メジャー リリースであり、Python 3.12 と比較して多くの新機能と最適化が含まれています。 3.13.1 は最新のメンテナンス リリースで、3.13.0 以降の約 400 のバグ修正、ビルドの改善、ドキュメントの変更が含まれています。

早速ソースをダウンロードしましょう。

$ wget https://www.python.org/ftp/python/3.13.1/Python-3.13.1.tar.xz
$

$ md5sum Python-3.13.1.tar.xz;echo 80c16badb94ffe235280d4d9a099b8bc
80c16badb94ffe235280d4d9a099b8bc Python-3.13.1.tar.xz
80c16badb94ffe235280d4d9a099b8bc
$

$ wget https://www.python.org/ftp/python/3.13.1/Python-3.13.1.tar.xz.asc

$ gpg --verify Python-3.13.1.tar.xz.asc
gpg: assuming signed data in 'Python-3.13.1.tar.xz'
gpg: Signature made Tue 03 Dec 2024 19:06:34 GMT
gpg: using RSA key 7169605F62C751356D054A26A821E680E5FA6305
gpg: Good signature from "Thomas Wouters <thomas@python.org>" [unknown]
gpg: aka "Thomas Wouters <thomas@xs4all.nl>" [unknown]
gpg: aka "Thomas Wouters <twouters@google.com>" [unknown]
gpg: aka "Thomas Wouters <thomas.wouters.prive@gmail.com>" [unknown]
gpg: aka "Thomas Wouters <thomaswout@gmail.com>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 7169 605F 62C7 5135 6D05 4A26 A821 E680 E5FA 6305
$


12月3日にサインされています。3.13.0 の時と同じように make します。今回は time コマンドで時間を計ってみました。

$ tar xvf Python-3.13.1.tar.xz
$ cd Python-3.13.1/
$ ./configure --prefix=/usr/local/python --with-readline --enable-shared --enable-optimizations
..............................
configure: creating ./config.status
config.status: creating Makefile.pre
config.status: creating Misc/python.pc
config.status: creating Misc/python-embed.pc
config.status: creating Misc/python-config.sh
config.status: creating Modules/Setup.bootstrap
config.status: creating Modules/Setup.stdlib
config.status: creating Modules/ld_so_aix
config.status: creating pyconfig.h
configure: creating Modules/Setup.local
configure: creating Makefile
$
$ time make
........The necessary bits to build these optional modules were not found:
_dbm
To find the necessary bits, look in configure.ac and config.log.

Checked 112 modules (33 built-in, 77 shared, 1 n/a on linux-aarch64, 0 disabled, 1 missing, 0 failed on import)
make[1]: Leaving directory '/home/espiya/src/Python-3.13.1'

real 51m52.210s
user 49m17.303s
sys 1m36.002s
$


やはり、このRaspberry Pi では、52分くらいかかりますね。
一応、テストも行っておきます。

$ make test
........
21 tests skipped:
test.test_asyncio.test_windows_events
test.test_asyncio.test_windows_utils test.test_gdb.test_backtrace
test.test_gdb.test_cfunction test.test_gdb.test_cfunction_full
test.test_gdb.test_misc test.test_gdb.test_pretty_print
test_android test_dbm_ndbm test_devpoll test_free_threading
test_ioctl test_kqueue test_launcher test_msvcrt test_startfile

4 tests skipped (resource denied): test_winapi test_winconsoleio test_winreg test_winsound test_wmi

test_peg_generator test_tkinter test_ttk test_zipfile64

2 re-run tests:
test_trace test_zipfile

2 tests failed:
test_trace test_zipfile

451 tests OK.

Total duration: 13 min 28 sec
Total tests: run=44,581 failures=2 skipped=1,991
Total test files: run=476/478 failed=2 skipped=21 resource_denied=4 rerun=2
Result: FAILURE then FAILURE
make: *** [Makefile:2194: test] Error 2
$


test_zipfile の部分がエラーになっているところみたいです。
ほとんど問題なさそうなので、そのままインストールします。

$ make install

$
$ python3 --version
Python 3.13.1
$


通常の使い方では、これでよさそうです。
今までの経緯から推測して、おそらく2か月に一度くらいのアップデートがあって、現在テスト中の 3.14 を待つことになるようです。今後は 3.13.1 を使用します。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Raspberry Pi に、llvm の lld をインストールする。Cython も入れてみる。

2024-11-28 22:05:12 | インストールと設定
前回インストールした llvm , clang に続いて、lld もインストールしてみました。

https://lld.llvm.org/

によれば、(DeepL で翻訳)

LLDはLLVMプロジェクトのリンカーで、システム・リンカーのドロップイン・リプレースメントであり、システム・リンカーよりもはるかに高速に動作する。また、ツールチェーン開発者にとって便利な機能も提供する。

ですね。

lld 単独で build しようとすると、うまくいきませんでした。llvm は基本的に llvm-project の中のものと密接に関連しているようで、
ここでも llvm-project-19.1.0.src/ の下で行う必要があるようです。しかも、新しい build 用ディレクトリを作成して build すると、llvm 関連も再び make しているようにみえたので、最初にbuildするときに使った build-proj ディレクトリを使うのがよさそうです。前回作成した build-proj ディレクトリを使います。

$ cd build-proj
$ cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_ENABLE_PROJECTS=lld -DCMAKE_INSTALL_PREFIX=/usr/local/python ../llvm
............
-- Configuring done (18.2s)
-- Generating done (39.1s)
-- Build files have been written to: /home/espiya/src/llvm-project-19.1.0.src/build-proj
$

$ make
.....................................
[100%] Built target yaml2obj
[100%] Built target ExampleIRTransforms
[100%] Built target Bye
[100%] Built target InlineAdvisorPlugin
[100%] Built target InlineOrderPlugin
[100%] Built target TestPlugin
[100%] Built target DoublerPlugin
[100%] Built target DynamicLibraryLib
[100%] Built target PipSqueak
[100%] Built target SecondLib
[100%] Built target benchmark
[100%] Built target benchmark_main
[100%] Built target llvm-locstats
$

# make install
......
-- Up-to-date: /usr/local/python/include/llvm/TargetParser/ARMTargetParserDef.inc
-- Up-to-date: /usr/local/python/include/llvm/TargetParser/AArch64TargetParserDef.inc
-- Up-to-date: /usr/local/python/include/llvm/TargetParser/RISCVTargetParserDef.inc
-- Installing: /usr/local/python/lib/cmake/llvm/LLVMConfigExtensions.cmake
#

$ which lld
/usr/local/python/bin/lld
$
$ lld --version
lld is a generic driver.
Invoke ld.lld (Unix), ld64.lld (macOS), lld-link (Windows), wasm-ld (WebAssembly) instead
$ ld.lld --version
LLD 19.1.0 (compatible with GNU linkers)
$


ここまででインストールできた、llvm を使って、Python 3.13.0 の --enable-experimental-jit オプション付きで build してみましが、やはりうまくいきませんでした。

しかたがないので、別の Python 高速化ツールを考えました。 Cython にしました。(以下は、 Firefox で翻訳しました。)

https://pypi.org/project/Cython/

Cython 言語を使用すると、Python 自体と同じくらい簡単に、Python 言語用の C 拡張機能を作成できます。 Cython は Pyrex をベースにしたソース コード トランスレータですが、より最先端の機能と最適化をサポートしています。

Cython 言語は Python 言語のスーパーセットです (ほぼすべての Python コードも有効な Cython コードです)。ただし、Cython はオプションの静的型付けをサポートしており、C 関数をネイティブに呼び出し、C++ クラスで操作し、変数とクラス属性で高速な C 型を宣言します。これにより、コンパイラーは Cython コードから非常に効率的な C コードを生成できます。

このため、Cython は、外部 C/C++ ライブラリ用のグルー コードや、Python コードの実行を高速化する高速 C モジュールを作成するのに理想的な言語になります。

ワンタイムビルドの場合には注意してください。 CI/テストの場合、PyPI で提供されるホイール パッケージのいずれかでカバーされておらず、当社が提供する純粋な Python ホイールが使用されていないプラットフォームでは、コンパイルされていない (遅い) バージョンの完全なソース ビルドよりも大幅に高速です。


こちらのインストールは pip3 が使えるので簡単です。本当に使えるかどうかはまだ分かりません。

$ pip3 install Cython
Defaulting to user installation because normal site-packages is not writeable
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting Cython
Downloading Cython-3.0.11-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl.metadata (3.2 kB)
Downloading Cython-3.0.11-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl (3.3 MB)
qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq 3.3/3.3 MB 14.8 MB/s eta 0:00:00
Installing collected packages: Cython
Successfully installed Cython-3.0.11
$ which cython
/home/espiya/.local/bin/cython
$ cython --version
Cython version 3.0.11
$


使い方は以下を参考にして、今後機会があれば試してみたいと思います。

https://cython.readthedocs.io/en/latest/src/tutorial/
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

Raspberry Pi に LLVM + Clang 19.1.0 をインストールする。

2024-11-15 23:07:37 | コンピュータ言語
Python3 のインストールでも分かるように、clang と llvm もこれからは必要そうです。
そこで、今使っている Raspberry Pi に llvm と clang をインストールしてみます。
最新のものは 19.1.0 でした。

先に、関連ありそうなパッケージを入れておきます。

# apt install cmake
# apt install ninja-buil
# apt install llvm llvm-dev
# apt install clang

$ /usr/bin/cmake --version
cmake version 3.25.1

CMake suite maintained and supported by Kitware (kitware.com/cmake).
$
$ /usr/bin/clang --version
Debian clang version 14.0.6
Target: aarch64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
$

ですね。

念のために、最初に cmake を最新にしておきます。
環境設定は例によって、python3.sh というファイル使います。

$ source ~/python3.sh

$ wget https://github.com/Kitware/CMake/releases/doload/v3.31.0/cmake-3.31.0.tar.gz
$ tar xvf cmake-3.31.0.tar.gz
$ cd cmake-3.31.0

$ ./configure --prefix=/usr/local/python
......
-- Configuring done (126.3s)
-- Generating done (2.9s)
-- Build files have been written to: /home/espiya/src/cmake/cmake-3.31.0
---------------------------------------------
CMake has bootstrapped. Now run gmake.
$


make でなくて gmake と言っていますが、

$ which gmake
/usr/bin/gmake
$ ls -l /usr/bin/gmake
lrwxrwxrwx 1 root root 4 Apr 10 2021 /usr/bin/gmake -> make
$

make コマンドです。 make して、インストールします。

$ gmake

# gmake install


確認します。

$ cmake --version
cmake version 3.31.0

CMake suite maintained and supported by Kitware (kitware.com/cmake).
$


これで、cmake は最新になりました。

これを使って、llvm と clang をインストールしてみます。実は、Raspberry Pi でこれは非常に大変で、色々ためしてみたのですが、中々うまくいかないので苦労しました。最終的には、

https://clang.llvm.org/get_started.html

を参考にしました。

$ wget https://github.com/llvm/llvm-project/releases/download/llvmorg-19.1.0/llvm-project-19.1.0.src.tar.xz
$ wget https://github.com/llvm/llvm-project/releases/download/llvmorg-19.1.0/llvm-project-19.1.0.src.tar.xz.sig
$
$ gpg --verify llvm-project-19.1.0.src.tar.xz.sig
gpg: assuming signed data in 'llvm-project-19.1.0.src.tar.xz'
gpg: Signature made Tue 17 Sep 2024 12:42:39 BST
gpg:      using RSA key D574BD5D1D0E98895E3BF90044F2485E45D59042
gpg: Good signature from "Tobias Hieta '<tobias@hieta.se>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg:      There is no indication that the signature belongs to the owner.
Primary key fingerprint: D574 BD5D 1D0E 9889 5E3B F900 44F2 485E 45D5 9042
$


$ tar xvf llvm-project-19.1.0.src.tar.xz
$
$ cd llvm-project-19.1.0.src
$ mkdir build-proj
$ cd build-proj


$ cmake -DLLVM_ENABLE_PROJECTS=clang -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local/python -G "Unix Makefiles" ../llvm
...........
-- Configuring done (52.2s)
-- Generating done (27.7s)
-- Build files have been written to: /home/espiya/src/llvm-project-19.1.0.src/build-proj
$


$ make
.............
[100%] Linking CXX static library ../../../lib/libbenchmark.a
[100%] Built target benchmark
[100%] Building CXX object third-party/benchmark/src/CMakeFiles/benchmark_main.ir/benchmark_main.cc.o
[100%] Linking CXX static library ../../../lib/libbenchmark_main.a
[100%] Built target benchmark_main
[100%] Copying llvm-locstats into /home/espiya/src/llvm-project-19.1.0.src/buil-proj/./bin
[100%] Built target llvm-locstats
$


このマシンでは、1日以上かかりました。 〇〇% と表示されるので一応目安になります。テストもできます。

$ make check-clang
...........
[100%] Running the Clang regression tests
llvm-lit: /home/espiya/src/llvm-project-19.1.0.src/llvm/utils/lit/lit/llvm/config.py:508: note: using clang: /home/espiya/src/llvm-project-19.1.0.src/build-proj/bin/clang

Testing Time: 3883.81s

Total Discovered Tests: 37989
Skipped : 10 (0.03%)
Unsupported : 150 (0.39%)
Passed : 37802 (99.51%)
Expectedly Failed: 27 (0.07%)
[100%] Built target check-clang
$

こちらも 1時間以上かかりました。

/usr/local/python へのインストール方法は書いていないのですが、普通に make で良さそうです。

# make install
......
-- Up-to-date: /usr/local/python/include/llvm/CodeGen
-- Installing: /usr/local/python/include/llvm/CodeGen/GenVT.inc
-- Up-to-date: /usr/local/python/include/llvm/TargetParser
-- Installing: /usr/local/python/include/llvm/TargetParser/ARMTargetParserDef.inc
-- Installing: /usr/local/python/include/llvm/TargetParser/AArch64TargetParserDef.inc
-- Installing: /usr/local/python/include/llvm/TargetParser/RISCVTargetParserDef.inc
-- Installing: /usr/local/python/lib/cmake/llvm/LLVMConfigExtensions.cmake
#

$ clang --version
clang version 19.1.0
Target: aarch64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/local/python/bin
$


これで、clang 19.1.0 が使えるようになりました。時間はかかりましたが、Raspberry Pi でもビルドできたのが良かったです。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする

入門者が、Python プログラミングにおいて、生成AI(Copilot)を使ってコメントとdocstring を付ける。

2024-10-30 18:11:29 | Python
以前紹介した、
PyFlo The beginners guide to becoming a Python programmer
https://pyflo.net/
の中で、「Guided Project 1」をクリックすると、
Flag Creater
https://pyflo.net/flag/
というものがありました。

文化の日も近いので、日の丸を文字で作るプログラムを作ってみました。
Wikipedia で日章旗を調べると、
縦を2とすると横が3、その中央にある円の直径が縦の 3/5 となっています。
縦を 2.0 とすると、横は 3.0 となり、 中央の円の半径は 2 * (3/5) / 2 = 0.6 となります。
半角文字の大きさの比率がだいたい縦:横 2:1 となるので、1行の文字数は旗の左下隅を X-Y平面の原点においたとして、
その座標は、
左上 (0,20) 、 右上 (60,20) 、 
左下 (0,0) 、 右下 (60,0)
としました。変換してそれぞれ、(0.0 , 2.0) 、(3.0 , 2.0)、 (0.0 , 0.0)、(3.0 , 0.0)になります。

これでプログラムを作ってみます。関数も使わない単純なものですが、このプログラムにコメントや docstring を入れるために、 Microsoft Copilot を使いました。

まず、docstring 生成を次のプロンプトで依頼しました。そのとき、プログラムがどのようなものかを簡単に説明する文を陽に入れてみました。

「次のPython プログラムの docstring を生成して下さい。
これは、日章旗を文字で生成するためのプログラムです。
日章旗は、縦の長さを2、幅の長さを3、中央の日の丸の半径を 0.6 になるように作成します。

w = 60
h = 20
a0 = '+' + '-'*(w-1) + '+'
a20 = '+' + '-'*(w-1) + '+'
a = '|' + ' '*(w-1) + '|'

print(a0)
for i in range(1,h):
   y = (h - i) / (h / 2)

   b = a[0]
   for j in range(1,w):
      x = j / (w / 3)

      if ( (x-1.5)**2 + (y-1.0)**2 < 0.36 ) :
         b += '*'
      else:
         b += a[j]
   b += a[-1]

   print(b)

print(a20) 」


Copilot の回答は以下の通りでした。

ここから======
もちろん、こちらがあなたのプログラムのためのdocstringです:

def draw_nisshoki():
   """
   This function prints the Japanese national flag (Nisshoki) using ASCII characters.

   The flag's proportions are a height to width ratio of 2:3, with a red circle (the sun)
   in the center. The circle's radius is 0.6, scaled appropriately to fit within the grid.

   The border of the grid is made up of '+' and '-' characters for the top and bottom,
   and '|' characters for the sides. The sun is drawn using '*' characters inside the grid.

   Variables:
   w (int): The width of the grid.
   h (int): The height of the grid.
   a0 (str): The top border of the grid.
   a20 (str): The bottom border of the grid.
   a (str): The side borders of the grid.

   The function uses nested loops to calculate the positions of the '*' characters
   that form the sun based on the coordinates (x, y) within the grid.
   The equation `( (x-1.5)**2 + (y-1.0)**2 < 0.36 )` is used to determine whether
   a particular point should be part of the sun shape or not.
   """
   w = 60
      .................
      (プロンプトで入力したプログラムなので途中省略)
      .................
   print(a20)

======ここまで


関数にされてしまいました。しかもなぜか英語でした。これは、docstring は、関数やクラスの中で使うかららしいです。 一応 DeepL で翻訳(少し修正あり)しておきます。

この関数は、日本の国旗(日章旗)をASCII文字で印刷します。

 国旗の縦横比は2:3で、中央に赤い円(太陽)がある。円の半径は0.6で、グリッドに収まるように適切に拡大縮小されています。

 グリッドの境界線は、上下に'+'と'-'、左右に'|'で構成されている。太陽はグリッドの内側に'*'文字を使って描かれます。

 変数

 w (int): グリッドの幅。
 h (int): グリッドの高さ。
 a0 (str): グリッドの上辺。
 a20 (str): グリッドの下端。
 a (str): グリッドのサイドボーダー。

 この関数は,ネストされたループを使用して,グリッド内の座標 (x, y) に基づいて太陽を形成する '*' 文字の位置を計算します.

 方程式 `( (x-1.5)**2 + (y-1.0)**2 < 0.36 )` は、特定の点が太陽の形に含まれるかどうかを決定するために使用されます。

プログラムの内容を、ほぼ正確に表してくれていますね。

そこで、今度はこのプロンプトの docstring を コメント にして再び Copilot にたずねました。

「次のPython プログラムを説明するための分かりやすいコメントをプログラムに追加して下さい。
これは、日章旗を文字で生成するためのプログラムです。
日章旗は、縦の長さを2、幅の長さを3、中央の日の丸の半径を 0.6 になるように作成します。
(この後のプログラムは同じなので省略)」


Copilot の回答は以下の通りでした。

ここから======
以下に、プログラムにコメントを追加しました。これで、各部分の動作がわかりやすくなると思います。

```python
# 幅と高さを設定
w = 60
h = 20

# 上部と下部の枠線を作成
a0 = '+' + '-'*(w-1) + '+'
a20 = '+' + '-'*(w-1) + '+'
# 空白の行を作成
a = '|' + ' '*(w-1) + '|'

# 上部の枠線を表示
print(a0)

# 高さ分のループを開始
for i in range(1, h):
   # y座標を計算(中心を基準にした相対位置)
   y = (h - i) / (h / 2)

   # 行の開始文字を設定
   b = a[0]
   # 幅分のループを開始
   for j in range(1, w):
      # x座標を計算(中心を基準にした相対位置)
      x = j / (w / 3)

      # 中心からの距離が半径0.6以内なら '*' を追加、それ以外は空白を追加
      if ( (x-1.5)**2 + (y-1.0)**2 < 0.36 ):
         b += '*'
      else:
         b += a[j]
   # 行の終了文字を追加
   b += a[-1]

   # 行を表示
   print(b)

# 下部の枠線を表示
print(a20)
```

このコメントが、プログラムの理解に役立つことを願っています!他に質問があれば教えてくださいね。

======ここまで


一言も伝えていないのに、プログラムだけから、

上枠(a0)、下枠(a20)と解釈したり、
「中心を基準にした相対位置」と解釈したり、
if 文で陽に 0.36 としか書いていないのにプロンプトから?「半径0.6」と解釈したりと、

しっかりとコメントしてくれています。これは良いですね。

以上、簡単なプログラムを作成して Copilot でコメントやdocstring を付けてもらいましたが、満足できるものでした。

ということは、Python 入門者は生成AIを活用して自分がプログラミングしたプログラムに対してコメントや docstring を付けてもらい、それを参考にしてさらに知識を得ることが、かなり有用であると言えそうです。

最後にプログラムを動作させたときの画像を表示しておきます。作成したプログラムは flag.py というファイルです。


docstring は、Python の有用な機能なのは、SimplePrograms で学ぶうちに理解しました。そうであるなら、初心者は生成AIを積極的に活用して docstring を使うという流れになるかもしれませんね。
コメント
  • X
  • Facebookでシェアする
  • はてなブックマークに追加する
  • LINEでシェアする