高校化学(日記)

##  高校化学で使うPythonコードをまとめました。


```python
# Program Name: mars_oxygen_dissolution.py
# Creation Date: 20250508
# Overview: Calculate the amount of oxygen dissolved in water on Mars using Henry's law
# Usage: Run this script directly with `python mars_oxygen_dissolution.py` from terminal

# 必要なライブラリはなし（print関数のみ使用）

# --- 数値設定 / Constants ---
standard_pressure = 1.01e5       # 地球での酸素分圧 [Pa] / Oxygen partial pressure on Earth
mars_pressure_total = 610        # 火星の全大気圧 [Pa] / Total atmospheric pressure on Mars
oxygen_fraction_mars = 0.13      # 火星における酸素の体積比 / Oxygen fraction on Mars
henry_solubility = 4.06e-2       # ヘンリーの法則に基づく酸素の溶解度 [g/L/atm]
water_volume = 1.00e3            # 水の体積 [L] / Volume of water

# --- 火星での酸素分圧計算 / Partial pressure of O2 on Mars ---
mars_oxygen_pressure = mars_pressure_total * oxygen_fraction_mars / 100  # [Pa]

# --- 溶存酸素量の計算 / Dissolved oxygen on Mars ---
dissolved_oxygen = henry_solubility * mars_oxygen_pressure / standard_pressure * water_volume  # [g]

# --- 結果表示 / Output results ---
print("【火星の水1,000Lに溶ける酸素の質量】")
print(f"火星の酸素分圧: {mars_oxygen_pressure:.2f} Pa")
print(f"水1,000Lに溶ける酸素の量: {dissolved_oxygen:.4e} g")  # 指数表示


```

```python
# Program Name: carbon14_decay_visualizer.py
# Creation Date: 20250508
# Overview: Visualize the decay of radioactive carbon-14 over time using its half-life
# Usage: Run this script directly with `python carbon14_decay_visualizer.py` from terminal

# --- 必要なライブラリのインポート / Import required libraries ---
import numpy as np
import matplotlib.pyplot as plt

# --- パラメータ設定 / Parameter definitions ---
initial_ratio = 1.0         # 初期比率 / Initial proportion of ^14C
half_life = 5730            # ^14Cの半減期 [年] / Half-life of carbon-14 in years
num_half_lives = 5          # 何回分の半減期を描画するか / Number of half-life intervals

# --- 時間データの生成 / Generate time array ---
years = np.arange(0, half_life * num_half_lives + 1, 10)  # 10年刻み / 10-year steps

# --- 放射性同位体の減衰公式に基づく計算 / Exponential decay function ---
# N(t) = N0 * (1/2)^(t / t_half)
ratios = initial_ratio * (0.5) ** (years / half_life)

# --- グラフ描画 / Plotting ---
plt.figure(figsize=(10, 6))
plt.plot(years, ratios, marker='o')
plt.xticks(np.arange(0, half_life * (num_half_lives + 1), half_life))
plt.yticks([1.0, 0.5, 0.25, 0.125, 0.0625])
plt.title("Carbon-14 Decay Over Time")
plt.xlabel("Elapsed Time (years)")
plt.ylabel("Remaining ^14C Ratio")
plt.grid(True)
plt.tight_layout()
plt.show()

```


```python
# Program Name: carbonate_equilibrium_calculator.py
# Creation Date: 20250508
# Overview: Calculate carbonate species concentrations from CO₂ partial pressure and pH in seawater
# Usage: Run this script with `python carbonate_equilibrium_calculator.py`

# --- ライブラリインポート / Import necessary libraries ---
import numpy as np

# --- パラメータ定義 / Define input parameters ---
pH = 8.0                         # 水素イオン指数 / Hydrogen ion concentration (log scale)
H_conc = 10 ** -pH               # [H+] [mol/L]
K0 = 10 ** -1.5                  # CO₂ ⇄ H₂CO₃ (Henry's law)
K1 = 10 ** -6.4                  # H₂CO₃ ⇄ H+ + HCO₃⁻
K2 = 10 ** -10.3                 # HCO₃⁻ ⇄ H+ + CO₃²⁻
PCO2 = 0.0004                    # CO₂分圧（例: 400 ppm = 0.0004 atm）/ Partial pressure of CO₂ [atm]

# --- H2CO3濃度の計算（ヘンリーの法則） / Calculate [H₂CO₃] using Henry's law ---
H2CO3 = K0 * PCO2  # [mol/L]

# --- [HCO3⁻] と [CO₃²⁻] を求める / Derive concentrations based on equilibria ---
HCO3 = (K1 * H2CO3) / H_conc
CO3 = (K2 * HCO3) / H_conc

# --- 結果表示 / Print results ---
print("pH =", pH)
print("[H⁺] = {:.2e} mol/L".format(H_conc))
print("[H₂CO₃] = {:.2e} mol/L".format(H2CO3))
print("[HCO₃⁻] = {:.2e} mol/L".format(HCO3))
print("[CO₃²⁻] = {:.2e} mol/L".format(CO3))

```

