-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVT_Processor.html
More file actions
3363 lines (2913 loc) · 116 KB
/
VT_Processor.html
File metadata and controls
3363 lines (2913 loc) · 116 KB
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
===============================================================================
NeuroEng Voltage Transient Processor - Data Overlay
===============================================================================
Author: Ifra Ilyas Ansari
Created: 2025-08-07
Modified: 2025-10-15
Version: v2.6
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CSV Graph Plotter</title>
<script src="https://cdn.plot.ly/plotly-2.30.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/papaparse@5.4.1/papaparse.min.js"></script>
<style>
:root{
--bg:#0f0f12; --card:#15161a; --muted:#9aa3af; --text:#e5e7eb;
--amber:#E6B800; --blue:#1E90FF;
}
html, body {
height:100%;
background:var(--bg);
color:var(--text);
margin:0;
font-family:Inter, ui-sans-serif, system-ui, -apple-system;
}
.container {
display:grid;
grid-template-columns: 320px 1fr;
gap:16px;
padding:16px;
box-sizing:border-box;
height:100%;
}
.container.analysis-mode {
grid-template-columns: 320px 1fr 320px;
}
.sidebar {
background:var(--card);
border-radius:16px;
padding:16px;
overflow:auto;
}
.main-content {
background:var(--card);
border-radius:16px;
padding:16px;
overflow:auto;
}
.title {
font-size:18px;
font-weight:700;
margin:0 0 8px;
}
.description {
color:var(--muted);
font-size:12px;
margin:4px 0 12px;
}
.file-input-button {
display:inline-block;
background:#22252b;
padding:10px 12px;
border-radius:10px;
cursor:pointer;
font-weight:600;
border:1px solid #2a2d34;
}
.file-list {
margin-top:12px;
border-top:1px solid #2a2d34;
}
.file-item {
display:flex;
justify-content:space-between;
align-items:center;
padding:10px 0;
border-bottom:1px solid #2a2d34;
gap:8px;
}
.file-item button {
background:#22252b;
border:1px solid #2a2d34;
color:var(--text);
border-radius:8px;
padding:6px 10px;
cursor:pointer;
}
.toolbar {
display:flex;
gap:8px;
align-items:center;
margin:8px 0 12px;
flex-wrap:wrap;
}
.plot-container {
width:100%;
height:72vh;
min-height:420px;
background:#ffffff;
border-radius:12px;
}
.status-text {
color:var(--muted);
font-size:14px;
}
.tab-container {
display:flex;
gap:4px;
margin-bottom:12px;
}
.tab-button {
background:#22252b;
border:1px solid #2a2d34;
color:var(--text);
padding:8px 16px;
border-radius:8px;
cursor:pointer;
font-weight:600;
transition:all 0.2s ease;
}
.tab-button.active {
background:var(--amber);
color:#000;
border-color:var(--amber);
}
.tab-button:hover:not(.active) {
background:#2a2d34;
}
</style>
</head>
<body>
<div class="container">
<!-- Sidebar for file selection -->
<aside class="sidebar">
<h1 class="title">CSV Graph Plotter</h1>
<p class="description">
Upload CSV files with TIME, CH1 (Voltage), and CH2 (Current) columns to plot voltage and current graphs.
</p>
<!-- Hidden file input -->
<input id="csvFileInput" type="file" accept=".csv" multiple style="display:none" />
<label class="file-input-button" for="csvFileInput">📁 Choose CSV Files</label>
<!-- List of loaded files -->
<div class="file-list" id="loadedFilesList"></div>
</aside>
<!-- Main content area -->
<main class="main-content">
<!-- Toolbar with navigation and export buttons -->
<div class="toolbar">
<button id="previousFileButton">◀ Previous</button>
<button id="nextFileButton">Next ▶</button>
<span id="currentFileStatus" class="status-text"></span>
<span style="flex:1 1 auto"></span>
<button id="toggleMarkersButton">🎯 Show Markers</button>
<button id="extendedPulseButton">📏 Hide Extended Pulse</button>
<button id="fillPulseAreaButton">🎨 Show Area Fill</button>
<button id="showPulsePointsButton">📍 Show Pulse Points</button>
<button id="zoomToPulseButton">🔍 Zoom to Pulse</button>
</div>
<!-- Tab container for five different views -->
<div class="tab-container">
<button id="rawTab" class="tab-button active">Raw Data</button>
<button id="pulseTab" class="tab-button">Pulse Detection</button>
<button id="shiftedTab" class="tab-button">Time Shifted</button>
<button id="analysisTab" class="tab-button">Voltage picker</button>
<button id="exportTab" class="tab-button">Export</button>
</div>
<!-- Plot area - hidden when in Export view -->
<div id="plotArea" class="plot-container"></div>
<!-- Export view - only shown when Export tab is active -->
<div id="exportView" class="export-view" style="display:none; height:72vh; min-height:420px; background:var(--card); border-radius:12px; padding:20px; text-align:center;">
<div style="max-width:600px; margin:0 auto;">
<h2 style="font-size:24px; margin-bottom:30px;">Export Data</h2>
<!-- EXPORT ALL section -->
<div style="background:#1a4d3a; padding:20px; border-radius:12px; margin-bottom:20px; border:2px solid #28a745;">
<h3 style="color:#28a745; margin-bottom:15px; font-size:20px;">📦 Export All Files</h3>
<p style="margin-bottom:20px;">Export data from all loaded CSV files at once.</p>
<button id="exportAllPulseCsvButton" style="background:#28a745; color:#fff; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:10px;">
⬇️ Export All Pulse CSV Files
</button>
<button id="exportAllDataCsvButton" style="background:#28a745; color:#fff; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:10px;">
⬇️ Export All Data CSV Files
</button>
<button id="exportAllPngButton" style="background:#28a745; color:#fff; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:15px;">
⬇️ Export All PNG Files
</button>
<p style="font-size:12px; color:var(--muted); text-align:left; margin-top:15px;">
Creates separate files for each loaded file:<br>
• Pulse CSV: Exports pulse region data with time-shifted values<br>
• Data CSV: Exports all data points from each file<br>
• PNG: Exports plot images for each file<br>
• Files will be downloaded individually with descriptive names
</p>
</div>
<!-- Single file export section -->
<div style="background:#22252b; padding:20px; border-radius:12px; margin-bottom:20px;">
<h3 style="color:var(--amber); margin-bottom:15px; font-size:18px;">📄 Current File Export</h3>
<p style="margin-bottom:20px;">Export the detected pulse region data to a CSV file with both original and time-shifted values.</p>
<button id="exportPulseCsvButtonLarge" style="background:var(--amber); color:#000; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:15px;">
⬇️ Export Pulse CSV
</button>
<p style="font-size:12px; color:var(--muted); text-align:left; margin-top:15px;">
The exported CSV file will contain:<br>
• Index of each data point<br>
• Original time values (microseconds)<br>
• Time-shifted values relative to pulse start (microseconds)<br>
• Voltage values (V)<br>
• Current values (A)
</p>
</div>
<div style="background:#22252b; padding:20px; border-radius:12px; margin-bottom:20px;">
<button id="exportPngButtonLarge" style="background:var(--amber); color:#000; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:10px;">
⬇️ Export Plot as PNG
</button>
<button id="exportVoltagePickerPngButtonLarge" style="background:var(--amber); color:#000; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:15px;">
⬇️ Export Voltage Picker PNG
</button>
<button id="exportAllVoltagePickerPngButton" style="background:#28a745; color:#fff; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:15px;">
⬇️ Export All Voltage Picker PNG
</button>
<p style="font-size:12px; color:var(--muted); text-align:left; margin-top:15px;">
• Export Plot as PNG: Exports the current plot view as displayed<br>
• Export Voltage Picker PNG: Exports only the highlighted pulse regions (voltage picker view)
</p>
</div>
<div style="background:#22252b; padding:20px; border-radius:12px;">
<button id="exportCsvButtonLarge" style="background:var(--amber); color:#000; border:none; padding:15px 30px; border-radius:8px; font-size:18px; font-weight:600; cursor:pointer; display:block; width:100%; margin-bottom:15px;">
⬇️ Export All Data as CSV
</button>
<p style="font-size:12px; color:var(--muted); text-align:left; margin-top:15px;">
Exports all data points from the current file as a CSV file.
</p>
</div>
</div>
</div>
</main>
<!-- Right sidebar for analysis mode (initially hidden) -->
<aside id="rightSidebar" class="sidebar" style="display:none;">
<h1 class="title">Manual Analysis</h1>
<p class="description">
Click on voltage points in the graph to select them for analysis. Select 8 points: v1, v2, v3, v4, v5, v6, v7, and v8.
</p>
<!-- Manual Point Selection Instructions -->
<div style="margin-bottom:20px; padding:12px; background:#22252b; border-radius:8px; border-left:4px solid var(--amber);">
<div style="font-weight:600; margin-bottom:8px; color:var(--amber);">Instructions:</div>
<div style="font-size:12px; line-height:1.4;">
1. Click on the voltage graph to select points<br>
2. Points will be assigned in order: v1 → v2 → v3 → v4 → v5 → v6 → v7 → v8<br>
3. Use "Clear All" to reset and start over<br>
4. Individual points can be cleared using their "Clear" buttons
</div>
</div>
<!-- Current Selection Status -->
<div style="margin-bottom:20px;">
<div style="font-weight:600; margin-bottom:8px;">Next Point to Select:</div>
<div id="nextPointIndicator" style="font-size:14px; color:var(--amber); font-weight:600;">v1</div>
</div>
<!-- Manual Point Selection Controls -->
<div style="margin-bottom:20px;">
<button
id="clearAllPointsButton"
style="width:100%; padding:8px; background:#dc3545; color:#fff; border:none; border-radius:8px; font-weight:600; cursor:pointer; margin-bottom:8px;"
>
Clear All Points
</button>
<button
id="toggleSelectionModeButton"
style="width:100%; padding:8px; background:var(--blue); color:#fff; border:none; border-radius:8px; font-weight:600; cursor:pointer;"
>
Enable Selection Mode
</button>
</div>
<!-- Selected Points Display -->
<div id="manualPointsDisplay">
<h3 style="margin:16px 0 8px; font-size:14px; font-weight:600;">Selected Points:</h3>
<div id="selectedPointsList" style="font-size:12px; line-height:1.4;">
<div style="color:var(--muted); font-style:italic;">No points selected yet</div>
</div>
</div>
<!-- Selection Progress -->
<div style="margin-top:16px; padding:12px; background:#22252b; border-radius:8px;">
<div style="font-weight:600; margin-bottom:8px; color:var(--amber);">Selection Progress:</div>
<div id="selectionProgress" style="font-size:12px; line-height:1.4;">
<div style="display:flex; gap:8px; margin-bottom:4px; flex-wrap:wrap;">
<span id="v1Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v1</span>
<span id="v2Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v2</span>
<span id="v3Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v3</span>
<span id="v4Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v4</span>
<span id="v5Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v5</span>
<span id="v6Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v6</span>
<span id="v7Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v7</span>
<span id="v8Status" style="padding:2px 6px; border-radius:4px; background:#dc3545; color:#fff; font-size:10px;">v8</span>
</div>
<div style="font-size:10px; color:var(--muted);">Red = Not Selected, Green = Selected</div>
</div>
</div>
<!-- Export Voltage Picker Points -->
<div style="margin-top:16px; padding:12px; background:#1a4d3a; border-radius:8px; border:2px solid #28a745;">
<div style="font-weight:600; margin-bottom:8px; color:#28a745;">Export Selected Points:</div>
<button
id="exportVoltagePickerPointsButton"
style="width:100%; padding:10px; background:#28a745; color:#fff; border:none; border-radius:8px; font-weight:600; cursor:pointer; margin-bottom:8px;"
>
📊 Export Voltage Picker CSV
</button>
<div style="font-size:10px; color:var(--muted); line-height:1.3;">
Exports the 8 selected voltage points (v1-v8) and corresponding current values (i1-i8) with original row numbers from the CSV file.
</div>
</div>
</aside>
</div>
<script>
// Application state to manage loaded files and current selection
const applicationState = {
loadedFiles: [], // Array of file data objects
currentFileIndex: -1, // Index of currently displayed file
isPlotRendered: false, // Track if plot has been rendered
isTimeShifted: false, // Track if currently showing time-shifted view
isRawView: true, // Track if currently showing raw data view (default: true)
isPulseView: false, // Track if currently showing pulse detection view
isAnalysisView: false, // Track if currently showing analysis view
isExportView: false, // Track if currently showing export view
showDetectionMarkers: false, // Track if detection markers are visible
extendedPulseHighlight: true, // Track if extended pulse highlighting is enabled (default: true)
zoomToPulse: false, // Track if zoomed to pulse region (default: false)
fillPulseArea: false, // Track if pulse area should be filled (default: false)
showPulsePoints: false, // Track if individual pulse points should be shown (default: false)
selectionModeEnabled: false, // Track if manual point selection mode is enabled
nextPointToSelect: 'v1' // Track which point will be selected next
};
// Plot styling configuration
const plotColors = {
voltage: "#E6B800", // Amber color for voltage
current: "#1E90FF" // Blue color for current
};
const plotLayout = {
paperBackgroundColor: '#ffffff',
plotBackgroundColor: '#ffffff',
textColor: '#000000',
gridColor: '#e5e7eb',
axisColor: '#000000'
};
/**
* Get the currently selected file data
* @returns {Object|null} Current file data or null if none selected
*/
function getCurrentFileData() {
if (applicationState.currentFileIndex >= 0 &&
applicationState.currentFileIndex < applicationState.loadedFiles.length) {
return applicationState.loadedFiles[applicationState.currentFileIndex];
}
return null;
}
/**
* Parse Tektronix CSV file format
* Looks for header row containing TIME, CH1, CH2 columns
* @param {File} csvFile - The CSV file to parse
* @returns {Promise<Array>} Promise resolving to array of data rows
*/
function parseTektronixCsv(csvFile) {
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.onerror = () => reject(new Error("Failed to read file"));
fileReader.onload = () => {
const fileContent = String(fileReader.result);
const contentLines = fileContent.split(/\r\n|\n|\r/);
// Find the header row (usually around row 16 in Tektronix files)
let headerRowIndex = -1;
for (let i = 0; i < Math.min(contentLines.length, 200); i++) {
const currentLine = contentLines[i];
// Look for TIME, CH1, and CH2 columns
if (/TIME/i.test(currentLine) &&
/CH\s*1|CH1/i.test(currentLine) &&
/CH\s*2|CH2/i.test(currentLine)) {
headerRowIndex = i;
break;
}
}
if (headerRowIndex < 0) {
reject(new Error("CSV header not found. Expected columns: TIME, CH1, CH2"));
return;
}
// Parse CSV starting from header row
const csvContent = contentLines.slice(headerRowIndex).join("\n");
Papa.parse(csvContent, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
complete: (parseResult) => {
// Filter out invalid rows
const validRows = parseResult.data.filter(row =>
row &&
row.TIME != null &&
row.CH1 != null &&
row.CH2 != null
);
resolve(validRows);
},
error: (parseError) => reject(parseError)
});
};
fileReader.readAsText(csvFile);
});
}
/**
* Process a CSV file and extract time, voltage, and current data
* @param {File} csvFile - The CSV file to process
* @returns {Promise<Object>} Promise resolving to processed file data
*/
async function processUploadedFile(csvFile) {
try {
const parsedRows = await parseTektronixCsv(csvFile);
// Extract data arrays
const timeData = parsedRows.map(row => Number(row.TIME));
const voltageData = parsedRows.map(row => Number(row.CH1));
const currentData = parsedRows.map(row => Number(row.CH2));
return {
fileName: csvFile.name,
timeValues: timeData,
voltageValues: voltageData,
currentValues: currentData,
dataPointCount: timeData.length
};
} catch (error) {
console.error(`Error processing file ${csvFile.name}:`, error);
throw error;
}
}
/**
* Find minimum and maximum values in current data with their indices
* @param {Array} currentValues - Array of current values
* @returns {Object} Object containing min/max values and their indices
*/
function findCurrentMinMax(currentValues) {
if (!currentValues || currentValues.length === 0) {
return { minValue: null, maxValue: null, minIndex: -1, maxIndex: -1 };
}
let minValue = currentValues[0];
let maxValue = currentValues[0];
let minIndex = 0;
let maxIndex = 0;
for (let i = 1; i < currentValues.length; i++) {
if (currentValues[i] < minValue) {
minValue = currentValues[i];
minIndex = i;
}
if (currentValues[i] > maxValue) {
maxValue = currentValues[i];
maxIndex = i;
}
}
return { minValue, maxValue, minIndex, maxIndex };
}
/**
* Find minimum and maximum values in voltage data with their indices
* @param {Array} voltageValues - Array of voltage values
* @returns {Object} Object containing min/max values and their indices
*/
function findVoltageMinMax(voltageValues) {
if (!voltageValues || voltageValues.length === 0) {
return { minValue: null, maxValue: null, minIndex: -1, maxIndex: -1 };
}
let minValue = voltageValues[0];
let maxValue = voltageValues[0];
let minIndex = 0;
let maxIndex = 0;
for (let i = 1; i < voltageValues.length; i++) {
if (voltageValues[i] < minValue) {
minValue = voltageValues[i];
minIndex = i;
}
if (voltageValues[i] > maxValue) {
maxValue = voltageValues[i];
maxIndex = i;
}
}
return { minValue, maxValue, minIndex, maxIndex };
}
/**
* Find pulse start by combining slope analysis, distance from 0A, and length to CURRENT_MIN
* @param {Array} currentValues - Array of current values
* @param {Array} timeValues - Array of time values
* @param {number} minIndex - Index of the minimum current value
* @returns {Object} Object containing pulse start value and index
*/
function findPulseStart(currentValues, timeValues, minIndex) {
if (!currentValues || !timeValues || currentValues.length === 0 || minIndex < 1) {
return { pulseStartValue: null, pulseStartIndex: -1 };
}
const minValue = currentValues[minIndex];
const minTime = timeValues[minIndex];
let bestScore = -Infinity;
let pulseStartIndex = minIndex;
// Find normalization factors
let maxAbsSlope = 0;
let maxDistanceFromZero = 0;
let maxLengthToMin = 0;
// First pass: find normalization factors
for (let i = minIndex - 1; i >= 0; i--) {
const currentValue = currentValues[i];
const currentTime = timeValues[i];
const deltaY = minValue - currentValue;
const deltaX = minTime - currentTime;
if (deltaX === 0) continue;
const slope = deltaY / deltaX;
const absSlope = Math.abs(slope);
const distanceFromZero = Math.abs(currentValue);
// Calculate length (distance) from current point to CURRENT_MIN
// Using Euclidean distance in time-current space
const lengthToMin = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
if (absSlope > maxAbsSlope) maxAbsSlope = absSlope;
if (distanceFromZero > maxDistanceFromZero) maxDistanceFromZero = distanceFromZero;
if (lengthToMin > maxLengthToMin) maxLengthToMin = lengthToMin;
}
// Second pass: calculate composite score for each point
for (let i = minIndex - 1; i >= 0; i--) {
const currentValue = currentValues[i];
const currentTime = timeValues[i];
const deltaY = minValue - currentValue;
const deltaX = minTime - currentTime;
if (deltaX === 0) continue;
const slope = deltaY / deltaX;
const distanceFromZero = Math.abs(currentValue);
const lengthToMin = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
// Normalize slope (we want negative slopes, so invert for scoring)
const normalizedSlope = maxAbsSlope > 0 ? -slope / maxAbsSlope : 0;
// Normalize distance from zero (we want points closer to zero)
const normalizedDistance = maxDistanceFromZero > 0 ? 1 - (distanceFromZero / maxDistanceFromZero) : 1;
// Normalize length to min (we want maximum length for better pulse detection)
const normalizedLength = maxLengthToMin > 0 ? lengthToMin / maxLengthToMin : 0;
// Composite score with three factors:
// 40% weight on slope (steepest dip)
// 40% weight on distance from zero (baseline proximity) - increased preference
// 20% weight on length to min (pulse duration/extent)
const compositeScore = (0.4 * normalizedSlope) + (0.4 * normalizedDistance) + (0.2 * normalizedLength);
// Only consider negative slopes (actual dips)
if (slope < 0 && compositeScore > bestScore) {
bestScore = compositeScore;
pulseStartIndex = i;
}
}
return {
pulseStartValue: currentValues[pulseStartIndex],
pulseStartIndex: pulseStartIndex
};
}
/**
* Find voltage pulse start by combining slope analysis, distance from 0V, and length to VOLTAGE_MIN
* @param {Array} voltageValues - Array of voltage values
* @param {Array} timeValues - Array of time values
* @param {number} minIndex - Index of the minimum voltage value
* @returns {Object} Object containing pulse start value and index
*/
function findVoltagePulseStart(voltageValues, timeValues, minIndex) {
if (!voltageValues || !timeValues || voltageValues.length === 0 || minIndex < 1) {
return { pulseStartValue: null, pulseStartIndex: -1 };
}
const minValue = voltageValues[minIndex];
const minTime = timeValues[minIndex];
let bestScore = -Infinity;
let pulseStartIndex = minIndex;
// Find normalization factors
let maxAbsSlope = 0;
let maxDistanceFromZero = 0;
let maxLengthToMin = 0;
// First pass: find normalization factors
for (let i = minIndex - 1; i >= 0; i--) {
const currentValue = voltageValues[i];
const currentTime = timeValues[i];
const deltaY = minValue - currentValue;
const deltaX = minTime - currentTime;
if (deltaX === 0) continue;
const slope = deltaY / deltaX;
const absSlope = Math.abs(slope);
const distanceFromZero = Math.abs(currentValue);
// Calculate length (distance) from current point to VOLTAGE_MIN
// Using Euclidean distance in time-voltage space
const lengthToMin = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
if (absSlope > maxAbsSlope) maxAbsSlope = absSlope;
if (distanceFromZero > maxDistanceFromZero) maxDistanceFromZero = distanceFromZero;
if (lengthToMin > maxLengthToMin) maxLengthToMin = lengthToMin;
}
// Second pass: calculate composite score for each point
for (let i = minIndex - 1; i >= 0; i--) {
const currentValue = voltageValues[i];
const currentTime = timeValues[i];
const deltaY = minValue - currentValue;
const deltaX = minTime - currentTime;
if (deltaX === 0) continue;
const slope = deltaY / deltaX;
const distanceFromZero = Math.abs(currentValue);
const lengthToMin = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));
// Normalize slope (we want negative slopes, so invert for scoring)
const normalizedSlope = maxAbsSlope > 0 ? -slope / maxAbsSlope : 0;
// Normalize distance from zero (we want points closer to zero)
const normalizedDistance = maxDistanceFromZero > 0 ? 1 - (distanceFromZero / maxDistanceFromZero) : 1;
// Normalize length to min (we want maximum length for better pulse detection)
const normalizedLength = maxLengthToMin > 0 ? lengthToMin / maxLengthToMin : 0;
// Composite score with three factors:
// 40% weight on slope (steepest dip)
// 40% weight on distance from zero (baseline proximity) - increased preference
// 20% weight on length to min (pulse duration/extent)
const compositeScore = (0.4 * normalizedSlope) + (0.4 * normalizedDistance) + (0.2 * normalizedLength);
// Only consider negative slopes (actual dips)
if (slope < 0 && compositeScore > bestScore) {
bestScore = compositeScore;
pulseStartIndex = i;
}
}
return {
pulseStartValue: voltageValues[pulseStartIndex],
pulseStartIndex: pulseStartIndex
};
}
/**
* Find pulse end - the first point crossing to 0 or 0 itself after CURRENT_MAX
* @param {Array} currentValues - Array of current values
* @param {number} maxIndex - Index of the maximum current value
* @returns {Object} Object containing pulse end value and index
*/
function findPulseEnd(currentValues, maxIndex) {
if (!currentValues || currentValues.length === 0 || maxIndex < 0 || maxIndex >= currentValues.length - 1) {
return { pulseEndValue: null, pulseEndIndex: -1 };
}
// Search from the point after CURRENT_MAX to the end of the data
for (let i = maxIndex + 1; i < currentValues.length; i++) {
const currentValue = currentValues[i];
// Check if current point is exactly 0
if (currentValue === 0) {
return {
pulseEndValue: currentValue,
pulseEndIndex: i
};
}
// Check for zero crossing (sign change from previous point)
if (i > maxIndex + 1) {
const previousValue = currentValues[i - 1];
// Zero crossing occurs when signs are different (and neither is zero)
if (previousValue !== 0 && currentValue !== 0 &&
Math.sign(previousValue) !== Math.sign(currentValue)) {
// Determine which point is closer to zero for the crossing
if (Math.abs(currentValue) <= Math.abs(previousValue)) {
return {
pulseEndValue: currentValue,
pulseEndIndex: i
};
} else {
return {
pulseEndValue: previousValue,
pulseEndIndex: i - 1
};
}
}
}
}
// If no zero crossing found, return null (no pulse end detected)
return { pulseEndValue: null, pulseEndIndex: -1 };
}
/**
* Find voltage pulse end - the first point crossing to 0 or 0 itself after VOLTAGE_MAX
* @param {Array} voltageValues - Array of voltage values
* @param {number} maxIndex - Index of the maximum voltage value
* @returns {Object} Object containing pulse end value and index
*/
function findVoltagePulseEnd(voltageValues, maxIndex) {
if (!voltageValues || voltageValues.length === 0 || maxIndex < 0 || maxIndex >= voltageValues.length - 1) {
return { pulseEndValue: null, pulseEndIndex: -1 };
}
// Search from the point after VOLTAGE_MAX to the end of the data
for (let i = maxIndex + 1; i < voltageValues.length; i++) {
const currentValue = voltageValues[i];
// Check if current point is exactly 0
if (currentValue === 0) {
return {
pulseEndValue: currentValue,
pulseEndIndex: i
};
}
// Check for zero crossing (sign change from previous point)
if (i > maxIndex + 1) {
const previousValue = voltageValues[i - 1];
// Zero crossing occurs when signs are different (and neither is zero)
if (previousValue !== 0 && currentValue !== 0 &&
Math.sign(previousValue) !== Math.sign(currentValue)) {
// Determine which point is closer to zero for the crossing
if (Math.abs(currentValue) <= Math.abs(previousValue)) {
return {
pulseEndValue: currentValue,
pulseEndIndex: i
};
} else {
return {
pulseEndValue: previousValue,
pulseEndIndex: i - 1
};
}
}
}
}
// If no zero crossing found, return null (no pulse end detected)
return { pulseEndValue: null, pulseEndIndex: -1 };
}
/**
* COMMENTED OUT FOR FUTURE REFERENCE - AUTOMATIC ANALYSIS ALGORITHM
* Calculate voltage analysis points based on voltage curve behavior
* @param {Object} fileData - File data containing time, voltage, and current arrays
* @param {number} gapValueMicroseconds - Gap value in microseconds (not used in new algorithm)
* @returns {Object} Object containing the calculated points
*/
/*
function calculateVoltageAnalysisPoints(fileData, gapValueMicroseconds) {
// Find voltage pulse start
const voltageMinMax = findVoltageMinMax(fileData.voltageValues);
const voltagePulseStart = findVoltagePulseStart(fileData.voltageValues, fileData.timeValues, voltageMinMax.minIndex);
if (voltagePulseStart.pulseStartIndex < 0) {
return {
v1: null, v2: null, v3: null, v4: null, v5: null,
error: "Could not find voltage pulse start"
};
}
// v1 - VOLTAGE_PULSE_START
const v1 = {
index: voltagePulseStart.pulseStartIndex,
time: fileData.timeValues[voltagePulseStart.pulseStartIndex],
voltage: voltagePulseStart.pulseStartValue,
description: "VOLTAGE_PULSE_START"
};
// v2 - Find where rapid voltage drop slows down after V1 (within next 10 points, close to 0 time)
let v2 = null;
const v1Index = voltagePulseStart.pulseStartIndex;
// Get current pulse start time for reference (this should be close to time 0)
const currentMinMax = findCurrentMinMax(fileData.currentValues);
const currentPulseStart = findPulseStart(fileData.currentValues, fileData.timeValues, currentMinMax.minIndex);
if (currentPulseStart.pulseStartIndex >= 0 && v1Index < fileData.voltageValues.length - 3) {
const pulseStartTime = fileData.timeValues[currentPulseStart.pulseStartIndex];
// Look within the next 10 points after V1, but prioritize points close to current pulse start time
const maxSearchRange = Math.min(10, fileData.voltageValues.length - v1Index - 1);
let bestV2Index = -1;
let bestScore = -Infinity;
// Calculate voltage drops for the first few points after V1
const drops = [];
for (let i = v1Index + 1; i < Math.min(v1Index + 5, fileData.voltageValues.length - 1); i++) {
const currentVoltage = fileData.voltageValues[i];
const nextVoltage = fileData.voltageValues[i + 1];
const voltageDrop = currentVoltage - nextVoltage; // Positive = voltage dropping
drops.push(voltageDrop);
}
if (drops.length >= 2) {
// Calculate average initial drop rate
const avgInitialDrop = drops.reduce((sum, drop) => sum + drop, 0) / drops.length;
// Search within next 10 points after V1
for (let i = v1Index + 1; i <= v1Index + maxSearchRange && i < fileData.voltageValues.length - 1; i++) {
const currentVoltage = fileData.voltageValues[i];
const nextVoltage = fileData.voltageValues[i + 1];
const currentDrop = currentVoltage - nextVoltage;
// Calculate how close this point is to the current pulse start time
const timeFromPulseStart = Math.abs(fileData.timeValues[i] - pulseStartTime);
const timeProximityScore = 1.0 / (1.0 + timeFromPulseStart * 1e6); // Higher score for closer to pulse start
// Calculate drop reduction score (higher when drop slows down significantly)
let dropReductionScore = 0;
if (avgInitialDrop > 0) {
const dropReduction = Math.max(0, (avgInitialDrop - currentDrop) / avgInitialDrop);
dropReductionScore = dropReduction;
}
// Composite score: 70% weight on time proximity, 30% on drop reduction
const compositeScore = (0.7 * timeProximityScore) + (0.3 * dropReductionScore);
// Only consider points where drop has reduced significantly (at least 30% reduction)
if (dropReductionScore > 0.3 && compositeScore > bestScore) {
bestScore = compositeScore;
bestV2Index = i;
}
}
// If no point with significant drop reduction found, take the point closest to pulse start time within range
if (bestV2Index < 0) {
let minTimeDistance = Infinity;
for (let i = v1Index + 1; i <= v1Index + maxSearchRange && i < fileData.voltageValues.length; i++) {
const timeFromPulseStart = Math.abs(fileData.timeValues[i] - pulseStartTime);
if (timeFromPulseStart < minTimeDistance) {
minTimeDistance = timeFromPulseStart;
bestV2Index = i;
}
}
}
// Create V2 point if found
if (bestV2Index >= 0) {
const timeShiftedV2 = (fileData.timeValues[bestV2Index] - pulseStartTime) * 1e6; // Convert to microseconds
v2 = {
index: bestV2Index,
time: fileData.timeValues[bestV2Index],
voltage: fileData.voltageValues[bestV2Index],
description: `End of rapid voltage drop (${timeShiftedV2.toFixed(2)} µs from pulse start, ${bestV2Index - v1Index} points after V1)`
};
}
}
}
// v3 - VOLTAGE_MIN
const v3 = {
index: voltageMinMax.minIndex,
time: fileData.timeValues[voltageMinMax.minIndex],
voltage: voltageMinMax.minValue,
description: "VOLTAGE_MIN"
};
return { v1, v2, v3, v4: null, v5: null, error: null };
}
*/
/**
* Manual voltage and current analysis points - store manually selected points
*/
const manualVoltagePoints = {
v1: null,
v2: null,
v3: null,
v4: null,
v5: null,
v6: null,
v7: null,
v8: null
};
const manualCurrentPoints = {
i1: null,
i2: null,
i3: null,
i4: null,
i5: null,
i6: null,
i7: null,
i8: null
};
/**
* Set a manual voltage point and corresponding current point
* @param {string} pointName - Name of the point (v1, v2, v3, v4, v5, v6, v7, v8)
* @param {number} index - Index in the data array
* @param {number} time - Time value
* @param {number} voltage - Voltage value
*/
function setManualVoltagePoint(pointName, index, time, voltage) {
if (!['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8'].includes(pointName)) {
return;
}
console.log(`Setting manual voltage point ${pointName}:`, { index, time, voltage });
// Get current file data to capture corresponding current value
const currentFile = getCurrentFileData();
if (!currentFile) {
console.error('No current file data available');
return;
}
// Get the corresponding current value at the same index
const currentValue = currentFile.currentValues[index];
// Set the voltage point
manualVoltagePoints[pointName] = {
index: index,
time: time,
voltage: voltage,
description: `Manually selected ${pointName.toUpperCase()}`
};
// Set the corresponding current point
const currentPointName = pointName.replace('v', 'i'); // v1 -> i1, v2 -> i2, etc.
manualCurrentPoints[currentPointName] = {
index: index,
time: time,
current: currentValue,
description: `Corresponding current for ${pointName.toUpperCase()}`
};
console.log('Manual voltage points after setting:', manualVoltagePoints);