Completed
Push — master ( 4e0cb0...0037c0 )
by Ismail
49s
created

GD.loadPcRedrawValidation   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 25
rs 6.7272
cc 7
nc 3
nop 2
1
/*
2
    GD - GeoDiver's JavaScript module
3
4
    Define a global GD (acronym for GeoDiver) object containing all
5
    GD associated methods:
6
*/
7
8
// define global GD object
9
var GD;
10
if (!GD) {
0 ignored issues
show
Bug introduced by
The variable GD seems to be never initialized.
Loading history...
11
  GD = {};
12
}
13
14
// GD module
15
(function() {
16
  GD.setUpValidatorDefaults = function() {
17
    $.validator.addMethod('geoDb', function (value) {
18
        return /^G[DS][SE]\d\d?\d?\d?\d?$/i.test(value);
19
    }, 'Please enter a valid GEO dataset accession number (in the format GDSxxxx).');
20
21
    $.validator.addMethod('checkIfGeoExists', function(value) {
22
      var doesNotExist = [1,2,3,4,7,8,9,11,13,14,22,24,25,27,28,29,32,41,42,43,44,54,55,57,65,66,67,68,70,71,72,73,74,75,76,79,81,82,83,84,87,89,90,97,98,101,102,103,107,109,114,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,136,137,138,139,140,141,142,143,146,147,148,149,150,151,152,153,154,155,159,163,165,166,173,175,176,178,179,180,184,185,188,189,190,191,193,194,195,196,197,202,204,206,207,208,209,210,211,212,216,217,218,219,220,221,226,228,229,230,231,235,237,257,260,263,269,271,273,275,277,284,286,327,328,330,331,333,334,335,336,338,340,341,342,343,347,348,349,350,351,357,361,363,365,370,371,372,373,375,376,377,379,380,381,382,383,391,392,393,396,397,398,403,405,406,407,408,419,442,445,447,448,450,452,454,455,456,457,458,459,460,461,462,464,465,466,467,474,475,482,485,489,490,492,496,497,500,503,506,512,523,530,537,539,540,541,542,543,544,545,546,547,548,549,550,551,558,566,569,570,571,572,573,581,585,590,593,594,595,597,601,603,613,616,619,620,626,628,629,633,634,642,643,644,645,646,650,655,669,673,674,675,676,678,688,689,691,692,693,697,706,712,713,714,715,716,727,729,730,733,736,741,745,746,747,749,753,754,757,758,760,762,763,764,774,783,784,789,792,793,795,796,797,798,800,801,802,803,804,805,815,816,818,819,821,822,824,839,842,850,861,864,865,875,876,886,888,889,895,896,897,898,903,904,914,921,923,924,929,930,931,932,933,934,935,936,937,938,939,941,950,952,957,973,974,975,978,979,980,985,986,990,1000,1004,1005,1006,1007,1008,1016,1021,1024,1025,1026,1029,1031,1034,1035,1040,1041,1042,1045,1046,1052,1060,1061,1066,1069,1070,1075,1081,1082,1086,1087,1089,1090,1091,1092,1097,1098,1100,1101,1102,1104,1105,1114,1117,1118,1119,1120,1121,1122,1123,1124,1125,1126,1127,1128,1129,1130,1131,1132,1133,1134,1135,1136,1137,1138,1139,1140,1141,1142,1143,1144,1145,1146,1147,1148,1149,1150,1151,1152,1153,1154,1155,1156,1157,1158,1159,1160,1161,1162,1163,1164,1165,1166,1167,1168,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179,1180,1181,1182,1183,1184,1185,1186,1187,1188,1189,1190,1191,1192,1193,1194,1195,1196,1197,1198,1199,1200,1201,1202,1203,1206,1207,1208,1216,1217,1218,1223,1224,1229,1242,1246,1259,1260,1262,1267,1268,1281,1283,1291,1296,1297,1308,1322,1337,1341,1345,1355,1356,1358,1364,1368,1370,1377,1378,1386,1387,1391,1403,1410,1415,1416,1417,1418,1420,1425,1426,1428,1430,1432,1433,1437,1441,1454,1457,1458,1459,1460,1461,1462,1463,1470,1471,1482,1483,1487,1493,1506,1508,1524,1525,1535,1536,1537,1538,1539,1540,1554,1556,1558,1561,1564,1566,1567,1569,1570,1573,1574,1575,1576,1577,1578,1586,1587,1588,1589,1590,1591,1592,1594,1595,1598,1601,1602,1603,1605,1613,1614,1619,1623,1624,1625,1628,1639,1643,1656,1659,1668,1669,1671,1680,1682,1683,1698,1708,1720,1721,1722,1725,1737,1738,1740,1742,1749,1751,1754,1755,1762,1769,1770,1775,1781,1782,1787,1789,1790,1811,1814,1817,1818,1819,1820,1822,1823,1828,1829,1831,1834,1856,1859,1860,1861,1863,1866,1867,1868,1876,1885,1888,1889,1893,1894,1895,1896,1897,1898,1899,1900,1907,1909,1918,1919,1927,1930,1935,1944,1945,1946,1947,1948,1949,1950,1953,1958,1961,1966,1967,1969,1970,1971,1991,1992,1994,1996,1997,1998,1999,2000,2017,2022,2033,2059,2062,2067,2068,2075,2076,2085,2108,2116,2117,2121,2122,2127,2128,2129,2130,2131,2133,2137,2140,2148,2155,2166,2198,2199,2210,2220,2238,2247,2252,2256,2257,2262,2271,2273,2275,2278,2279,2280,2286,2290,2293,2296,2299,2305,2306,2315,2337,2340,2345,2348,2357,2369,2376,2392,2393,2394,2401,2402,2403,2404,2405,2407,2409,2435,2436,2441,2449,2450,2458,2459,2465,2467,2473,2476,2488,2492,2500,2503,2505,2506,2507,2510,2512,2527,2538,2539,2541,2543,2544,2551,2557,2560,2568,2574,2620,2621,2634,2644,2645,2670,2679,2689,2690,2692,2711,2714,2726,2776,2792,2793,2796,2797,2798,2799,2800,2801,2806,2807,2828,2829,2836,2837,2839,2844,2845,2849,2871,2888,2890,2891,2894,2896,2897,2898,2899,2900,2907,2942,2943,2979,2985,2986,2992,2994,2995,2997,3013,3015,3016,3019,3020,3021,3022,3024,3026,3053,3055,3063,3065,3066,3067,3075,3076,3090,3093,3094,3098,3146,3161,3164,3165,3166,3167,3168,3169,3170,3185,3200,3201,3202,3204,3205,3206,3208,3212,3213,3214,3219,3236,3237,3246,3247,3248,3249,3250,3261,3263,3264,3265,3266,3269,3270,3271,3272,3273,3275,3276,3277,3278,3279,3280,3286,3301,3302,3303,3304,3307,3314,3317,3327,3328,3335,3336,3337,3338,3339,3340,3347,3348,3359,3372,3377,3378,3380,3381,3389,3390,3391,3409,3443,3449,3450,3451,3457,3458,3460,3541,3542,3543,3546,3563,3565,3569,3584,3585,3586,3587,3588,3589,3590,3611,3614,3617,3645,3650,3651,3652,3693,3695,3708,3731,3760,3778,3817,3821,3822,3828,3845,3877,3878,3879,3937,3947,3967,3968,3969,3970,3971,3979,3994,4020,4022,4031,4033,4044,4049,4060,4062,4068,4072,4073,4075,4076,4086,4087,4097,4098,4111,4112,4117,4122,4126,4127,4139,4183,4184,4187,4192,4197,4241,4292,4293,4405,4529,4530,4561,4603,4604,4605,4616,4623,4624,4625,4626,4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642,4643,4644,4645,4646,4647,4648,4649,4650,4651,4652,4653,4654,4655,4656,4657,4658,4659,4660,4661,4662,4663,4666,4667,4668,4670,4671,4672,4673,4674,4675,4676,4677,4678,4679,4680,4681,4682,4683,4684,4685,4686,4687,4688,4689,4690,4691,4692,4693,4694,4695,4696,4697,4698,4699,4701,4702,4703,4704,4705,4706,4707,4708,4709,4710,4711,4712,4713,4714,4715,4716,4717,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731,4732,4733,4734,4735,4736,4737,4738,4739,4740,4741,4742,4743,4744,4745,4746,4747,4748,4749,4750,4751,4752,4753,4789,4790,4792,4793,4860,4861,4862,4863,4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4878,4888,4889,4890,4905,4906,4907,4908,4909,4918,4919,4920,4921,4922,4923,4924,4925,4927,4932,4933,4934,4935,4938,4939,4942,4945,4946,4948,4951,4952,4963,4975,4976,4977,4982,4995,4996,4997,4998,4999,5000,5001,5002,5003,5004,5005,5011,5027,5035,5036,5038,5039,5042,5043,5044,5068,5069,5081,135,1330,3666,3727,3796,3890,3897,3922,3946,3957,3986,4807,5021,5037];
23
      if (value.length > 3) {
24
        if($.inArray( parseInt( value.substring(3) ), doesNotExist) !== -1 && /^GDS\d\d?\d?\d?$/i.test(value)) {
25
          return false;
26
        } else { return true; }
27
      } else { return true; }
28
    }, 'This GEO dataset accession number does not exist.');
29
30
    $.validator.setDefaults({
31
      errorClass: 'invalid',
32
      validClass: "valid",
33
      errorPlacement: function (error, element) {
34
          $(element)
35
            .closest("form")
36
            .find("label[for='" + element.attr("id") + "']")
37
            .attr('data-error', error.text());
38
      },
39
    });
40
  };
41
42
  ///// AJAXs
43
44
  GD.loadGeoDbValidation = function() {
45
    'use strict';
46
    $('#load_geo_db').validate({
47
      rules: {
48
        geo_db: {
49
          geoDb: true,
50
          checkIfGeoExists: true,
51
          required: true
52
        },
53
      },
54
      submitHandler: function() {
55
        $('.card-action').remove();
56
        $('#results_section').empty();
57
        var geo_db = $('input[name=geo_db]').val().toUpperCase();
58
        $('#modal_header_text').text('Loading GEO Dataset: ' + geo_db);
59
        $('#modal_text').text('This should take a few seconds. Please leave this page open');
60
        $('#loading_modal').modal({ dismissible: false });
61
        $('#loading_modal').modal('open');
62
        $.ajax({
63
          type: 'POST',
64
          url: '/load_geo_db',
65
          data: $('#load_geo_db').serialize(),
66
          success: function(response) {
67
            $( response ).insertAfter( "#load_geo_card" );
68
            $('#geo_db_summary').html(response);
69
            $('#geo_db_summary').show();
70
            $('.adv_param_collapsible').collapsible();
71
            $("input:radio[name=factor]:first").attr('checked', true);
72
            $('#' + $("input:radio[name=factor]:first").attr('id') + '_select').show();
73
            $('#adv_params_btn').click(function(){
74
              if ( ! $('#adv_params_params_tabs').hasClass('tabs_initialised')) {
75
                setTimeout(
76
                  function(){
77
                    $('#adv_params_params_tabs').tabs();
78
                    $('#adv_params_params_tabs').addClass('tabs_initialised');
79
                  }, 1);
80
              }
81
            });
82
            $('select[name="groupa[]"]').on('change', function(){
83
              if ( $.isEmptyObject( $('select[name="groupa[]"]:enabled').val() ) ) {
84
                $('#groupa_params').attr('data-tooltip', 'This is Group A' );
85
                $('#groupa_params').tooltip({delay: 50});
86
              } else {
87
                $('#groupa_params').attr('data-tooltip', 'Group A: ' + $('select[name="groupa[]"]:enabled').val().join(", ") );
88
                $('#groupa_params').tooltip({delay: 50});
89
              }
90
            });
91
            $('select[name="groupb[]"]').on('change', function(){
92
              if ( $.isEmptyObject( $('select[name="groupb[]"]:enabled').val() ) ) {
93
                $('#groupb_params').attr('data-tooltip', 'This is Group B' );
94
                $('#groupb_params').tooltip({delay: 50});
95
              } else {
96
                $('#groupb_params').attr('data-tooltip', 'Group B: ' + $('select[name="groupb[]"]:enabled').val().join(", ") );
97
                $('#groupb_params').tooltip({delay: 50});
98
              }
99
            });
100
            GD.ensureOnlyOneSelectOption();
101
            GD.addAdvParamLogic();
102
            GD.addFactorToggle();
103
            $('select').material_select();
104
            $('.tooltipped').tooltip();
105
            GD.addGeoDbInfo($('input[name=geo_db]').val());
106
            GD.analyseValidation();
107
            $('#loading_modal').modal('close');
108
          },
109
          error: function(e, status) {
110
            GD.ajaxError(e, status);
111
          }
112
        });
113
      }
114
    });
115
  };
116
117
  GD.exemplar_results = function() {
118
    $('#exemplar_result').click(function(){
119
      $('input[name=geo_db]').val('GDS5093');
120
      $('#load_geo_db').submit();
121
    });
122
  };
123
124
  GD.analyseValidation = function() {
125
    'use strict';
126
    $('#analyse').validate({
127
      rules: {},
128
      submitHandler: function() {
129
        // Manually check if groupa / groupb is empty
130
        if ( $.isEmptyObject( $('select[name="groupa[]"]:enabled').val() )  || $.isEmptyObject( $('select[name="groupb[]"]:enabled').val() )  ) {
131
          $('.select_factors_validations').text('Please select the factors in the two groups to analyse.');
132
          return false;
133
        }
134
        $('.select_factors_validations').text('');
135
        $('#results_section').empty();
136
        var geo_db = $('input[name=geo_db]').val().toUpperCase();
137
        $('input[name="dgea_cluster_by_genes"]').val($('input[name="dgea_cluster_by_genes"]').is(':checked'));
138
        $('input[name="dgea_cluster_by_samples"]').val($('input[name="dgea_cluster_by_samples"]').is(':checked'));
139
        $('input[name="gsea_cluster_by_genes"]').val($('input[name="gsea_cluster_by_genes"]').is(':checked'));
140
        $('input[name="gsea_cluster_by_samples"]').val($('input[name="gsea_cluster_by_samples"]').is(':checked'));
141
        $('#modal_header_text').text('Analysing GEO Dataset: ' + geo_db);
142
        $('#modal_text').text('This should take a few minutes. Please leave this page open');
143
        $('#loading_modal').modal({ dismissible: false});
144
        $('#loading_modal').modal('open');
145
        $.ajax({
146
          type: 'POST',
147
          url: '/analyse',
148
          data: $('#analyse').serialize(),
149
          success: function(response) {
150
            $('#results_section').show();
151
            $('#results_section').html(response).imagesLoaded().then(function(){
152
              $('#pca_tabs').tabs(); // init material tabs
153
              $('#results_tabs').tabs(); // init material tabs
154
              GD.createPlots();
155
              $('.materialboxed').materialbox(); // init materialbox
156
              $('.select_factors input.select-dropdown').removeAttr('disabled');
157
              GD.download_all_results();
158
              GD.delete_result();
159
              GD.share_result();
160
              GD.show_GeoDB_modal();
161
              GD.remove_share();
162
              $('#loading_modal').modal('close');
163
              $('html, body').animate({
164
                  scrollTop: $('#results_section').offset().top
165
              });
166
            });
167
          },
168
          error: function(e, status) {
169
            GD.ajaxError(e, status);
170
          }
171
        });
172
        return undefined;
173
      }
174
    });
175
  };
176
177
  GD.geneExpressionAjax = function(currentRow, geneId) {
178
    $('#modal_header_text').text('Loading Graphics for Gene: ' + geneId);
179
    $('#modal_text').text('This should take a few seconds. Please leave this page open');
180
    $('#loading_modal').modal({ dismissible: false});
181
    $('#loading_modal').modal('open');
182
    var resultId = currentRow.closest('.results_card').data('result');
183
    var geoDb    = currentRow.closest('.results_card').data('geodb');
184
    var user     = currentRow.closest('.results_card').data('user');
185
    $.ajax({
186
      type: 'POST',
187
      url: '/gene_expression_graph',
188
      data: {gene_id: geneId, result_id: resultId, geo_db: geoDb, user: user},
189
      success: function(response) {
190
        currentRow.addClass('parent');
191
        currentRow.after('<tr class="child" id="'+ geneId + 'ChildRow"><td colspan="8"><div id="' + geneId + 'Plot"></div></td></tr>');
192
        GD.createExpressionPlot(response, geneId);
193
        $('#loading_modal').modal('close');
194
      },
195
      error: function(e, status) {
196
        GD.ajaxError(e, status);
197
      }
198
    });
199
  };
200
201
  GD.interactionNetworkAjax = function(currentRow, pathId) {
202
    $('#modal_header_text').text('Loading Graphics for GeneSet: ' + pathId);
203
    $('#modal_text').text('This should take a few seconds. Please leave this page open');
204
    $('#loading_modal').modal({ dismissible: false});
205
    $('#loading_modal').modal('open');
206
    var resultId = currentRow.closest('.results_card').data('result');
207
    var geoDb    = currentRow.closest('.results_card').data('geodb');
208
    var user     = currentRow.closest('.results_card').data('user');
209
    $.ajax({
210
      type: 'POST',
211
      url: '/interaction_image',
212
      data: {path_id: pathId, result_id: resultId, geo_db: geoDb, user: user},
213
      success: function(response) {
214
        currentRow.addClass('parent');
215
        currentRow.after(response);
216
        $('#loading_modal').modal('close');
217
      },
218
      error: function(e, status) {
219
        GD.ajaxError(e, status);
220
      }
221
    });  };
222
223
  GD.ajaxError = function(e, status) {
224
    var errorMessage;
225
    if (e.status == 500 || e.status == 400) {
226
      errorMessage = e.responseText;
227
      $('#results_section').show();
228
      $('#results_section').html(errorMessage);
229
      $('#loading_modal').modal('close'); // remove progress notification
230
    } else {
231
      errorMessage = e.responseText;
232
      $('#results_section').show();
233
      $('#results_section').html('<div class="card red lighten-2" role="alert"><div class="card-content white-text"><h3>Oops! GeoDiver is Drowning!</h3><p style="font-size: 1.5rem"><strong>Apologies, there was an error with your request. Please try again.</strong></p><p>Error Message:' + errorMessage + ' The server responded with the status code: ' + String(e.status) + '. Please refresh the page and try again.</p><p>If the error persists, please contact the administrator.</p></div></div>');
234
      $('#loading_modal').modal('close'); // remove progress notification
235
    }
236
  };
237
238
  GD.loadPcRedrawValidation = function() {
239
    $('#pca3d_redraw').validate({
240
      rules: {},
241
      submitHandler: function(form, event) {
242
        // Manually check if groupa / groupb is empty
243
        if ( $.isEmptyObject( $('select[name="PC3doption1"]').val() ) || $.isEmptyObject( $('select[name="PC3doption2"]').val() ) || $.isEmptyObject( $('select[name="PC3doption3"]').val() ) ) {
244
          $('.select_pc3_validations').text('Please select the Principle components to analyse.');
245
          return false;
246
        }
247
        // Manually check if PC2dOption1 == PC2dOption2
248
        if (( $('select[name="PC3doption1"]').val() === $('select[name="PC3doption2"]').val() ) ||
249
            ( $('select[name="PC3doption3"]').val() === $('select[name="PC3doption2"]').val() ) ||
250
            ( $('select[name="PC3doption1"]').val() === $('select[name="PC3doption3"]').val() ) ) {
251
          $('.select_pc3_validations').text('Please select different principal components to analyse.');
252
          return false;
253
        }
254
        $('.select_pc3_validations').text('');
255
        event.preventDefault(); // because we're not submitting at all
256
        $('#principle_plot').empty();
257
        var x = $('select[name=PC3doption1]').val();
258
        var y = $('select[name=PC3doption2]').val();
259
        var z = $('select[name=PC3doption3]').val();
260
        var jsonFile = $('#overview').data("overview-json");
261
        $.getJSON(jsonFile, function(json) {
262
          GD.create3dPCAScatterPlot(json.pcdata, x, y, z);
263
        });
264
        return undefined;
265
      }
266
    });
267
    $('#pca2d_redraw').validate({
268
      rules: {},
269
      submitHandler: function(form, event) {
270
        // Manually check if PC2dOption1 / PC2dOption2 is empty
271
        if ( $.isEmptyObject( $('select[name="PC2doption1"]').val() )  || $.isEmptyObject( $('select[name="PC2doption2"]').val() ) ) {
272
          $('.select_pc2_validations').text('Please select the principal components to analyse.');
273
          return false;
274
        }
275
        // Manually check if PC2dOption1 == PC2dOption2
276
        if ( $('select[name="PC2doption1"]').val() === $('select[name="PC2doption2"]').val() ) {
277
          $('.select_pc2_validations').text('Please select different principal components to analyse.');
278
          return false;
279
        }
280
281
        $('.select_pc2_validations').text('');
282
        event.preventDefault(); // because we're not submitting at all
283
        $('#principle_plot').empty();
284
        var x = $('select[name=PC2doption1]').val();
285
        var y = $('select[name=PC2doption2]').val();
286
        var jsonFile = $('#overview').data("overview-json");
287
        $.getJSON(jsonFile, function(json) {
288
          GD.create2dPCAScatterPlot(json.pcdata, x, y);
289
        });
290
        return undefined;
291
      }
292
    });
293
  };
294
295
296
  ///// PLOTS
297
298
  GD.createPlots = function() {
299
    var jsonFile = $('#overview').data("overview-json");
300
    $.getJSON(jsonFile, function(json) {
301
      GD.pcaPlot = GD.createPCAPLOT(json.pc.cumVar, json.pc.expVar, json.pc.pcnames);
302
      GD.pca2dScatterPlot = GD.create2dPCAScatterPlot(json.pcdata, 'PC1', 'PC2');
303
      GD.pca3dScatterPlot = GD.create3dPCAScatterPlot(json.pcdata, 'PC1', 'PC2', 'PC3');
304
305
      GD.initialiatizePcaScatterPlot(json.pc.pcnames);
306
      $('select').material_select();
307
    });
308
309
    $('#pca_tabs').on('click', '.tab a', function() {
310
      if ($(this).attr('href') === '#pca2d' ) {
311
        Plotly.Plots.resize(GD.pca2dScatterPlot);
312
      } else {
313
        Plotly.Plots.resize(GD.pca3dScatterPlot);
314
      }
315
    });
316
317
    var dgeaJsonFile = $('#DGEA').data("dgea-json");
318
    $.getJSON(dgeaJsonFile, function(json) {
319
      GD.volcanoPlot = GD.createVolcanoPlot(json.vol.logFC, json.vol.pVal, json.vol.genes);
320
      GD.initializeToptable(json.tops, 'dgea-top-table', 'dgea-top-table-wrapper');
321
    });
322
323
    var gseaJsonFile = $('#GSEA').data("gsea-json");
324
    $.getJSON(gseaJsonFile, function(json) {
325
      GD.initializeToptable(json.tops, 'gsea-top-table', 'gsea-top-table-wrapper');
326
    });
327
    window.addEventListener('resize', function() {
328
      /** global: Plotly */
329
      Plotly.Plots.resize(GD.pcaPlot);
330
      Plotly.Plots.resize(GD.volcanoPlot);
331
      Plotly.Plots.resize(GD.pca2dScatterPlot);
332
      Plotly.Plots.resize(GD.pca3dScatterPlot);
333
    });
334
    GD.addGraphTooltips();
335
  };
336
337
  GD.create2dPCAScatterPlot = function(pcdata, x, y) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
338
    var group1, group2, group1_name, group2_name, data, layout, parentWidth, PCAplotGd3, pcaPlot;
339
    group1_name = pcdata.group1[0];
340
    group2_name = pcdata.group2[0];
341
    console.log(group1_name);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
342
    console.log(group2_name);
343
    group1 = { x: pcdata[ x + '.' + group1_name], y: pcdata[y + '.' + group1_name], text: pcdata.Group1, type: 'scatter', mode: 'markers', name: group1_name, marker: { symbol: 'circle' } };
344
    group2 = { x: pcdata[ x + '.' + group2_name], y: pcdata[y + '.' + group2_name], text: pcdata.Group2, type: 'scatter', mode: 'markers', name: group2_name, marker: { symbol: 'square' } };
345
    data = [group1, group2];
346
    layout = { xaxis: { title: x }, yaxis: { title: y }, hovermode: 'closest' };
347
348
    parentWidth = 100;
349
    PCAplotGd3 = Plotly.d3.select('#pca2d_plot')
350
                       .style({width: parentWidth + '%',
351
                              'margin-left': (100 - parentWidth) / 2 + '%'});
352
    pcaPlot = PCAplotGd3.node();
353
354
    Plotly.newPlot(pcaPlot, data, layout);
355
    return pcaPlot;
356
  };
357
358
  GD.create3dPCAScatterPlot = function(pcdata, x, y, z) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
359
    var group1, group2, group1_name, group2_name, data, layout, parentWidth, PCAplotGd3, pcaPlot;
360
    group1_name = pcdata.group1[0];
361
    group2_name = pcdata.group2[0];
362
    group1 = { x: pcdata[ x + '.' + group1_name], y: pcdata[y + '.' + group1_name], z: pcdata[ z + '.' + group1_name], text: pcdata.Group1, type: 'scatter3d', mode: 'markers', name: group1_name, marker: { symbol: 'circle' } };
363
    group2 = { x: pcdata[ x + '.' + group2_name], y: pcdata[y + '.' + group2_name], z: pcdata[ z + '.' + group2_name], text: pcdata.Group2, type: 'scatter3d', mode: 'markers', name: group2_name, marker: { symbol: 'square' } };
364
    data = [group1, group2];
365
    layout = { scene: {xaxis: { title: x }, yaxis: { title: y }, zaxis: {title: z} }, hovermode: 'closest' };
366
367
    parentWidth = 100;
368
    PCAplotGd3 = Plotly.d3.select('#pca3d_plot')
369
                       .style({width: parentWidth + '%',
370
                              'margin-left': (100 - parentWidth) / 2 + '%'});
371
    pcaPlot = PCAplotGd3.node();
372
    Plotly.newPlot(pcaPlot, data, layout);
373
    return pcaPlot;
374
  };