```python
# Program Name: lithium_ion_battery_analysis.py
# Creation Date: 20250508
# Overview: Quantitative evaluation of Li-ion battery discharge, molar transfer, and energy density
# Usage: Run with `python lithium_ion_battery_analysis.py`

# --- 必要なライブラリのインポート / Import necessary libraries ---
import matplotlib.pyplot as plt

# --- 入力パラメータの定義 / Define input parameters ---
current_mA = 20                      # 放電電流 [mA] / Discharge current
mass_LiC6 = 0.060                    # LiC6の質量 [g]
M_LiC6 = 72.93                       # LiC6のモル質量 [g/mol]
n_electron_per_mol = 1              # LiC6あたり放出される電子数
F = 96485                           # ファラデー定数 [C/mol]
voltage_cell = 3.7                  # セル電圧 [V]
mass_LiCoO2_delta = 0.5             # LiCoO₂の質量差 [g]
M_LiCoO2 = 97.87                    # LiCoO₂のモル質量 [g/mol]
mass_Al_doped = 0.02                # Al置換正極のLi脱離による質量差 [g]

# --- 放電にかかる時間の計算 / Calculate discharge time ---
mol_LiC6 = mass_LiC6 / M_LiC6                        # mol数 / mols of LiC6
total_charge_C = mol_LiC6 * F * n_electron_per_mol   # 総電荷 [C]
current_A = current_mA / 1000                        # 電流 [A]
discharge_time_s = total_charge_C / current_A        # 放電時間 [秒]

# --- モル数計算 / Molar quantity calculations ---
mol_LiCoO2_loss = mass_LiCoO2_delta / M_LiCoO2
mol_Li_from_Al_doped = mass_Al_doped / M_LiCoO2

# --- エネルギー密度の計算 / Energy density calculation ---
energy_Wh = (total_charge_C * voltage_cell) / 3600   # 放出エネルギー [Wh]
specific_energy = energy_Wh / (mass_LiC6 + mass_LiCoO2_delta) * 1000  # Wh/kg

# --- 結果表示 / Print results ---
print(f"放電にかかる時間（{current_mA} mA, {mass_LiC6:.3f}g LiC₆使用）: 約 {discharge_time_s:.1f} 秒（約 {discharge_time_s/60:.1f} 分）")
print(f"LiCoO₂の質量減少から求めたLi⁺のモル数 x: 約 {mol_LiCoO2_loss:.4f} mol")
print(f"Al置換正極からのLi⁺放出モル数 y: 約 {mol_Li_from_Al_doped:.4f} mol")
print(f"セル全体のエネルギー密度: 約 {specific_energy:.1f} Wh/kg")

# --- グラフ表示 / Optional: Plot discharge time vs current ---
currents = [10, 20, 30, 40, 50]  # mA
times = [total_charge_C / (i / 1000) / 60 for i in currents]  # minutes

plt.plot(currents, times, marker='o')
plt.title("Discharge Time vs Current")
plt.xlabel("Current (mA)")
plt.ylabel("Discharge Time (minutes)")
plt.grid(True)
plt.tight_layout()
plt.show()

```
```python
# Program Name: ck_ab_binding_simulation.py
# Creation Date: 20250111
# Overview: モデルに基づき、CkとAbの反応動態および複合体割合Xを評価
# Usage: python ck_ab_binding_simulation.py をターミナルで実行

# --- ライブラリのインストール / Install required libraries ---
# （Google Colabなどではコメントアウト解除して実行）
# !pip install matplotlib numpy

# --- 必要なライブラリの読み込み / Import libraries ---
import numpy as np
import matplotlib.pyplot as plt

# --- 定数と初期値の設定 / Define constants and parameters ---
k1 = 1e-3  # 順反応速度定数 / Forward rate constant [L mol^-1 s^-1]
k2 = 1e-3  # 逆反応速度定数 / Reverse rate constant [s^-1]
K = k1 / k2  # 平衡定数 / Equilibrium constant

# --- 濃度範囲 / Range of [Ab] values ---
ab_list = np.linspace(1e-6, 1e-4, 20)  # [Ab] from 1μM to 100μM

# --- Ck濃度一定 / [Ck]₀ fixed ---
ck_0 = 1e-5  # 初期Ck濃度 / Initial concentration of Ck [mol/L]

# --- 結合割合Xの計算 / Calculate binding ratio X ---
def compute_X(ab, ck0, K):
    return (K * ab) / (K * ab + 1)

X_list = compute_X(ab_list, ck_0, K)

# --- 結果の表示 / Print results ---
print(" [Ab] (mol/L)     Binding Ratio X")
for ab, x in zip(ab_list, X_list):
    print(f"{ab:.2e}       {x:.4f}")

# --- プロット / Plot the result ---
plt.figure(figsize=(8, 5))
plt.plot(ab_list * 1e6, X_list, marker='o', linestyle='-', color='darkblue')  # μM単位
plt.title("Binding Ratio X vs. Antibody Concentration [Ab]")
plt.xlabel("[Ab] (μmol/L)")
plt.ylabel("Binding Ratio X")
plt.grid(True)
plt.tight_layout()
plt.show()

```

