// Shared JavaScript functions for TRIMSP-NL Workbench. const electronExecSync = (typeof module !== 'undefined' && module.exports) ? require('child_process').execSync : null; // This is an object that contains all GUI ids and values var All = new Object(); // True while a simulation scan is running. Blocks re-entrant Run clicks that // would otherwise reassign the global All and let two scans write the same // files concurrently. var runInProgress = false; function isObject(item) { // simple object check // https://stackoverflow.com/a/34749873 return (item && typeof item === 'object' && !Array.isArray(item)); } function mergeDeep(target, ...sources) { // function for deep-merging objects // https://stackoverflow.com/a/34749873 if (!sources.length) { return target; } const source = sources.shift(); if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject(source[key])) { if (!target[key]) Object.assign(target, { [key]: {} }); mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return mergeDeep(target, ...sources); } // element data const elements = { "H": { "Z": 1, "A": 1.008, "rho": 0.08, "Elast": 0.1 }, "He": { "Z": 2, "A": 4.003, "rho": 0.12, "Elast": 0.1 }, "Li": { "Z": 3, "A": 6.939, "rho": 0.53, "Elast": 1.63 }, "Be": { "Z": 4, "A": 9.012, "rho": 1.85, "Elast": 3.32 }, "B": { "Z": 5, "A": 10.811, "rho": 2.34, "Elast": 5.77 }, "C": { "Z": 6, "A": 12.011, "rho": 2.26, "Elast": 7.37 }, "N": { "Z": 7, "A": 14.007, "rho": 1.03, "Elast": 4.92 }, "O": { "Z": 8, "A": 15.999, "rho": 2, "Elast": 2.6 }, "F": { "Z": 9, "A": 18.998, "rho": 1.11, "Elast": 0.84 }, "Ne": { "Z": 10, "A": 20.183, "rho": 1.5, "Elast": 0.02 }, "Na": { "Z": 11, "A": 22.99, "rho": 0.97, "Elast": 1.11 }, "Mg": { "Z": 12, "A": 24.312, "rho": 1.74, "Elast": 1.51 }, "Al": { "Z": 13, "A": 26.982, "rho": 2.7, "Elast": 3.39 }, "Si": { "Z": 14, "A": 28.086, "rho": 2.33, "Elast": 4.63 }, "P": { "Z": 15, "A": 30.974, "rho": 1, "Elast": 3.43 }, "S": { "Z": 16, "A": 32.064, "rho": 2.07, "Elast": 2.85 }, "Cl": { "Z": 17, "A": 35.453, "rho": 2.03, "Elast": 1.4 }, "Ar": { "Z": 18, "A": 39.948, "rho": 1.77, "Elast": 0.08 }, "K": { "Z": 19, "A": 39.102, "rho": 0.86, "Elast": 0.93 }, "Ca": { "Z": 20, "A": 40.08, "rho": 1.55, "Elast": 1.84 }, "Sc": { "Z": 21, "A": 44.956, "rho": 2.99, "Elast": 3.9 }, "Ti": { "Z": 22, "A": 47.9, "rho": 4.54, "Elast": 4.85 }, "V": { "Z": 23, "A": 50.942, "rho": 6.11, "Elast": 5.31 }, "Cr": { "Z": 24, "A": 51.996, "rho": 7.19, "Elast": 4.1 }, "Mn": { "Z": 25, "A": 54.938, "rho": 7.43, "Elast": 2.92 }, "Fe": { "Z": 26, "A": 55.847, "rho": 7.87, "Elast": 4.28 }, "Co": { "Z": 27, "A": 58.933, "rho": 8.9, "Elast": 4.39 }, "Ni": { "Z": 28, "A": 58.71, "rho": 8.9, "Elast": 4.44 }, "Cu": { "Z": 29, "A": 63.54, "rho": 8.96, "Elast": 3.49 }, "Zn": { "Z": 30, "A": 65.37, "rho": 7.13, "Elast": 1.35 }, "Ga": { "Z": 31, "A": 69.72, "rho": 5.91, "Elast": 2.81 }, "Ge": { "Z": 32, "A": 72.59, "rho": 5.32, "Elast": 3.85 }, "As": { "Z": 33, "A": 74.922, "rho": 5.72, "Elast": 2.96 }, "Se": { "Z": 34, "A": 78.96, "rho": 4.79, "Elast": 2.25 }, "Br": { "Z": 35, "A": 79.909, "rho": 3.14, "Elast": 1.22 }, "Kr": { "Z": 36, "A": 83.8, "rho": 3.1, "Elast": 0.12 }, "Rb": { "Z": 37, "A": 85.47, "rho": 1.53, "Elast": 0.85 }, "Sr": { "Z": 38, "A": 87.62, "rho": 2.54, "Elast": 1.72 }, "Y": { "Z": 39, "A": 88.905, "rho": 4.47, "Elast": 4.37 }, "Zr": { "Z": 40, "A": 91.22, "rho": 6.51, "Elast": 6.25 }, "Nb": { "Z": 41, "A": 92.906, "rho": 8.57, "Elast": 7.57 }, "Mo": { "Z": 42, "A": 95.94, "rho": 10.22, "Elast": 6.82 }, "Tc": { "Z": 43, "A": 98, "rho": 11.5, "Elast": 6.85 }, "Ru": { "Z": 44, "A": 101.07, "rho": 12.37, "Elast": 6.74 }, "Rh": { "Z": 45, "A": 102.905, "rho": 12.41, "Elast": 5.75 }, "Pd": { "Z": 46, "A": 106.4, "rho": 12.02, "Elast": 3.89 }, "Ag": { "Z": 47, "A": 107.87, "rho": 10.5, "Elast": 2.95 }, "Cd": { "Z": 48, "A": 112.4, "rho": 8.65, "Elast": 1.16 }, "In": { "Z": 49, "A": 114.82, "rho": 7.31, "Elast": 2.52 }, "Sn": { "Z": 50, "A": 118.69, "rho": 7.31, "Elast": 3.14 }, "Sb": { "Z": 51, "A": 121.75, "rho": 6.68, "Elast": 2.75 }, "Te": { "Z": 52, "A": 127.6, "rho": 6.24, "Elast": 2.23 }, "I": { "Z": 53, "A": 126.904, "rho": 4.93, "Elast": 1.11 }, "Xe": { "Z": 54, "A": 131.3, "rho": 3.8, "Elast": 0.16 }, "Cs": { "Z": 55, "A": 132.905, "rho": 1.9, "Elast": 0.8 }, "Ba": { "Z": 56, "A": 137.34, "rho": 3.59, "Elast": 1.9 }, "La": { "Z": 57, "A": 138.91, "rho": 6.15, "Elast": 4.47 }, "Ce": { "Z": 58, "A": 140.12, "rho": 6.77, "Elast": 4.32 }, "Pr": { "Z": 59, "A": 140.907, "rho": 6.77, "Elast": 3.7 }, "Nd": { "Z": 60, "A": 144.24001, "rho": 7.01, "Elast": 3.4 }, "Pm": { "Z": 61, "A": 147, "rho": 7.22, "Elast": 0.1 }, "Sm": { "Z": 62, "A": 150.35001, "rho": 7.52, "Elast": 2.14 }, "Eu": { "Z": 63, "A": 151.96001, "rho": 5.24, "Elast": 1.86 }, "Gd": { "Z": 64, "A": 157.25, "rho": 7.9, "Elast": 4.14 }, "Tb": { "Z": 65, "A": 158.924, "rho": 8.23, "Elast": 4.05 }, "Dy": { "Z": 66, "A": 162.5, "rho": 8.55, "Elast": 3.04 }, "Ho": { "Z": 67, "A": 164.92999, "rho": 8.8, "Elast": 3.14 }, "Er": { "Z": 68, "A": 167.25999, "rho": 9.07, "Elast": 3.29 }, "Tm": { "Z": 69, "A": 168.93401, "rho": 9.32, "Elast": 2.42 }, "Yb": { "Z": 70, "A": 173.03999, "rho": 6.9, "Elast": 1.6 }, "Lu": { "Z": 71, "A": 174.97, "rho": 9.84, "Elast": 4.43 }, "Hf": { "Z": 72, "A": 178.49001, "rho": 13.31, "Elast": 6.44 }, "Ta": { "Z": 73, "A": 180.948, "rho": 16.65, "Elast": 8.1 }, "W": { "Z": 74, "A": 183.85001, "rho": 19.35, "Elast": 8.9 }, "Re": { "Z": 75, "A": 186.2, "rho": 21.04, "Elast": 8.03 }, "Os": { "Z": 76, "A": 190.2, "rho": 22.6, "Elast": 8.17 }, "Ir": { "Z": 77, "A": 192.2, "rho": 22.4, "Elast": 6.94 }, "Pt": { "Z": 78, "A": 195.09, "rho": 21.45, "Elast": 5.84 }, "Au": { "Z": 79, "A": 196.967, "rho": 19.32, "Elast": 3.81 }, "Hg": { "Z": 80, "A": 200.59, "rho": 13.55, "Elast": 0.67 }, "Tl": { "Z": 81, "A": 204.37, "rho": 11.85, "Elast": 1.88 }, "Pb": { "Z": 82, "A": 207.19, "rho": 11.35, "Elast": 2.03 }, "Bi": { "Z": 83, "A": 208.98, "rho": 9.75, "Elast": 2.18 }, "Po": { "Z": 84, "A": 210, "rho": 9.3, "Elast": 1.5 }, "At": { "Z": 85, "A": 210, "rho": 0, "Elast": 0.1 }, "Rn": { "Z": 86, "A": 222, "rho": 0, "Elast": 0.2 }, "Fr": { "Z": 87, "A": 223, "rho": 0, "Elast": 0.1 }, "Ra": { "Z": 88, "A": 226, "rho": 0, "Elast": 1.66 }, "Ac": { "Z": 89, "A": 227, "rho": 0, "Elast": 4.25 }, "Th": { "Z": 90, "A": 232.03799, "rho": 11.72, "Elast": 6.2 }, "Pa": { "Z": 91, "A": 231, "rho": 15.4, "Elast": 0.1 }, "U": { "Z": 92, "A": 238.03, "rho": 18.95, "Elast": 5.55 }, "": { "Z": 0, "A": 0, "rho": 0, "Elast": 0 } } // projectile data const projectiles = { "muon": { "Z": 1, "A": 0.1134289259, "rho": 0, "Elast": 0, "ICRU": [], "IAEA": [] }, "Li-8": { "Z": 3, "A": 8.02248624, "rho": 0, "Elast": 0, "ICRU": [], "IAEA": [] }, "B-12": { "Z": 5, "A": 12.0143526, "rho": 0, "Elast": 0, "ICRU": [], "IAEA": [] }, "Mg-31": { "Z": 12, "A": 30.996648, "rho": 0, "Elast": 0, "ICRU": [], "IAEA": [] } } // electronic stopping coefficients from Anderson & Zeigler (1977). const az_table = { "H": { "AZ": [ 1.262, 1.44, 242.6, 12000.0, 0.1159 ] }, "He": { "AZ": [ 1.229, 1.397, 484.5, 5873.0, 0.05225 ] }, "Li": { "AZ": [ 1.411, 1.6, 725.6, 3013.0, 0.04578 ] }, "Be": { "AZ": [ 2.248, 2.59, 966.0, 153.8, 0.03475 ] }, "B": { "AZ": [ 2.474, 2.815, 1206.0, 1060.0, 0.02855 ] }, "C": { "AZ": [ 2.631, 2.989, 1445.0, 957.2, 0.02819 ] }, "N": { "AZ": [ 2.954, 3.35, 1683.0, 1900.0, 0.02513 ] }, "O": { "AZ": [ 2.652, 3.0, 1920.0, 2000.0, 0.0223 ] }, "F": { "AZ": [ 2.085, 2.352, 2157.0, 2634.0, 0.01816 ] }, "Ne": { "AZ": [ 1.951, 2.199, 2393.0, 2699.0, 0.01568 ] }, "Na": { "AZ": [ 2.542, 2.869, 2628.0, 1854.0, 0.01472 ] }, "Mg": { "AZ": [ 3.792, 4.293, 2862.0, 1009.0, 0.01397 ] }, "Al": { "AZ": [ 4.154, 4.739, 2766.0, 164.5, 0.01397 ] }, "Si": { "AZ": [ 4.15, 4.7, 3329.0, 550.0, 0.01321 ] }, "P": { "AZ": [ 3.232, 3.647, 3561.0, 1560.0, 0.01267 ] }, "S": { "AZ": [ 3.447, 3.891, 3792.0, 1219.0, 0.01211 ] }, "Cl": { "AZ": [ 5.047, 5.714, 4023.0, 878.6, 0.01178 ] }, "Ar": { "AZ": [ 5.731, 6.5, 4253.0, 530.0, 0.01123 ] }, "K": { "AZ": [ 5.151, 5.833, 4482.0, 545.7, 0.01129 ] }, "Ca": { "AZ": [ 5.521, 6.252, 4710.0, 553.3, 0.01112 ] }, "Sc": { "AZ": [ 5.201, 5.884, 4938.0, 560.9, 0.009995 ] }, "Ti": { "AZ": [ 4.862, 5.496, 5165.0, 568.5, 0.009474 ] }, "V": { "AZ": [ 4.48, 5.055, 5391.0, 952.3, 0.009117 ] }, "Cr": { "AZ": [ 3.983, 4.489, 5616.0, 1336.0, 0.008413 ] }, "Mn": { "AZ": [ 3.469, 3.907, 5725.0, 1461.0, 0.008829 ] }, "Fe": { "AZ": [ 3.519, 3.963, 6065.0, 1243.0, 0.007782 ] }, "Co": { "AZ": [ 3.14, 3.535, 6288.0, 1372.0, 0.007361 ] }, "Ni": { "AZ": [ 3.553, 4.004, 6205.0, 555.1, 0.008763 ] }, "Cu": { "AZ": [ 3.696, 4.175, 4673.0, 387.8, 0.02188 ] }, "Zn": { "AZ": [ 4.21, 4.75, 6953.0, 295.2, 0.006809 ] }, "Ga": { "AZ": [ 5.041, 5.697, 7173.0, 202.6, 0.006725 ] }, "Ge": { "AZ": [ 5.554, 6.3, 6496.0, 110.0, 0.009689 ] }, "As": { "AZ": [ 5.323, 6.012, 7611.0, 292.5, 0.006447 ] }, "Se": { "AZ": [ 5.874, 6.656, 7395.0, 117.5, 0.007684 ] }, "Br": { "AZ": [ 5.611, 6.335, 8046.0, 365.2, 0.006244 ] }, "Kr": { "AZ": [ 6.411, 7.25, 8262.0, 220.0, 0.006087 ] }, "Rb": { "AZ": [ 5.694, 6.429, 8478.0, 292.9, 0.006087 ] }, "Sr": { "AZ": [ 6.339, 7.159, 8693.0, 330.3, 0.006003 ] }, "Y": { "AZ": [ 6.407, 7.234, 8907.0, 367.8, 0.005889 ] }, "Zr": { "AZ": [ 6.734, 7.603, 9120.0, 405.2, 0.005765 ] }, "Nb": { "AZ": [ 6.902, 7.791, 9333.0, 442.7, 0.005587 ] }, "Mo": { "AZ": [ 6.425, 7.248, 9545.0, 480.2, 0.005367 ] }, "Tc": { "AZ": [ 6.799, 7.671, 9756.0, 517.6, 0.005315 ] }, "Ru": { "AZ": [ 6.108, 6.887, 9966.0, 555.1, 0.005151 ] }, "Rh": { "AZ": [ 5.924, 6.677, 10180.0, 592.5, 0.004919 ] }, "Pd": { "AZ": [ 5.238, 5.9, 10380.0, 630.0, 0.004758 ] }, "Ag": { "AZ": [ 5.623, 6.354, 7160.0, 337.6, 0.01394 ] }, "Cd": { "AZ": [ 5.814, 6.554, 10800.0, 355.5, 0.004626 ] }, "In": { "AZ": [ 6.23, 7.024, 11010.0, 370.9, 0.00454 ] }, "Sn": { "AZ": [ 6.41, 7.227, 11210.0, 386.4, 0.004474 ] }, "Sb": { "AZ": [ 7.5, 8.48, 8608.0, 348.0, 0.009074 ] }, "Te": { "AZ": [ 6.979, 7.871, 11620.0, 392.4, 0.004402 ] }, "I": { "AZ": [ 7.725, 8.716, 11830.0, 394.8, 0.004376 ] }, "Xe": { "AZ": [ 8.231, 9.289, 12030.0, 397.3, 0.004384 ] }, "Cs": { "AZ": [ 7.287, 8.218, 12230.0, 399.7, 0.004447 ] }, "Ba": { "AZ": [ 7.899, 8.911, 12430.0, 402.1, 0.004511 ] }, "La": { "AZ": [ 8.041, 9.071, 12630.0, 404.5, 0.00454 ] }, "Ce": { "AZ": [ 7.489, 8.444, 12830.0, 406.9, 0.00442 ] }, "Pr": { "AZ": [ 7.291, 8.219, 13030.0, 409.3, 0.004298 ] }, "Nd": { "AZ": [ 7.098, 8.0, 13230.0, 411.8, 0.004182 ] }, "Pm": { "AZ": [ 6.91, 7.786, 13430.0, 414.2, 0.004058 ] }, "Sm": { "AZ": [ 6.728, 7.58, 13620.0, 416.6, 0.003976 ] }, "Eu": { "AZ": [ 6.551, 7.38, 13820.0, 419.0, 0.003877 ] }, "Gd": { "AZ": [ 6.739, 7.592, 14020.0, 421.4, 0.003863 ] }, "Tb": { "AZ": [ 6.212, 6.996, 14210.0, 423.9, 0.003725 ] }, "Dy": { "AZ": [ 5.517, 6.21, 14400.0, 426.3, 0.003632 ] }, "Ho": { "AZ": [ 5.219, 5.874, 14600.0, 428.7, 0.003498 ] }, "Er": { "AZ": [ 5.071, 5.706, 14790.0, 433.0, 0.003405 ] }, "Tm": { "AZ": [ 4.926, 5.542, 14980.0, 433.5, 0.003342 ] }, "Yb": { "AZ": [ 4.787, 5.386, 15170.0, 435.9, 0.003292 ] }, "Lu": { "AZ": [ 4.893, 5.505, 15360.0, 438.4, 0.003243 ] }, "Hf": { "AZ": [ 5.028, 5.657, 15550.0, 440.8, 0.003195 ] }, "Ta": { "AZ": [ 4.738, 5.329, 15740.0, 443.2, 0.003186 ] }, "W": { "AZ": [ 4.574, 5.144, 15930.0, 442.4, 0.003144 ] }, "Re": { "AZ": [ 5.2, 5.851, 16120.0, 441.6, 0.003122 ] }, "Os": { "AZ": [ 5.07, 5.704, 16300.0, 440.9, 0.003082 ] }, "Ir": { "AZ": [ 4.945, 5.563, 16490.0, 440.1, 0.002965 ] }, "Pt": { "AZ": [ 4.476, 5.034, 16670.0, 439.3, 0.002871 ] }, "Au": { "AZ": [ 4.856, 5.46, 18320.0, 438.5, 0.002542 ] }, "Hg": { "AZ": [ 4.308, 4.843, 17040.0, 487.8, 0.002882 ] }, "Tl": { "AZ": [ 4.723, 5.311, 17220.0, 537.0, 0.002913 ] }, "Pb": { "AZ": [ 5.319, 5.982, 17400.0, 586.3, 0.002871 ] }, "Bi": { "AZ": [ 5.956, 6.7, 17800.0, 677.0, 0.00266 ] }, "Po": { "AZ": [ 6.158, 6.928, 17770.0, 586.3, 0.002812 ] }, "At": { "AZ": [ 6.204, 6.979, 17950.0, 586.3, 0.002776 ] }, "Rn": { "AZ": [ 6.181, 6.954, 18120.0, 586.3, 0.002748 ] }, "Fr": { "AZ": [ 6.949, 7.82, 18300.0, 586.3, 0.002737 ] }, "Ra": { "AZ": [ 7.506, 8.448, 18480.0, 586.3, 0.002727 ] }, "Ac": { "AZ": [ 7.649, 8.609, 18660.0, 586.3, 0.002697 ] }, "Th": { "AZ": [ 7.71, 8.679, 18830.0, 586.3, 0.002641 ] }, "Pa": { "AZ": [ 7.407, 8.336, 19010.0, 586.3, 0.002603 ] }, "U": { "AZ": [ 7.29, 8.204, 19180.0, 586.3, 0.002573 ] } } // electronic stopping coefficients from Berger et al. (1991) const icru_table = { "H": { "ICRU": [ 1.254, 1.44, 242.6, 12000.0, 0.1159 ] }, "He": { "ICRU": [ 1.229, 1.397, 484.5, 5873.0, 0.05225 ] }, "Li": { "ICRU": [ 1.411, 1.6, 725.6, 3013.0, 0.04578 ] }, "Be": { "ICRU": [ 2.248, 2.59, 966.0, 153.8, 0.03475 ] }, "B": { "ICRU": [ 2.474, 2.815, 1206.0, 1060.0, 0.02855 ] }, "C": { "ICRU": [ 2.2977695717982596, 2.601, 1701.0, 1279.0, 0.01638 ] }, "N": { "ICRU": [ 2.954, 3.35, 1683.0, 1900.0, 0.02513 ] }, "O": { "ICRU": [ 2.652, 3.0, 1920.0, 2000.0, 0.0223 ] }, "F": { "ICRU": [ 2.085, 2.352, 2157.0, 2634.0, 0.01816 ] }, "Ne": { "ICRU": [ 1.951, 2.199, 2393.0, 2699.0, 0.01568 ] }, "Na": { "ICRU": [ 2.542, 2.869, 2628.0, 1854.0, 0.01472 ] }, "Mg": { "ICRU": [ 3.791, 4.293, 2862.0, 1009.0, 0.01397 ] }, "Al": { "ICRU": [ 4.154, 4.739, 2766.0, 164.5, 0.02023 ] }, "Si": { "ICRU": [ 4.914, 5.598, 3193.0, 232.7, 0.01419 ] }, "P": { "ICRU": [ 3.232, 3.647, 3561.0, 1560.0, 0.01267 ] }, "S": { "ICRU": [ 3.447, 3.891, 3792.0, 1219.0, 0.01211 ] }, "Cl": { "ICRU": [ 5.301, 6.008, 3969.0, 645.1, 0.01183 ] }, "Ar": { "ICRU": [ 5.731, 6.5, 4253.0, 530.0, 0.01123 ] }, "K": { "ICRU": [ 5.152, 5.833, 4482.0, 545.7, 0.01129 ] }, "Ca": { "ICRU": [ 5.521, 6.252, 4710.0, 553.3, 0.01112 ] }, "Sc": { "ICRU": [ 5.201, 5.884, 4938.0, 560.9, 0.009995 ] }, "Ti": { "ICRU": [ 4.858, 5.489, 5260.0, 651.1, 0.00893 ] }, "V": { "ICRU": [ 4.479, 5.055, 5391.0, 952.3, 0.009117 ] }, "Cr": { "ICRU": [ 3.983, 4.489, 5616.0, 1336.0, 0.008413 ] }, "Mn": { "ICRU": [ 3.469, 3.907, 5725.0, 1461.0, 0.008829 ] }, "Fe": { "ICRU": [ 3.519, 3.963, 6065.0, 1243.0, 0.007782 ] }, "Co": { "ICRU": [ 3.14, 3.535, 6288.0, 1372.0, 0.007361 ] }, "Ni": { "ICRU": [ 3.553, 4.004, 6205.0, 555.1, 0.008763 ] }, "Cu": { "ICRU": [ 3.696, 4.194, 4649.0, 81.13, 0.02242 ] }, "Zn": { "ICRU": [ 4.21, 4.75, 6953.0, 295.2, 0.006809 ] }, "Ga": { "ICRU": [ 5.041, 5.697, 7173.0, 202.6, 0.006725 ] }, "Ge": { "ICRU": [ 5.554, 6.3, 6496.0, 110.0, 0.009689 ] }, "As": { "ICRU": [ 5.323, 6.012, 7611.0, 292.5, 0.006447 ] }, "Se": { "ICRU": [ 5.874, 6.656, 7395.0, 117.5, 0.007684 ] }, "Br": { "ICRU": [ 6.658, 7.536, 7694.0, 222.3, 0.006509 ] }, "Kr": { "ICRU": [ 6.413, 7.24, 11850.0, 153.7, 0.00288 ] }, "Rb": { "ICRU": [ 5.694, 6.429, 8478.0, 292.9, 0.006087 ] }, "Sr": { "ICRU": [ 6.339, 7.159, 8693.0, 330.3, 0.006003 ] }, "Y": { "ICRU": [ 6.407, 7.234, 8907.0, 367.8, 0.005889 ] }, "Zr": { "ICRU": [ 6.734, 7.603, 9120.0, 405.2, 0.005765 ] }, "Nb": { "ICRU": [ 6.901, 7.791, 9333.0, 442.7, 0.005587 ] }, "Mo": { "ICRU": [ 6.424, 7.248, 9545.0, 480.2, 0.005376 ] }, "Tc": { "ICRU": [ 6.799, 7.671, 9756.0, 517.6, 0.005315 ] }, "Ru": { "ICRU": [ 6.109, 6.887, 9966.0, 555.1, 0.005151 ] }, "Rh": { "ICRU": [ 5.924, 6.677, 10180.0, 592.5, 0.004919 ] }, "Pd": { "ICRU": [ 5.238, 5.9, 10380.0, 630.0, 0.004758 ] }, "Ag": { "ICRU": [ 5.345, 6.038, 6790.0, 397.8, 0.01676 ] }, "Cd": { "ICRU": [ 5.814, 6.554, 10800.0, 355.5, 0.004626 ] }, "In": { "ICRU": [ 6.229, 7.024, 11010.0, 370.9, 0.00454 ] }, "Sn": { "ICRU": [ 6.409, 7.227, 11210.0, 386.4, 0.004474 ] }, "Sb": { "ICRU": [ 7.5, 8.48, 8608.0, 348.0, 0.009074 ] }, "Te": { "ICRU": [ 6.979, 7.871, 11620.0, 392.4, 0.004402 ] }, "I": { "ICRU": [ 7.725, 8.716, 11830.0, 394.8, 0.004376 ] }, "Xe": { "ICRU": [ 8.337, 9.425, 10510.0, 269.6, 0.006206 ] }, "Cs": { "ICRU": [ 7.287, 8.218, 12230.0, 399.7, 0.004447 ] }, "Ba": { "ICRU": [ 7.899, 8.911, 12430.0, 402.1, 0.004511 ] }, "La": { "ICRU": [ 8.041, 9.071, 12630.0, 404.5, 0.00454 ] }, "Ce": { "ICRU": [ 7.488, 8.444, 12830.0, 406.9, 0.00442 ] }, "Pr": { "ICRU": [ 7.291, 8.219, 13030.0, 409.3, 0.004298 ] }, "Nd": { "ICRU": [ 7.098, 8.0, 13230.0, 411.8, 0.004182 ] }, "Pm": { "ICRU": [ 6.909, 7.786, 13430.0, 414.2, 0.004058 ] }, "Sm": { "ICRU": [ 6.728, 7.58, 13620.0, 416.6, 0.003976 ] }, "Eu": { "ICRU": [ 6.551, 7.38, 13820.0, 419.0, 0.003877 ] }, "Gd": { "ICRU": [ 6.739, 7.592, 14020.0, 421.4, 0.003863 ] }, "Tb": { "ICRU": [ 6.212, 6.996, 14210.0, 423.9, 0.003725 ] }, "Dy": { "ICRU": [ 5.517, 6.21, 14400.0, 426.3, 0.003632 ] }, "Ho": { "ICRU": [ 5.22, 5.874, 14600.0, 428.7, 0.003498 ] }, "Er": { "ICRU": [ 5.071, 5.706, 14790.0, 433.0, 0.003405 ] }, "Tm": { "ICRU": [ 4.926, 5.542, 14980.0, 433.5, 0.003342 ] }, "Yb": { "ICRU": [ 4.788, 5.386, 15170.0, 435.9, 0.003292 ] }, "Lu": { "ICRU": [ 4.893, 5.505, 15360.0, 438.4, 0.003243 ] }, "Hf": { "ICRU": [ 5.028, 5.657, 15550.0, 440.8, 0.003195 ] }, "Ta": { "ICRU": [ 4.738, 5.329, 15740.0, 443.2, 0.003186 ] }, "W": { "ICRU": [ 4.587, 5.16, 15410.0, 415.3, 0.003406 ] }, "Re": { "ICRU": [ 5.201, 5.851, 16120.0, 441.6, 0.003122 ] }, "Os": { "ICRU": [ 5.071, 5.704, 16300.0, 440.9, 0.003082 ] }, "Ir": { "ICRU": [ 4.946, 5.563, 16490.0, 440.1, 0.002965 ] }, "Pt": { "ICRU": [ 4.477, 5.034, 16670.0, 439.3, 0.002871 ] }, "Au": { "ICRU": [ 4.844, 5.458, 7852.0, 975.8, 0.02077 ] }, "Hg": { "ICRU": [ 4.307, 4.843, 17040.0, 487.8, 0.002882 ] }, "Tl": { "ICRU": [ 4.723, 5.311, 17220.0, 537.0, 0.002913 ] }, "Pb": { "ICRU": [ 5.319, 5.982, 17400.0, 586.3, 0.002871 ] }, "Bi": { "ICRU": [ 5.956, 6.7, 17800.0, 677.0, 0.00266 ] }, "Po": { "ICRU": [ 6.158, 6.928, 17770.0, 586.3, 0.002812 ] }, "At": { "ICRU": [ 6.203, 6.979, 17950.0, 586.3, 0.002776 ] }, "Rn": { "ICRU": [ 6.181, 6.954, 18120.0, 586.3, 0.002748 ] }, "Fr": { "ICRU": [ 6.949, 7.82, 18300.0, 586.3, 0.002737 ] }, "Ra": { "ICRU": [ 7.506, 8.448, 18480.0, 586.3, 0.002727 ] }, "Ac": { "ICRU": [ 7.648, 8.609, 18660.0, 586.3, 0.002697 ] }, "Th": { "ICRU": [ 7.711, 8.679, 18830.0, 586.3, 0.002641 ] }, "Pa": { "ICRU": [ 7.407, 8.336, 19010.0, 586.3, 0.002603 ] }, "U": { "ICRU": [ 7.29, 8.204, 19180.0, 586.3, 0.002673 ] } } // Electronic stopping coefficients derived from analyzing the IAEA database // https://www-nds.iaea.org/stopping/ // 100) { throw new SyntaxError("Brackets are nested too deeply in this formula"); } var x = mf.lastIndexOf("("); var y = mf.indexOf(")", x); if (y === -1) { // An opening bracket without a matching closing one would otherwise // rebuild the same string forever and freeze the tab. throw new SyntaxError("Unbalanced parentheses in formula"); } var z = mf.substr(x+1, y-x-1); var c = mf.substr(y+1); c = /^\d+/.exec(c); c=(c!= null)?Number(c[0]):1; // recursive var a = parse_formula(z); var b = ""; for(var k in a){ b+=k+""+a[k]*c; } mf = mf.substr(0, x)+ b + mf.substr(y+1+((c>1)?(c+'').length:0)); } var m = ""; // Separate element name from stoichiometry // while(m = /([A-Z]{1}[a-z]{0,}[0-9]{0,})/.exec(mf)){ while(m = /([A-Z]{1}[a-z]{0,}[0-9]{0,}\.?[0-9]{0,})/.exec(mf)){ // Element var m1 = /([A-Z]{1,}[a-z]{0,})/.exec(m[0]); // Stoichiometry //var m2 = /\d+/.exec(m[0]); var m2 = /\d+\.?\d{0,}/.exec(m[0]); if(typeof mol[m1[0]] == 'undefined') mol[m1[0]]=(m2!=null)?Number(m2[0]):1; else mol[m1[0]] += (m2!=null)?Number(m2[0]):1; mf = mf.replace(m[0], ""); } return mol; } function StoppingCoefficients(Element, flag) { // Select which tabulation to use for the Varelas-Biersack parameterization // of electronic stopping cross sections for proton-like projectiles // implanted in elemental targets. // flag = 1: use coefficients from Anderson & Ziegler (1977). if (flag == 1) { return elemPars[Element].AZ; } // flag = 2: use coefficients from ICRU Report 49 (1973). if (flag == 2) { return elemPars[Element].ICRU; } // flag = 3: use coefficients from McFadden et al. (2023) and McFadden et al. (unpublished). // // NOTE: these values were derived from up-to-date stopping data found inthe // IAEA's database of electronic stopping cross sections // (https://www-nds.iaea.org/stopping/). // For further details on their determination, see, e.g.: // Appendix A in McFadden at al., Phys. Rev. Applied 19, 044018 (2023). // https://doi.org/10.1103/PhysRevApplied.19.044018 if (flag == 3 && elemPars[Element].IAEA.length == 5) { return elemPars[Element].IAEA; // in the event that updated coefficients are unavailable for given element // fall back to using values from ICRU Report 49 } else { return elemPars[Element].ICRU; } } let transientWarningTimeout = null; function showTransientWarning(message, targetElement, duration = 4000) { let warning = document.getElementById('transientWarning'); if (!warning) { warning = document.createElement('div'); warning.id = 'transientWarning'; warning.className = 'transient-warning'; document.body.appendChild(warning); } warning.textContent = message; if (targetElement) { const rect = targetElement.getBoundingClientRect(); const viewportMargin = 12; const targetGap = 8; const maximumLeft = Math.max(viewportMargin, window.innerWidth - warning.offsetWidth - viewportMargin); const left = Math.min(Math.max(viewportMargin, rect.left), maximumLeft); let top = rect.bottom + targetGap; // Keep notifications inside the viewport, including for controls near its // right and bottom edges. Fixed-position elements use viewport coordinates. if (top + warning.offsetHeight > window.innerHeight - viewportMargin) { top = rect.top - warning.offsetHeight - targetGap; } top = Math.max(viewportMargin, Math.min(top, window.innerHeight - warning.offsetHeight - viewportMargin)); warning.style.left = `${left}px`; warning.style.top = `${top}px`; } warning.classList.add('visible'); if (transientWarningTimeout) { clearTimeout(transientWarningTimeout); } transientWarningTimeout = setTimeout(() => { warning.classList.remove('visible'); }, duration); } let statusBarState = { workPath: '', backend: '', lastSave: 'Not saved yet', run: 'Idle' }; function shortenStatusValue(value, maxLength = 56) { if (!value) { return '-'; } if (value.length <= maxLength) { return value; } return '...' + value.slice(-(maxLength - 3)); } function renderStatusBar() { const workPathNode = document.getElementById('statusWorkPath'); const backendNode = document.getElementById('statusBackend'); const lastSaveNode = document.getElementById('statusLastSave'); const runNode = document.getElementById('statusRun'); if (!workPathNode || !backendNode || !lastSaveNode || !runNode) { return; } workPathNode.textContent = shortenStatusValue(statusBarState.workPath); workPathNode.title = statusBarState.workPath || ''; backendNode.textContent = shortenStatusValue(statusBarState.backend); backendNode.title = statusBarState.backend || ''; lastSaveNode.textContent = shortenStatusValue(statusBarState.lastSave); lastSaveNode.title = statusBarState.lastSave || ''; runNode.textContent = shortenStatusValue(statusBarState.run); runNode.title = statusBarState.run || ''; } function updateStatusBar(updates = {}) { statusBarState = { ...statusBarState, ...updates }; renderStatusBar(); } function syncStatusBar() { const workPathField = document.getElementById('workPath'); const trimPathField = document.getElementById('trimPath'); let backend = amIWeb() ? 'Web backend' : 'Standalone app'; if (!amIWeb() && trimPathField && trimPathField.value) { backend = trimPathField.value; } updateStatusBar({ workPath: workPathField ? workPathField.value : statusBarState.workPath, backend: backend }); } function markDensityEstimated(fieldId, isEstimated) { const field = document.getElementById(fieldId); if (!field) { return; } field.classList.toggle('estimated-density', isEstimated); if (isEstimated) { field.title = 'Calculated density estimate'; } else { field.removeAttribute('title'); } } function clearDensityEstimateHighlight() { if (this && this.classList) { this.classList.remove('estimated-density'); this.removeAttribute('title'); } } function handleCompositionChange() { const normalized = normalizeCompositionAlias(this.value); if (normalized !== this.value.trim()) { this.value = normalized; showTransientWarning('Expanded alias to ' + normalized, this, 2500); } rho_fun.call(this); } function rho_fun() { var irow = this.parentNode.parentNode.rowIndex; var caller = this.id; var chem = normalizeCompositionAlias(document.getElementById(caller).value); document.getElementById(caller).value = chem; var rhoLi = "L"+irow+"rho"; var rho = 0; var estimatedDensity = 0; if (elemPars[chem]) { rho = elemPars[chem].rho; markDensityEstimated(rhoLi, false); } else { // Did not find density in elements list if (isFinite(rhos[chem])) { // Found in densities list of compositions rho = rhos[chem]; markDensityEstimated(rhoLi, false); } else { // suggest a material density based on composition (when it's undefined) let layer_formula; try { layer_formula = parse_formula(chem); } catch (parseError) { showTransientWarning("Could not parse composition: " + parseError.message, document.getElementById(rhoLi)); document.getElementById(rhoLi).value = 0; return; } // determine the stoichiometry sum (for normalization) let stoichiometry_sum = 0; for (const key of Object.keys(layer_formula)) { const amount = Number(layer_formula[key]); if (isFinite(amount) && amount > 0) { stoichiometry_sum += amount; } } // estimate the density from additive elemental molar volumes: // rho ~= total molar mass / total molar volume let total_molar_mass = 0; let total_molar_volume = 0; for (const key of Object.keys(layer_formula)) { const amount = Number(layer_formula[key]); if (!isFinite(amount) || amount <= 0) { continue; } if (!elemPars[key] || !isFinite(elemPars[key].rho) || !isFinite(elemPars[key].A) || elemPars[key].rho <= 0) { continue; } total_molar_mass += amount * elemPars[key].A; total_molar_volume += amount * (elemPars[key].A / elemPars[key].rho); } rho = 0; if (total_molar_volume > 0) { rho = total_molar_mass / total_molar_volume; } if (rho > 0) { estimatedDensity = 1; showTransientWarning("Warning: Estimated density from additive elemental molar volumes; please verify manually.", document.getElementById(rhoLi)); } markDensityEstimated(rhoLi, estimatedDensity); } } // Set value in appropriate cell document.getElementById(rhoLi).value = rho; } function openTab(event, tabName) { window.trimspActiveTab = tabName; // Declare all variables var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } // Get all elements with class="tablinks" and remove the class "active" tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } // Show the current tab, and add an "active" class to the button that opened the tab document.getElementById(tabName).style.display = "block"; if (event) event.currentTarget.className += " active"; if (tabName === "Plots") { requestAnimationFrame(() => resizePl()); } } function adjust_table() { var numLayer = document.getElementById("numLayer").value; var LTable = document.getElementById("LTable"); var Nrows = LTable.rows.length; var Comps = []; var Rhos = []; var Ds = []; // Need to loop to get the right number of rows when reloading if (numLayer >= Nrows) { for (i = Nrows;i<=numLayer;i++) { var row = LTable.insertRow(i); var Li = row.insertCell(0); Li.innerHTML = i; var compL = row.insertCell(1); var compCell = document.createElement("input"); compCell.id = "L"+i+"Comp"; compCell.name = "L"+i+"Comp"; compCell.size = 15; compCell.onchange = handleCompositionChange; if (Comps[i-1]) {compCell.value = Comps[i-1];}else{compCell.value = 'SrTiO3';} compL.appendChild(compCell); var rhoL = row.insertCell(2); var rhoCell = document.createElement("input"); rhoCell.id = "L"+i+"rho"; rhoCell.name = "L"+i+"rho"; rhoCell.size = 5; rhoCell.oninput = clearDensityEstimateHighlight; rhoL.appendChild(rhoCell); if (Rhos[i-1]) {rhoCell.value = Rhos[i-1];}else{rhoCell.value = '5.12';} var thickL = row.insertCell(3); var thickCell = document.createElement("input"); thickCell.id = "L"+i+"d"; thickCell.name = "L"+i+"d"; thickCell.size = 7; thickL.appendChild(thickCell); if (Ds[i-1]) {thickCell.value = Ds[i-1];}else{thickCell.value = '10000';} } } else { for (i = Nrows-1;i>numLayer;i--) { LTable.deleteRow(i); } } } function adjust_scans() { var scanSeq = document.getElementById("scanSeq").checked; var scanType = document.getElementById("scanType").value; var scanThreads = document.getElementById("scanThreads"); var scanControls = document.getElementById("ScansControls"); var scanRange = document.getElementById("ScansTable"); var scanList = document.getElementById("ScansLine"); // Default to half the available worker slots, rounded down, while keeping // at least one process. Web mode runs scan points in parallel through // concurrent CGI requests, bounded by TRIMSP_WEB_MAX_CONCURRENCY. if (scanThreads) { let availableThreads = 1; if (amIWeb()) { availableThreads = Math.max(1, TRIMSP_WEB_MAX_CONCURRENCY); } else if (typeof getParallelJobCount === 'function') { availableThreads = Math.max(1, getParallelJobCount()); } scanThreads.max = availableThreads; scanThreads.disabled = false; scanThreads.title = amIWeb() ? `The web backend runs up to ${availableThreads} scan points in parallel.` : `This computer provides up to ${availableThreads} worker slots.`; if (scanThreads.value === "" || Number(scanThreads.value) < 1) { scanThreads.value = Math.max(1, Math.floor(availableThreads / 2)); } else if (Number(scanThreads.value) > availableThreads) { scanThreads.value = availableThreads; } } scanControls.hidden = !scanSeq; if (!scanSeq) { scanRange.hidden = true; scanList.hidden = true; } else if (scanType === "scanLoop") { scanRange.hidden = false; scanList.hidden = true; } else { scanRange.hidden = true; scanList.hidden = false; } updateScanSummary(); } function updateScanSummary() { var summary = document.getElementById("scanSummary"); if (!summary) { return; } if (!document.getElementById("scanSeq").checked) { summary.dataset.level = "idle"; summary.textContent = "Single simulation using the Layers settings."; return; } var scanType = document.getElementById("scanType").value; var parameterSelect = document.getElementById("comboScan"); var parameter = parameterSelect.options[parameterSelect.selectedIndex].text; var workers = Number(document.getElementById("scanThreads").value) || 1; var pointCount = 0; var detail = ""; var warning = ""; if (scanType === "scanLoop") { var range = rangeScanValues( document.getElementById("scanFrom").value, document.getElementById("scanStep").value, document.getElementById("scanTo").value); if (range.error) { warning = range.error; } else { pointCount = range.values.length; detail = `${range.values[0]} to ${range.values[pointCount - 1]}, step ${document.getElementById("scanStep").value}`; } } else { var values = document.getElementById("scanList").value .split(",") .map(value => value.trim()) .filter(value => value !== ""); var depthValues = document.getElementById("scanListdz").value .split(",") .map(value => value.trim()) .filter(value => value !== ""); if (values.length === 0) { warning = "Enter at least one scan value."; } else if (values.some(value => !Number.isFinite(Number(value)))) { warning = "Every scan value must be numeric."; } else if (depthValues.length > 0 && depthValues.length !== values.length) { warning = "Depth increments must match the number of scan values."; } else { pointCount = values.length; detail = values.join(", "); } } if (warning) { summary.dataset.level = "warning"; summary.textContent = warning; return; } summary.dataset.level = "ready"; var pointLabel = pointCount === 1 ? "point" : "points"; var workerLabel = workers === 1 ? "worker" : "workers"; summary.textContent = `${parameter} | ${pointCount} ${pointLabel} | ${workers} ${workerLabel} | ${detail}`; } function ProjSmartDefaults() { var Proj = document.getElementById("ProjType").value; var sigEnergy = document.getElementById("sigEnergy"); var sigAngle = document.getElementById("sigAngle"); if (Proj == "muon") { sigEnergy.value = "450"; sigAngle.value = "15"; } else { sigEnergy.value = "0"; sigAngle.value = "0"; } } function ProjNumberLimit() { var numberProj = document.getElementById("numberProj").value; if (numberProj > 5000) { alert("Maximum number is 5000"); document.getElementById("numberProj").value = 5000; } } function prep_cfg(toggle) { // This function collects various values and returns // toggle=1 : returns object with all values // toggle!=1 : returns string containing cfg file let TrimSPcfg = ""; let strtmp = ""; let valtmp = ""; All['trimPath']=document.getElementById("trimPath").value; // Keep file output settings in the runtime state even though they are not // part of the projectile block. The scan runner depends on both values. All["fileNamePrefix"] = document.getElementById("fileNamePrefix").value; All["workPath"] = document.getElementById("workPath").value; // Thread count is a local GUI/runtime setting only. It must stay out of // TrimSP.cfg, but the local parallel runner still needs to read it. All["scanThreads"] = document.getElementById("scanThreads").value; // Prepare Layers section let LayersSec = "[Layers]\n"; let numLayer = document.getElementById("numLayer").value; All['numLayer']=numLayer; LayersSec = LayersSec + "numLayer="+numLayer+"\n"; for (i = 1;i<=numLayer;i++) { strtmp = "L"+i+"Comp"; valtmp = document.getElementById(strtmp).value; All[strtmp]=valtmp; LayersSec = LayersSec + strtmp +"="+ valtmp+"\n"; strtmp = "L"+i+"rho"; valtmp = document.getElementById(strtmp).value; All[strtmp]=valtmp; LayersSec = LayersSec + strtmp +"="+ valtmp+"\n"; strtmp = "L"+i+"d"; valtmp = document.getElementById(strtmp).value; All[strtmp]=valtmp; LayersSec = LayersSec + strtmp +"="+ valtmp+"\n"; } // Prepare projectile parameters section let parProj = ["ProjType","numberProj","z0","dz","valEnergy","sigEnergy","valAngle","sigAngle","rngType","ranSeed"]; let ProjSec = "[ProjectileParameters]\n"; for (key of parProj) { All[key]= document.getElementById(key).value; ProjSec = ProjSec + key + "=" + All[key] + "\n"; } // Prepare Files section let FilesSec = "[Files]\n"; FilesSec = FilesSec + "fileNamePrefix="+All["fileNamePrefix"]+"\nworkPath="+All["workPath"]+"\n"; // Prepare ScanSequence section let ScanSec = "[ScanSequence]\n"; strtmp = "scanSeq"; valtmp = 1*(document.getElementById(strtmp).checked); All[strtmp]=valtmp; ScanSec = ScanSec + strtmp +"="+ valtmp+"\n"; let parScan = ["comboScan","scanType","scanFrom","scanStep","scanTo","scanList","scanListdz"]; for (key of parScan) { All[key]= document.getElementById(key).value; ScanSec = ScanSec + key + "=" + All[key] + "\n"; } // Collect other parameters let parOther = ["parEF", "parESB", "parSHEATH", "parERC", "parRD", "parCA", "parKK0", "parKK0R", "parKDEE1", "parKDEE2", "parIPOT", "parIPOTR", "parIRL"]; for (key of parOther) { All[key]= document.getElementById(key).value; } // Get the stopping power coefficient (SPC) flag All["flagSPC"] = document.getElementById("flagSPC").value; // Construct full content of cfg file TrimSPcfg = FilesSec + LayersSec + ProjSec + ScanSec; if (toggle) { return All; } else { return TrimSPcfg; } } function setValues(content) { // This function takes cfg file content and substitutes values in the GUI // Split file content into lines var event = new Event('change'); var lines = content.toString().split('\n'); // Remove comment lines, empty lines and those starting with "[" var PATTERN= /^(?!\[)(?!\#)(\S)/, flines = lines.filter(function (str) {return PATTERN.test(str);}); for (var i=0; i All[key]); } else { TemplateFile = TemplateFile.replace(key, () => All[key]); } } } return TemplateFile; } function sum(array){ // Takes and array and returns the sum of its elements let sum_array = array.reduce(function(a, b){ return a + b; }, 0); return sum_array; } function yieldToRenderer() { return new Promise((resolve) => setTimeout(resolve, 0)); } // Upper bound on concurrent scan points in the browser backend. Each job is a // separate CGI request that runs its own TRIM.SP-NL process, so this keeps a // large scan from overwhelming the web server while still running several // points in parallel. var TRIMSP_WEB_MAX_CONCURRENCY = 4; // Upper bound on the number of points one scan may expand to. This guards // against a crafted link or an accidental step that would otherwise generate // an effectively unlimited list of jobs and freeze the tab. var TRIMSP_MAX_SCAN_POINTS = 5000; // Validated limits for client-owned input values. The Ziegler/ICRU stopping // fits are only tuned up to ~50 keV for helium (KDEE1=4, see // meaning-of-params.txt:177-185), so energies beyond 60 keV are outside the // model's fitted validity. Negative energies select the Maxwellian initial // distribution where |E0| is used as the ion temperature (trimspNL.F:806), so // the same magnitude cap applies to both modes. var TRIMSP_ENERGY_CAP_EV = 60000; // The engine casts the deck seed to a signed 32-bit integer // (ISEED = IDINT(RI), trimspNL.F:818-827), so any magnitude beyond that is // silently truncated. Restrict the seed to |v| <= 2^31-1. var TRIMSP_SEED_MAX_ABS = 2147483647; // Advisory projectile count for the web backend. This is not a hard limit: the // engine is single threaded and its cost per projectile is dominated by the // number of nuclear collisions along the track, so the same count can differ by // more than 5x across the projectile menu. Measured worst case is helium into a // light heavy-ish target at the 60 keV energy cap with the ZBL potential, at // about 4.0 ms per projectile on a 3.2 GHz core, which puts 25000 points at // roughly 100 s. The web backend watchdog (TRIMSP_CMD_TIMEOUT, 300 s) then // still has about a 3x margin, so this count normally completes while slower or // more heavily loaded deployments keep the watchdog as a backstop. The warning // is advisory only; the user keeps the final say. var TRIMSP_WEB_PROJ_ADVISORY = 25000; // Recoil cutoff substituted when the user turns on recoil calculation with a // cutoff of zero. A zero cutoff makes the transport respawn every recoiling // atom on every cascade generation, so NREC1/NREC2 grow geometrically instead // of draining and the run overruns the recoil arrays. The engine refuses that // combination, so the GUI supplies a usable value instead of letting the run // fail after the user presses Run. var TRIMSP_MIN_RECOIL_CUTOFF = 0.02; // True when the recoil calculation is enabled without a usable recoil cutoff. // The parIRL and parERC widgets are plain number inputs and a shared // configuration assigns their values directly, so this can be reached without // going through the change handler below. function recoilCutoffIsUnusable() { let irl = Number(document.getElementById("parIRL").value); let cutoff = Number(document.getElementById("parERC").value); return Number.isFinite(irl) && irl >= 1 && (!Number.isFinite(cutoff) || cutoff <= 0); } // Called when the parIRL widget changes. Turning recoil calculation on with no // cutoff is filled in for the user here, because that is a value they almost // never intend to type. Deliberately not wired to parERC: retyping the cutoff // afterwards is how a user insists on the combination, and the pre-run check // then refuses the run instead of silently overriding them. function handleRecoilModeChange() { if (!recoilCutoffIsUnusable()) { return; } let cutoffField = document.getElementById("parERC"); cutoffField.value = TRIMSP_MIN_RECOIL_CUTOFF; showTransientWarning( "Recoil calculation needs a cutoff, so parERC was set to " + TRIMSP_MIN_RECOIL_CUTOFF + ".", cutoffField, 6000); } // Returns an empty string when valid, otherwise a message that asks the user // to change the offending value. function validateEnergyValue(raw) { var str = String(raw).trim(); var value = Number(str); if (str === "" || !Number.isFinite(value)) { return "Energy must be numeric. Please change it."; } if (Math.abs(value) > TRIMSP_ENERGY_CAP_EV) { return "Energy magnitude must not exceed 60000 eV (the stopping fits are not validated beyond ~50 keV). Please change it."; } return ""; } function validateSeedString(raw) { var str = String(raw).trim(); if (str === "" || !/^[+-]?\d+$/.test(str)) { return "Seed must be an integer. Please change it."; } var value = Number(str); if (Math.abs(value) > TRIMSP_SEED_MAX_ABS) { return "Seed is out of range (use an integer between -2147483648 and 2147483647). Please change it."; } return ""; } // Expand a From/Step/To range into a list of scan values. Both ascending and // descending steps are valid (e.g. scanning from high to low energy), so the // old "loop while value <= to" form is replaced by a count-based expansion // that avoids zero-step and floating-point drift. Returns {values} or {error}. function rangeScanValues(fromText, stepText, toText) { var from = Number(fromText); var step = Number(stepText); var to = Number(toText); if (!Number.isFinite(from) || !Number.isFinite(step) || !Number.isFinite(to)) { return { error: "Enter numeric From, Step, and To values." }; } if (step === 0) { return { error: "Step must be non-zero." }; } if ((step > 0 && to < from) || (step < 0 && to > from)) { return { error: "To must be reachable from From with the given Step." }; } var count = Math.floor(Math.abs((to - from) / step)) + 1; if (count > TRIMSP_MAX_SCAN_POINTS) { return { error: "Too many scan points (max " + TRIMSP_MAX_SCAN_POINTS + ")." }; } var values = []; for (var i = 0; i < count; i++) { values.push(Number((from + i * step).toPrecision(12))); } return { values: values }; } // Format the live profile legend from the scan parameter currently being run. function formatScanLegend(scanName, scanValue) { if (scanName === "E") { return scanName + '=' + Number(scanValue) / 1000 + 'keV'; } return scanName + '=' + scanValue; } // Merge finished per-run *.seq files into one in-memory table ordered by the // original scan index, not by worker completion order. function buildCombinedSequenceLines(results) { let combinedSeqLines = []; const completedResults = results.filter(Boolean).sort((a, b) => a.index - b.index); for (const result of completedResults) { if (combinedSeqLines.length === 0) { combinedSeqLines = result.seqLines.slice(); } else { combinedSeqLines = combinedSeqLines.concat(result.seqLines.slice(1)); } } return combinedSeqLines; } // Rebuild the live profile and fraction plots from all completed scan jobs. // This keeps the display responsive while preserving deterministic ordering. function renderCompletedScanResults(results, allValues) { const completedResults = results.filter(Boolean).sort((a, b) => a.index - b.index); if (completedResults.length === 0) { return []; } Plotly.purge("plotRge"); for (const result of completedResults) { Plot_xy("plotRge", result.depth, result.nmuons, ['Depth (nm)', 'Stopped muons (%/nm)', result.legend]); } const combinedSeqLines = buildCombinedSequenceLines(results); const [combinedCols, combinedData] = parseDatContent(combinedSeqLines.join('\n')); const seqInfo = getSequenceColumnInfo(combinedCols, allValues["numLayer"]); const energy = combinedData[seqInfo.indexByName['Energy']]; const ntot = combinedData[seqInfo.indexByName['ntot']]; const plotSeries = [ { index: seqInfo.indexByName['backsc'], label: combinedCols[seqInfo.indexByName['backsc']], }, ...seqInfo.layerIndices.map((index, offset) => { let LComp = "L" + (offset + 1) + "Comp"; return { index: index, label: allValues[LComp] || seqInfo.layerHeaders[offset], }; }), ]; Plotly.purge("plotFrac"); for (const series of plotSeries) { let idata = combinedData[series.index]; for (let i = 0; i < idata.length; i++) { idata[i] = 100 * idata[i] / ntot[i]; } Plot_xy("plotFrac", energy, combinedData[series.index], ['E (keV)', 'Fraction of muons (%)', series.label]); } return combinedSeqLines; } async function runSimulationSequence() { let cmd = ''; let trimBin = All['trimPath']+"/trimspNL"; let randStr = ''; let webOrApp = amIWeb(); // Only for Node.js if (!webOrApp) { trimBin = getTrimBinaryPath(All["trimPath"]); // Check if workPath exists otherwise create it checkDir(All['workPath']); // from TrimSPelec.js, Electron/Node specific updateStatusBar({ backend: trimBin }); } else { // Add random string (5 char) to file names randStr = (Math.random() + 1).toString(36).substring(7); All["fileNamePrefix"] = randStr; All["workPath"] = "/tmp/" + randStr; // prep_cfg() reads these values from the DOM, so keep the hidden web // fields synchronized with the randomized server-side run directory. document.getElementById("fileNamePrefix").value = All["fileNamePrefix"]; document.getElementById("workPath").value = All["workPath"]; // A new web run replaces the previous archive link and diagnostics. let outputLink = document.getElementById("statusOutputLink"); if (outputLink) { outputLink.hidden = true; outputLink.removeAttribute("href"); } if (typeof webRunDiagnostics !== "undefined") { webRunDiagnostics.length = 0; } let runLog = document.getElementById("webRunLog"); if (runLog) { runLog.textContent = "No web requests have been made yet."; } updateStatusBar({ backend: 'Web backend' }); } updateStatusBar({ workPath: All["workPath"], run: 'Starting run...' }); // prep_cfg() refreshes All from the DOM, so freeze the RNG backend now. // The browser must ignore dropdown changes that happen while CGI requests // are still in flight, otherwise one scan could mix generators and produce // irreproducible results. const rngType = All["rngType"] || "pcg32"; if (!await writeAsciiFileAsync(All["workPath"] + "/TrimSP.cfg", prep_cfg(0), rngType)) { return(0); } let Progress =0; document.getElementById("pBar").style.width = Progress + "%"; document.getElementById("pBar").innerHTML = Progress + "%"; // This is a flag to indicate whether the lists of values and inclements are the same size All["SdzFlag"]=0; var SValues = []; let ScanName = "E"; let ScanAttrib = "valEnergy"; let scanError = ""; // Generate an arry of scanned values (one element for a single run) if (All["scanSeq"]) { // For multiple runs or a scan if (All["scanType"]=="scanVals") { SValues = All["scanList"].split(/,/) .map(function(v) {return v.trim();}) .filter(function(v) {return v !== "";}) .map(Number); var SdzValues = All["scanListdz"].split(/,/) .map(function(v) {return v.trim();}) .filter(function(v) {return v !== "";}); if (SValues.length == SdzValues.length) {All["SdzFlag"]=1;} if (SValues.length === 0) { scanError = "Enter at least one scan value."; } else if (SValues.some(function(v) {return !Number.isFinite(v);})) { scanError = "Every scan value must be numeric."; } else if (SValues.length > TRIMSP_MAX_SCAN_POINTS) { scanError = "Too many scan values (max " + TRIMSP_MAX_SCAN_POINTS + ")."; } } else { // rangeScanValues handles both ascending and descending steps and // rejects zero-size or unreachable ranges before expanding. var range = rangeScanValues(All["scanFrom"], All["scanStep"], All["scanTo"]); if (range.error) { scanError = range.error; } else { SValues = range.values; } } if (All["comboScan"]=="SigEScan") { ScanName = "SigE"; ScanAttrib = "sigEnergy"; } else if (All["comboScan"]=="AngleScan") { ScanName = "Angle"; ScanAttrib = "valAngle"; } else if (All["comboScan"]=="SigAngleScan") { ScanName = "SigAngle"; ScanAttrib = "sigAngle"; } else if (All["comboScan"]=="NProjScan") { ScanName = "N"; ScanAttrib = "numberProj"; } else if (All["comboScan"]=="dScan") { // The GUI currently exposes the thickness scan only for layer 1. ScanName = "Ld1"; ScanAttrib = "L1d"; } } else { // For single run, array with single value of valEnergy var singleEnergy = Number(All["valEnergy"]); if (!Number.isFinite(singleEnergy)) { scanError = "Energy must be numeric."; } SValues.push(singleEnergy); } if (scanError) { updateStatusBar({ run: scanError }); return(0); } // Cap the projectile energy magnitude before any job is generated. For an // energy sweep the scan values are authoritative; for any other sweep the // base valEnergy must still stay in the fitting range. var evalues = (ScanAttrib === "valEnergy") ? SValues : [Number(All["valEnergy"])]; for (var evIndex = 0; evIndex < evalues.length; evIndex++) { var energyError = validateEnergyValue(evalues[evIndex]); if (energyError) { updateStatusBar({ run: energyError }); return(0); } } // Advisory only, and web only: the standalone app runs the engine locally // with no watchdog, so a long run is the user's own choice there. A number // of projectiles that scales badly with the collision count can still exceed // the backend watchdog, so warn once per run without blocking it. For a // numberProj sweep the scan values are authoritative, otherwise the base // value is what every point uses. if (amIWeb()) { const projValues = (ScanAttrib === "numberProj") ? SValues : [Number(All["numberProj"])]; let worstProj = 0; for (var projIndex = 0; projIndex < projValues.length; projIndex++) { let projValue = Number(projValues[projIndex]); if (Number.isFinite(projValue) && projValue > worstProj) { worstProj = projValue; } } if (worstProj > TRIMSP_WEB_PROJ_ADVISORY) { showTransientWarning( "Warning: " + worstProj + " projectiles per point may exceed the web " + "time limit and fail. Runs above ~" + TRIMSP_WEB_PROJ_ADVISORY + " are safest; the run will start anyway.", document.getElementById("numberProj"), 8000); } } // Hard stop, unlike the projectile advisory above: with a zero recoil // cutoff the cascade does not converge, so the engine exits with an error // instead of producing results. Refuse the run here and say which field to // change, rather than letting the backend fail with a transport message. if (recoilCutoffIsUnusable()) { let cutoffField = document.getElementById("parERC"); let message = "parIRL=1 needs a parERC recoil cutoff above 0; " + TRIMSP_MIN_RECOIL_CUTOFF + " is a common choice."; updateStatusBar({ run: message }); showTransientWarning("Not running: " + message, cutoffField, 8000); cutoffField.focus(); return(0); } // Freeze the initial GUI state and expand the scan into independent jobs. // Each job gets its own input file name and a deterministic seed offset so // the results are reproducible even when runs finish out of order. const scanValues = SValues.slice(); const initialAll = Object.assign({}, All); const initialSeed = parseInt(initialAll["ranSeed"], 10); const seedError = validateSeedString(initialAll["ranSeed"]); if (seedError) { updateStatusBar({ run: seedError }); return(0); } let jobs = []; for (let iScan = 0; iScan < scanValues.length; iScan++) { let SValue = scanValues[iScan]; let jobAll = Object.assign({}, initialAll); jobAll[ScanAttrib] = SValue; if (!Number.isNaN(initialSeed)) { jobAll["ranSeed"] = String(initialSeed + iScan); } All = jobAll; let inputFileContent; try { inputFileContent = CreateInpFile(); } catch (error) { let message = (error && error.message) ? error.message : String(error); updateStatusBar({ run: message }); All = initialAll; return(0); } if (inputFileContent && typeof inputFileContent === "object" && inputFileContent.ok === false) { updateStatusBar({ run: inputFileContent.error || "Could not build the input file." }); All = initialAll; return(0); } if (typeof inputFileContent !== "string" || inputFileContent.length === 0) { updateStatusBar({ run: "Could not build the input file." }); All = initialAll; return(0); } let FILENAME = jobAll["fileNamePrefix"] + "_" + ScanName + SValue; jobs.push({ index: iScan, scanValue: SValue, filename: FILENAME, inputFileContent: inputFileContent, legend: formatScanLegend(ScanName, SValue), }); } All = initialAll; // Results must land in the work dir that existed when the run started, // never in or next to whatever All points at if a second Run was attempted. const runWorkPath = initialAll["workPath"]; // Results are stored by original scan index. The plots and final merged // sequence file are always rebuilt from this ordered array. let results = new Array(jobs.length); // Read back the outputs of one completed run and convert them into the // normalized data structures used by the live plots. async function collectRunResult(job) { let [cols,data]= await readDatFileAsync(runWorkPath+"/"+job.filename+".rge"); let depth=data[0]; let nmuons=data[1]; let dz = (depth[1]-depth[0])/10; let norm = dz*sum(nmuons)/100; for (let i=0; i 1 && (webOrApp || typeof executeFileAsync === 'function'); if (!canRunPool) { // Sequential path for a single job, or the local fallback when no async // executor exists. Local single runs keep inherited stdio for the log. try { for (const job of jobs) { if (!await writeAsciiFileAsync(runWorkPath+"/"+job.filename+".inp", job.inputFileContent, rngType)) { return(0); } if (!webOrApp) { cmd = "cd " + runWorkPath; cmd += ";" + trimBin + ' ' + job.filename + ' ' + rngType; electronExecSync(cmd, {stdio: 'inherit'}); } results[job.index] = await collectRunResult(job); updateStatusBar({ run: `Completed ${results.filter(Boolean).length}/${jobs.length}: ${job.legend}` }); await updateCompletedResults(); } } catch (error) { console.error('Scan job failed:', error); updateStatusBar({ run: 'Run failed' }); return(0); } } else { // Bounded worker pool. Web jobs run server-side through the CGI; local jobs // use executeFileAsync. Jobs are inserted into the final result set by scan // index as they complete, so out-of-order finishes do not affect the plots. let availableThreads = webOrApp ? TRIMSP_WEB_MAX_CONCURRENCY : Math.max(1, getParallelJobCount()); let requestedThreads = parseInt(initialAll["scanThreads"], 10); if (Number.isNaN(requestedThreads) || requestedThreads < 1) { requestedThreads = Math.max(1, Math.floor(availableThreads / 2)); } else if (requestedThreads > availableThreads) { requestedThreads = availableThreads; } const maxConcurrent = Math.min(jobs.length, requestedThreads, availableThreads); let nextJob = 0; let activeJobs = 0; let completedJobs = 0; try { await new Promise((resolve, reject) => { function launchNextJobs() { while (activeJobs < maxConcurrent && nextJob < jobs.length) { const job = jobs[nextJob]; nextJob += 1; activeJobs += 1; updateStatusBar({ run: `Running ${completedJobs}/${jobs.length} completed, ${activeJobs} active` }); // Pass the selected RNG backend explicitly so sequential and // parallel runs use the same generator choice. writeAsciiFileAsync(runWorkPath+"/"+job.filename+".inp", job.inputFileContent, rngType) .then((written) => { if (!written) { throw new Error(`Could not submit ${job.filename}`); } if (webOrApp) { return; } return executeFileAsync(trimBin, [job.filename, rngType], runWorkPath); }) .then(() => collectRunResult(job)) .then(async (result) => { results[result.index] = result; activeJobs -= 1; completedJobs += 1; updateStatusBar({ run: `Completed ${completedJobs}/${jobs.length}, ${activeJobs} active` }); await updateCompletedResults(); if (completedJobs === jobs.length) { resolve(); return; } launchNextJobs(); }) .catch(reject); } } launchNextJobs(); }); } catch (error) { console.error('Scan job failed:', error); updateStatusBar({ run: 'Run failed' }); return(0); } } let combinedSeqLines = buildCombinedSequenceLines(results); let seq_file = runWorkPath+"/"+initialAll["fileNamePrefix"]+"_Seq_Results.dat"; if (combinedSeqLines.length > 0) { if (!await writeAsciiFileAsync(seq_file, combinedSeqLines.join('\n') + '\n', rngType)) { return(0); } } Progress=100; document.getElementById("pBar").style.width = Progress + "%"; document.getElementById("pBar").innerHTML = Progress + "%"; updateStatusBar({ run: `Completed ${SValues.length} run(s)` }); await yieldToRenderer(); return(0); } async function startSequence() { // Re-entrancy guard: starting a second run while one is in flight would // reassign the global All and let two scans write the same server files. if (runInProgress) { updateStatusBar({ run: 'A run is already in progress.' }); return(0); } runInProgress = true; const runButton = document.getElementById("runSimulationButton"); if (runButton) { runButton.disabled = true; } try { return await runSimulationSequence(); } finally { runInProgress = false; if (runButton) { runButton.disabled = false; } } } function readDatFile(filename) { // Read column data file and return // cols - labels of columns // data - 2D array with the columns let lines = readAsciiFile(filename); return parseDatContent(lines); } async function readDatFileAsync(filename) { // Async counterpart used by the scan pipeline in both web and Electron. let lines = await readAsciiFileAsync(filename); return parseDatContent(lines); } function parseDatContent(lines) { // Parse whitespace-separated column data from an in-memory string. let data = []; let i=0; // line counter for (let line of lines.trim().split('\n')) { // take labels from the first row if (i==0) { var cols = line.trim().split(/[#\s]+/g); } else { let words = line.trim().split(/[#\s]+/g); for (let j=0; j indexByName[name] == null); if (missing.length > 0) { throw new Error('Unexpected sequence-file header. Missing columns: ' + missing.join(', ')); } const fixedCount = requiredSummaryFields.length; let layerHeaders = cols.slice(fixedCount); if (expectedLayers != null && expectedLayers >= 0) { layerHeaders = layerHeaders.slice(0, expectedLayers); } return { indexByName: indexByName, requiredSummaryFields: requiredSummaryFields, layerStartIndex: fixedCount, layerHeaders: layerHeaders, layerIndices: layerHeaders.map((_, offset) => fixedCount + offset), }; } function plotProfiles(filenames) { // Plot rge files filenames var win = window.open("", "_blank", "toolbar=no, menubar=no"); win.document.open(); win.document.write(''); win.document.write('
'); win.document.write(''); win.addEventListener('resize', sizePlot); win.document.close(); var plotDiv=win.document.getElementById("newPlot"); // Build sortable labels from the trailing scan token in each file name. // The old code used the first "_" in the full path, which breaks for // prefixes such as "Au_Cr_Si_3layer_E15000.rge". let plottedFiles = []; for (let i = 0; i < filenames.length; i++) { const filename = Array.isArray(filenames) ? filenames[i] : filenames[i]; const baseName = filename.split(/[\\/]/).pop(); const stem = baseName.replace(/\.rge$/i, ''); const lastUnderscore = stem.lastIndexOf('_'); let legend = stem; let sortValue = i; if (lastUnderscore !== -1) { const scanToken = stem.substring(lastUnderscore + 1); const energyMatch = scanToken.match(/^E(-?\d+(?:\.\d+)?)$/); if (energyMatch) { const energyEv = Number(energyMatch[1]); legend = 'E=' + (energyEv / 1000) + 'keV'; sortValue = energyEv; } else { legend = scanToken; } } plottedFiles.push({ filename: filename, legend: legend, sortValue: sortValue, }); } plottedFiles.sort((a, b) => a.sortValue - b.sortValue); // loop on sorted values and plot for (let i = 0; i < plottedFiles.length; i++) { let [cols,data]= readDatFile(plottedFiles[i].filename); // convert depth to nm and normalize profile let depth=data[0]; let nmuons=data[1]; let dz = (depth[1]-depth[0])/10; let norm = dz*sum(nmuons)/100; for (let i=0; i'); win.document.write('
'); win.document.write(''); win.addEventListener('resize', sizePlot); win.document.close(); var plotDiv=win.document.getElementById("newPlot"); var [cfort,cdata]= readDatFile(filename); let seqInfo = getSequenceColumnInfo(cfort); let energy = cdata[seqInfo.indexByName['Energy']]; let ntot = cdata[seqInfo.indexByName['ntot']]; let plotSeries = [ { index: seqInfo.indexByName['backsc'], label: cfort[seqInfo.indexByName['backsc']], }, ...seqInfo.layerIndices.map((index, offset) => ({ index: index, label: seqInfo.layerHeaders[offset], })), ]; // Now loop over all for (let series of plotSeries) { // Normalize let idata = cdata[series.index]; for (let i=0; i'); win.document.write('
'); win.document.write(''); win.addEventListener('resize', sizePlot); win.document.close(); var plotDiv=win.document.getElementById("newPlot"); let [cfort,cdata]= readDatFile(filename); let seqInfo = getSequenceColumnInfo(cfort); let energy = cdata[seqInfo.indexByName['Energy']]; let mean = cdata[seqInfo.indexByName['range']]; let strag = cdata[seqInfo.indexByName['straggeling']]; for (let i=0; i