375
376
  GD.createPCAPLOT = function(cumVar, expVar, pcaNames) {
377
    var CumulativePCA = { x: pcaNames, y: cumVar, type: 'scatter', name: 'Cumulative PCA' };
378
    var PCA = { x: pcaNames, y: expVar, type: 'scatter', name: 'PCA' };
379
    var data = [CumulativePCA, PCA];
380
    var layout = { legend: { x: 0, y: 100, traceorder: 'normal' } };
381
382
    var parentWidth = 100;
383
    var PCAplotGd3 = Plotly.d3.select('#PCA_plot')
384
                       .style({width: parentWidth + '%',
385
                              'margin-left': (100 - parentWidth) / 2 + '%'});
386
    var pcaPlot = PCAplotGd3.node();
387
    Plotly.newPlot(pcaPlot, data, layout);
388
    return pcaPlot;
389
  };
390
391
  //
392
  GD.createVolcanoPlot = function(xValues, yValues, genes) {
393
    var trace1 = { x: xValues, y: yValues, text: genes, mode: 'markers', type: 'scatter', name: 'volcano_plot', marker: { size: 7.5 } };
394
    var data = [trace1];
395
    var layout = { xaxis: { title: 'Log 2 Fold Change'}, yaxis: { title: '-Log10(P Value)' }, hovermode: 'closest' };
396
    var parentWidth = 100;
397
    var volcanoPlotGd3 = Plotly.d3.select('#volcano_plot')
398
                       .style({width: parentWidth + '%',
399
                              'margin-left': (100 - parentWidth) / 2 + '%'});
400
    var volcanoPlot = volcanoPlotGd3.node();
401
    Plotly.newPlot(volcanoPlot, data, layout);
402
    return volcanoPlot;
403
  };