```python
# Program Name: cytokine_antibody_binding_analysis.py
# Creation Date: 20250508
# Overview: Analyze cytokine-antibody binding kinetics using equilibrium constants and plot results
# Usage: Run with `python cytokine_antibody_binding_analysis.py` in terminal

# --- 必要なライブラリのインポート / Import required libraries ---
import numpy as np
import matplotlib.pyplot as plt

# --- パラメータの設定 / Define parameters ---
K_Ab1 = 1.0e9     # [L/mol] 平衡定数 for Ab1
K_Ab2 = 1.0e9     # [L/mol] 平衡定数 for Ab2
K_Ab3 = 1.0e8     # [L/mol] 平衡定数 for Ab3

Ab_range = np.linspace(0, 1e-7, 1000)  # [Ab]_0 の範囲（0〜100nM）

# --- 結合率 X の計算式（X = K[Ab] / (K[Ab] + 1)）/ Compute binding ratio ---
def compute_X(K, Ab0):
    return (K * Ab0) / (K * Ab0 + 1)

X_Ab1 = compute_X(K_Ab1, Ab_range)
X_Ab2 = compute_X(K_Ab2, Ab_range)
X_Ab3 = compute_X(K_Ab3, Ab_range)

# --- グラフ描画 / Plotting ---
plt.figure(figsize=(8, 6))
plt.plot(Ab_range * 1e9, X_Ab1, label='Ab1 (K=1e9)', linewidth=2)
plt.plot(Ab_range * 1e9, X_Ab2, label='Ab2 (K=1e9)', linestyle='--', linewidth=2)
plt.plot(Ab_range * 1e9, X_Ab3, label='Ab3 (K=1e8)', linestyle=':', linewidth=2)
plt.axhline(0.9, color='gray', linestyle=':', label='X = 0.9')

plt.title('Binding ratio X vs. Antibody concentration [Ab]', fontsize=14)
plt.xlabel('Antibody concentration [Ab] (nM)', fontsize=12)
plt.ylabel('Binding Ratio X', fontsize=12)
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()

# --- X=0.9 を満たす [Ab] の計算 / Compute [Ab]_0 for X = 0.9 ---
X_target = 0.9
def required_Ab(K, X):
    return (X / (1 - X)) / K

Ab1_required = required_Ab(K_Ab1, X_target)
Ab2_required = required_Ab(K_Ab2, X_target)
Ab3_required = required_Ab(K_Ab3, X_target)

# --- 結果の表示 / Print results ---
print("Required [Ab]_0 for X = 0.9:")
print(f"Ab1: {Ab1_required:.1e} mol/L")
print(f"Ab2: {Ab2_required:.1e} mol/L")
print(f"Ab3: {Ab3_required:.1e} mol/L")

```


```python
# Program Name: wax_combustion_water_mass_calc.py
# Creation Date: 20250508
# Overview: Calculates the mass of water produced from the combustion of cerotic acid (C26H52O2)
# Usage: Paste into Google Colab and run to get the mass of H2O generated from 99g of wax

# --- 必要なライブラリのインポート / Import necessary library ---
import sympy as sp

# --- 入力パラメータの定義 / Define parameters ---
molar_mass_wax = 396   # セロチン酸のモル質量 [g/mol] / Molar mass of C26H52O2
mass_wax = 99          # ロウソクの質量 [g] / Given wax mass
molar_mass_H2O = 18    # 水のモル質量 [g/mol] / Molar mass of H2O
H_atoms_per_molecule = 52  # 1分子中の水素原子数 / Number of H atoms per molecule of C26H52O2
H2O_per_molecule = H_atoms_per_molecule // 2  # 生成される水の分子数 / H2O molecules per wax molecule

# --- 計算処理 / Calculation ---
mol_wax = mass_wax / molar_mass_wax                  # ロウのモル数 / Moles of wax
mol_H2O = mol_wax * H2O_per_molecule                 # 生成されるH2Oのモル数 / Moles of water
mass_H2O = mol_H2O * molar_mass_H2O                  # 水の質量 [g] / Mass of water generated

# --- 出力 / Output ---
print("▼ 計算結果 / Result")
print(f"1モルのロウソクが生成する水: {H2O_per_molecule} mol")
print(f"ロウソクのモル数: {mol_wax:.4f} mol")
print(f"生成される水のモル数: {mol_H2O:.4f} mol")
print(f"生成される水の質量: {mass_H2O:.1f} g")  # 答え：117 g（教科書通り）

```

```python
# Program Name: arrhenius_dissociation_and_activity_plot.py
# Creation Date: 20250508
# Overview: A program to calculate dissociation degree (Arrhenius) and plot activity coefficient (γ) vs concentration (C)
# Usage: Run this in Google Colab or local Jupyter environment

import numpy as np
import matplotlib.pyplot as plt

# --- Parameters / パラメータの設定 ---
K = 1.5e-5         # Dissociation constant [mol/L] / 電離定数
M = 60             # Molar mass of acetic acid [g/mol] / 酢酸のモル質量
mass = 1.0         # Mass of acetic acid [g] / 酢酸の質量
volume = 1.0       # Solution volume [L] / 水溶液体積

# --- Calculations / 計算 ---
C = mass / M                                       # Initial concentration [mol/L] / 初期濃度
alpha = np.sqrt(K / C)                             # Degree of dissociation α / 電離度

print(f"Initial concentration C: {C:.4f} mol/L")
print(f"Dissociation constant K: {K:.2e} mol/L")
print(f"Degree of dissociation (α): {alpha:.4f}")

# --- Plot activity coefficient vs concentration / 活量係数 vs 濃度 ---
C_range = np.linspace(0.0001, 0.016, 100)
z1 = 1  # Monovalent ion / 一価イオン
z2 = 2  # Divalent ion / 二価イオン

gamma_z1 = 10 ** (-0.509 * z1**2 * np.sqrt(C_range))   # Debye-Hückel for z=1
gamma_z2 = 10 ** (-0.509 * z2**2 * np.sqrt(C_range))   # Debye-Hückel for z=2

# --- Plot / グラフ描画 ---
plt.figure(figsize=(8, 5))
plt.plot(C_range, gamma_z1, label="z = 1")
plt.plot(C_range, gamma_z2, label="z = 2")
plt.title("Activity Coefficient vs Concentration")
plt.xlabel("Concentration (mol/L)")
plt.ylabel("Activity Coefficient γ")
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()

```


