TikzをEmacsのOrgモードで使う

概要

TikZによるLaTeXグラフィックス | Stefan Kottwitz, 黒川 利明 を購入した。 TikZはやろうやろうと考えていたのでこれを気にある程度勉強したい。

書籍中のコードは PacktPublishing/LaTeX-graphics-with-TikZ: LaTeX graphics with TikZ, by Packt Publishing にある。

Emacsの環境

書籍のP.008に掲載されているコードは以下にある。

上記をEmacsのOrgモードのコードブロックで使えるようにする。ちょっと複雑になってしまうが、あとで実用的な方法を考えよう。

#+header: :file "images/v0ud5YVim1jv4.png"
#+header: :results raw :fit yes :border 0cm
#+header: :imagemagick t
#+header: :iminoptions -density 400
#+header: :imoutoptions -geometry 200 -flatten
#+begin_src latex :results file
  \begin{tikzpicture}
    \draw[thin,dotted] (-3,-3) grid (3,3);
    \draw[->] (-3,0) -- (3,0);
    \draw[->] (0,-3) -- (0,3);
  \end{tikzpicture}
#+end_src
v0ud5YVim1jv4.png

参考文献

Mergiraf: Gitのマージドライバー?

概要

MergirafTree-sitter を利用したgitのマージを補助するツールのようだ。

gitで他の開発者が実装したブランチをマージする際に開発箇所が被ると衝突の回避をする必要がある。gitがうまく解決してくれることがあるが、手動は気を使う作業になる。

Margiral はその衝突を回避するために構文(syntax)を考慮してマージ作業をしてくれるようだ。

gitやバージョン管理のツールはこれ以外にもいくつかあるので、併せて試してみたい。

参考文献

“Understanding Machine Learning” Lemma19.2 について

概要

(Shalev-Shwartz and Ben-David 2009) を読んでいる。ふと定理の数式を実験できないかと考えた。

lemma 19.2

詳細は省くが、以下のような数式がある。 これを実験できないか?

\[ \underset{S \sim \mathcal{D}^m}{\mathbb{E}}\left[\sum_{i: C_i \cap S=\emptyset} \mathbb{P}\left[C_i\right]\right] \leq \frac{r}{m e} \]

コード

\(\mathcal{D}^m\) を 0 から 1000000 の値を一様に出力する確率分布だとして実験する。

import numpy as np

def D(size, low=0, high=1000000):
    return np.random.randint(X_low, X_high, size)
def P(n, low=0, high=1000000):
    return n / (X_high - X_low)

m = 2000
r = 10
C = D((r, 10))

N = 100
lst_sum_P = []
for _ in range(N):
    sum_P = 0
    S = D(m)
    for i in range(r):
        if np.intersect1d(S, C[i]).size == 0:
            pass
        else:
            sum_P += P(C[i].size)
    lst_sum_P.append(sum_P)

np.mean(lst_sum_P) <= r / (m * np.e)
True

参考文献

Shalev-Shwartz, Shai, and Shai Ben-David. 2009. Understanding Machine Learning. Cambridge University Press. https://doi.org/10.1017/cbo9781107298019.

“Breaking CityHash64, MurmurHash2/3, wyhash, and more…” を読んだ

Breaking CityHash64, MurmurHash2/3, wyhash, and more… を読んだ。

  • 非暗号学的ハッシュ関数(non-criptographic hash function)をセキュリティ目的に使った場合の脆弱性について
  • 暗号学的ハッシュ関数の安全性は Pre-image resistance, Second pre-image resistance, Collision resistance で満足すべき
  • ハッシュ関数の実装調べて、逆演算を用いることで脆弱性を突いている

卒論でMD6のコンポーネントに対して高階差分解析をやったことを思いだした。また、ハッシュ関数を実装してみよう。

winstonでログ出力

winston を使ったスタックトレースの出しかた。

logger.ts

import { createLogger, format, transports } from 'winston';

const { combine, timestamp, errors, printf, cli, metadata } = format;


const myFormat = printf(({ level, message, metadata }) => {
  if (metadata && metadata.stack) {
    return `${metadata.timestamp} ${level}: ${metadata.stack}`;
  } else {
    return `${metadata.timestamp} ${level}: ${message}`;
  }
});