404
405
  GD.createExpressionPlot = function (response, geneId) {
406
    var trace1 = { x: response.group1.x, y: response.group1.y, type: 'bar', name: response.group1_name[0] };
407
    var trace2 = { x: response.group2.x, y: response.group2.y, type: 'bar', name: response.group2_name[0] };
408
    var data = [trace1, trace2];
409
    var layout = { barmode: 'group', xaxis: { title: 'Sample', tickangle: -40, position: -0.5}, yaxis: { title: 'Expression' } };
410
    var parentWidth = 100;
411
    var expressionPlotGd3 = Plotly.d3.select('#' + geneId + 'Plot')
412
                       .style({width: parentWidth + '%',
413
                              'margin-left': (100 - parentWidth) / 2 + '%'});
414
    var expressionPlot = expressionPlotGd3.node();
415
    Plotly.newPlot(expressionPlot, data, layout);
416
    window.addEventListener('resize', function() {
417
      Plotly.Plots.resize(expressionPlot);
418
    });
419
  };
420
421
  ///// General GD functions
422
  GD.initializeToptable = function(dataset, tableId, tableWrapperId) {
423
    dataset = GD.addPlotIconToTopTable(dataset);
424
    $('#' + tableId).dataTable({
425
      "oLanguage": {
426
        "sStripClasses": "",
427
        "sSearch": "",
428
        "sSearchPlaceholder": "Enter Keywords Here",
429
        "sInfo": "_START_ -_END_ of _TOTAL_",
430
        "sLengthMenu": '<span>Rows per page:</span><select class="browser-default">' +
431
          '<option value="10">10</option>' +
432
          '<option value="20">20</option>' +
433
          '<option value="30">30</option>' +
434
          '<option value="40">40</option>' +
435
          '<option value="50">50</option>' +
436
          '<option value="-1">All</option>' +
437
          '</select></div>'
438
      },
439
      data: dataset,
440
      order: [[ 5, "asc" ]],
441
      bAutoWidth: false
442
    });
443
444
    GD.makePlotIconClickable(tableWrapperId);
445
446
    $('#' + tableWrapperId).on('click', '.search-toggle', function() {
447
      if ($('.hiddensearch').css('display') == 'none') {
448
        $('.hiddensearch').slideDown();
449
      } else {
450
        $('.hiddensearch').slideUp();
451
      }
452
    });
453
454
    $('#' + tableWrapperId).on('click', '.download-top-table', function() {
455
        $('#modal_header_text').text('Creating Download Link');
456
        $('#modal_text').text('This should take a few seconds. Please leave this page open');
457
        $('#loading_modal').modal({ dismissible: false});
458
        $('#loading_modal').modal('open');
459
        $.fileDownload($(this).attr('href'), {
460
            successCallback: function() {
461
              $('#loading_modal').modal('close');
462
            },
463
            failCallback: function() {
464
              $('#loading_modal').modal('close');
465
            }
466
        });
467
        return false; //this is critical to stop the click event which will trigger a normal file download!
468
    });
469
  };