```python
# Program Name: arrhenius_dissociation_combined.py
# Creation Date: 20250508
# Overview: 電離度αと活量係数γを一括で計算・可視化する統合プログラム
# Usage: Google Colab等で実行して、濃度依存性や物質間の比較を視覚的に確認

import numpy as np
import matplotlib.pyplot as plt

# --- 定数とモル質量・価数の設定 / Define constants, molar mass, valence ---
K_acetic = 1.5e-5  # 酢酸の電離定数 / Dissociation constant of acetic acid
molar_mass = {'CH3COOH': 60.0, 'KCl': 74.6, 'MgSO4': 120.4}  # モル質量 [g/mol]
z_valence = {'KCl': 1, 'MgSO4': 2}  # 価数 z

# --- 濃度範囲の定義 / Define concentration range ---
C_values = np.linspace(0.001, 0.1, 100)  # 濃度範囲 [mol/L]

# --- 電離度αの計算関数 / Function to calculate dissociation degree α ---
def calc_alpha(K, C_array):
    # 電離度α = sqrt(K / C)
    return np.sqrt(K / C_array)

# --- 活量係数γの計算関数 / Function to calculate activity coefficient γ ---
def calc_gamma(C, z):
    # log10(γ) = -0.5 z^2 √C → γ = 10^(-0.5 z^2 √C)
    return 10 ** (-0.5 * z**2 * np.sqrt(C))

# --- αの計算と描画 / Compute and plot dissociation degree ---
alpha_vals = calc_alpha(K_acetic, C_values)

plt.figure()
plt.plot(C_values, alpha_vals, label='Acetic Acid α')
plt.title("Dissociation Degree of Acetic Acid")
plt.xlabel("Concentration [mol/L]")
plt.ylabel("α")
plt.grid(True)
plt.legend()

# --- 各物質の活量係数をプロット / Plot activity coefficient γ for each salt ---
plt.figure()
for substance in ['KCl', 'MgSO4']:
    gamma_vals = calc_gamma(C_values, z_valence[substance])
    plt.plot(C_values, gamma_vals, label=f"{substance} γ (z={z_valence[substance]})")

plt.title("Activity Coefficient γ vs Concentration")
plt.xlabel("Concentration [mol/L]")
plt.ylabel("Activity Coefficient γ")
plt.legend()
plt.grid(True)

# --- 実濃度でのγ計算 / Compute γ at specific concentrations ---
C_KCl = molar_mass['KCl'] / 1000
C_MgSO4 = molar_mass['MgSO4'] / 1000
gamma_KCl = calc_gamma(C_KCl, z_valence['KCl'])
gamma_MgSO4 = calc_gamma(C_MgSO4, z_valence['MgSO4'])

print("=== 活量係数 / Activity Coefficients ===")
print(f"KCl:  C = {C_KCl:.4f} mol/L → γ = {gamma_KCl:.2f}")
print(f"MgSO₄: C = {C_MgSO4:.4f} mol/L → γ = {gamma_MgSO4:.2f}")


```


```python
# Program Name: thermochemical_analysis_combined.py
# Creation Date: 20250508
# Overview: This program analyzes multiple thermochemical and molecular problems from textbook examples.
# Usage: Run the script in a Python environment or Google Colab to simulate, calculate, and visualize.

import numpy as np
import matplotlib.pyplot as plt

# --- 物理定数と初期値 / Physical constants and initial conditions ---
pi = np.pi
Na = 6.022e23  # アボガドロ数 / Avogadro's number

# --- 熱化学方程式のエネルギー計算 / Thermochemical reaction heat calculation ---
# Q1, Q2, Q3, Q4 のエネルギー(kJ)を仮定値として定義 / Define hypothetical reaction heats (kJ)
Q1 = -890  # 例: CH4 + 2O2 → CO2 + 2H2O (exothermic)
Q2 = 100
Q3 = -200
Q4 = 250

# 総反応熱の計算 / Total reaction heat calculation
total_Q = Q1 - Q2 + 4 * Q3 + 8 * Q4

# --- フラーレンのn決定（凝固点降下法）/ Fullerene n determination using freezing point depression ---
Kf = 5.12  # ベンゼンの凝固点降下定数 / Benzene's cryoscopic constant
delta_T = 5.12  # 凝固点降下 / Freezing point depression
m_solute = 0.123  # g
m_solvent = 0.050  # kg
M0 = 720  # ベース分子量 / base molar mass
M_coeff = 31  # 可変部分の係数

# nを数値的に探索 / Numerical search for n
def estimate_n(Kf, delta_T, m_solute, m_solvent):
    for n in range(1, 100):
        M = M0 + M_coeff * n
        calc_delta_T = Kf * m_solute / (M * m_solvent)
        if abs(calc_delta_T - delta_T) < 0.01:
            return n, M
    return None, None

n_fullerene, M_fullerene = estimate_n(Kf, delta_T, m_solute, m_solvent)

# --- イオン半径差からの空隙判断 / Void fit based on ionic radius ---
R_small = 0.13  # nm
R_large = 0.33  # nm
radius_ratio = R_small / R_large
center_void = R_small + (R_large - R_small)  # 中心空隙の推定

# --- 体心立方格子の充填率計算 / Packing efficiency of body-centered cubic (BCC) ---
V_atom = (4 / 3) * pi * (0.5 * 2 / np.sqrt(3)) ** 3
V_cell = (2 / np.sqrt(3)) ** 3
packing_efficiency = V_atom / V_cell

# --- 結果の出力 / Print results ---
print("【熱化学反応の総反応熱】 / Total Reaction Heat: ", total_Q, "kJ")
print("【フラーレンの構成n値】 / Estimated n for C60(OH)3n: ", n_fullerene)
print("【最適な空隙中心の大きさ】 / Center void (nm):", round(center_void, 3))
print("【体心立方格子の充填率】 / Packing Efficiency (BCC):", round(packing_efficiency * 100, 1), "%")

# --- グラフプロット / Plot Packing Efficiency ---
plt.figure()
plt.bar(['BCC Packing Efficiency'], [packing_efficiency * 100])
plt.title("Packing Efficiency of BCC Structure")
plt.ylabel("Efficiency (%)")
plt.ylim(0, 100)
plt.grid(True)
plt.show()

```

