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
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
os.environ["DDE_BACKEND"] = "pytorch"
|
| 5 |
+
|
| 6 |
+
import sys
|
| 7 |
+
import json
|
| 8 |
+
import time
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from materials_config import MATERIALS, params_to_filename
|
| 11 |
+
from utils import create_model, train_model, save_model
|
| 12 |
+
|
| 13 |
+
MODELS_DIR = os.path.join(os.path.dirname(__file__), "models")
|
| 14 |
+
RESULTS_FILE = os.path.join(MODELS_DIR, "training_results.json")
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def train_single_material(name, true_lam, true_mu, iterations_adam=5000):
|
| 18 |
+
print(f"\n{'=' * 60}")
|
| 19 |
+
print(f"Training: {name}")
|
| 20 |
+
print(f" True λ = {true_lam:.4f}, True μ = {true_mu:.4f}")
|
| 21 |
+
print(f"{'=' * 60}")
|
| 22 |
+
|
| 23 |
+
start_time = time.time()
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
model, lmbd, mu = create_model(true_lam, true_mu, n_points=5000)
|
| 27 |
+
lambda_est, mu_est, losshistory, train_state = train_model(
|
| 28 |
+
model, lmbd, mu, iterations_adam=iterations_adam, verbose=True
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
filename = params_to_filename(true_lam, true_mu)
|
| 32 |
+
filepath = os.path.join(MODELS_DIR, filename)
|
| 33 |
+
save_model(model, lmbd, mu, filepath)
|
| 34 |
+
|
| 35 |
+
elapsed = time.time() - start_time
|
| 36 |
+
|
| 37 |
+
result = {
|
| 38 |
+
"name": name,
|
| 39 |
+
"true_lambda": true_lam,
|
| 40 |
+
"true_mu": true_mu,
|
| 41 |
+
"estimated_lambda": lambda_est,
|
| 42 |
+
"estimated_mu": mu_est,
|
| 43 |
+
"lambda_error_pct": abs(lambda_est - true_lam) / true_lam * 100,
|
| 44 |
+
"mu_error_pct": abs(mu_est - true_mu) / true_mu * 100,
|
| 45 |
+
"filename": filename,
|
| 46 |
+
"training_time_sec": elapsed,
|
| 47 |
+
"success": True,
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
print(f"\n Results for {name}:")
|
| 51 |
+
print(
|
| 52 |
+
f" λ: {true_lam:.4f} -> {lambda_est:.6f} (error: {result['lambda_error_pct']:.2f}%)"
|
| 53 |
+
)
|
| 54 |
+
print(
|
| 55 |
+
f" μ: {true_mu:.4f} -> {mu_est:.6f} (error: {result['mu_error_pct']:.2f}%)"
|
| 56 |
+
)
|
| 57 |
+
print(f" Time: {elapsed:.1f}s")
|
| 58 |
+
print(f" Saved: {filepath}")
|
| 59 |
+
|
| 60 |
+
return result
|
| 61 |
+
|
| 62 |
+
except Exception as e:
|
| 63 |
+
print(f"\n ERROR training {name}: {e}")
|
| 64 |
+
import traceback
|
| 65 |
+
|
| 66 |
+
traceback.print_exc()
|
| 67 |
+
return {
|
| 68 |
+
"name": name,
|
| 69 |
+
"true_lambda": true_lam,
|
| 70 |
+
"true_mu": true_mu,
|
| 71 |
+
"success": False,
|
| 72 |
+
"error": str(e),
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def train_all_materials(materials=None, iterations_adam=5000):
|
| 77 |
+
os.makedirs(MODELS_DIR, exist_ok=True)
|
| 78 |
+
|
| 79 |
+
if materials is None:
|
| 80 |
+
materials = MATERIALS
|
| 81 |
+
|
| 82 |
+
results = []
|
| 83 |
+
total = len(materials)
|
| 84 |
+
|
| 85 |
+
print(f"\n{'#' * 60}")
|
| 86 |
+
print(f"Batch Training - {total} materials")
|
| 87 |
+
print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
| 88 |
+
print(f"{'#' * 60}")
|
| 89 |
+
|
| 90 |
+
for i, (name, params) in enumerate(materials.items(), 1):
|
| 91 |
+
print(f"\n[{i}/{total}] Processing {name}...")
|
| 92 |
+
result = train_single_material(
|
| 93 |
+
name, params["lambda"], params["mu"], iterations_adam
|
| 94 |
+
)
|
| 95 |
+
result["material_info"] = params
|
| 96 |
+
results.append(result)
|
| 97 |
+
|
| 98 |
+
with open(RESULTS_FILE, "w") as f:
|
| 99 |
+
json.dump(results, f, indent=2)
|
| 100 |
+
|
| 101 |
+
print(f"\n{'#' * 60}")
|
| 102 |
+
print("Training Complete!")
|
| 103 |
+
print(f"{'#' * 60}")
|
| 104 |
+
|
| 105 |
+
successful = [r for r in results if r.get("success", False)]
|
| 106 |
+
failed = [r for r in results if not r.get("success", False)]
|
| 107 |
+
|
| 108 |
+
print(f"\nSuccessful: {len(successful)}/{total}")
|
| 109 |
+
if failed:
|
| 110 |
+
print(f"Failed: {len(failed)}/{total}")
|
| 111 |
+
for r in failed:
|
| 112 |
+
print(f" - {r['name']}: {r.get('error', 'Unknown error')}")
|
| 113 |
+
|
| 114 |
+
avg_lambda_err = sum(r["lambda_error_pct"] for r in successful) / len(successful)
|
| 115 |
+
avg_mu_err = sum(r["mu_error_pct"] for r in successful) / len(successful)
|
| 116 |
+
total_time = sum(r.get("training_time_sec", 0) for r in successful)
|
| 117 |
+
|
| 118 |
+
print(f"\nAverage Errors:")
|
| 119 |
+
print(f" λ: {avg_lambda_err:.2f}%")
|
| 120 |
+
print(f" μ: {avg_mu_err:.2f}%")
|
| 121 |
+
print(f"Total training time: {total_time / 60:.1f} minutes")
|
| 122 |
+
|
| 123 |
+
return results
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def train_specific_materials(names, iterations_adam=5000):
|
| 127 |
+
materials = {n: MATERIALS[n] for n in names if n in MATERIALS}
|
| 128 |
+
return train_all_materials(materials, iterations_adam)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
import argparse
|
| 133 |
+
|
| 134 |
+
parser = argparse.ArgumentParser(
|
| 135 |
+
description="Train PINN models for material identification"
|
| 136 |
+
)
|
| 137 |
+
parser.add_argument(
|
| 138 |
+
"--materials",
|
| 139 |
+
nargs="*",
|
| 140 |
+
default=None,
|
| 141 |
+
help="Specific materials to train (default: all)",
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--iterations", type=int, default=5000, help="Adam iterations (default: 5000)"
|
| 145 |
+
)
|
| 146 |
+
parser.add_argument(
|
| 147 |
+
"--list", action="store_true", help="List available materials and exit"
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
args = parser.parse_args()
|
| 151 |
+
|
| 152 |
+
if args.list:
|
| 153 |
+
print("Available materials:")
|
| 154 |
+
for name, params in MATERIALS.items():
|
| 155 |
+
print(f" {name}: λ={params['lambda']:.3f}, μ={params['mu']:.3f}")
|
| 156 |
+
sys.exit(0)
|
| 157 |
+
|
| 158 |
+
if args.materials:
|
| 159 |
+
train_specific_materials(args.materials, args.iterations)
|
| 160 |
+
else:
|
| 161 |
+
train_all_materials(iterations_adam=args.iterations)
|