470
471
  GD.addPlotIconToTopTable = function(dataset) {
472
    $.each(dataset, function(key, row) {
473
      row.push( '<i class="material-icons child-row-chart light-blue-text text-darken-3">insert_chart</i>' );
474
    });
475
    return (dataset);
476
  };
477
478
  GD.makePlotIconClickable = function(tableWrapperId) {
479
    $('#' + tableWrapperId).on('click', '.child-row-chart', function() {
480
      var currentRow = $(this).closest('tr');
481
      var geneId = currentRow.children('td:first').text();
482
      if ( $( '#' + geneId + 'ChildRow' ).length ) {
483
        $('#' + geneId + 'ChildRow').remove();
484
      } else {
485
        if (tableWrapperId === 'dgea-top-table-wrapper') {
486
          GD.geneExpressionAjax(currentRow, geneId);
487
        } else if (tableWrapperId === 'gsea-top-table-wrapper'){
488
          GD.interactionNetworkAjax(currentRow, geneId);
489
        }
490
      }
491
    });
492
  };
493
494
  GD.initialiatizePcaScatterPlot = function(pcnames) {
495
    $.each(pcnames, function(key,value) {
496
      $('#PC2doption1').append($("<option></option>")
497
        .attr("value", value).text(value));
498
      $('#PC2doption2').append($("<option></option>")
499
        .attr("value", value).text(value));
500
      $('#PC3doption1').append($("<option></option>")
501
        .attr("value", value).text(value));
502
      $('#PC3doption2').append($("<option></option>")
503
        .attr("value", value).text(value));
504
      $('#PC3doption3').append($("<option></option>")
505
        .attr("value", value).text(value));
506
    });
507
    GD.loadPcRedrawValidation();
508
  };