```python
# Program Name: chemistry_calculations_full.py
# Creation Date: 20250508
# Overview: This script contains a collection of chemistry-related calculations derived from textbook problems,
#           including cryoscopic molality, complexometric titration, metal hydride volume estimation, and decomposition percentage.
# Usage: Run this script using `python chemistry_calculations_full.py`

# 必要なライブラリのインポート / Import necessary libraries
import math

# --- 1. 凝固点降下からnを求める計算 / Calculate n from freezing point depression ---
# 与えられた値を代入 / Define given values
Kf = 5.12  # 凝固点降下定数 / Cryoscopic constant (K·kg/mol)
delta_Tf = 0.0110  # 凝固点降下 (K)
mass_solute = 123e-3  # 質量 (g)
mass_solvent = 0.050  # ベンゼン質量 (kg)

# 分子量の式からnを含む形に / Molecular weight includes n
# 分子量 = 720 + 31n
# molality = mol solute / kg solvent = delta_Tf / Kf

molality = delta_Tf / Kf
molar_mass = mass_solute / (molality * mass_solvent)
n = round((molar_mass - 720) / 31)

# --- 2. 滴定でCa2+濃度を求める / Calculate Ca2+ concentration from titration ---
V_titrant = 0.010  # L
C_titrant = 0.10  # mol/L
V_sample = 5.0 / 1000  # L

x = V_titrant * C_titrant / V_sample

# --- 3. 水素吸蔵合金の体積 / Calculate volume of metal alloy storing H2 ---
volume_per_cell = 0.260e-24  # cm^3 to dm^3
N_A = 6.02e23  # アボガドロ数
mass_H2 = 1.0  # kg
M_H2 = 2.0  # g/mol
mol_H2 = 1.0e3 / M_H2

n_cells = mol_H2 * N_A / 18
total_volume = n_cells * volume_per_cell

# --- 4. マラカイト分解による質量減少率 / Decomposition mass loss ---
M_Cu2 = 79.5  # g/mol (2 mol Cu)
M_Cu2CO3OH2 = 221.0  # g/mol

loss_ratio = (M_Cu2CO3OH2 - M_Cu2) / M_Cu2CO3OH2 * 100

# 出力 / Print results
print("【1】nの値 (凝固点降下による)：", n)
print("【2】Ca2+の濃度 [mol/L]：", x)
print("【3】合金の体積 [L]：", round(total_volume, 2))
print("【4】質量減少率 [%]：", round(loss_ratio, 1))

```

```python
# Program Name: chemistry_calculations_full.py
# Creation Date: 20250508
# Overview: This script contains a collection of chemistry-related calculations derived from textbook problems,
#           including cryoscopic molality, complexometric titration, metal hydride volume estimation, and decomposition percentage.
# Usage: Run this script using `python chemistry_calculations_full.py`

# 必要なライブラリのインポート / Import necessary libraries
import math

# --- 1. 凝固点降下からnを求める計算 / Calculate n from freezing point depression ---
# 与えられた値を代入 / Define given values
Kf = 5.12  # 凝固点降下定数 / Cryoscopic constant (K·kg/mol)
delta_Tf = 0.0110  # 凝固点降下 (K)
mass_solute = 123e-3  # 質量 (g)
mass_solvent = 0.050  # ベンゼン質量 (kg)

# 分子量の式からnを含む形に / Molecular weight includes n
# 分子量 = 720 + 31n
# molality = mol solute / kg solvent = delta_Tf / Kf

molality = delta_Tf / Kf
molar_mass = mass_solute / (molality * mass_solvent)
n = round((molar_mass - 720) / 31)

# --- 2. 滴定でCa2+濃度を求める / Calculate Ca2+ concentration from titration ---
V_titrant = 0.010  # L
C_titrant = 0.10  # mol/L
V_sample = 5.0 / 1000  # L

x = V_titrant * C_titrant / V_sample

# --- 3. 水素吸蔵合金の体積 / Calculate volume of metal alloy storing H2 ---
volume_per_cell = 0.260e-24  # cm^3 to dm^3
N_A = 6.02e23  # アボガドロ数
mass_H2 = 1.0  # kg
M_H2 = 2.0  # g/mol
mol_H2 = 1.0e3 / M_H2

n_cells = mol_H2 * N_A / 18
total_volume = n_cells * volume_per_cell

# --- 4. マラカイト分解による質量減少率 / Decomposition mass loss ---
M_Cu2 = 79.5  # g/mol (2 mol Cu)
M_Cu2CO3OH2 = 221.0  # g/mol

loss_ratio = (M_Cu2CO3OH2 - M_Cu2) / M_Cu2CO3OH2 * 100

# 出力 / Print results
print("【1】nの値 (凝固点降下による)：", n)
print("【2】Ca2+の濃度 [mol/L]：", x)
print("【3】合金の体積 [L]：", round(total_volume, 2))
print("【4】質量減少率 [%]：", round(loss_ratio, 1))

```

