-
Notifications
You must be signed in to change notification settings - Fork 175
/
sessions.class.inc
653 lines (586 loc) · 21.5 KB
/
sessions.class.inc
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
<?php declare(strict_types=1);
/**
* This class features the code for the menu portion of the LORIS
* electrophysiology browser module.
*
* PHP version 7
*
* @category Behavioural
* @package Main
* @subpackage Electrophysiology
* @author Loris team <[email protected]>
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
* @link https://github.com/aces/Loris
*/
namespace LORIS\electrophysiology_browser;
use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Message\ResponseInterface;
use LORIS\electrophysiology_browser\Models\ElectrophysioFile;
/**
* Provides the PHP code for the menu filter for the electrophysiology browser
*
* @category Behavioural
* @package Main
* @subpackage Sessions
* @author Loris team <[email protected]>
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPLv3
* @link https://github.com/aces/Loris
*/
class Sessions extends \NDB_Page
{
public $skipTemplate = true; // stops from looking for a smarty template
protected $timepoint;
protected $sessionID;
protected $candidate;
/**
* Determine whether the user has permission to view this page
*
* @param \User $user The user whose access is being checked
*
* @return bool whether the user has access
*/
function _hasAccess(\User $user) : bool
{
return (($user->hasPermission('electrophysiology_browser_view_allsites')
|| ($user->hasCenter($this->timepoint->getCenterID())
&& $user->hasPermission('electrophysiology_browser_view_site'))
) && $user->hasProject($this->timepoint->getProject()->getId()));
}
/**
* Load the required variables in order to check that the user
* has access to the session.
*
* @param \User $user The user to load the resources for
* @param ServerRequestInterface $request The PSR15 Request being handled
*
* @throws \NotFound If the session id is non-numerical
* @throws \LorisException If the session is not found
*
* @return void
*/
public function loadResources(
\User $user, ServerRequestInterface $request
) : void {
$path = $request->getUri()->getPath();
$matches = [];
if (preg_match('#/sessions/(\d+)#', $path, $matches) !== 1) {
throw new \NotFound("Invalid session");
}
$session_id = intval($matches[1]);
try {
$this->timepoint = \NDB_Factory::singleton()->timepoint(
new \SessionID(strval($session_id))
);
$this->sessionID = $session_id;
} catch(\LorisException $e) {
throw new \NotFound("Session not found");
}
parent::loadResources($user, $request);
}
/**
* Handles a login request
*
* @param ServerRequestInterface $request The incoming PSR7 request
*
* @return ResponseInterface The outgoing PSR7 response
*/
public function handle(ServerRequestInterface $request) : ResponseInterface
{
$parameters = $request->getQueryParams();
$user = $request->getAttribute('user');
if (!$this->_hasAccess($user)) {
return (new \LORIS\Middleware\PageDecorationMiddleware($user))
->process(
$request,
new \LORIS\Http\StringStream("Permission denied")
)->withStatus(403);
}
$accepted_hdrs = explode(
',',
$request->getHeaderLine('Accept')
);
if (in_array('text/html', $accepted_hdrs, true)) {
return parent::handle($request);
}
if ($request->getMethod() != 'GET') {
return (new \LORIS\Http\Response\JSON\MethodNotAllowed(
['GET']
));
}
if (!isset($parameters['outputType'])) {
return (new \LORIS\Http\Response\JSON\BadRequest(
'OutputType required'
));
}
$outputType = $parameters['outputType'];
if (!in_array($outputType, ['raw', 'derivative', 'all_types'])) {
return (new \LORIS\Http\Response\JSON\BadRequest(
'Invalid output type'
));
}
return $this->getSessionData($outputType);
}
/**
* Get the session data information.
*
* @param string $outputType output type to be displayed
*
* @return ResponseInterface The JSON response
*/
function getSessionData($outputType)
{
$db = \NDB_Factory::singleton()->database();
$query = 'SELECT
DISTINCT(pf.SessionID)
FROM physiological_file pf
LEFT JOIN session s ON (s.ID=pf.SessionID)
LEFT JOIN candidate c USING (CandID)
LEFT JOIN psc ON (s.CenterID=psc.CenterID)
LEFT JOIN physiological_output_type pot
USING (PhysiologicalOutputTypeID)
WHERE
s.Active = "Y"
AND pf.FileType IN ('.
'"bdf", "cnt", "edf", "set", "vhdr", "vsm", "archive"'.
') ORDER BY pf.SessionID';
$response = [];
$sessions = $db->pselect($query, []);
$sessions = array_column($sessions, 'SessionID');
$response['patient'] = $this->getSubjectData($outputType);
$response['database'] = array_values(
$this->getFilesData($outputType)
);
$response['sessions'] = $sessions;
$currentIndex = array_search($this->sessionID, $sessions);
$response['nextSession'] = $sessions[$currentIndex+1] ?? '';
$response['prevSession'] = $sessions[$currentIndex-1] ?? '';
return new \LORIS\Http\Response\JSON\OK($response);
}
/**
* Get the subject data information.
*
* @param string $outputType output type to be displayed
*
* @return array with the subject information
*/
function getSubjectData($outputType)
{
$subjectData = [];
$candidate = \NDB_Factory::singleton()->candidate(
$this->timepoint->getCandID()
);
$subjectData['pscid'] = $candidate->getPSCID();
$subjectData['dccid'] = $candidate->getCandID();
$subjectData['visit_label'] = $this->timepoint->getVisitLabel();
$subjectData['sessionID'] = $this->timepoint->getSessionID();
$subjectData['site'] = $this->timepoint->getPSC();
$subjectData['dob'] = $candidate->getCandidateDoB();
$subjectData['sex'] = $candidate->getCandidateSex();
$subjectData['subproject'] = $this->timepoint->getData('SubprojectTitle');
$subjectData['output_type'] = $outputType;
return $subjectData;
}
/**
* Get the list of electrophysiology recordings with their recording information.
*
* @param string $outputType output type to be displayed
*
* @return array with the file collection
*/
function getFilesData(string $outputType)
{
$db = \NDB_Factory::singleton()->database();
$fileCollection = [];
$params = [];
$params['SID'] = $this->sessionID;
$query = 'SELECT
pf.PhysiologicalFileID
FROM
physiological_file pf ';
if ($outputType != 'all_types') {
$query .= 'LEFT JOIN physiological_output_type pot ON ';
$query .= 'pf.PhysiologicalOutputTypeID='
.'pot.PhysiologicalOutputTypeID ';
$query .= 'WHERE SessionID=:SID ';
$query .= 'AND pot.OutputTypeName = :OTN AND pf.ParentID IS NULL ';
$params['OTN'] = $outputType;
} else {
$query .= "WHERE SessionID=:SID AND pf.ParentID IS NULL";
}
$physiologicalFiles = $db->pselect($query, $params);
foreach ($physiologicalFiles as $file) {
$fileCollection[]['file'] = $this->getSummary($file);
}
return $fileCollection;
}
/**
* Get the electrophysiology recording summary metadata.
*
* @param array $file electrophysiology file data
*
* @return array with the file metadata
*/
function getSummary(array $file) : array
{
$fileSummary = [];
$physioFileID = intval($file['PhysiologicalFileID']);
$physioFileObj = new ElectrophysioFile($physioFileID);
$physioFile = $physioFileObj->getParameter('FilePath');
$modality = $physioFileObj->getParameter('Modality');
$modalityPrefix = $modality === 'ieeg' ? 'iEEG' : 'EEG';
$modalityCapName = $modality === 'ieeg' ? 'Electrode' : 'Cap';
$fileSummary['id'] = $physioFileID;
$fileSummary['name'] = basename($physioFile);
// Summary
$channels = ['EEG', 'EOG', 'ECG', 'EMG'];
if ($modality === 'ieeg') {
$channels = array_merge(['ECOG', 'SEEG'], $channels);
}
$fileSummary['summary'] = [
[
'name' => 'Sampling Frequency',
'value' => $physioFileObj->getParameter('SamplingFrequency'),
],
];
$fileSummary['summary'] = array_merge(
$fileSummary['summary'],
array_map(
fn($channel) =>
[
'name' => $channel.' Channel Count',
'value' => $physioFileObj->getParameter(
$channel.'ChannelCount'
),
],
$channels
)
);
$fileSummary['summary'] = array_merge(
$fileSummary['summary'],
[
[
'name' => 'Reference',
'value' => $physioFileObj->getParameter(
$modalityPrefix.'Reference'
),
],
[
'name' => 'Powerline Frequency',
'value' => $physioFileObj->getParameter('PowerLineFrequency'),
],
]
);
// Details
$fileSummary['details'] = [
[
'name' => 'Task Name',
'value' => $physioFileObj->getParameter('TaskName'),
],
[
'name' => 'Task Description',
'value' => $physioFileObj->getParameter('TaskDescription'),
],
[
'name' => 'Instructions',
'value' => $physioFileObj->getParameter('Instructions'),
],
[
'name' => 'Recording Type',
'value' => $physioFileObj->getParameter('RecordingType'),
],
[
'name' => 'Recording Split Count',
'value' => $physioFileObj->getParameter('SplitCount'),
],
[
'name' => 'Recording Duration',
'value' => $physioFileObj->getParameter('RecordingDuration'),
],
[
'name' => 'Epoch Length',
'value' => $physioFileObj->getParameter('EpochLength'),
],
[
'name' => 'Subject Artefact Description',
'value' => $physioFileObj->getParameter(
'SubjectArtefactDescription'
),
],
[
'name' => 'Head Circumference',
'value' => $physioFileObj->getParameter('HeadCircumference'),
],
[
'name' => 'Placement Scheme',
'value' => $physioFileObj->getParameter(
$modalityPrefix.'PlacementScheme'
),
],
[
'name' => 'Ground',
'value' => $physioFileObj->getParameter($modalityPrefix.'Ground'),
],
[
'name' => 'Trigger Channel Count',
'value' => $physioFileObj->getParameter('TriggerChannelCount'),
],
[
'name' => 'Misc Channel Count',
'value' => $physioFileObj->getParameter('MiscChannelCount'),
],
[
'name' => 'CogAtlas ID',
'value' => $physioFileObj->getParameter('CogAtlasID'),
],
[
'name' => 'CogPO ID',
'value' => $physioFileObj->getParameter('CogPOID'),
],
[
'name' => 'Institution Name',
'value' => $physioFileObj->getParameter('InstitutionName'),
],
[
'name' => 'Institution Address',
'value' => $physioFileObj->getParameter('InstitutionAddress'),
],
[
'name' => 'Manufacturer',
'value' => $physioFileObj->getParameter('Manufacturer'),
],
[
'name' => 'Manufacturers Model Name',
'value' => $physioFileObj->getParameter(
'ManufacturersModelName'
),
],
[
'name' => $modalityCapName.' Manufacturer',
'value' => $physioFileObj->getParameter(
$modalityCapName.'Manufacturer'
),
],
[
'name' => $modalityCapName.' Manufacturer\'s Model Name',
'value' => $physioFileObj->getParameter(
$modalityCapName.'ManufacturersModelName'
),
],
[
'name' => 'Device Serial Number',
'value' => $physioFileObj->getParameter('DeviceSerialNumber'),
],
[
'name' => 'Hardware Filters',
'value' => $physioFileObj->getParameter('HardwareFilters'),
],
[
'name' => 'Software Versions',
'value' => $physioFileObj->getParameter('SoftwareVersions'),
],
[
'name' => 'Software Filters',
'value' => $physioFileObj->getParameter('SoftwareFilters'),
],
];
if ($modality == 'ieeg') {
$fileSummary['details'][] = [
'name' => 'DC Offset Correction',
'value' => $physioFileObj->getParameter('DCOffsetCorrection'),
];
$fileSummary['details'][] = [
'name' => 'Electrode Groups',
'value' => $physioFileObj->getParameter('ElectrodeGroups'),
];
$fileSummary['details'][] = [
'name' => 'Electrical Stimulation',
'value' => $physioFileObj->getParameter('ElectricalStimulation'),
];
$fileSummary['details'][] = [
'name' => 'Electrical Stimulation Parameters',
'value' => $physioFileObj->getParameter(
'ElectricalStimulationParameters'
),
];
}
// get the links to the files for downloads
$fileSummary['downloads'] = $this->getDownloadLinks($physioFileObj);
$fileSummary['chunks_urls'] = $physioFileObj->getChunksURLs();
$fileSummary['splitData'] = $physioFileObj->getSplitData(0);
return $fileSummary;
}
/**
* Gets the download link for all the electrophysiology files
*
* @param ElectrophysioFile $physioFile ElectrophysiologyFile instance
*
* @return array array with the path to the different files associated to the
* electrophysiology file
*/
function getDownloadlinks(ElectrophysioFile $physioFile): array
{
$nSplit = intval($physioFile->getParameter('SplitCount'));
$downloadLinks = [];
if ($nSplit === 0) {
$downloadLinks[] = [
'groupName' => '',
'links' => $this->getPhysioFileDownloadlinks($physioFile),
];
} else {
foreach (range(0, $nSplit-1) as $i) {
$splitData = $physioFile->getSplitData($i);
if (is_null($splitData)) {
continue;
}
$splitPhysioFile = $splitData['splitPhysioFile'];
$downloadLinks[] = [
'groupName' => 'Split '.($i+1),
'links' => $this->getPhysioFileDownloadlinks(
$splitPhysioFile
),
];
}
}
return $downloadLinks;
}
/**
* Gets the download link for the files associated to a particular
* electrophysiology file (channels.tsv, electrodes.tsv, task events.tsv...)
*
* @param ElectrophysioFile $physioFileObj ElectrophysiologyFile instance
*
* @return array array with the path to the different files associated to the
* electrophysiology file
*/
function getPhysioFileDownloadlinks(ElectrophysioFile $physioFileObj): array
{
$physioFileID = $physioFileObj->getParameter('PhysiologicalFileID');
$physioFile = $physioFileObj->getParameter('FilePath');
$db = \NDB_Factory::singleton()->database();
$downloadLinks = [];
$downloadLinks[] = [
'type' => 'physiological_file',
'file' => $physioFile,
'label' => 'EEG File',
];
$queries = [
'physiological_electrode' => 'physiological_electrode_file',
'physiological_channel' => 'physiological_channel_file',
'physiological_task_event' => 'physiological_task_event_file',
'physiological_annotation_archive' => 'physiological_annotation_files',
'physiological_archive' => 'all_files',
];
$labels = [
'physiological_electrode_file' => 'Electrodes',
'physiological_channel_file' => 'Channels',
'physiological_task_event_file' => 'Events',
'physiological_annotation_files' => 'Annotations',
'all_files' => 'All Files',
];
foreach ($queries as $query_key => $query_value) {
$query_statement = "SELECT
DISTINCT(FilePath), '$query_value' AS FileType
FROM
$query_key
WHERE
PhysiologicalFileID=:PFID";
$query_statement = $db->pselectRow(
$query_statement,
['PFID' => $physioFileID]
);
if (isset($query_statement['FileType'])) {
$downloadLinks[] = [
'type' => $query_statement['FileType'],
'file' => $query_statement['FilePath'],
'label' => $labels[$query_statement['FileType']]
];
} else {
$downloadLinks[] = [
'type' => $query_value,
'file' => '',
'label' => $labels[$query_value],
];
}
}
$queryFDT = "SELECT
Value AS FilePath,
'physiological_fdt_file' AS FileType
FROM
physiological_parameter_file
JOIN parameter_type AS pt USING (ParameterTypeID)
WHERE
pt.Name='fdt_file'
AND PhysiologicalFileID=:PFID";
$queryFDT = $db->pselectRow($queryFDT, ['PFID' => $physioFileID]);
if (isset($queryFDT['FileType'])) {
$downloadLinks[] = [
'type' => $queryFDT['FileType'],
'file' => $queryFDT['FilePath'],
'label' => '',
];
} else {
$downloadLinks[] = [
'type' => 'physiological_fdt_file',
'file' => '',
'label' => '',
];
}
return $downloadLinks;
}
/**
* Get JS Dependencies
*
* @return array of extra JS files that this page depends on
*/
function getJSDependencies()
{
$depends = parent::getJSDependencies();
$factory = \NDB_Factory::singleton();
$baseurl = $factory->settings()->getBaseURL();
$depends = array_merge(
$depends,
[
$baseurl
. '/electrophysiology_browser/js/electrophysiologySessionView.js',
]
);
return $depends;
}
/**
* Get CSS Dependencies
*
* @return array
*/
function getCSSDependencies()
{
$depends = parent::getCSSDependencies();
$factory = \NDB_Factory::singleton();
$baseurl = $factory->settings()->getBaseURL();
$depends = array_merge(
$depends,
[
$baseurl
. '/electrophysiology_browser/css/electrophysiology_browser.css',
]
);
return $depends;
}
/**
* Generate a breadcrumb trail for this page.
*
* @return \LORIS\BreadcrumbTrail
*/
public function getBreadcrumbs(): \LORIS\BreadcrumbTrail
{
return new \LORIS\BreadcrumbTrail(
new \LORIS\Breadcrumb(
'Electrophysiology Browser',
'/electrophysiology_browser'
),
new \LORIS\Breadcrumb(
'View Session',
"/electrophysiology_browser/sessions/$this->sessionID"
)
);
}
}