509
510
  //
511
  GD.addFactorToggle = function() {
512
    $("input:radio[name=factor]").click(function() {
513
      var target = '#' + $(this).attr('id') + '_select';
514
      if ('#' + $('.select_factors:visible').attr('id') !== target) {
515
        $('.select_factors').hide();
516
        $('.select_factors select').attr("disabled", "disabled");
517
        $(target).show();
518
        $(target + ' select').removeAttr("disabled");
519
      }
520
      $('#groupa_params').attr('data-tooltip', 'This is Group A' );
521
      $('#groupa_params').tooltip({delay: 50});
522
      $('#groupb_params').attr('data-tooltip', 'This is Group B' );
523
      $('#groupb_params').tooltip({delay: 50});
524
      GD.ensureOnlyOneSelectOption();
525
    });
526
  };
527
528
  GD.addAdvParamLogic = function() {
529
    GD.show_hide_div('#DGEA_input', '#DGEAparams');
530
    GD.show_hide_div('#GSEA_input', '#GSEAparams');
531
    GD.show_hide_div('#dgea_toptable', '#dgea_toptable_params');
532
    GD.show_hide_div('#dgea_heatmap', '#dgea_heatmap_params');
533
    GD.show_hide_div('#gsea_heatmap', '#gsea_heatmap_params');
534
    $("input:radio[name=gsea_type]").click(function() {
535
      if ( $("input:radio[name=gsea_type]:checked").val() == 'ExpVsCtrl') {
536
        $('#gage_select_control').show();
537
      } else {
538
        $('#gage_select_control').hide();
539
      }
540
    });
541
  };
