-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathutils.js
More file actions
471 lines (415 loc) · 16.4 KB
/
utils.js
File metadata and controls
471 lines (415 loc) · 16.4 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
/*
* Copyright (c) 2012-2017 LabKey Corporation
*
* Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
*/
// Contains helpers that aren't specific to plot, layer, geom, etc. and are used throughout the API.
if(!LABKEY.vis){
/**
* @namespace The namespace for the internal LabKey visualization library. Contains classes within
* {@link LABKEY.vis.Plot}, {@link LABKEY.vis.Layer}, and {@link LABKEY.vis.Geom}.
*/
LABKEY.vis = {};
}
if (!LABKEY.vis.PlotProperties) {
LABKEY.vis.PlotProperties = {};
if (!LABKEY.vis.PlotProperties.BoundType) {
LABKEY.vis.PlotProperties.BoundType = {
Absolute: 'absolute',
MeanDeviation: 'meanDev',
StandardDeviation: 'stddev'
}
}
if (!LABKEY.vis.PlotProperties.Color) {
LABKEY.vis.PlotProperties.Color = {
Outlier: 'red',
Mean: 'darkgrey',
OneSD: 'green',
TwoSD: 'blue',
}
}
if (!LABKEY.vis.PlotProperties.BoundLabel) {
LABKEY.vis.PlotProperties.BoundLabel = {
Upper: 'upperBound',
Lower: 'lowerBound'
}
}
if (!LABKEY.vis.PlotProperties.ValueConversion) {
LABKEY.vis.PlotProperties.ValueConversion = {
StandardDeviation: 'standardDeviation',
PercentDeviation: 'percentDeviation',
DeltaFromMean: 'deltaFromMean'
}
}
}
LABKEY.vis.makeLine = function(x1, y1, x2, y2){
//Generates a path between two coordinates.
return "M " + x1 + " " + y1 + " L " + x2 + " " + y2;
};
LABKEY.vis.makePath = function(data, xAccessor, yAccessor){
var pathString = '';
for(var i = 0; i < data.length; i++){
var x = xAccessor(data[i]);
var y = yAccessor(data[i]);
if(!LABKEY.vis.isValid(x) || !LABKEY.vis.isValid(y)){
continue;
}
if(pathString == ''){
pathString = pathString + 'M' + x + ' ' + y;
} else {
pathString = pathString + ' L' + x + ' ' + y;
}
}
return pathString;
};
LABKEY.vis.createGetter = function(aes){
if(typeof aes.value === 'function'){
aes.getValue = aes.value;
} else {
aes.getValue = function(row){
if(row instanceof Array) {
/*
* For Path geoms we pass in the entire array of values for the path to the aesthetic. So if the user
* provides only a string for an Aes value we'll assume they want the first object in the path array to
* determing the value.
*/
if(row.length > 0) {
row = row[0];
} else {
return null;
}
}
return row[aes.value];
};
}
};
LABKEY.vis.convertAes = function(aes){
var newAes= {};
for(var aesthetic in aes){
var newAesName = (aesthetic == 'y') ? 'yLeft' : aesthetic;
newAes[newAesName] = {};
newAes[newAesName].value = aes[aesthetic];
}
return newAes;
};
LABKEY.vis.mergeAes = function(oldAes, newAes) {
newAes = LABKEY.vis.convertAes(newAes);
for(var attr in newAes) {
if(newAes.hasOwnProperty(attr)) {
if (newAes[attr].value != null) {
LABKEY.vis.createGetter(newAes[attr]);
oldAes[attr] = newAes[attr];
} else {
delete oldAes[attr];
}
}
}
};
/**
* Groups data by the groupAccessor, and subgroupAccessor if provided, passed in.
* Ex: A set of rows with participantIds in them, would return an object that has one attribute
* per participant id. Each attribute will be an array of all of the rows the participant is in.
* @param data Array of data (likely result of selectRows API call)
* @param groupAccessor Function defining how to access group data from array rows
* @param subgroupAccessor Function defining how to access subgroup data from array rows
* @returns {Object} Map of groups, and subgroups, to arrays of data for each
*/
LABKEY.vis.groupData = function(data, groupAccessor, subgroupAccessor)
{
var groupedData = {},
hasSubgroupAcc = subgroupAccessor != undefined && subgroupAccessor != null;
for (var i = 0; i < data.length; i++)
{
var value = groupAccessor(data[i]);
if (!groupedData[value])
groupedData[value] = hasSubgroupAcc ? {} : [];
if (hasSubgroupAcc)
{
var subvalue = subgroupAccessor(data[i]);
if (!groupedData[value][subvalue])
groupedData[value][subvalue] = [];
groupedData[value][subvalue].push(data[i]);
}
else
{
groupedData[value].push(data[i]);
}
}
return groupedData;
};
/**
* Groups data by the groupAccessor, and subgroupAccessor if provided, passed in and returns the number
* of occurrences for that group/subgroup. Most commonly used for processing data for a bar plot.
* @param data
* @param groupAccessor
* @param subgroupAccessor
* @param propNameMap
* @returns {Array}
*/
LABKEY.vis.groupCountData = function(data, groupAccessor, subgroupAccessor, propNameMap)
{
var counts = [], total = 0,
nameProp = propNameMap && propNameMap.name ? propNameMap.name : 'name',
subnameProp = propNameMap && propNameMap.subname ? propNameMap.subname : 'subname',
countProp = propNameMap && propNameMap.count ? propNameMap.count : 'count',
totalProp = propNameMap && propNameMap.total ? propNameMap.total : 'total',
hasSubgroupAcc = subgroupAccessor != undefined && subgroupAccessor != null,
groupedData = LABKEY.vis.groupData(data, groupAccessor, subgroupAccessor);
for (var groupName in groupedData)
{
if (groupedData.hasOwnProperty(groupName))
{
if (hasSubgroupAcc)
{
for (var subgroupName in groupedData[groupName])
{
if (groupedData[groupName].hasOwnProperty(subgroupName))
{
var row = {rawData: groupedData[groupName][subgroupName]},
count = row.rawData.length;
total += count;
row[nameProp] = groupName;
row[subnameProp] = subgroupName;
row[countProp] = count;
row[totalProp] = total;
counts.push(row);
}
}
}
else
{
var row = {rawData: groupedData[groupName]},
count = row.rawData.length;
total += count;
row[nameProp] = groupName;
row[countProp] = count;
row[totalProp] = total;
counts.push(row);
}
}
}
return counts;
};
/**
* Generate an array of aggregate values for the given groups/subgroups in the data array.
* @param {Array} data The response data from selectRows.
* @param {String} dimensionName The grouping variable to get distinct members from.
* @param {String} subDimensionName The subgrouping variable to get distinct members from
* @param {String} measureName The variable to calculate aggregate values over. Nullable.
* @param {String} aggregate MIN/MAX/SUM/COUNT/etc. Defaults to COUNT.
* @param {String} nullDisplayValue The display value to use for null dimension values. Defaults to 'null'.
* @param {Boolean} includeTotal Whether or not to include the cumulative totals. Defaults to false.
* @param {String} errorBarType SD/STDERR. Defaults to null/undefined.
* @param {Boolean} keepNames True to use the dimension names in the results data. Defaults to false.
* @param {String} rowPropName (Optional) The property name to use when accessing the dimension value from the row object.
* @returns {Array} An array of results for each group/subgroup/aggregate
*/
LABKEY.vis.getAggregateData = function(data, dimensionName, subDimensionName, measureName, aggregate, nullDisplayValue, includeTotal, errorBarType, keepNames = false, rowPropName)
{
var results = [], subgroupAccessor,
groupAccessor = typeof dimensionName === 'function' ? dimensionName : function(row){ return LABKEY.vis.getValue(row[dimensionName], rowPropName);},
hasSubgroup = subDimensionName != undefined && subDimensionName != null,
hasMeasure = measureName != undefined && measureName != null,
measureAccessor = hasMeasure ? function(row){ return LABKEY.vis.getValue(row[measureName], 'value'); } : null;
if (hasSubgroup) {
if (typeof subDimensionName === 'function') {
subgroupAccessor = subDimensionName;
} else {
subgroupAccessor = function (row) { return LABKEY.vis.getValue(row[subDimensionName]); }
}
}
var groupData = LABKEY.vis.groupCountData(data, groupAccessor, subgroupAccessor);
for (var i = 0; i < groupData.length; i++)
{
var row = {label: groupData[i].name};
if (row.label == null || row.label == 'null')
row.label = nullDisplayValue || 'null';
if (hasSubgroup)
{
row.subLabel = groupData[i].subname;
if (row.subLabel == null || row.subLabel == 'null')
row.subLabel = nullDisplayValue || 'null';
}
if (includeTotal) {
row.total = groupData[i].total;
}
var values = measureAccessor !== undefined && measureAccessor !== null
? LABKEY.vis.Stat.sortNumericAscending(groupData[i].rawData, measureAccessor)
: null;
if (aggregate === undefined || aggregate === null || aggregate === 'COUNT')
{
row.value = values != null ? values.length : groupData[i].count;
}
else if (typeof LABKEY.vis.Stat[aggregate] == 'function')
{
try {
if (values?.length > 0) {
row.value = LABKEY.vis.Stat[aggregate](values);
} else {
row.value = null;
}
row.aggType = aggregate;
} catch (e) {
row.value = null;
}
if (errorBarType === 'SD' || errorBarType === 'SEM') {
row.error = LABKEY.vis.Stat[errorBarType](values, true);
row.errorType = errorBarType;
}
}
else
{
throw 'Aggregate ' + aggregate + ' is not yet supported.';
}
if (keepNames) {
// if the value was/is a number, convert it back so that the axis domain min/max calculate correctly
var dimValue = row.label;
row[dimensionName] = { value: !isNaN(Number(dimValue)) ? Number(dimValue) : dimValue };
row[measureName] = { value: row.value };
row[measureName].aggType = aggregate;
if (row.hasOwnProperty('subLabel')) {
row[subDimensionName] = { value: row.subLabel };
}
if (row.hasOwnProperty('error')) {
row[measureName].error = row.error;
}
if (row.hasOwnProperty('errorType')) {
row[measureName].errorType = row.errorType;
}
}
results.push(row);
}
return results;
};
LABKEY.vis.getColumnAlias = function(aliasArray, measureInfo) {
/*
Lookup the column alias (from the getData response) by the specified measure information
aliasArray: columnAlias array from the getData API response
measureInfo: 1. a string with the name of the column to lookup
2. an object with a measure alias OR measureName
3. an object with both measureName AND pivotValue
*/
if (!aliasArray)
aliasArray = [];
if (typeof measureInfo != "object")
measureInfo = {measureName: measureInfo};
for (var i = 0; i < aliasArray.length; i++)
{
var arrVal = aliasArray[i];
if (measureInfo.measureName && measureInfo.pivotValue)
{
if (arrVal.measureName == measureInfo.measureName && arrVal.pivotValue == measureInfo.pivotValue)
return arrVal.columnName;
}
else if (measureInfo.alias)
{
if (arrVal.alias == measureInfo.alias)
return arrVal.columnName;
}
else if (measureInfo.measureName && arrVal.measureName == measureInfo.measureName)
return arrVal.columnName;
}
return null;
};
LABKEY.vis.isValid = function(value) {
return !(value == undefined || value == null || (typeof value == "number" && !isFinite(value)));
};
LABKEY.vis.arrayObjectIndexOf = function(myArray, searchTerm, property) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
};
LABKEY.vis.discreteSortFn = function(a,b) {
// Issue 23015: sort categorical x-axis alphabetically with special case for "Not in X" and "[Blank]"
var aIsEmptyCategory = a && typeof a === 'string' && (a.indexOf("Not in ") == 0 || a == '[Blank]'),
bIsEmptyCategory = b && typeof b === 'string' && (b.indexOf("Not in ") == 0 || b == '[Blank]');
if (aIsEmptyCategory)
return 1;
else if (bIsEmptyCategory)
return -1;
else if (a != b)
return LABKEY.vis.naturalSortFn(a,b);
return 0;
};
LABKEY.vis.naturalSortFn = function(aso, bso) {
// http://stackoverflow.com/questions/19247495/alphanumeric-sorting-an-array-in-javascript
var a, b, a1, b1, i= 0, n, L,
rx=/(\.\d+)|(\d+(\.\d+)?)|([^\d.]+)|(\.\D+)|(\.$)/g;
if (aso === bso) return 0;
if (typeof aso !== 'string' || typeof bso !== 'string') return 0;
a = aso.toLowerCase().match(rx);
b = bso.toLowerCase().match(rx);
L = a.length;
while (i < L) {
if (!b[i]) return 1;
a1 = a[i]; b1 = b[i++];
if (a1 !== b1) {
n = a1 - b1;
if (!isNaN(n)) return n;
return a1 > b1 ? 1 : -1;
}
}
return b[i] ? -1 : 0;
};
LABKEY.vis.getValue = function(obj, preferredProp) {
if (obj && typeof obj == 'object') {
if (preferredProp && obj.hasOwnProperty(preferredProp)) {
return obj[preferredProp];
} else if (obj.hasOwnProperty('formattedValue')) {
return obj.formattedValue;
} else if (obj.hasOwnProperty('displayValue')) {
return obj.displayValue;
}
return obj.value;
}
return obj;
};
LABKEY.vis.isValidDate = function(date) {
return date instanceof Date && !isNaN(date);
}
LABKEY.vis.formatDate = function(date, format) {
if (!LABKEY.vis.isValidDate(date)) return date;
// Helper function to pad numbers with a leading zero
const pad = (num) => num.toString().padStart(2, '0');
// Month name arrays
const monthAbbrs = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
const monthFullNames = [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
// Get date and time components
const day = date.getDate();
const monthIndex = date.getMonth(); // 0-11
const year = date.getFullYear();
const hours = date.getHours(); // 0-23
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const milliseconds = date.getMilliseconds();
// --- 12-hour clock and AM/PM ---
const ampm = hours >= 12 ? 'PM' : 'AM';
// 0 (midnight) or 12 (noon) should be 12
const hours12 = hours % 12 || 12;
// --- Token Replacement ---
let formatted = format;
// Year
formatted = formatted.replace(/yyyy/g, year.toString());
formatted = formatted.replace(/yy/g, year.toString().slice(-2));
// Month
formatted = formatted.replace(/MMMM/g, monthFullNames[monthIndex]);
formatted = formatted.replace(/MMM/g, monthAbbrs[monthIndex]);
formatted = formatted.replace(/MM/g, pad(monthIndex + 1)); // 1-12
// Day
formatted = formatted.replace(/dd/g, pad(day));
// Time
formatted = formatted.replace(/HH/g, pad(hours)); // 24-hour
formatted = formatted.replace(/hh/g, pad(hours12)); // 12-hour
formatted = formatted.replace(/mm/g, pad(minutes));
formatted = formatted.replace(/ss/g, pad(seconds));
formatted = formatted.replace(/SSS/g, milliseconds.toString().padStart(3, '0'));
formatted = formatted.replace(/ a/g, ' ' + ampm);
return formatted;
}