```python
# Program Name: chemistry_calculations_full.py
# Creation Date: 20250508
# Overview: This script contains a collection of chemistry-related calculations derived from textbook problems,
#           including cryoscopic molality, complexometric titration, metal hydride volume estimation, and decomposition percentage.
# Usage: Run this script using `python chemistry_calculations_full.py`

# 必要なライブラリのインポート / Import necessary libraries
import math

# --- 1. 凝固点降下からnを求める計算 / Calculate n from freezing point depression ---
# 与えられた値を代入 / Define given values
Kf = 5.12  # 凝固点降下定数 / Cryoscopic constant (K·kg/mol)
delta_Tf = 0.0110  # 凝固点降下 (K)
mass_solute = 123e-3  # 質量 (g)
mass_solvent = 0.050  # ベンゼン質量 (kg)

# 分子量の式からnを含む形に / Molecular weight includes n
# 分子量 = 720 + 31n
# molality = mol solute / kg solvent = delta_Tf / Kf

molality = delta_Tf / Kf
molar_mass = mass_solute / (molality * mass_solvent)
n = round((molar_mass - 720) / 31)

# --- 2. 滴定でCa2+濃度を求める / Calculate Ca2+ concentration from titration ---
V_titrant = 0.010  # L
C_titrant = 0.10  # mol/L
V_sample = 5.0 / 1000  # L

x = V_titrant * C_titrant / V_sample

# --- 3. 水素吸蔵合金の体積 / Calculate volume of metal alloy storing H2 ---
volume_per_cell = 0.260e-24  # cm^3 to dm^3
N_A = 6.02e23  # アボガドロ数
mass_H2 = 1.0  # kg
M_H2 = 2.0  # g/mol
mol_H2 = 1.0e3 / M_H2

n_cells = mol_H2 * N_A / 18
total_volume = n_cells * volume_per_cell

# --- 4. マラカイト分解による質量減少率 / Decomposition mass loss ---
M_Cu2 = 79.5  # g/mol (2 mol Cu)
M_Cu2CO3OH2 = 221.0  # g/mol

loss_ratio = (M_Cu2CO3OH2 - M_Cu2) / M_Cu2CO3OH2 * 100

# 出力 / Print results
print("【1】nの値 (凝固点降下による)：", n)
print("【2】Ca2+の濃度 [mol/L]：", x)
print("【3】合金の体積 [L]：", round(total_volume, 2))
print("【4】質量減少率 [%]：", round(loss_ratio, 1))

```


```python
# Pythonプログラム名: chemical_calculations_chapters5_to7.py
# Program name: chemical_calculations_chapters5_to7.py

# 必要なライブラリのインポート / Import necessary libraries
import math

# 1. フラーレンの分子量計算 / Fullerene molecular weight estimation
def calculate_n_for_fullerene(delta_T, K, m_solute, m_solvent):
    def molecular_weight(n): return 720 + 31 * n
    target = delta_T / K * m_solvent / m_solute
    for n in range(1, 50):
        if abs(1 / molecular_weight(n) - target) < 0.001:
            return n
    return None

# 2. EDTA滴定によるCa2+濃度 / Calcium concentration via titration
def calcium_concentration(volume_EDTA, conc_EDTA, volume_sample):
    return volume_EDTA * conc_EDTA / volume_sample

# 3. 水素吸蔵体積 / Hydrogen storage volume
def hydrogen_volume(mass_h2, density=2.0, avogadro=6.02e23, h_per_cell=18, cell_volume=0.260e-24):
    mol_h2 = mass_h2 / density
    num_cells = mol_h2 * avogadro / h_per_cell
    return num_cells * cell_volume

# 4. グラフ構造原子占有率 / Atomic packing ratio in unit cell
def atomic_packing_ratio():
    numerator = 4 / 3 * math.pi * (math.sqrt(3) / 8)**3
    return round(numerator / (8 * math.sqrt(3) / 3), 2)

# 5. メタンの燃焼熱（熱化学方程式） / Combustion enthalpy calculation
def combustion_enthalpy(Q1, Q2, Q3, Q4):
    return Q1 - Q2 + 4 * Q3 + 8 * Q4

# 6. CO2の密度（理想気体式） / CO2 density under pressure using ideal gas law
def co2_density(P, M, R, T):
    return round(P * M / (R * T), 1)

# 7. メタノール水溶液の質量 / Mass of methanol-water solution needed
def methanol_solution_mass(mol, J_per_mol, molar_mass_mix, density):
    return mol * J_per_mol * molar_mass_mix / density / 1000

# 8. CO2排出深度の計算 / CO2 depth at which it becomes liquid
def co2_depth_at_liquefaction(boundary_pressure):
    return boundary_pressure / (1e5 + 1e4)

# 9. 製鉄に必要な酸素量と体積 / Oxygen consumption in iron production
def oxygen_volume(n_mol, T, R, P, factor):
    return (n_mol * R * T * factor) / P

# テスト出力 / Sample outputs
print("1. n (フラーレン):", calculate_n_for_fullerene(0.0110, 5.12, 0.123, 0.050))
print("2. Ca2+ 濃度:", calcium_concentration(0.010, 0.10, 5.0), "mol/L")
print("3. 水素吸蔵体積:", hydrogen_volume(1.0), "L")
print("4. 原子占有率:", atomic_packing_ratio())
print("5. 燃焼熱Q:", combustion_enthalpy(-891, -286*2, 0, 0), "kJ")
print("6. CO2密度:", co2_density(2e5, 44.0, 8.31, 288), "g/L")
print("7. メタノール溶液の質量:", methanol_solution_mass(1, 1/(726e-3), 32+18, 0.94), "kg")
print("8. CO2液化最浅深度:", co2_depth_at_liquefaction(5e5), "m")
print("9. 酸素体積:", oxygen_volume(1000e3 * 4.0 / 100 * 1/12, 300, 0.082, 2.0, 0.75), "L")

```