542
543
  GD.show_hide_div = function(checkbox, div) {
544
    $(checkbox).change(function(){
545
      if($(this).prop("checked")) {
546
        $(div).show();
547
      } else {
548
        $(div).hide();
549
      }
550
    });
551
  };
552
553
  GD.addGeoDbInfo = function (geoAccession) {
554
    var accession = geoAccession.toUpperCase();
555
    var jsonFile = 'http://' + window.location.host + '/GeoDiver/DBs/' + accession + '.json';
556
    $.getJSON(jsonFile, function(json) {
557
      $('#dataset_accession').text(' ' + json.Accession);
558
      $('#dataset_title').text(json.Title);
559
      $('#dataset_summary').text(json.Description);
560
      $('#dataset_organism').text(json.Sample_Organism);
561
      $('#dataset_summary').text(json.Description);
562
      $('#dataset_citation').text(json.Reference);
563
    });
564
  };
565
566
  GD.addUserDropDown = function() {
567
    $('.dropdown-button').dropdown({
568
      inDuration: 300, outDuration: 225, hover: true, belowOrigin: true, alignment: 'right'
569
    });
570
  };
571
572
  GD.download_all_results = function () {
573
    $('#results_section').on('click', '#download-all-results', function(event) {
574
      event.preventDefault();
575
      $('#modal_header_text').text('Creating Download Link');
576
      $('#modal_text').text('This should take a few seconds. Please leave this page open');
577
      $('#loading_modal').modal({ dismissible: false});
578
      $('#loading_modal').modal('open');
579
      $.fileDownload($(this).data('download'), {
580
          successCallback: function() {
581
            $('#loading_modal').modal('close');
582
          },
583
          failCallback: function() {
584
            $('#loading_modal').modal('close');
585
          }
586
      });
587
      $('#loading_modal').modal('close');
588
      return false; //this is critical to stop the click event which will trigger a normal file download!
589
    });
590
  };
