File size: 25,224 Bytes
f614769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import csv\n",
    "import os\n",
    "import uuid\n",
    "from glob import glob\n",
    "from multiprocessing import Pool, cpu_count\n",
    "from pathlib import Path\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import yaml\n",
    "from matplotlib import colors as mcolors\n",
    "from tqdm import tqdm\n",
    "\n",
    "from utils import (\n",
    "    FileHandler,\n",
    "    PropertyCalculator,\n",
    "    find_missing_csv_files_v8,\n",
    "    plot_scatter,\n",
    "    process_file,\n",
    "    save_bond_errors_to_txt,\n",
    "    save_to_csv,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Set up analysis folders and constants"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "models = [\"MACE\", \"M3GNet\", \"CHGNet\", \"MatterSim\", \"Orb\"]  # , \"SevenNet\"]\n",
    "model_map = {model.lower(): model for model in models}\n",
    "colors = [\"#698B66\", \"#D04F81\", \"#9069A1\", \"#9DC183\", \"#F4C2C2\", \"#D7BDE2\"]\n",
    "\n",
    "\n",
    "# root_folder = \"/share/datasets-05/aimat_uip/uip_results_0/orb/\"\n",
    "root_folder = \"/store/nosnap/mlip-eval/results/mattersim\"\n",
    "\n",
    "\n",
    "model_name = Path(root_folder).name\n",
    "results_folder = \"./results\"\n",
    "\n",
    "os.makedirs(f\"{results_folder}/{model_name}/figs\", exist_ok=True)\n",
    "os.makedirs(f\"{results_folder}/figs\", exist_ok=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "## Overall Model's completion comparison"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Change the root_folder and model_name to run for different models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "combined_df, missing_csv_dirs, unreadable_csv_dirs = find_missing_csv_files_v8(\n",
    "    root_folder, model_name, results_folder\n",
    ")\n",
    "\n",
    "\n",
    "completion_dict = yaml.safe_load(open(f\"{results_folder}/completion_dict.yaml\", \"r\"))\n",
    "completion_dict[model_map[model_name]] = {\n",
    "    \"completed_simulations\": len(combined_df),\n",
    "    \"total_folders\": len(combined_df) + len(missing_csv_dirs),\n",
    "}\n",
    "with open(f\"{results_folder}/completion_dict.yaml\", \"w\") as f:\n",
    "    yaml.safe_dump(completion_dict, f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## This is just for plotting the values obtained from the model completion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "models = list(completion_dict.keys())\n",
    "total_folders = [info[\"total_folders\"] for info in completion_dict.values()]\n",
    "completed_simulations = [\n",
    "    info[\"completed_simulations\"] for info in completion_dict.values()\n",
    "]\n",
    "\n",
    "# Calculate fractions\n",
    "completed_fractions = [\n",
    "    completed / total for completed, total in zip(completed_simulations, total_folders)\n",
    "]\n",
    "\n",
    "# Calculate the fraction of incomplete simulations\n",
    "incomplete_fractions = [\n",
    "    1 - completed_fraction for completed_fraction in completed_fractions\n",
    "]\n",
    "\n",
    "# Create lighter colors for incomplete simulations by reducing alpha values\n",
    "incomplete_colors = [mcolors.to_rgba(color, alpha=0.4) for color in colors]\n",
    "\n",
    "# Plot\n",
    "fig, ax = plt.subplots(figsize=(8, 6))\n",
    "\n",
    "# Stack bars for completed and incomplete simulations\n",
    "completed_bars = ax.bar(\n",
    "    models, completed_fractions, color=colors, label=\"Completed Simulations\"\n",
    ")\n",
    "incomplete_bars = ax.bar(\n",
    "    models,\n",
    "    incomplete_fractions,\n",
    "    bottom=completed_fractions,\n",
    "    color=incomplete_colors,\n",
    "    label=\"Incomplete Simulations\",\n",
    ")\n",
    "\n",
    "# Add percentage text labels on the bars\n",
    "for i, model in enumerate(models):\n",
    "    # Add text for completed simulations (green color)\n",
    "    ax.text(\n",
    "        model,\n",
    "        completed_fractions[i] / 2,\n",
    "        f\"{completed_fractions[i]*100:.1f}%\",\n",
    "        ha=\"center\",\n",
    "        va=\"center\",\n",
    "        color=\"blue\",\n",
    "        fontsize=12,\n",
    "    )\n",
    "\n",
    "    # Add text for incomplete simulations (red color)\n",
    "    ax.text(\n",
    "        model,\n",
    "        completed_fractions[i] + incomplete_fractions[i] / 2,\n",
    "        f\"{incomplete_fractions[i]*100:.1f}%\",\n",
    "        ha=\"center\",\n",
    "        va=\"center\",\n",
    "        color=\"red\",\n",
    "        fontsize=12,\n",
    "    )\n",
    "\n",
    "# Labels and title\n",
    "ax.set_ylabel(\"Fraction of Simulations\")\n",
    "ax.set_ylim(0, 1.1)  # Set limit for y-axis\n",
    "# ax.set_title('Fraction of Completed & Incomplete Simulations')\n",
    "\n",
    "# Show plot\n",
    "plt.show()\n",
    "plt.savefig(f\"{results_folder}/figs/fraction_of_simulations.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parity plots"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Read the csv data generated for the different model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "combined_data_mace = pd.read_csv(f\"{results_folder}/{model_name}/{model_name}.csv\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Just change model name for different model and set unfiltered_parity = True to plot unfiltered data\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Create figures\n",
    "fig_density, ax_density = plt.subplots(figsize=(6, 6))\n",
    "fig_lattice, ax_lattice = plt.subplots(figsize=(6, 6))\n",
    "# Density data\n",
    "act_density = combined_data_mace[\"Exp_Density (g/cm³)\"].values\n",
    "pred_density = combined_data_mace[\"Sim_Density (g/cm³)\"].values\n",
    "act_a = combined_data_mace[\"Exp_a (Å)\"].values\n",
    "pred_a = combined_data_mace[\"Sim_a (Å)\"].values\n",
    "act_b = combined_data_mace[\"Exp_b (Å)\"].values\n",
    "pred_b = combined_data_mace[\"Sim_b (Å)\"].values\n",
    "\n",
    "act_c = combined_data_mace[\"Exp_c (Å)\"].values\n",
    "pred_c = combined_data_mace[\"Sim_c (Å)\"].values\n",
    "\n",
    "\n",
    "unfiltered_parity = False  # Set to True to plot unfiltered data\n",
    "\n",
    "# Initialize dictionary to store all R2 scores\n",
    "r2_scores_dict = {}\n",
    "\n",
    "# Define marker styles\n",
    "marker_density = \"D\"  # Diamond\n",
    "markers = [\"o\", \"s\", \"^\"]  # Circle, Square, Triangle\n",
    "\n",
    "# Apply masks\n",
    "mask_density = (pred_density <= 1.5 * act_density) & (pred_density >= 0.5 * act_density)\n",
    "mask_a = (pred_a <= 1.5 * act_a) & (pred_a >= 0.5 * act_a)\n",
    "mask_b = (pred_b <= 1.5 * act_b) & (pred_b >= 0.5 * act_b)\n",
    "mask_c = (pred_c <= 1.5 * act_c) & (pred_c >= 0.5 * act_c)\n",
    "mask_final = mask_density & mask_a & mask_b & mask_c\n",
    "\n",
    "if unfiltered_parity:\n",
    "    mask_final = np.ones_like(mask_final, dtype=bool)  # All True\n",
    "\n",
    "# Plot density data\n",
    "r2_density, removed_sys = plot_scatter(\n",
    "    ax_density,\n",
    "    mask_final,\n",
    "    act_density,\n",
    "    pred_density,\n",
    "    \"Density (g/cm³)\",\n",
    "    \"m\",\n",
    "    marker_density,\n",
    "    model_name,\n",
    "    r2_scores_dict,\n",
    ")\n",
    "\n",
    "# Plot lattice parameters\n",
    "r2_scores = []\n",
    "for param, act, pred, color, marker in zip(\n",
    "    [\"Cell Parameter a (Å)\", \"Cell Parameter b (Å)\", \"Cell Parameter c (Å)\"],\n",
    "    [act_a, act_b, act_c],\n",
    "    [pred_a, pred_b, pred_c],\n",
    "    [\"r\", \"g\", \"b\"],\n",
    "    markers,\n",
    "):\n",
    "    r2, removed = plot_scatter(\n",
    "        ax_lattice,\n",
    "        mask_final,\n",
    "        act,\n",
    "        pred,\n",
    "        param,\n",
    "        color,\n",
    "        marker,\n",
    "        model_name,\n",
    "        r2_scores_dict,\n",
    "    )\n",
    "    r2_scores.append(r2)\n",
    "\n",
    "# Set titles and labels\n",
    "ax_density.set_title(f\"Density\\n$R^2$ Score: {r2_density:.2f}\", fontsize=16)\n",
    "ax_density.set_xlabel(\"Experimental Density (g/cm³)\", fontsize=16)\n",
    "ax_density.set_ylabel(\"Simulated Density (g/cm³)\", fontsize=16)\n",
    "ax_density.legend()\n",
    "fig_density.savefig(f\"{results_folder}/{model_name}/figs/density_r2_scores.png\")\n",
    "\n",
    "overall_r2 = (\n",
    "    f\"a: {r2_scores[0]:.2f}, b: {r2_scores[1]:.2f}, c: {r2_scores[2]:.2f}\"\n",
    "    if all(not np.isnan(r2) for r2 in r2_scores)\n",
    "    else \"N/A\"\n",
    ")\n",
    "ax_lattice.set_title(f\"Lattice Parameters\\n$R^2$ Scores: {overall_r2}\", fontsize=16)\n",
    "ax_lattice.set_xlabel(\"Experimental Lattice Parameters (Å)\", fontsize=16)\n",
    "ax_lattice.set_ylabel(\"Simulated Lattice Parameters (Å)\", fontsize=16)\n",
    "ax_lattice.legend(loc=\"upper left\")\n",
    "fig_lattice.savefig(f\"{results_folder}/{model_name}/figs/lattice_r2_scores.png\")\n",
    "\n",
    "r2_scores = yaml.safe_load(open(f\"{results_folder}/r2_scores.yaml\", \"r\"))\n",
    "r2_scores[model_map[model_name]] = r2_scores_dict\n",
    "with open(f\"{results_folder}/r2_scores.yaml\", \"w\") as f:\n",
    "    yaml.safe_dump(r2_scores, f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### This is just for plotting the R2 score saved in txt file from the above run"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Example Data\n",
    "metrics = [\n",
    "    \"Density (g/cm³)\",\n",
    "    \"Cell Parameter a (Å)\",\n",
    "    \"Cell Parameter b (Å)\",\n",
    "    \"Cell Parameter c (Å)\",\n",
    "]  # Bars in each group\n",
    "\n",
    "# Bar settings\n",
    "x = np.arange(len(models))  # Group positions\n",
    "width = 0.2  # Width of each bar\n",
    "\n",
    "# Create the figure and axis\n",
    "fig, ax = plt.subplots(figsize=(8, 6))\n",
    "\n",
    "# Plot bars for each metric with custom colors\n",
    "for i, (metric, color) in enumerate(zip(metrics, colors)):\n",
    "    ax.bar(\n",
    "        x + i * width,\n",
    "        [r2_scores[model][metric] for model in models],\n",
    "        width,\n",
    "        label=metric,\n",
    "        color=color,\n",
    "    )\n",
    "\n",
    "# Customize plot\n",
    "# ax.set_xlabel('Models', fontsize=14)\n",
    "ax.set_ylabel(\"$R^2$ Score\", fontsize=16)\n",
    "ax.set_xticks(x + width * 1.5)  # Adjust group position\n",
    "ax.set_xticklabels(models, fontsize=16)\n",
    "\n",
    "# Position legend over bars\n",
    "ax.legend(\n",
    "    fontsize=16,\n",
    "    title_fontsize=12,\n",
    "    loc=\"upper center\",\n",
    "    bbox_to_anchor=(0.5, 1.2),\n",
    "    ncol=2,\n",
    ")\n",
    "\n",
    "# Add grid and display\n",
    "# ax.grid(axis='y', linestyle='--', alpha=0.7)\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "plt.savefig(f\"{results_folder}/figs/r2_scores.png\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Trajectory based analysis - Set up to run with multiprocessing."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Just change the root folder name and model_name for different model. \n",
    "\n",
    "Splits processing up into `num_cpus()-2` processes and saves out a csv for each split."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def process_slice(args):\n",
    "    root_folder, model_name, slice_number, xyz_files_slice, log_files_slice = args\n",
    "    unique_uuid = uuid.uuid1().__str__()\n",
    "    file_handler = FileHandler(root_folder, incoming_uuid=unique_uuid)\n",
    "    calculator = PropertyCalculator()\n",
    "\n",
    "    master_densities = []\n",
    "    master_lattice_params = []\n",
    "    master_temperature = []\n",
    "    master_rdf_values = []\n",
    "    master_time_temp_data = []\n",
    "    os.makedirs(f\"{model_name}/results/slice_{slice_number}\", exist_ok=True)\n",
    "    for (system_name, xyz_file_path), (_, log_file_path) in tqdm(\n",
    "        zip(xyz_files_slice, log_files_slice),\n",
    "        total=len(xyz_files_slice),\n",
    "        desc=f\"Processing Slice {slice_number}\",\n",
    "    ):\n",
    "        (\n",
    "            densities,\n",
    "            lattice_params,\n",
    "            temperature,\n",
    "            rdf_error,\n",
    "            time_temp_data,\n",
    "            bond_error,\n",
    "        ) = process_file(\n",
    "            file_handler, calculator, system_name, xyz_file_path, log_file_path\n",
    "        )\n",
    "\n",
    "        bond_error_file_name = (\n",
    "            f\"{model_name}/results/slice_{slice_number}/bond_errors_{model_name}.txt\"\n",
    "        )\n",
    "        save_bond_errors_to_txt(bond_error_file_name, bond_error)\n",
    "\n",
    "        master_densities.append(densities)\n",
    "        master_lattice_params.append(lattice_params)\n",
    "        master_temperature.append(temperature)\n",
    "        master_rdf_values.append(rdf_error)\n",
    "        master_time_temp_data.append(time_temp_data)\n",
    "\n",
    "    os.makedirs(f\"{model_name}/results/slice_{slice_number}\", exist_ok=True)\n",
    "    save_to_csv(\n",
    "        f\"{model_name}/results/slice_{slice_number}/master_densities_{model_name}.csv\",\n",
    "        master_densities,\n",
    "    )\n",
    "    save_to_csv(\n",
    "        f\"{model_name}/results/slice_{slice_number}/master_lattice_params_{model_name}.csv\",\n",
    "        master_lattice_params,\n",
    "    )\n",
    "    save_to_csv(\n",
    "        f\"{model_name}/results/slice_{slice_number}/master_temperature_{model_name}.csv\",\n",
    "        [[temp] for temp in master_temperature],\n",
    "    )\n",
    "    save_to_csv(\n",
    "        f\"{model_name}/results/slice_{slice_number}/master_rdf_values_{model_name}.csv\",\n",
    "        master_rdf_values,\n",
    "    )\n",
    "    save_to_csv(\n",
    "        f\"{model_name}/results/slice_{slice_number}/master_time_temp_data_{model_name}.csv\",\n",
    "        master_time_temp_data,\n",
    "    )\n",
    "    print(f\"Data saved for slice {slice_number} with model name '{model_name}'.\")\n",
    "\n",
    "\n",
    "def process_traj_to_csv(root_folder, model_name):\n",
    "    file_handler = FileHandler(root_folder, incoming_uuid=uuid.uuid1().__str__())\n",
    "    xyz_files, log_files = file_handler.find_xyz_files()\n",
    "\n",
    "    total_files = len(xyz_files)\n",
    "    num_slices = cpu_count() - 2\n",
    "    slice_size = total_files // num_slices\n",
    "\n",
    "    args_list = [\n",
    "        (\n",
    "            root_folder,\n",
    "            model_name,\n",
    "            slice_number,\n",
    "            xyz_files[slice_number * slice_size : (slice_number + 1) * slice_size],\n",
    "            log_files[slice_number * slice_size : (slice_number + 1) * slice_size],\n",
    "        )\n",
    "        for slice_number in range(num_slices)\n",
    "    ]\n",
    "\n",
    "    with Pool(num_slices) as pool:\n",
    "        pool.map(process_slice, args_list)\n",
    "\n",
    "\n",
    "process_traj_to_csv(root_folder, model_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "#### Combines all splits into `./results_folder/model_name/all`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def combine_csv_files(input_pattern, output_file):\n",
    "    combined_data = []\n",
    "    headers = set()\n",
    "\n",
    "    # First pass to collect all unique headers\n",
    "    for csv_file in glob(input_pattern, recursive=True):\n",
    "        with open(csv_file, \"r\") as f:\n",
    "            reader = csv.reader(f)\n",
    "            file_header = tuple(next(reader))\n",
    "            headers.update(file_header)\n",
    "\n",
    "    headers = sorted(headers)\n",
    "    header_index_map = {header: index for index, header in enumerate(headers)}\n",
    "\n",
    "    # Second pass to read data and align columns\n",
    "    for csv_file in glob(input_pattern, recursive=True):\n",
    "        with open(csv_file, \"r\") as f:\n",
    "            reader = csv.reader(f)\n",
    "            file_header = tuple(next(reader))\n",
    "            file_header_index_map = {\n",
    "                header: index for index, header in enumerate(file_header)\n",
    "            }\n",
    "\n",
    "            for row in reader:\n",
    "                aligned_row = [np.nan] * len(headers)\n",
    "                for header, value in zip(file_header, row):\n",
    "                    aligned_row[header_index_map[header]] = value\n",
    "                combined_data.append(aligned_row)\n",
    "\n",
    "    # Write combined data to output file\n",
    "    with open(output_file, \"w\", newline=\"\") as f:\n",
    "        writer = csv.writer(f)\n",
    "        writer.writerow(headers)\n",
    "        writer.writerows(combined_data)\n",
    "\n",
    "\n",
    "def combine_bond_error_files(input_pattern, output_file):\n",
    "    with open(output_file, \"w\") as outfile:\n",
    "        for txt_file in glob(input_pattern, recursive=True):\n",
    "            with open(txt_file, \"r\") as infile:\n",
    "                outfile.write(infile.read())\n",
    "\n",
    "\n",
    "def combine_all_csvs(model_name):\n",
    "    all_folder = os.path.join(f\"{results_folder}/{model_name}\", \"all\")\n",
    "    os.makedirs(all_folder, exist_ok=True)\n",
    "\n",
    "    combine_csv_files(\n",
    "        os.path.join(\n",
    "            f\"{results_folder}/{model_name}\",\n",
    "            \"slice_*\",\n",
    "            f\"master_densities_{model_name}.csv\",\n",
    "        ),\n",
    "        os.path.join(all_folder, f\"master_densities_{model_name}.csv\"),\n",
    "    )\n",
    "    combine_csv_files(\n",
    "        os.path.join(\n",
    "            f\"{results_folder}/{model_name}\",\n",
    "            \"slice_*\",\n",
    "            f\"master_lattice_params_{model_name}.csv\",\n",
    "        ),\n",
    "        os.path.join(all_folder, f\"master_lattice_params_{model_name}.csv\"),\n",
    "    )\n",
    "    combine_csv_files(\n",
    "        os.path.join(\n",
    "            f\"{results_folder}/{model_name}\",\n",
    "            \"slice_*\",\n",
    "            f\"master_temperature_{model_name}.csv\",\n",
    "        ),\n",
    "        os.path.join(all_folder, f\"master_temperature_{model_name}.csv\"),\n",
    "    )\n",
    "    combine_csv_files(\n",
    "        os.path.join(\n",
    "            f\"{results_folder}/{model_name}\",\n",
    "            \"slice_*\",\n",
    "            f\"master_rdf_values_{model_name}.csv\",\n",
    "        ),\n",
    "        os.path.join(all_folder, f\"master_rdf_values_{model_name}.csv\"),\n",
    "    )\n",
    "    combine_csv_files(\n",
    "        os.path.join(\n",
    "            f\"{results_folder}/{model_name}\",\n",
    "            \"slice_*\",\n",
    "            f\"master_time_temp_data_{model_name}.csv\",\n",
    "        ),\n",
    "        os.path.join(all_folder, f\"master_time_temp_data_{model_name}.csv\"),\n",
    "    )\n",
    "\n",
    "    # Combine bond error files\n",
    "    combine_bond_error_files(\n",
    "        os.path.join(f\"{results_folder}/{model_name}\", \"slice_*\", \"bond_errors_*.txt\"),\n",
    "        os.path.join(all_folder, f\"bond_errors_{model_name}.txt\"),\n",
    "    )\n",
    "\n",
    "    print(f\"All data combined and saved in {all_folder}\")\n",
    "\n",
    "\n",
    "combine_all_csvs(model_name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Read the saved master csv file for density, rdf and plot the time progress of error"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "master_densities = pd.read_csv(\n",
    "    f\"results/{model_name}/all/master_densities_mattersim.csv\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "master_densities = np.array(master_densities)\n",
    "\n",
    "# Calculate percentage error from initial value for each trajectory\n",
    "initial_densities = master_densities[:, 0:1]\n",
    "percentage_errors = (\n",
    "    -1 * ((master_densities - initial_densities) / initial_densities) * 100\n",
    ")\n",
    "\n",
    "# Define error bins\n",
    "error_bins = [0, 2, 5, 10, np.inf]\n",
    "bin_labels = [\"[0, 2)%\", \"[2, 5)%\", \"[5, 10)%\", \"[10, -∞)%\"]\n",
    "\n",
    "# Count trajectories in each bin at each timestep\n",
    "timesteps = master_densities.shape[1]\n",
    "binned_counts = np.zeros((len(bin_labels), timesteps))\n",
    "\n",
    "for t in range(timesteps):\n",
    "    bins = np.digitize(percentage_errors[:, t], error_bins[:-1])\n",
    "    for i in range(len(bin_labels)):\n",
    "        binned_counts[i, t] = np.sum(bins == i + 1)\n",
    "\n",
    "# Calculate mean and standard deviation of percentage errors\n",
    "mean_errors = np.mean(percentage_errors, axis=0)\n",
    "std_errors = np.std(percentage_errors, axis=0)\n",
    "\n",
    "# Define the x-axis values (timesteps)\n",
    "x_values = np.arange(timesteps)\n",
    "\n",
    "# Create the combined plot\n",
    "fig, ax1 = plt.subplots(figsize=(15, 6))\n",
    "\n",
    "# Plot the area plot (stackplot) on the first y-axis\n",
    "stack = ax1.stackplot(\n",
    "    np.log(x_values + 1), binned_counts, labels=bin_labels, colors=colors\n",
    ")\n",
    "ax1.set_xlabel(\"Timesteps (log scale)\")\n",
    "ax1.set_ylabel(\"Number of Simulations\")\n",
    "\n",
    "# Create a second y-axis\n",
    "ax2 = ax1.twinx()\n",
    "\n",
    "# Plot the mean trajectory with error fill on the second y-axis\n",
    "(mean_line,) = ax2.plot(\n",
    "    np.log(x_values + 1), mean_errors, label=\"Mean Error Trajectory\", color=\"blue\"\n",
    ")\n",
    "ax2.set_ylabel(\"Percentage Density Error (%)\", color=\"blue\")\n",
    "# ax2.set_ylim(0, 19)  # Adjust based on the data\n",
    "ax2.tick_params(axis=\"y\", labelcolor=\"blue\")\n",
    "ax2.spines[\"right\"].set_color(\"blue\")\n",
    "\n",
    "# Combine legends into one\n",
    "(\n",
    "    handles,\n",
    "    labels,\n",
    ") = ax1.get_legend_handles_labels()  # Get handles and labels from stackplot\n",
    "handles.append(mean_line)  # Add the mean trajectory line\n",
    "labels.append(\"Mean Error Trajectory\")  # Add the corresponding label\n",
    "\n",
    "# Add a single legend with appropriate size and placement\n",
    "ax1.legend(\n",
    "    handles,\n",
    "    labels,\n",
    "    loc=\"upper center\",\n",
    "    bbox_to_anchor=(0.5, 1.1),  # Adjusted position for combined legend\n",
    "    fontsize=\"small\",  # Set smaller font size for better fit\n",
    "    frameon=False,  # Remove legend box outline for a cleaner look\n",
    "    ncol=len(bin_labels) + 1,  # Adjust number of columns\n",
    ")\n",
    "\n",
    "# Add \"Error Range\" text\n",
    "plt.text(\n",
    "    -0.05, 1.02, \"Error Ranges:\", transform=plt.gca().transAxes, ha=\"left\", fontsize=16\n",
    ")\n",
    "\n",
    "plt.tight_layout()\n",
    "plt.show()\n",
    "plt.savefig(f\"{results_folder}/figs/error_ranges.png\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}