```python
# -*- coding: utf-8 -*-
# プログラム名: chemical_principles_analysis.py
# 概要: 反応熱、電気分解、気体の状態方程式、反応速度論などの基礎化学計算と可視化を統合したツール
# Description: Integrated chemical principles tool covering thermochemistry, electrolysis, gas laws, and kinetics

import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as const

# --- 1. 理想気体の状態方程式から密度を求める / Gas density from PV=nRT ---
def calculate_gas_density(P, M, T):
    """理想気体の密度 (g/L) を計算 / Calculate gas density"""
    R = 8.31  # J/(mol·K)
    rho = (P * M) / (R * T)  # g/m³ → g/L
    return rho / 1000

# --- 2. 熱化学方程式に基づく反応熱の合成計算 / Hess's law ---
def calculate_reaction_enthalpy(Q1, Q2, Q3, Q4):
    """反応熱 Q = -Q1 + 4Q2 + 3Q3 + 8Q4"""
    return -Q1 + 4 * Q2 + 3 * Q3 + 8 * Q4

# --- 3. 電気分解に必要な電気量と電流効率の評価 / Electrolysis charge calculation ---
def electrolysis_current_efficiency(m, M, n_electron, I, t):
    """電流効率 = 実際に得られた量 ÷ 理論値"""
    F = 96500  # ファラデー定数
    Q_theoretical = (m / M) * n_electron * F
    Q_actual = I * t
    return Q_theoretical / Q_actual

# --- 4. 反応速度論から速度定数の計算 / Kinetics: Rate constant ---
def calculate_k2(B, Kb, OH_eq):
    """速度定数 k2 の計算式 / Rate constant from derived equation"""
    return B / (Kb + 2 * OH_eq)

# --- 5. OH⁻ の時間変化プロット / Plotting OH⁻ over time ---
def plot_oh_concentration():
    """OH⁻濃度の時間変化のシミュレーションプロット"""
    t = np.linspace(0, 8e-7, 100)
    OH = 1.300e-3 + (1.320e-3 - 1.300e-3) * (1 - np.exp(-5e6 * t))  # 仮の指数関数モデル
    plt.plot(t * 1e7, OH * 1e3)  # x: ×10⁻⁷s, y: ×10⁻³ mol/L
    plt.xlabel("Time ($\\times10^{-7}$ s)")
    plt.ylabel("[OH⁻] (×10⁻³ mol/L)")
    plt.title("Change in Hydroxide Ion Concentration Over Time")
    plt.grid(True)
    plt.show()

# --- 実行例 / Execution Examples ---
if __name__ == "__main__":
    # 1. Gas density
    print("CO2 density at 10m depth:", calculate_gas_density(2.00e5, 44, 288), "g/L")

    # 2. Reaction enthalpy
    print("Reaction enthalpy Q =", calculate_reaction_enthalpy(Q1=100, Q2=200, Q3=300, Q4=400), "kJ")

    # 3. Electrolysis efficiency
    print("Electrolysis current efficiency =", electrolysis_current_efficiency(9.81, 24.3, 2, 1000, 24*3600))

    # 4. Kinetics
    print("Rate constant k2 =", calculate_k2(B=-1.1e7, Kb=1.7e-5, OH_eq=1.319e-3), "L/mol·s")

    # 5. Plot OH⁻ concentration change
    plot_oh_concentration()

```