591
592
  GD.delete_result = function () {
593
    $('#results_section').on('click', '#delete_results', function() {
594
      $('#delete_modal').modal('open');
595
      var resultId = $(this).closest('.card').data('result');
596
      var geoDb =  $(this).closest('.card').data('geodb');
597
      $('#delete_modal').attr('data-result', resultId);
598
      $('#delete_modal').attr('data-geodb', geoDb);
599
    });
600
601
    $('.delete-results').click(function() {
602
      $('#modal_header_text').text('Deleting Result');
603
      $('#modal_text').text('This should take a few seconds. Please leave this page open');
604
      $('#loading_modal').modal({ dismissible: false});
605
      $('#loading_modal').modal('open');
606
      var resultId = $('#delete_modal').data('result');
607
      var geoDb =  $('#delete_modal').data('geodb');
608
      $.ajax({
609
        type: 'POST',
610
        url: '/delete_result',
611
        data: {result_id: resultId, geo_db: geoDb},
612
        success: function() {
613
          location.reload();
614
        },
615
        error: function(e, status) {
616
          GD.ajaxError(e, status);
617
        }
618
      });
619
    });
620
  };
621
622
  GD.show_GeoDB_modal = function () {
623
    $('#results_section').on('click', '.open_db_info_modal', function() {
624
      var accession = $(this).data('accession');
625
      GD.addGeoDbInfo(accession);
626
      $('#dbInfo').modal('open');
627
    });
628
  };
629
630
  GD.share_result = function () {
631
    $('#results_section').on('click', '#share_btn', function() {
632
      var share_link =  $(this).closest('.card').data('share-link');
633
      $('#share_the_link_btn').show();
634
      $('#share_btn').hide();
635
      $('#share_link_input').val(share_link);
636
      $('#share_link_input').prop("readonly", true);
637
      $('#share_modal').modal('open');
638
      $('#share_modal').attr('data-share-link', share_link);
639
      $('#share_link_input').select();
640
      $.ajax({
641
        type: 'POST',
642
        url: share_link,
643
        error: function(e, status) {
644
          GD.ajaxError(e, status);
645
        }
646
      });
647
    });
648
    $('#results_section').on('click', '#share_the_link_btn', function() {
649
      var share_link =  $(this).closest('.card').data('share-link');
650
      $('#share_link_input1').val(share_link);
651
      $('#share_link_input1').prop("readonly", true);
652
      $('#share_the_link_modal').modal('open');
653
      $('#share_the_link_modal').attr('data-share-link', share_link);
654
      $('#share_link_input1').select();
655
    });
656
657
    $(".share_link_input").focus(function() {
658
      $(this).select();
659
      // Work around Chrome's little problem
660
      $(this).mouseup(function() {
661
          // Prevent further mouseup intervention
662
          $(this).unbind("mouseup");
663
          return false;
664
      });
665
    });
666
  };
