utils-new.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /**
  2. * 函数拟合工具 - 工具函数
  3. */
  4. /**
  5. * 从表格中获取数据点
  6. * @returns {Array} 数据点数组,每个元素包含x和y属性
  7. */
  8. function getDataPointsFromTable() {
  9. // 检查是否使用新的Excel表格
  10. const excelTable = document.getElementById('fit-excel-table');
  11. if (excelTable && window.dataTable) {
  12. const data = window.dataTable.getTableData(excelTable);
  13. const dataPoints = [];
  14. for (let i = 0; i < data.length; i++) {
  15. const row = data[i];
  16. if (row.length >= 2) {
  17. const x = row[0];
  18. const y = row[1];
  19. if (!isNaN(x) && !isNaN(y)) {
  20. dataPoints.push({ x, y });
  21. }
  22. }
  23. }
  24. return dataPoints;
  25. } else {
  26. // 兼容旧版表格
  27. const dataTable = document.getElementById('data-table');
  28. const rows = dataTable.querySelectorAll('tbody tr');
  29. const dataPoints = [];
  30. rows.forEach(row => {
  31. const xInput = row.querySelector('.x-value');
  32. const yInput = row.querySelector('.y-value');
  33. if (xInput && yInput) {
  34. const x = parseFloat(xInput.value);
  35. const y = parseFloat(yInput.value);
  36. if (!isNaN(x) && !isNaN(y)) {
  37. dataPoints.push({ x, y });
  38. }
  39. }
  40. });
  41. return dataPoints;
  42. }
  43. }
  44. /**
  45. * 从表格获取回归数据
  46. * @returns {Object} 包含X(自变量矩阵)和y(因变量向量)的对象
  47. */
  48. function getDataFromTable() {
  49. // 检查是否使用新的Excel表格
  50. const excelTable = document.getElementById('regression-excel-table');
  51. if (excelTable && window.dataTable) {
  52. const data = window.dataTable.getTableData(excelTable);
  53. const X = [];
  54. const y = [];
  55. for (let i = 0; i < data.length; i++) {
  56. const row = data[i];
  57. if (row.length >= 2) { // 至少需要一个X和一个y
  58. const xRow = row.slice(0, row.length - 1); // 最后一列是y值
  59. const yValue = row[row.length - 1];
  60. // 检查所有值是否有效
  61. let allValid = true;
  62. for (let j = 0; j < xRow.length; j++) {
  63. if (isNaN(xRow[j])) {
  64. allValid = false;
  65. break;
  66. }
  67. }
  68. if (isNaN(yValue)) {
  69. allValid = false;
  70. }
  71. // 如果所有值都有效,添加到数据集
  72. if (allValid) {
  73. X.push(xRow);
  74. y.push(yValue);
  75. }
  76. }
  77. }
  78. return { X, y };
  79. } else {
  80. // 兼容旧版表格
  81. const rows = document.querySelectorAll('#regression-table tbody tr');
  82. const X = [];
  83. const y = [];
  84. rows.forEach(row => {
  85. const xInputs = row.querySelectorAll('.x1-value, .x2-value, [class^="x"][class$="-value"]:not(.x1-value):not(.x2-value)');
  86. const yInput = row.querySelector('.y-value');
  87. if (xInputs.length > 0 && yInput) {
  88. const xRow = [];
  89. let allValid = true;
  90. // 收集所有x值
  91. xInputs.forEach(input => {
  92. const value = parseFloat(input.value);
  93. if (isNaN(value)) {
  94. allValid = false;
  95. }
  96. xRow.push(value);
  97. });
  98. // 获取y值
  99. const yValue = parseFloat(yInput.value);
  100. if (isNaN(yValue)) {
  101. allValid = false;
  102. }
  103. // 如果所有值都有效,添加到数据集
  104. if (allValid) {
  105. X.push(xRow);
  106. y.push(yValue);
  107. }
  108. }
  109. });
  110. return { X, y };
  111. }
  112. }
  113. /**
  114. * 解析CSV数据
  115. * @param {string} csvText - CSV格式的文本
  116. * @returns {Object} 包含X(自变量矩阵)和y(因变量向量)的对象
  117. */
  118. function parseCSVData(csvText) {
  119. if (!csvText.trim()) {
  120. return { X: [], y: [] };
  121. }
  122. try {
  123. // 按行分割
  124. const lines = csvText.trim().split(/\r?\n/);
  125. // 检查是否有足够的行
  126. if (lines.length < 2) {
  127. throw new Error('数据行数不足');
  128. }
  129. // 解析数据
  130. const X = [];
  131. const y = [];
  132. for (let i = 0; i < lines.length; i++) {
  133. const values = lines[i].split(/[,\t]/).map(val => parseFloat(val.trim()));
  134. // 检查是否有足够的列
  135. if (values.length < 2) {
  136. continue;
  137. }
  138. // 检查所有值是否有效
  139. let allValid = true;
  140. for (let j = 0; j < values.length; j++) {
  141. if (isNaN(values[j])) {
  142. allValid = false;
  143. break;
  144. }
  145. }
  146. if (allValid) {
  147. // 最后一列作为y值,其余作为X值
  148. X.push(values.slice(0, values.length - 1));
  149. y.push(values[values.length - 1]);
  150. }
  151. }
  152. return { X, y };
  153. } catch (error) {
  154. console.error('解析CSV数据错误:', error);
  155. return { X: [], y: [] };
  156. }
  157. }
  158. /**
  159. * 格式化数字,保留指定小数位
  160. * @param {number} value - 要格式化的数值
  161. * @param {number} decimals - 小数位数
  162. * @returns {string} 格式化后的数字字符串
  163. */
  164. function formatNumber(value, decimals = 4) {
  165. return Number(value).toFixed(decimals);
  166. }
  167. /**
  168. * 计算相关系数 (R²)
  169. * @param {Array} xValues - X值数组
  170. * @param {Array} yValues - Y值数组
  171. * @param {Function} predictFn - 预测函数,接收x返回预测的y
  172. * @returns {number} 相关系数
  173. */
  174. function calculateRSquared(xValues, yValues, predictFn) {
  175. if (xValues.length !== yValues.length || xValues.length === 0) {
  176. return 0;
  177. }
  178. // 计算y的平均值
  179. const yMean = yValues.reduce((sum, y) => sum + y, 0) / yValues.length;
  180. // 计算总平方和(SST)
  181. const sst = yValues.reduce((sum, y) => sum + Math.pow(y - yMean, 2), 0);
  182. // 计算残差平方和(SSE)
  183. let sse = 0;
  184. for (let i = 0; i < xValues.length; i++) {
  185. const yPred = predictFn(xValues[i]);
  186. sse += Math.pow(yValues[i] - yPred, 2);
  187. }
  188. // 计算R²
  189. return 1 - (sse / sst);
  190. }
  191. /**
  192. * 计算均方根误差(RMSE)
  193. * @param {Array} xValues - X值数组
  194. * @param {Array} yValues - Y值数组
  195. * @param {Function} predictFn - 预测函数,接收x返回预测的y
  196. * @returns {number} RMSE值
  197. */
  198. function calculateRMSE(xValues, yValues, predictFn) {
  199. if (xValues.length !== yValues.length || xValues.length === 0) {
  200. return 0;
  201. }
  202. let sumSquaredError = 0;
  203. for (let i = 0; i < xValues.length; i++) {
  204. const yPred = predictFn(xValues[i]);
  205. sumSquaredError += Math.pow(yValues[i] - yPred, 2);
  206. }
  207. return Math.sqrt(sumSquaredError / xValues.length);
  208. }
  209. /**
  210. * 生成统计结果HTML
  211. * @param {Object} params - 统计参数
  212. * @returns {string} HTML字符串
  213. */
  214. function generateStatsHTML(params) {
  215. const { coefficients, rSquared, rmse, formula, dataPoints } = params;
  216. let html = '<h4>拟合统计</h4>';
  217. html += '<table>';
  218. html += '<tr><th>参数</th><th>值</th></tr>';
  219. html += `<tr><td>数据点数量</td><td>${dataPoints}</td></tr>`;
  220. html += `<tr><td>决定系数 (R²)</td><td>${formatNumber(rSquared)}</td></tr>`;
  221. html += `<tr><td>均方根误差 (RMSE)</td><td>${formatNumber(rmse)}</td></tr>`;
  222. html += '<tr><th colspan="2">系数</th></tr>';
  223. if (Array.isArray(coefficients)) {
  224. coefficients.forEach((coef, index) => {
  225. let coefName = '';
  226. switch (index) {
  227. case 0: coefName = formula === 'linear' ? 'a (斜率)' : 'a'; break;
  228. case 1: coefName = formula === 'linear' ? 'b (截距)' : 'b'; break;
  229. default: coefName = String.fromCharCode(97 + index); // a, b, c, d...
  230. }
  231. html += `<tr><td>${coefName}</td><td>${formatNumber(coef)}</td></tr>`;
  232. });
  233. } else if (typeof coefficients === 'object') {
  234. for (const key in coefficients) {
  235. html += `<tr><td>${key}</td><td>${formatNumber(coefficients[key])}</td></tr>`;
  236. }
  237. }
  238. html += '</table>';
  239. return html;
  240. }