```python
import numpy as np
import matplotlib.pyplot as plt

# --- グラフ生成: Clausius-Clapeyron 関係を可視化 ---
# 蒸気圧データ（例）
T = np.linspace(250, 350, 100)  # 温度範囲（K）
R = 2.0  # cal/mol·K
delta_H = 6.23e3  # cal/mol, 例: 蒸発熱

# Clausius-Clapeyron 式から P を計算 (P = A * exp(-ΔH / RT)) 形式
# 定数 A を仮定（対数プロットの傾きを見るのが目的なので値は任意）
A = 1e8  # atm 単位で適当に設定
P = A * np.exp(-delta_H / (R * T))

# プロット
plt.figure(figsize=(8, 6))
plt.plot(1 / T, np.log10(P), label="log10(P) vs 1/T")
plt.xlabel("1 / Temperature (1/K)")
plt.ylabel("log10(P) [atm]")
plt.title("Clausius-Clapeyron Relation: log10(P) vs 1/T")
plt.grid(True)
plt.legend()
plt.tight_layout()
plt.show()

```

##  高校化学で使うPythonコードをまとめました2

```Python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# --- 定数 / Constants ---
h = 6.626e-34  # プランク定数 Planck constant [J·s]
c = 3.00e8     # 光速 Speed of light [m/s]

# --- 元素と炎色反応の波長データ（nm） ---
elements = ['Na', 'K', 'Ca', 'Sr', 'Ba', 'Cu']
colors = ['黄', '紫', '橙', '紅', '黄緑', '青緑']
wavelengths_nm = [589, 766, 622, 670, 524, 510]  # 波長 [nm]

# --- 計算: 波長→エネルギー変換 / Wavelength to photon energy ---
wavelengths_m = np.array(wavelengths_nm) * 1e-9  # mに変換
energies_J = (h * c) / wavelengths_m             # E = h*c/λ

# --- DataFrame作成 / Create Table ---
df = pd.DataFrame({
    'Element': elements,
    'Flame Color': colors,
    'Wavelength (nm)': wavelengths_nm,
    'Photon Energy (J)': energies_J
})

# --- 表示 / Display ---
print(df)

# --- 可視化 / Visualization ---
plt.figure(figsize=(8,5))
plt.bar(df['Element'], df['Photon Energy (J)'], color='skyblue')
plt.xlabel("Element")
plt.ylabel("Photon Energy [J]")
plt.title("Photon Energy by Flame Test")
plt.grid(True)
plt.show()

```


```Python
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

# 再現するデータ点（教科書の溶解度曲線から視覚的に読み取った近似値）
# 横軸: 温度 (°C), 縦軸: 溶解度 (g/100g水)
temperature = np.array([0, 20, 40, 60, 80, 100])
solubility_NaNO3 = np.array([75, 85, 100, 120, 145, 170])  # 硝酸ナトリウム（NaNO3）
solubility_NaCl = np.array([35, 36, 37, 38, 39, 40])       # 塩化ナトリウム（NaCl）

# 線形補間（必要に応じて kind='cubic' に変更可能）
interp_nano3 = interp1d(temperature, solubility_NaNO3, kind='linear')
interp_nacl = interp1d(temperature, solubility_NaCl, kind='linear')

# 補間点
temp_dense = np.linspace(0, 100, 500)
solubility_nano3_dense = interp_nano3(temp_dense)
solubility_nacl_dense = interp_nacl(temp_dense)

# グラフ描画
plt.figure(figsize=(8, 5))
plt.plot(temperature, solubility_NaNO3, 'o', label='NaNO₃ (data)', color='blue')
plt.plot(temp_dense, solubility_nano3_dense, '-', label='NaNO₃ (interpolated)', color='blue', alpha=0.6)
plt.plot(temperature, solubility_NaCl, 'o', label='NaCl (data)', color='red')
plt.plot(temp_dense, solubility_nacl_dense, '-', label='NaCl (interpolated)', color='red', alpha=0.6)
plt.xlabel('Temperature (°C)')
plt.ylabel('Solubility (g/100g H₂O)')
plt.title('Solubility vs Temperature')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.show()

```



```Python
import numpy as np
import matplotlib.pyplot as plt

# 定数定義（単位は原子単位系）
a0 = 1  # ボーア半径
r = np.linspace(0, 10, 500)

# 1s軌道の波動関数（簡略化）
psi = (1 / np.sqrt(np.pi)) * np.exp(-r / a0)
prob_density = 4 * np.pi * r**2 * (psi**2)  # 球対称での確率密度

plt.plot(r, prob_density)
plt.title("Radial Probability Density for Hydrogen 1s Orbital")
plt.xlabel("Distance from nucleus (Bohr radius)")
plt.ylabel("Probability Density")
plt.grid(True)
plt.show()

```



```Python
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# --- ダミーデータを生成（本来は energy_results.csv から読み込む）/ Generate dummy data ---
# 原子間距離 (Å) とエネルギー (Hartree)
distances = np.arange(0.3, 2.05, 0.05)
energies = -1.0 + 0.8 * (distances - 0.74)**2  # 最小値が 0.74Å にあるようにしたパラボラ

# --- データフレーム化してCSV形式で保存する（実際のGANSU出力ファイルと同様の形式にする） ---
energy_df = pd.DataFrame({
    "Distance (Å)": distances,
    "Total Energy (hartree)": energies
})

# --- グラフを描画 / Plot energy vs distance ---
plt.plot(energy_df["Distance (Å)"], energy_df["Total Energy (hartree)"], marker='o')
plt.title("Energy vs. Bond Distance for H₂")
plt.xlabel("Distance (Å)")
plt.ylabel("Total Energy (hartree)")
plt.grid(True)
plt.tight_layout()
plt.show()

```