-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaeTimelines.js
536 lines (440 loc) · 24.4 KB
/
aeTimelines.js
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
var aeTimelines = function (webcharts, d3$1) {
'use strict';
/*------------------------------------------------------------------------------------------------\
Clone a variable (http://stackoverflow.com/a/728694).
\------------------------------------------------------------------------------------------------*/
function clone(obj) {
var copy;
//Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
//Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
//Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
//Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
const settings =
//Template-specific settings
{ id_col: 'USUBJID',
seq_col: 'AESEQ',
stdy_col: 'ASTDY',
endy_col: 'AENDY',
term_col: 'AETERM',
color: { value_col: 'AESEV',
label: 'Severity/Intensity',
values: ['MILD', 'MODERATE', 'SEVERE'],
colors: ['#66bd63' // green
, '#fdae61' // sherbet
, '#d73027' // red
, '#377eb8', '#984ea3', '#ff7f00', '#a65628', '#f781bf', '#999999'] },
highlight: { value_col: 'AESER',
label: 'Serious Event',
value: 'Y',
detail_col: null,
attributes: { 'stroke': 'black',
'stroke-width': '2',
'fill': 'none' } },
filters: null,
details: null,
custom_marks: null
//Standard chart settings
, x: { column: 'wc_value',
type: 'linear',
label: null },
y: { column: null // set in syncSettings()
, type: 'ordinal',
label: '',
sort: 'earliest',
behavior: 'flex' },
marks: [{ type: 'line',
per: null // set in syncSettings()
, tooltip: null // set in syncSettings()
, attributes: { 'stroke-width': 5,
'stroke-opacity': .5 } }, { type: 'circle',
per: null // set in syncSettings()
, tooltip: null // set in syncSettings()
, attributes: { 'fill-opacity': .5,
'stroke-opacity': .5 } }],
legend: { location: 'top' },
y_behavior: 'flex',
gridlines: 'y',
no_text_size: false,
range_band: 15,
margin: { top: 50 } // for second x-axis
, resizable: true
};
function syncSettings(preSettings) {
const nextSettings = clone(preSettings);
nextSettings.y.column = nextSettings.id_col;
//Lines (AE duration)
nextSettings.marks[0].per = [nextSettings.id_col, nextSettings.seq_col];
nextSettings.marks[0].tooltip = `Reported Term: [${ nextSettings.term_col }]` + `\nStart Day: [${ nextSettings.stdy_col }]` + `\nStop Day: [${ nextSettings.endy_col }]`;
//Circles (AE start day)
nextSettings.marks[1].per = [nextSettings.id_col, nextSettings.seq_col, 'wc_value'];
nextSettings.marks[1].tooltip = `Reported Term: [${ nextSettings.term_col }]` + `\nStart Day: [${ nextSettings.stdy_col }]` + `\nStop Day: [${ nextSettings.endy_col }]`;
nextSettings.marks[1].values = { wc_category: [nextSettings.stdy_col] };
//Define highlight marks.
if (nextSettings.highlight) {
//Lines (highlighted event duration)
let highlightLine = { 'type': 'line',
'per': [nextSettings.id_col, nextSettings.seq_col],
'tooltip': `Reported Term: [${ nextSettings.term_col }]` + `\nStart Day: [${ nextSettings.stdy_col }]` + `\nStop Day: [${ nextSettings.endy_col }]` + `\n${ nextSettings.highlight.label }: [${ nextSettings.highlight.detail_col ? nextSettings.highlight.detail_col : nextSettings.highlight.value_col }]`,
'values': {},
'attributes': nextSettings.highlight.attributes || {} };
highlightLine.values[nextSettings.highlight.value_col] = nextSettings.highlight.value;
highlightLine.attributes.class = 'highlight';
nextSettings.marks.push(highlightLine);
//Circles (highlighted event start day)
let highlightCircle = { 'type': 'circle',
'per': [nextSettings.id_col, nextSettings.seq_col, 'wc_value'],
'tooltip': `Reported Term: [${ nextSettings.term_col }]` + `\nStart Day: [${ nextSettings.stdy_col }]` + `\nStop Day: [${ nextSettings.endy_col }]` + `\n${ nextSettings.highlight.label }: [${ nextSettings.highlight.detail_col ? nextSettings.highlight.detail_col : nextSettings.highlight.value_col }]`,
'values': { 'wc_category': nextSettings.stdy_col },
'attributes': nextSettings.highlight.attributes || {} };
highlightCircle.values[nextSettings.highlight.value_col] = nextSettings.highlight.value;
highlightCircle.attributes.class = 'highlight';
nextSettings.marks.push(highlightCircle);
}
//Define mark coloring and legend.
nextSettings.color_by = nextSettings.color.value_col;
nextSettings.colors = nextSettings.color.colors;
nextSettings.legend = nextSettings.legend || { location: 'top' };
nextSettings.legend.label = nextSettings.color.label;
nextSettings.legend.order = nextSettings.color.values;
//Default filters
if (!nextSettings.filters || nextSettings.filters.length === 0) {
nextSettings.filters = [{ value_col: nextSettings.color.value_col, label: nextSettings.color.label }, { value_col: nextSettings.id_col, label: 'Subject Identifier' }];
if (nextSettings.highlight) nextSettings.filters.unshift({ value_col: nextSettings.highlight.value_col, label: nextSettings.highlight.label });
}
//Default detail listing columns
const defaultDetails = [{ 'value_col': nextSettings.seq_col, label: 'Sequence Number' }, { 'value_col': nextSettings.stdy_col, label: 'Start Day' }, { 'value_col': nextSettings.endy_col, label: 'Stop Day' }, { 'value_col': nextSettings.term_col, label: 'Reported Term' }];
//Add settings.color.value_col to default details.
defaultDetails.push({ 'value_col': nextSettings.color.value_col,
'label': nextSettings.color.label });
//Add settings.highlight.value_col and settings.highlight.detail_col to default details.
if (nextSettings.highlight) {
defaultDetails.push({ 'value_col': nextSettings.highlight.value_col,
'label': nextSettings.highlight.label });
if (nextSettings.highlight.detail_col) defaultDetails.push({ 'value_col': nextSettings.highlight.detail_col,
'label': nextSettings.highlight.label + ' Details' });
}
//Add settings.filters columns to default details.
nextSettings.filters.forEach(filter => {
if (filter !== nextSettings.id_col && filter.value_col !== nextSettings.id_col) defaultDetails.push({ 'value_col': filter.value_col,
'label': filter.label });
});
//Redefine settings.details with defaults.
if (!nextSettings.details) nextSettings.details = defaultDetails;else {
//Allow user to specify an array of columns or an array of objects with a column property
//and optionally a column label.
nextSettings.details = nextSettings.details.map(d => {
return {
value_col: d.value_col ? d.value_col : d,
label: d.label ? d.label : d.value_col ? d.value_col : d };
});
//Add default details to settings.details.
defaultDetails.reverse().forEach(defaultDetail => nextSettings.details.unshift(defaultDetail));
}
//Add custom marks to marks array.
if (nextSettings.custom_marks) nextSettings.custom_marks.forEach(custom_mark => {
custom_mark.attributes = custom_mark.attributes || {};
custom_mark.attributes.class = 'custom';
nextSettings.marks.push(custom_mark);
});
return nextSettings;
}
const controlInputs = [{ type: 'dropdown', option: 'y.sort', label: 'Sort Plants', values: ['earliest', 'alphabetical-descending'], require: true }];
function syncControlInputs(preControlInputs, preSettings) {
preSettings.filters.reverse().forEach((d, i) => {
const thisFilter = { type: 'subsetter',
value_col: d.value_col ? d.value_col : d,
label: d.label ? d.label : d.value_col ? d.value_col : d };
preControlInputs.unshift(thisFilter);
});
return preControlInputs;
}
function syncSecondSettings(preSettings) {
const nextSettings = clone(preSettings);
nextSettings.y.column = nextSettings.seq_col;
nextSettings.y.sort = 'alphabetical-descending';
nextSettings.marks[0].per = [nextSettings.seq_col];
nextSettings.marks[1].per = [nextSettings.seq_col, 'wc_value'];
if (nextSettings.highlight) {
nextSettings.marks[2].per = [nextSettings.seq_col];
nextSettings.marks[3].per = [nextSettings.seq_col, 'wc_value'];
}
nextSettings.range_band = settings.range_band * 2;
nextSettings.margin = null;
nextSettings.transitions = false;
return nextSettings;
}
/*------------------------------------------------------------------------------------------------\
Expand a data array to one item per original item per specified column.
\------------------------------------------------------------------------------------------------*/
function lengthenRaw(data, columns) {
let my_data = [];
data.forEach(d => {
columns.forEach(column => {
let obj = Object.assign({}, d);
obj.wc_category = column;
obj.wc_value = d[column];
my_data.push(obj);
});
});
return my_data;
}
function onInit() {
//Count total number of IDs for population count.
this.populationCount = d3.set(this.raw_data.map(d => d[this.config.id_col])).values().length;
//Remove non-AE records.
this.superRaw = this.raw_data.filter(d => /[^\s]/.test(d[this.config.term_col]));
//Set empty settings.color_by values to 'N/A'.
this.superRaw.forEach(d => d[this.config.color_by] = /[^\s]/.test(d[this.config.color_by]) ? d[this.config.color_by] : 'N/A');
//Append unspecified settings.color_by values to settings.legend.order and define a shade of
//gray for each.
const color_by_values = d3.set(this.superRaw.map(d => d[this.config.color_by])).values();
color_by_values.forEach((color_by_value, i) => {
if (this.config.legend.order.indexOf(color_by_value) === -1) {
this.config.legend.order.push(color_by_value);
this.chart2.config.legend.order.push(color_by_value);
}
});
//Derived data manipulation
this.raw_data = lengthenRaw(this.superRaw, [this.config.stdy_col, this.config.endy_col]);
this.raw_data.forEach(d => {
d.wc_value = d.wc_value ? +d.wc_value : NaN;
});
//Create div for back button and participant ID title.
this.chart2.wrap.insert('div', ':first-child').attr('id', 'backButton').insert('button', '.legend').html('← Back').style('cursor', 'pointer').on('click', () => {
this.wrap.style('display', 'block');
this.table.draw([]);
this.chart2.wrap.style('display', 'none');
this.chart2.wrap.select('.id-title').remove();
this.controls.wrap.style('display', 'block');
});
}
function onLayout() {
//Add div for participant counts.
this.wrap.select('.legend').append('span').classed('annote', true).style('float', 'right');
//Add top x-axis.
var x2 = this.svg.append('g').attr('class', 'x2 axis linear');
x2.append('text').attr({ 'class': 'axis-title top',
'dy': '2em',
'text-anchor': 'middle' }).text(this.config.x_label);
}
function onDataTransform() {}
/*------------------------------------------------------------------------------------------------\
Annotate number of participants based on current filters, number of participants in all, and
the corresponding percentage.
Inputs:
chart - a webcharts chart object
id_col - a column name in the raw data set (chart.raw_data) representing the observation of interest
id_unit - a text string to label the units in the annotation (default = 'participants')
selector - css selector for the annotation
\------------------------------------------------------------------------------------------------*/
function updateSubjectCount(chart, id_col, selector, id_unit) {
//count the number of unique ids in the current chart and calculate the percentage
const filtered_data = chart.raw_data.filter(d => {
let filtered = d[chart.config.seq_col] === '';
chart.filters.forEach(di => {
if (filtered === false && di.val !== 'All') filtered = Object.prototype.toString.call(di.val) === '[object Array]' ? di.val.indexOf(d[di.col]) === -1 : di.val !== d[di.col];
});
return !filtered;
});
const currentObs = d3.set(filtered_data.map(d => d[id_col])).values().length;
const percentage = d3.format('0.1%')(currentObs / chart.populationCount);
//clear the annotation
let annotation = d3.select(selector);
annotation.selectAll('*').remove();
//update the annotation
const units = id_unit ? ' ' + id_unit : ' plant(s)';
annotation.text(currentObs + ' of ' + chart.populationCount + units + ' shown (' + percentage + ')');
}
function onDraw() {
//Annotate number of selected participants out of total participants.
updateSubjectCount(this, this.config.id_col, '.annote', 'Plant Type(s)');
//Sort y-axis based on `Sort IDs` control selection.
const yAxisSort = this.controls.wrap.selectAll('.control-group').filter(d => d.option && d.option === 'y.sort').select('option:checked').text();
if (yAxisSort === 'earliest') {
//Redefine filtered data as it defaults to the final mark drawn, which might be filtered in
//addition to the current filter selections.
const filtered_data = this.raw_data.filter(d => {
let filtered = d[this.config.seq_col] === '';
this.filters.forEach(di => {
if (filtered === false && di.val !== 'All') filtered = Object.prototype.toString.call(di.val) === '[object Array]' ? di.val.indexOf(d[di.col]) === -1 : di.val !== d[di.col];
});
return !filtered;
});
//Capture all subject IDs with adverse events with a start day.
const withStartDay = d3.nest().key(d => d[this.config.id_col]).rollup(d => d3.min(d, di => +di[this.config.stdy_col])).entries(filtered_data.filter(d => !isNaN(parseFloat(d[this.config.stdy_col])) && isFinite(d[this.config.stdy_col]))).sort((a, b) => a.values > b.values ? -2 : a.values < b.values ? 2 : a.key > b.key ? -1 : 1).map(d => d.key);
//Capture all subject IDs with adverse events without a start day.
const withoutStartDay = d3.set(filtered_data.filter(d => +d[this.config.seq_col] > 0 && (isNaN(parseFloat(d[this.config.stdy_col])) || !isFinite(d[this.config.stdy_col])) && withStartDay.indexOf(d[this.config.id_col]) === -1).map(d => d[this.config.id_col])).values();
this.y_dom = withStartDay.concat(withoutStartDay);
} else this.y_dom = this.y_dom.sort(d3.descending);
}
/*------------------------------------------------------------------------------------------------\
Sync colors of legend marks and chart marks.
\------------------------------------------------------------------------------------------------*/
function syncColors(chart) {
//Recolor legend.
let legendItems = chart.wrap.selectAll('.legend-item:not(.highlight)');
legendItems.each(function (d, i) {
d3.select(this).select('.legend-mark').style('stroke', chart.config.colors[chart.config.legend.order.indexOf(d.label)]).style('stroke-width', '25%');
});
//Recolor circles.
let circles = chart.svg.selectAll('circle.wc-data-mark:not(.highlight), circle.wc-data-mark:not(.custom)');
circles.each(function (d, i) {
const color_by_value = d.values.raw[0][chart.config.color_by];
d3.select(this).style('stroke', chart.config.colors[chart.config.legend.order.indexOf(color_by_value)]);
d3.select(this).style('fill', chart.config.colors[chart.config.legend.order.indexOf(color_by_value)]);
});
//Recolor lines.
let lines = chart.svg.selectAll('path.wc-data-mark:not(.highlight), path.wc-data-mark:not(.custom)');
lines.each(function (d, i) {
const color_by_value = d.values[0].values.raw[0][chart.config.color_by];
d3.select(this).style('stroke', chart.config.colors[chart.config.legend.order.indexOf(color_by_value)]);
});
}
/*------------------------------------------------------------------------------------------------\
Add highlighted adverse event legend item.
\------------------------------------------------------------------------------------------------*/
function addHighlightLegendItem(chart) {
chart.wrap.select('.legend li.highlight').remove();
let highlightLegendItem = chart.wrap.select('.legend').append('li').attr('class', 'highlight').style({ 'list-style-type': 'none',
'margin-right': '1em',
'display': 'inline-block' });
let highlightLegendColorBlock = highlightLegendItem.append('svg').attr({ width: '1.75em',
height: '1.5em' }).style({ 'position': 'relative',
'top': '0.35em' });
highlightLegendColorBlock.append('circle').attr({ cx: 10,
cy: 10,
r: 4 }).style(chart.config.highlight.attributes);
highlightLegendColorBlock.append('line').attr({ x1: 2 * 3.14 * 4 - 10,
y1: 10,
x2: 2 * 3.14 * 4 - 5,
y2: 10 }).style(chart.config.highlight.attributes).style('shape-rendering', 'crispEdges');
highlightLegendItem.append('text').style('margin-left', '.35em').text(chart.config.highlight.label);
}
function onResize() {
let context = this;
//Sync legend and mark colors.
syncColors(this);
//Add highlight adverse event legend item.
if (this.config.highlight) addHighlightLegendItem(this);
//Draw second x-axis at top of chart.
let x2Axis = d3$1.svg.axis().scale(this.x).orient('top').tickFormat(this.xAxis.tickFormat()).innerTickSize(this.xAxis.innerTickSize()).outerTickSize(this.xAxis.outerTickSize()).ticks(this.xAxis.ticks()[0]);
let g_x2_axis = this.svg.select('g.x2.axis').attr('class', 'x2 axis linear');
g_x2_axis.call(x2Axis);
g_x2_axis.select('text.axis-title.top').attr('transform', 'translate(' + this.raw_width / 2 + ',-' + this.config.margin.top + ')');
g_x2_axis.select('.domain').attr({ 'fill': 'none',
'stroke': '#ccc',
'shape-rendering': 'crispEdges' });
g_x2_axis.selectAll('.tick line').attr('stroke', '#eee');
//Draw second chart when y-axis tick label is clicked.
this.svg.select('.y.axis').selectAll('.tick').style('cursor', 'pointer').on('click', d => {
let csv2 = this.raw_data.filter(di => di[this.config.id_col] === d);
this.chart2.wrap.style('display', 'block');
this.chart2.draw(csv2);
this.chart2.wrap.select('#backButton').append('strong').attr('class', 'id-title').style('margin-left', '1%').text('Plant: ' + d);
//Sort listing by sequence.
const seq_col = context.config.seq_col;
let tableData = this.superRaw.filter(di => di[this.config.id_col] === d).sort((a, b) => +a[seq_col] < b[seq_col] ? -1 : 1);
//Define listing columns.
this.table.config.cols = d3.set(this.config.details.map(detail => detail.value_col)).values();
this.table.config.headers = d3.set(this.config.details.map(detail => detail.label)).values();
this.table.draw(tableData);
this.table.wrap.selectAll('th,td').style({ 'text-align': 'left',
'padding-right': '10px' });
//Hide timelines.
this.wrap.style('display', 'none');
this.controls.wrap.style('display', 'none');
});
/**-------------------------------------------------------------------------------------------\
Second chart callbacks.
\-------------------------------------------------------------------------------------------**/
this.chart2.on('datatransform', function () {
//Define color scale.
this.config.color_dom = context.colorScale.domain();
});
this.chart2.on('draw', function () {
//Sync x-axis domain of second chart with that of the original chart.
this.x_dom = context.x_dom;
});
this.chart2.on('resize', function () {
//Sync legend and mark colors.
syncColors(this);
//Add highlight adverse event legend item.
if (this.config.highlight) addHighlightLegendItem(this);
});
}
/*------------------------------------------------------------------------------------------------\
Add assign method to Object if nonexistent.
\------------------------------------------------------------------------------------------------*/
if (typeof Object.assign != 'function') {
(function () {
Object.assign = function (target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert undefined or null to object');
}
var output = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source !== undefined && source !== null) {
for (var nextKey in source) {
if (source.hasOwnProperty(nextKey)) {
output[nextKey] = source[nextKey];
}
}
}
}
return output;
};
})();
}
function aeTimeline(element, settings$$) {
//Merge default settings with custom settings.
const mergedSettings = Object.assign({}, settings, settings$$);
//Sync properties within settings object.
const syncedSettings = syncSettings(mergedSettings);
//Sync control inputs with settings object.
const syncedControlInputs = syncControlInputs(controlInputs, syncedSettings);
//Sync properties within secondary settings object.
const syncedSecondSettings = syncSecondSettings(syncedSettings);
//Create controls.
const controls = webcharts.createControls(element, { location: 'top', inputs: syncedControlInputs });
//Create chart.
const chart = webcharts.createChart(element, syncedSettings, controls);
chart.on('init', onInit);
chart.on('layout', onLayout);
chart.on('datatransform', onDataTransform);
chart.on('draw', onDraw);
chart.on('resize', onResize);
//Create participant-level chart.
const chart2 = webcharts.createChart(element, syncedSecondSettings).init([]);
chart2.wrap.style('display', 'none');
chart.chart2 = chart2;
//Create participant-level listing.
const table = webcharts.createTable(element, {}).init([]);
chart.table = table;
return chart;
}
return aeTimeline;
}(webCharts, d3);