export const logger = createLogger({
  format: combine(
    errors({ stack: true }),
    timestamp(),
    cli(),
    metadata(),
    myFormat,
  ),
  transports: [new transports.Console()],
});

logger.test.ts

import {logger} from '../../src/logger.js'
import { test } from 'vitest'


test("winstonの通常ログ", () => {
  logger.info("これはINFOです。");
});


test("winstonの例外時にスタックトレースを表示する", () => {
  try {
    throw new RangeError("これは範囲エラーです.");
  }catch(err) {
    logger.error(err);
  }
});

テスト出力

 RUN  v2.1.0 /home/hoge/projects/hello_typescript

stdout | __tests__/unit/logger.test.ts > winstonの通常ログ
2024-11-04T10:58:55.786Z info:     これはINFOです。

stdout | __tests__/unit/logger.test.ts > winstonの例外時にスタックトレースを表示する
2024-11-04T10:58:55.789Z error: RangeError: これは範囲エラーです.
    at /home/hoge/projects/hello_typescript/__tests__/unit/logger.test.ts:12:11
    at file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:146:14
    at file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:529:11
    at runWithTimeout (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:61:7)
    at runTest (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:982:17)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runSuite (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:1131:15)
    at runFiles (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:1188:5)
    at startTests (file:///home/hoge/projects/hello_typescript/node_modules/@vitest/runner/dist/index.js:1197:3)
    at file:///home/hoge/projects/hello_typescript/node_modules/vitest/dist/chunks/runBaseTests.9YDrdSI4.js:130:11

 ✓ __tests__/unit/logger.test.ts (2)
 ✓ __tests__/unit/main.test.ts (3)
 ✓ build/__tests__/unit/main.test.js (2)

 Test Files  3 passed (3)
      Tests  7 passed (7)
   Start at  19:58:55
   Duration  209ms (transform 52ms, setup 0ms, collect 95ms, tests 12ms, environment 0ms, prepare 141ms)

“Can a Rubik’s Cube be brute-forced?” を読んだ

Can a Rubik’s Cube be brute-forced? を読んだ。

  • ルービックキューブをどのように解けるかを解説した記事である
  • ルービックキューブを解く有名なアルゴリズムは以下がある
    • Korf’s algorithm
    • Thistlethwaite’s algorithm
  • ルービックキューブを順列パズルと考え、総当たりを考える
  • パターンは43京ほどあるが、10億まで減らせる方法がある
  • 順列を表わすデータ構造として、 “Permutaion Trie” がある
  • 作者がCommon Lispで実装したものが stylewarning/cl-permutation: Permutations and permutation groups in Common Lisp. にある

ルービックキューブと群論は (Joyner 2010) で興味をもったことを思いだした。Common Lispも会得しようと考えていたが、いまだ覚つかない。これらを高レベルに融合するのが私の人生の目標の一つであったが、それは果せるだろうか?

参考文献

Joyner, David. 2010. 群論の味わい ー置換群で解き明かすルービックキューブと15パズルー. Translated by 川辺 治之. 単行本. 共立出版. https://lead.to/amazon/jp/?op=bt&la=ja&key=4320019415.

正弦関数のマクローリン展開の計算

概要

解析学の級数の理解のために、正弦関数のマクローリン展開の数値例を使おうと考えた。

計算

正弦関数(sin関数)の高階微分とテイラー展開(マクローリン展開)| 関数の微分 | 微分積分 | 数学 | ワイズ を参考に以下のようにコードにした。

import math
import numpy as np

def calc_sin_Maclaurin(x, n):
    ans = []
    for k in range(n):
        term = (-1)**k * x**(2*k+1) / math.factorial(2*k+1)
        ans.append(term)
    return sum(ans), ans
np.sin(np.sqrt(2)), calc_sin_Maclaurin(np.sqrt(2), 10)[0]

確認のためにプロットしてみる。

import matplotlib.pyplot as plt
import numpy as np

vfunc = np.vectorize(lambda x: calc_sin_Maclaurin(x, 10)[0])

fig, ax = plt.subplots(1, 1)
x = np.linspace(0, 10, 1000)
ax.plot(x, vfunc(x), label="Maclaurin(x, 10)")
ax.plot(x, np.sin(x), label="sin(x)")
ax.set_ylim(-2, 2)
plt.legend()
fig.savefig(outfile)
outfile
6NWdAb_jDAk_M.png

これで以下の級数を利用しよう。

calc_sin_Maclaurin(np.sqrt(2), 5)[1]
1.4142135623730951 -0.4714045207910318 0.04714045207910319 -0.0022447834323382474 6.23550953427291e-05

参考文献

“Unsafe Rust Is Harder Than C” を読んだ

Unsafe Rust Is Harder Than C を読んだ。

  • Rustのunsafeなコードの説明である
  • 侵入型リンクリスト(intrusive linked lists)のようなデータ構造を実装した際の経験を記事にしている
  • Photohashというソフトウェアを作成するために、効率的な並列処理が必要になった
  • そのため、独自のチャネルを実装することにしたようだ

ペル方程式を解くコード

連分数の計算 を元にペル方程式を計算する。ペル方程式の連分数を用いた魔法の解法 – tsujimotterのノートブックを参考にした。

ペル方程式は以下のように表わされる。特にDが素数の時に興味がある。

\[ x^{2} – Dy^{2} = 1 \]

まず、D=61で計算してみる。計算手順は以下のようになる。

  • \(\sqrt{61}\) の連分数展開を求める
  • 連分数の周期を確認し、奇数なら2周期とする
  • 近似分数 \(\frac{P}{Q}\) を求める
  • \(P^{2} – 61Q^{2} = 1\) となる

cfrac = get_continued_fraction(61)
if 1 == (len(cfrac[1:]) % 2):
    cfrac += cfrac[1:]
get_approx_fraction(cfrac[:-1])

つぎに115以下の素数を ペル方程式 – Wikipedia にある一覧表で確認する。

import sympy

lst_pq = [['D(prime)', 'P', 'Q'], None]
for i, p in enumerate(sympy.primerange(115)):
    cfrac = get_continued_fraction(p)
    if 1 == (len(cfrac[1:]) % 2):
        cfrac += cfrac[1:]
    pq = get_approx_fraction(cfrac[:-1])
    lst_pq.append([p, pq.numerator, pq.denominator])
lst_pq
D(prime) P Q
2 3 2
3 2 1
5 9 4
7 8 3
11 10 3
13 649 180
17 33 8
19 170 39
23 24 5
29 9801 1820
31 1520 273
37 73 12
41 2049 320
43 3482 531
47 48 7
53 66249 9100
59 530 69
61 1766319049 226153980
67 48842 5967
71 3480 413
73 2281249 267000
79 80 9
83 82 9
89 500001 53000
97 62809633 6377352
101 201 20
103 227528 22419
107 962 93
109 158070671986249 15140424455100
113 1204353 113296

EmacsのTypescript環境

久々にTypeScriptを書く必要があったので、環境を構築した。

まず、 nvm で 22.2.0 をインストール。(バージョンは適当。)

nvm install 22.2.0

ボイラープレートを利用して雛形を作成する。

git clone https://github.com/jsynowiec/node-typescript-boilerplate.git
cd node-typescript-boilerplate

nvmNode.js のバージョンを 22.2.0 に指定する

nvm use 22.2.0

依存パッケージをインストールする。

npm install

以下のようにemacsの設定ファイルに記載する。

;; 拡張子.tsのファイルを開いたら、typescript-ts-modeにする
(add-to-list 'auto-mode-alist '("\\.ts" . typescript-ts-mode))

;; eslintなどはプロジェクトのnode_module内のものを使いたいため
(use-package add-node-modules-path
  :straight t
  :hook ((typescript-ts-mode . add-node-modules-path))
  :config
  ;; https://github.com/codesuki/add-node-modules-path/issues/23 より
  (setq add-node-modules-path-command '("echo \"$(npm root)/.bin\"")))

;; 必要か?
(use-package nvm
  :straight (:host github :repo "rejeep/nvm.el")
  :config
  ;; Optionally set a default node version
  (nvm-use "22.2.0"))

Emacsのコマンドで M-x lsp-install-server を実行して、 ts-ls をインストールする。

これで環境が構築できた。