667
668
  GD.remove_share = function () {
669
    $('.remove_link').click(function() {
670
      var share_link =  $(this).closest('.modal').data('share-link');
671
      var remove_link = share_link.replace(/\/sh\//, '/rm/');
672
      $('#share_the_link_btn').hide();
673
      $('#share_btn').show();
674
      $('#share_modal').modal('close');
675
      $('#share_the_link_modal').modal('close');
676
      $.ajax({
677
        type: 'POST',
678
        url: remove_link,
679
        error: function(e, status) {
680
          GD.ajaxError(e, status);
681
        }
682
      });
683
    });
684
  };
685
686
  GD.ensureOnlyOneSelectOption = function() {
687
    $('.select_factors:visible select[name="groupa[]"], .select_factors:visible select[name="groupb[]"]').on('change', function() {
688
      // RESET both arrays
689
      $('.select_factors:visible select[name="groupa[]"]').siblings('ul').children('li').not(':first-child').prop('disabled', false);
690
      $('.select_factors:visible select[name="groupa[]"]').siblings('ul').children('li').not(':first-child').removeClass('disabled');
691
      $('.select_factors:visible select[name="groupa[]"]').siblings('ul').children('li').not(':first-child').find('input:checkbox').prop('disabled', false);
692
      $('.select_factors:visible select[name="groupa[]"]').children().not(':first-child').prop('disabled', false);
693
694
      $('.select_factors:visible select[name="groupb[]"]').siblings('ul').children('li').not(':first-child').prop('disabled', false);
695
      $('.select_factors:visible select[name="groupb[]"]').siblings('ul').children('li').not(':first-child').removeClass('disabled');
696
      $('.select_factors:visible select[name="groupb[]"]').siblings('ul').children('li').not(':first-child').find('input:checkbox').prop('disabled', false);
697
      $('.select_factors:visible select[name="groupb[]"]').children().not(':first-child').prop('disabled', false);
698
699
      var aValues = $('.select_factors:visible select[name="groupa[]"]').val();
700
      var bValues = $('.select_factors:visible select[name="groupb[]"]').val();
701
      var selector, valueIndex;
702
703
      $.each(aValues, function(i){
704
        selector = '.select_factors:visible select[name="groupb[]"] option[value="' + aValues[i] + '"]';
705
        $(selector).prop('disabled', true);
706
        valueIndex = $(selector).index() + 1;
707
        $('.select_factors:visible select[name="groupb[]"]').siblings('ul').children('li:nth-child('+ valueIndex +')').addClass('disabled');
708
        $('.select_factors:visible select[name="groupb[]"]').siblings('ul').children('li:nth-child('+ valueIndex +')').find('input:checkbox').prop('disabled', true);
709
      });
710
      $.each(bValues, function(i){
711
        selector = '.select_factors:visible select[name="groupa[]"] option[value="' + bValues[i] + '"]';
712
        $(selector).prop('disabled', true);
713
        valueIndex = $(selector).index() + 1;
714
        $('.select_factors:visible select[name="groupa[]"]').siblings('ul').children('li:nth-child('+ valueIndex +')').addClass('disabled');
715
        $('.select_factors:visible select[name="groupa[]"]').siblings('ul').children('li:nth-child('+ valueIndex +')').find('input:checkbox').prop('disabled', true);
716
      });
717
    });
718
  };
719
720
  GD.addGraphTooltips = function () {
721
    $('#dgea-top-table .child-row-chart').tooltip({tooltip: 'Show a graph for the inidividual expression levels for this Gene', position: 'left' });
722
    $('#gsea-top-table .child-row-chart').tooltip({tooltip: 'Show a colour coded interaction network for this pathway', position: 'left' });
723
  };
724
725
  GD.setupGoogleAuthentication = function () {
726
    gapi.auth.authorize({
727
      immediate: true,
728
      response_type: 'code',
729
      cookie_policy: 'single_host_origin',
730
      client_id: GD.CLIENT_ID,
731
      scope: 'email'
732
    });
733
    $('.login_button').on('click', function(e) {
734
      e.preventDefault();
735
      /** global: gapi */
736
      gapi.auth.authorize({
737
        immediate: false,
738
        response_type: 'code',
739
        cookie_policy: 'single_host_origin',
740
        client_id: GD.CLIENT_ID,
741
        scope: 'email'
742
      }, function(response) {
743
        if (response && !response.error) {
744
          // google authentication succeed, now post data to server.
745
          jQuery.ajax({
746
            type: 'POST',
747
            url: "/auth/google_oauth2/callback",
748
            data: response,
749
            success: function() {
750
              // TODO - just update the DOM instead of a redirect
751
              $(location).attr('href', 'http://' + window.location.host + '/analyse');
752
            }
753
          });
754
        } else {
755
          // TODO: ERROR Response google authentication failed
756
        }
757
      });
758
    });
759
  };
760
}());
761
762
(function($) {
763
  $.fn.exists = function() {return this.length>0;};
764
765
  // Fn to allow an event to fire after all images are loaded
766
  $.fn.imagesLoaded = function () {
767
    var $imgs = this.find('img[src!=""]');
768
    // if there's no images, just return an already resolved promise
769
    if (!$imgs.length) {return $.Deferred().resolve().promise();}
770
771
    // for each image, add a deferred object to the array which resolves when the image is loaded (or if loading fails)
772
    var dfds = [];
773
    $imgs.each(function(){
774
        var dfd = $.Deferred();
775
        dfds.push(dfd);
776
        /** global: Image */
777
        var img = new Image();
778
        img.onload = function(){dfd.resolve();};
779
        img.onerror = function(){dfd.resolve();};
780
        img.src = this.src;
781
    });
782
    // return a master promise object which will resolve when all the deferred objects have resolved
783
    // IE - when all the images are loaded
784
    return $.when.apply($,dfds);
785
  };
786
787
  $(function() {
788
    $('.button-collapse').sideNav();
789
    $('select').material_select();
790
    $('#login_modal').modal();
791
    if ($('#load_geo_db').length) {
792
      GD.setUpValidatorDefaults();
793
      GD.loadGeoDbValidation();
794
    }
795
    if ($('#exemplar_result').length) { GD.exemplar_results(); }
796
    GD.addUserDropDown();
797
  });
798
799
  $(function() {
800
    return $.ajax({
801
      url: 'https://apis.google.com/js/client:plus.js?onload=gpAsyncInit',
802
      dataType: 'script',
803
      cache: true
804
    });
805
  });
806
807
  window.gpAsyncInit = function() {
808
    GD.setupGoogleAuthentication();
809
  };
810
})(jQuery);
811