-
Notifications
You must be signed in to change notification settings - Fork 1
/
analyzedphenotypes.module
1080 lines (880 loc) · 33 KB
/
analyzedphenotypes.module
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
<?php
/**
* @file
* The main functionality of this module.
*/
// Include system variables API.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.systemvars.api');
// Include general API and helper functions.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.api');
// Include Tripal/Chado support API.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.trait.api');
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.cv.api');
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.genus.api');
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.projects.api');
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.database.api');
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.tripaljob.api');
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.ontology.api');
// Materialized views, data summary.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.materializedview.api');
// Expected, downloadable, header combinationns - column headers.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.columnheaders.api');
// Field names.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.formfields.api');
// Unit and data types.
module_load_include('inc', 'analyzedphenotypes', 'api/analyzedphenotypes.datatype.api');
// Validators.
module_load_include('inc', 'analyzedphenotypes', 'includes/analyzedphenotypes.validators');
// Fields.
module_load_include('inc', 'analyzedphenotypes', 'includes/TripalFields/analyzedphenotypes.fields');
module_load_include('inc', 'analyzedphenotypes', 'includes/TripalFields/hp__phenotypic_variability/hp__phenotypic_variability_formatterforms');
module_load_include('inc', 'analyzedphenotypes', 'includes/TripalFields/ncit__data/ncit__data_formatterforms');
/**
* Implements hook_menu().
*/
function analyzedphenotypes_menu() {
$items = array();
// DATA SUMMARY:
// Main menu items for phenotypes: shows a beanplot -select trait and project.
$items['phenotypes'] = array(
'title' => 'Phenotypes',
'description' => 'Summarizes phenotypic data available.',
'page callback' => 'analyzed_phenotypes_all_data_summary_page',
'access arguments' => array('access analyzed phenotypes'),
'file' => 'includes/analyzedphenotypes.summary.page.inc',
'type' => MENU_NORMAL_ITEM,
);
// Violin Plot.
$items['phenotypes/trait-distribution'] = array(
'title' => 'Trait Distribution Plot',
'description' => 'Summarizes phenotypic data for a given trait and project.',
'page callback' => 'drupal_get_form',
'page arguments' => array('analyzedphenotypes_traitplot_app_form'),
'access arguments' => array('access analyzed phenotypes'),
'file' => 'includes/analyzedphenotypes.traitplot.page.inc',
'type' => MENU_NORMAL_ITEM,
);
$items['json/phenotypes/traitplot/%/%/%/%'] = array(
'page callback' => 'analyzedphenotypes_traitplot_json',
'page arguments' => array(3, 4, 5, 6),
'access arguments' => array('access analyzed phenotypes'),
'file' => 'includes/analyzedphenotypes.traitplot.page.inc',
'type' => MENU_CALLBACK,
);
$tripal_extension_ap = 'admin/tripal/extension/analyzedphenotypes';
// Main administrative pages for analyzed phenotypes.
$items[$tripal_extension_ap] = array(
'title' => 'Analyzed Phenotypes',
'description' => 'Provides phenotypic trait pages, charts, upload and download for partially filtered (not raw) phenotypic data.',
'access arguments' => array('administer tripal'),
);
// CONFIGURATION PAGE:
$items[$tripal_extension_ap . '/setup'] = array(
'title' => 'Set-up Ontologies',
'description' => 'Set the controlled vocabularies to be used by this module, as well, as other options to customize it to your data.',
'page callback' => 'drupal_get_form',
'page arguments' => array('analyzedphenotypes_setup_form'),
'access arguments' => array('administer tripal'),
'file' => 'includes/analyzedphenotypes.configuration.page.inc',
'weight' => 2,
'type' => MENU_NORMAL_ITEM,
);
$items[$tripal_extension_ap . '/config'] = array(
'title' => 'Configure',
'description' => 'Customize the display of this module.',
'page callback' => 'drupal_get_form',
'page arguments' => array('analyzedphenotypes_config_form'),
'access arguments' => array('administer tripal'),
'file' => 'includes/analyzedphenotypes.configuration.page.inc',
'weight' => 2,
'type' => MENU_NORMAL_ITEM,
);
// FORM IMPLEMENTATIONS:
// DOWNLOAD DATA.
$items['phenotypes/download'] = array(
'title' => 'Download Analyzed Phenotypic Data',
'description' => 'Download Analyzed Phenotypic Data.',
'page callback' => 'drupal_get_form',
'page arguments' => array('analyzedphenotypes_downloaddata_form'),
'access arguments' => array('access administration pages'),
'file' => 'includes/analyzedphenotypes.downloaddata.page.inc',
'weight' => 2,
'type' => MENU_NORMAL_ITEM,
);
// MENU CALLBACK:
// Generate data in JSON object.
// Global menu callback used to generate JSON.
$items[$tripal_extension_ap . '/json/%/%'] = array(
'page callback' => 'analyzedphenotypes_data_json',
'page arguments' => array(5, 6),
'access arguments' => array('upload analyzed phenotypes'),
'type' => MENU_CALLBACK,
);
$items[$tripal_extension_ap . '/phenotyped-stock/json/%/%'] = array(
'page callback' => 'analyzedphenotypes_autocomplete_phenotyped_stock',
'page arguments' => array(6,7),
'access arguments' => array('access content'),
'type' => MENU_CALLBACK,
);
// Generate validation result.
$items[$tripal_extension_ap . '/validation_result/%/%'] = array(
'page callback' => 'ap_report_validationresult',
'page arguments' => array(5, 6),
'access arguments' => array('upload analyzed phenotypes'),
'type' => MENU_CALLBACK,
);
// Tripal Download Implementation.
$items['phenotype/download/analyzed_phenotypic_data'] = array(
'title' => 'Analyzed Phenotypic Data Download',
'page callback' => 'trpdownload_download_page',
'page arguments' => array('analyzedphenotypes_download'),
'access arguments' => array('access administration pages'),
'type' => MENU_CALLBACK,
);
return $items;
}
/**
* Implements hook_permission().
*/
function analyzedphenotypes_permission() {
return array(
// Administer Tripal.
'administer tripal' => array(
'title' => t('Administer Tripal'),
),
// Upload Analyzed Phenotypes.
'upload analyzed phenotypes' => array(
'title' => t('Upload Analyzed Phenotypic Data'),
),
// Download Analyzed Phenotypes.
'download analyzed phenotypes' => array(
'title' => t('Download Analyzed Phenotypic Data'),
),
// Access Analyzed Phenotypes.
'access analyzed phenotypes' => array(
'title' => t('Access Analyzed Phenotypic Data'),
),
);
}
/**
* Implements hook_theme().
*/
function analyzedphenotypes_theme($existing, $type, $theme, $path) {
$items = array();
// Form implementations:
// Configuration form.
$items['analyzedphenotypes_configuration_form'] = array(
'template' => 'analyzedphenotypes_pages',
'render element' => 'form',
'path' => $path . '/theme',
);
// Data downloader.
$items['analyzedphenotypes_downloaddata_form'] = array(
'template' => 'analyzedphenotypes_pages',
'render element' => 'form',
'path' => $path . '/theme',
);
// Form table.
$items['analyzedphenotypes_form_table'] = array(
'render element' => 'form',
);
// Module page directory
$items['analyzedphenotypes_admin_page_directory'] = array(
'template' => 'analyzedphenotypes_pages',
'render element' => 'form',
'path' => $path . '/theme',
);
// Report errors generated by validators.
$items['analyzedphenotypes_validator_report'] = array(
'template' => 'analyzedphenotypes_validators',
'path' => $path . '/theme',
);
// Phenotype Trait Summary Fields.
$items['analyzedphenotypes_trait_summary_fields'] = array(
'render element' => 'element',
);
return $items;
}
/**
* Theme callback to render analyzedphenotypes_form_table field type.
*
* Credits to : Electronic Press
* @link http://e9p.net/theming-drupal-7-form-elements-table. @endlink
*/
function theme_analyzedphenotypes_form_table(&$variables) {
$form = $variables['form'];
$rows = $form['rows'];
$header = $form['#header'];
// Setup the structure to be rendered and returned.
$content = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => array(),
);
foreach (element_children($rows) as $row_index) {
$row = array();
foreach (element_children($rows[$row_index]) as $col_index) {
$row[] = drupal_render($rows[$row_index][$col_index]);
}
// A row in the table.
$content['#rows'][] = $row;
}
// Render the table and return.
return drupal_render($content);
}
/**
* Implements hook_preprocess().
*/
function analyzedphenotypes_preprocess_analyzedphenotypes_admin_page_directory(&$variables, $hook) {
$variables['path_extension'] = 'admin/tripal/extension/analyzedphenotypes';
$variables['directory'] = $variables['form']['#ap_admin_directory'];
return $variables;
}
/**
* Implements hook_libraries_info().
*
* Define external libraries: Spreadsheet Writer.
*/
function analyzedphenotypes_libraries_info() {
// Spreadsheet writer.
// Let Drupal decide where library is.
$lib_writer = libraries_get_path('PHP_XLSXWriter_plus');
$libraries['spreadsheet_writer'] = array(
'name' => 'PHP_XLSXWriter_plus Spreadsheet Writer',
'vendor url' => 'https://github.com/SystemDevil/PHP_XLSXWriter_plus',
'version' => 1,
'download url' => 'https://github.com/SystemDevil/PHP_XLSXWriter_plus/archive/master.zip',
'library path' => $lib_writer,
'files' => array('xlsxwriter.class.php'),
);
return $libraries;
}
/**
* Used for autocomplete in forms for identifying stocks
*
* @param $string
* The string to search for.
*
* @return
* A json array of terms that begin with the provided string.
*
* @ingroup tripal_stock_api
*/
function analyzedphenotypes_autocomplete_phenotyped_stock($trait_id, $string = '') {
$items = [];
$sql = "
SELECT
B.stock_id as id, B.uniquename, B.name,
O.genus, O.species,
CVT.name as type
FROM {stock} B
INNER JOIN {organism} O ON O.organism_id = B.organism_id
INNER JOIN {cvterm} CVT ON CVT.cvterm_id = B.type_id
WHERE
(lower(B.uniquename) like lower(:str)
OR lower(B.name) like lower(:str))
AND B.stock_id IN (SELECT stock_id from {mview_phenotype} WHERE trait_id=:trait)
ORDER by B.name
LIMIT 10 OFFSET 0
";
$records = chado_query($sql, [':trait' => $trait_id, ':str' => $string . '%']);
while ($r = $records->fetchObject()) {
$key = "$r->name [id: $r->id]";
$items[$key] = "$r->name ($r->uniquename, $r->type, $r->genus $r->species)";
}
drupal_json_output($items);
}
/**
* Function callback: Convert query results or parameters suplied to an array of JSON object
* and supply the result to field or form elements (ie. autocomplete form field, validation
* progress etc.) that requires data in this notation.
*
* @param $page_argument_5
* A string indicating the source of call and what type of data is requested.
* #5 of the menu's page aruguments.
* eg. Projects, ontology etc.
* @param $page_argument_6
* Additional parameter required.
* #6 of the menu's page aruguments.
* eg. Job Id when generating progress report for Job Status source type.
* @param $key
* Default to null, value entered in a field (eg. autocomplete field).
*
* @return
* A JSON object.
*
* @see hook_menu() implementation - Generate data in JSON object, above that handles all page elements in this
* module that requires JSON.
*/
function analyzedphenotypes_data_json($page_argument_5, $page_argument_6, $key = null) {
$data_JSON = array();
$property = $page_argument_5;
$parameter = $page_argument_6;
switch($property) {
//
case 'projects':
// Fetch project/experiment that matches a keyword in AP data loader
// Select experiment autocomplete form field in:
// admin.form.inc - analyzedphenotypes_loader_form_upload() : Stage #1 - Select experiment, genus and upload file.
// Parameters:
// $page_argument_5 : projects.
// $page_argument_6 : experiment.
// $key : Keyword enterd in the field.
$data_JSON = array();
// Pattern match projects, return the first 10.
$projectprop = ap_match_projectname(
array('key' => $key),
array('fullmatch' => FALSE, 'limitrows' => 10)
);
if ($projectprop) {
foreach($projectprop as $id => $name) {
$data_JSON[$name] = $name;
}
}
break;
//
case 'jobstatus':
// Update job status of a Tripal Job request in AP data loader page in:
// admin.form.inc - analyzedphenotypes_loader_form_validates() : Stage #2 - Validate data.
// admin.form.inc - analyzedphenotypes_loader_form_save() : Stage #4 - Save Data.
// Parameters:
// $page_argument_5 : jobstatus.
// $page_argument_6 : Tripal Job job id number.
// $key : null.
$data_JSON = array();
$job = ap_get_tripaljob($parameter);
if ($job) {
$job_status = strtolower(trim($job['status']));
if ($job_status == 'completed') {
// Job completed, return completed!
// Set job to completed - 100%.
$progress = 100;
$message = 'Completed';
if ($job['progress'] != $progress) {
ap_update_tripaljob_progress($parameter, $progress);
}
}
else {
// Job not complete. Next percent to pass on to the progress bar.
// Percent written by write function called in validators.
$tripal_jobprop = ap_read_tripaljob_progress($parameter, 'jobprogress');
$progress = (empty($tripaljobprop)) ? '...' : trim($tripaljobprop);
$message = ($progress == '100' || $job['status'] == $job_status)
? 'Completed' : $job['status'];
}
$data_JSON = array(
'percentage' => $progress,
'message' => $message,
);
}
break;
//
case 'ontology':
// Fetch otology terms that matches a keyword in AP data loader
// Enter ontology term autocomplete form feild in:
// admin.form.inc - analyzedphenotypes_loader_form_describe() : Stage #3 - Describe Traits.
// Parameters:
// $page_argument_5 : ontology.
// $page_argument_6 : genus ontology (on) configuration settings.
// $key : null.
$data_JSON = array();
// Fetch terms in a cv.
$ontology_suggestions = ap_get_cvterm(
array('keyword' => $key, 'genus' => $parameter),
array('dataset' => 'cvtermidname')
);
// Limit the result shown to 10. This will
// prevent a long list that will break the layout since
// Drupal does not add a scrollbars to drop select when
// it is long list.
$suggest_limit = 10;
foreach($ontology_suggestions as $i => $term) {
$data_JSON[ $term['name'] ] = $term['name'];
if ($i == $suggest_limit) break;
}
break;
//
case 'cvterms':
// Fetch controlled vocabulary terms that matches a keyword in AP data loader
// configuration page term autocomplete form field in:
// admin.form.inc - analyzedphenotypes_admin_settings().
// Parameters:
// $page_argument_5 : cvterms.
// $page_argument_6 : cv.
// $key : Keyword entered in the field.
$data_JSON = array();
// Fetch all terms that match a keyword. No conditions to scope of search.
$cvterms = ap_get_cvterm(
array('keyword' => $key),
array('dataset' => 'namecvname_format')
);
// Limit the result shown to 10. This will
// prevent a long list that will break the layout since
// Drupal does not add a scrollbars to drop select when
// it is long list.
$suggest_limit = 10;
foreach($cvterms as $i => $term) {
$data_JSON[ $term['namecvname'] ] = $term['namecvname'];
if ($i == $suggest_limit) break;
}
break;
//
case 'germplasm':
$field_values = unserialize($parameter);
foreach($field_values as $i => $g) {
$data_JSON[$g] = $g;
}
break;
//
case 'traitunit':
// Fetch all units.
$units = ap_define_datatypes();
// Only the ones that have the keyword get suggested
// to the unit field in describe trait.
foreach($units as $u => $i) {
if (stristr($u, $key)) {
// Has the keyword?
$data_JSON[$u] = $u . ' (' . $i['name'] . ')';
}
}
break;
//
case 'projectgenus':
// Fetch the genus of of the project if it
// has been previously set.
$project_name = strip_tags($parameter);
if ($project_name) {
$project_genus = ap_get_projectgenus(
array('project_name' => $project_name)
);
if ($project_genus) {
$data_JSON['genus'] = $project_genus;
}
}
break;
//
// Define additional case here.
// default:
}
print drupal_json_output($data_JSON);
// Do not show the Drupal headers and formatting.
// This is critical as if anything else is printed to the screen you will see
// an AJAX error instead of your progress bar ;-).
exit();
}
// TRIPAL DOWNLOAD API IMPLEMENTATION
/**
* Implements hook_register_tripaldownload_type().
*/
function analyzedphenotypes_register_trpdownload_type() {
$types = array();
// The key is the machine name of my download type.
$types['analyzedphenotypes_download'] = array(
// A human readable name to show in an administrative interface one day.
'type_name' => 'Analyzed Phenotypic Data Download',
// A human readable description of the format.
'format' => '',
// An array of functions that the API will use to customize your experience.
'functions' => array(
// The function that tripal jobs will call to generate the file.
'generate_file' => 'analyzedphenotypes_trpdownload_generate_file',
// OPTIONAL: provide a summary to the user on the download page.
'summarize' => 'analyzedphenotypes_trpdownload_summarize_download',
// OPTIONAL: determine your own filename.
'get_filename' => 'analyzedphenotypes_trpdownload_get_filename',
// OPTIONAL: Change the file suffix (defaults to .txt)
'get_file_suffix' => 'analyzedphenotypes_trpdownload_get_suffix',
// OPTIONAL: determine the human-readable format based on a function.
'get_format' => 'analyzedphenotypes_trpdownload_get_readable_format',
),
);
return $types;
}
/**
* Generate a readable and unique filename for the file to be generated.
*/
function analyzedphenotypes_trpdownload_get_filename($vars) {
// Filename.
$filename = 'analyzed_phenotypic_data_download' . date('YMd') .'_'. time();
return $filename;
}
/**
* determine the human-readable format based on a function.
*/
function analyzedphenotypes_trpdownload_get_readable_format($vars) {
// File Extension from file type field options.
foreach($vars as $l => $v) {
if(is_array($v)) {
foreach($v as $j => $m) {
if ($j == 'code') {
$code = $m;
}
}
}
}
$v = base64_decode($code);
if (!empty($v)) {
// Field names.
$fldname = ap_construct_download_fieldnames();
$filters = explode('&', $v);
foreach($filters as $i) {
list($filter, $value) = explode('=', $i);
if ($filter == $fldname['filetype']['base']) {
$file_type = trim($value);
break;
}
}
switch($file_type) {
case 'tsv':
$format = 'Tab Separated Values (.tsv)';
break;
case 'csv':
$format = 'Comma Separated Values (.csv)';
break;
case 'xlsx':
$format = 'Microsoft Excel Spreadsheet (.xlsx)';
break;
}
return $format;
}
}
/**
* Determine the file suffix for the file to be generated.
*/
function analyzedphenotypes_trpdownload_get_suffix($vars) {
// File Extension from file type field options.
foreach($vars as $l => $v) {
if(is_array($v)) {
foreach($v as $j => $m) {
if ($j == 'code') {
$code = $m;
}
}
}
}
$v = base64_decode($code);
if (!empty($v)) {
// Field names.
$fldname = ap_construct_download_fieldnames();
$filters = explode('&', $v);
foreach($filters as $i) {
list($filter, $value) = explode('=', $i);
if ($filter == $fldname['filetype']['base']) {
$file_type = trim($value);
break;
}
}
return $file_type;
}
}
/**
* Function callback: generate csv file.
*/
function analyzedphenotypes_trpdownload_generate_file($vars, $job_id = NULL) {
// Use this character to separate entries in a string.
$delimiter = '~';
$code = '';
foreach($vars['q'] as $j => $m) {
if ($j == 'code') {
$code = $m;
break;
}
}
$filename = $vars['filename'];
// Start extracting filters.
if (empty($code) && empty($filename)) {
die('Could not generate file. No filters selected.');
}
else {
// Filters selected.
$v = base64_decode($code);
if (empty($v)) {
die('Could not generate file. No filters selected.');
}
else {
// Convert the query string to key and value pair.
// Key should still match field name returned by _fieldnames().
// FILTER or FORM FIELD VALUE.
$filters = explode('&', $v);
$filter_value = array();
foreach($filters as $i) {
@list($filter, $value) = explode('=', $i);
// Field name = Value selected.
$filter_value[$filter] = $value;
}
print "Parameters include: " . print_r($filter_value, TRUE);
// Global/standard field names used in form, submit etc.
// experiment, genus, species, traits, year, location, germplasmtype,
// missingdata, filetype, averagerep, rfriendly, columnheaders
$fldname = ap_construct_download_fieldnames();
// File type field name value.
$file_type = $filter_value[ $fldname['filetype']['base'] ];
// Fetch all valid file types for download.
// Use the result to ensure that only these registered types are allowed.
$d = ap_define_datafile_extensions('file_download');
$download_type = array_keys($d);
if (in_array($file_type, $download_type)) {
// TSV, CSV or XLSX.
// This array will hold datapoints for write-to-file.
$to_write = array();
// Start by reading the column headers field. This contains the headers
// programmatically picked and/or selected by user. In addition, this
// contains the set of columns required as well as the order it appears in file.
// FILTER/FIELD NAME: columnheaders.
$h = $filter_value[ $fldname['columnheaders']['base'] ];
// Entries are delimited by $delimeter value, break it to individual unit.
$g = explode($delimiter, $h);
$column_headers_picked = array_map('trim', $g);
// Save indicies of important columns.
$i_expt = array_search('Experiment', $column_headers_picked);
$i_germ = array_search('Germplasm Name', $column_headers_picked);
$i_year = array_search('Year', $column_headers_picked);
$i_locn = array_search('Location', $column_headers_picked);
$coli = array_flip( $column_headers_picked );
// Make a blank row.
$blank_row = array_keys($column_headers_picked);
foreach($blank_row as $k => $v) { $blank_row[$k] = ''; }
// Make a clone copy of this array.
$tmp_column_headers_picked = $column_headers_picked;
// Does user want it RFriendly-ied?
// FILTER/FIELD NAME: rfriendly.
if ($filter_value[ $fldname['rfriendly']['base'] ]) {
$column_headers_picked_rfriendly = array();
foreach($column_headers_picked as $col) {
$col = trim($col);
if (!empty($col)) {
$rf = ap_convert_rcolumnheader($col);
$column_headers_picked_rfriendly[] = $rf;
}
}
// Reset the original column headers and use this rfriendly version.
unset($column_headers_picked);
$column_headers_picked = $column_headers_picked_rfriendly;
}
// The first item to write are the column headers.
$to_write[] = $column_headers_picked;
// Fetch dataset for a given filters.
$filters = $filter_value;
// Match field to actual chado column names.
// Limit rows to project, trait, year, location, germplasm type and germplasm.
$column = array(
$fldname['experiment']['base'] => 'mp.experiment_id',
$fldname['traits']['base'] => "mp.trait_id||','||mp.method_id||','||mp.unit_id",
$fldname['germplasmtype']['base'] => 's.type_id',
$fldname['year']['base'] => 'mp.year',
$fldname['location']['base'] => 'mp.location',
// As entered in the germplasm field.
$fldname['germplasm']['base'] => "CONCAT(s.name, ' (', s.uniquename, ')')",
);
$limit = array();
foreach($column as $filter => $col) {
$filter_val = $filters[$filter];
// Convert filter so chado_query arguments (:placeholder = value).
// Exclude filter with value = all.
if ($filter_val != 'all') {
$placeholder = ':' . $filter;
$limit['limit'][] = $col . ' IN (' . $placeholder . ')';
$limit['args'][$placeholder] = explode($delimiter, $filter_val);
}
}
$limit['limit'] = implode(' AND ', $limit['limit']);
// If the user selected optional columns then we need to add them to the query...
// (e.g. origin, data collector).
// @todo currently the column headers functionality seems broken...
// Get ready to compile the file.
// Each row from the following SQL query is a trait-value cell in the resulting file.
// As such we need to loop over multiple results to compile a single row...
// The query is sorted to allow us to do this.
// Variable to hold the current row as we compile it.
$cur_row = $blank_row;
$cur_row_key = NULL;
// Finally, our query uses the phenotype mview for better performance.
$sql = "
SELECT
mp.experiment_id, mp.experiment_name,
mp.trait_id||','||mp.method_id||','||mp.unit_id as trait_key,
mp.trait_name, mp.method_name, mp.unit_name,
s.stock_id, mp.stock_name,
mp.location, mp.year,
mp.values
FROM {mview_phenotype} mp
LEFT JOIN {stock} s ON s.stock_id=mp.stock_id
WHERE " . $limit['limit'] . "
ORDER BY experiment_id ASC, location ASC, year ASC, stock_name ASC
";
$result = chado_query($sql, $limit['args']);
// Now, for each result from the query...
foreach($result as $r) {
// Is this a new row?
$result_key = implode($delimiter, array($r->experiment,$r->stock_id,$r->location,$r->year));
// If it is a new row then we need to...
if ($cur_row_key !== $result_key) {
// 1) Save the last row...
if ($cur_row != $blank_row) {
ksort($cur_row);
$to_write[] = $cur_row;
}
// 2) initialize it.
$cur_row_key = $result_key;
$cur_row = $blank_row;
if ($i_expt !== FALSE) { $cur_row[$i_expt] = $r->experiment_name; }
$cur_row[$i_germ] = $r->stock_name;
$cur_row[$i_locn] = $r->location;
$cur_row[$i_year] = $r->year;
}
// Add the current trait to the row.
// The values are storaged as a JSON array so first convert them.
$values = json_decode($r->values);
if (is_array($values)) {
$value = array_sum($values)/count($values);
$value = round($value, 2);
$full_trait_name = $r->trait_name.' ('.$r->method_name.'; '.$r->unit_name.')';
$i_trait = $coli[$full_trait_name];
$cur_row[$i_trait] = $value;
}
else {
// @todo add an error message here.
}
}
if ($to_write) {
analyzedphenotypes_trpdownload_writefile($filename, $to_write, $file_type);
}
}
else {
// File type not supported.
die('Could not generate file. File type not supported.');
}
//
}
}
}
/**
* FUNCTION GENERATE FILE.
* Create a tsv, csv and xlsx file.
*
* @param $filename
* String, destination filename.
* @param $data_rows
* An array containing the headers (index 0) and data points to write to a file.
* @param $file_type
* String, indicating the type of file (tsv, csv, xlsx).
*/
function analyzedphenotypes_trpdownload_writefile($filename, $data_rows, $file_type) {
$filepath = variable_get('trpdownload_fullpath', '') . $filename;
switch($file_type) {
//
case 'tsv':
//
case 'csv':
$FILE = fopen($filepath, 'w') or die ('Unable to create file to write to...');
foreach($data_rows as $row) {
if ($file_type == 'tsv') {
fputcsv($FILE, $row, "\t");
}
else {
fputcsv($FILE, $row);
}
}
fclose($FILE);
break;
//
case 'xlsx':
// Load spreadsheet writer library.
$xlsx_writer = libraries_load('spreadsheet_writer');
include_once $xlsx_writer['library path'] . '/'. $xlsx_writer['files'][0];
$writer = new XLSXWriter();
@$writer->writeSheet($data_rows, 'measurements', array(), array());
$writer->writeToFile($filepath);
break;
}
}
// AP TRAIT SUMMARY FIELDS:
/**
* Implementes hook_field_group_formatter_info().
* Define field group.
* Credits to: https://www.drupal.org/node/1017962
*/
function analyzedphenotypes_field_group_formatter_info() {
$info = array();
// Field group of type: traitsummary.
$settings = array(
'traitsummary' => array(
'label' => t('Analyzed Phenotypes Data Summary'),
'description' => t('This fieldgroup renders the Analyzed Phenotypes Data Summary with the field title as an item'),
'instance_settings' => array(
'id' => '',
'classes' => '',
)
)
);
// Form and Display key the same.
$info = array(
'form' => $settings,
'display' => $settings,
);
return $info;
}
/**
* Implements hook_field_group_format_settings().
* Form elements format settings, add validation callback, js handler etc. here
*/