aboutsummaryrefslogtreecommitdiff
path: root/gn3/correlation/show_corr_results.py
blob: 55d83663634c22452f55bf3f3c655adbf62428ad (plain)
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
"""module contains code for doing correlation"""

import json
import collections
import numpy
import scipy.stats
import rpy2.robjects as ro
from flask import g
from gn3.base.data_set import create_dataset
from gn3.utility.db_tools import escape
from gn3.utility.helper_functions import get_species_dataset_trait
from gn3.utility.corr_result_helpers import normalize_values
from gn3.base.trait import create_trait
from gn3.utility import hmac
from . import correlation_functions


class CorrelationResults:
    """class for computing correlation"""
    # pylint: disable=too-many-instance-attributes
    # pylint:disable=attribute-defined-outside-init

    def __init__(self, start_vars):
        self.assertion_for_start_vars(start_vars)

    @staticmethod
    def assertion_for_start_vars(start_vars):
        # pylint: disable = E, W, R, C

        # should better ways to assert the variables
        # example includes sample
        assert("corr_type" in start_vars)
        assert(isinstance(start_vars['corr_type'], str))
        # example includes pearson
        assert('corr_sample_method' in start_vars)
        assert('corr_dataset' in start_vars)
        # means the  limit
        assert('corr_return_results' in start_vars)

        if "loc_chr" in start_vars:
            assert('min_loc_mb' in start_vars)
            assert('max_loc_mb' in start_vars)

    def get_formatted_corr_type(self):
        """method to formatt corr_types"""
        self.formatted_corr_type = ""
        if self.corr_type == "lit":
            self.formatted_corr_type += "Literature Correlation "
        elif self.corr_type == "tissue":
            self.formatted_corr_type += "Tissue Correlation "
        elif self.corr_type == "sample":
            self.formatted_corr_type += "Genetic Correlation "

        if self.corr_method == "pearson":
            self.formatted_corr_type += "(Pearson's r)"
        elif self.corr_method == "spearman":
            self.formatted_corr_type += "(Spearman's rho)"
        elif self.corr_method == "bicor":
            self.formatted_corr_type += "(Biweight r)"

    def process_samples(self, start_vars, sample_names, excluded_samples=None):
        """method to process samples"""


        if not excluded_samples:
            excluded_samples = ()

        sample_val_dict = json.loads(start_vars["sample_vals"])
        print(sample_val_dict)
        if sample_names is None:
            raise  NotImplementedError

        for sample in sample_names:
            if sample not in excluded_samples:
                value = sample_val_dict[sample]

                if not value.strip().lower() == "x":
                    self.sample_data[str(sample)] = float(value)

    def do_tissue_correlation_for_trait_list(self, tissue_dataset_id=1):
        """Given a list of correlation results (self.correlation_results),\
        gets the tissue correlation value for each"""
        # pylint: disable = E, W, R, C

        # Gets tissue expression values for the primary trait
        primary_trait_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values(
            symbol_list=[self.this_trait.symbol])

        if self.this_trait.symbol.lower() in primary_trait_tissue_vals_dict:
            primary_trait_tissue_values = primary_trait_tissue_vals_dict[self.this_trait.symbol.lower(
            )]
            gene_symbol_list = [
                trait.symbol for trait in self.correlation_results if trait.symbol]

            corr_result_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values(
                symbol_list=gene_symbol_list)

            for trait in self.correlation_results:
                if trait.symbol and trait.symbol.lower() in corr_result_tissue_vals_dict:
                    this_trait_tissue_values = corr_result_tissue_vals_dict[trait.symbol.lower(
                    )]

                    result = correlation_functions.cal_zero_order_corr_for_tiss(primary_trait_tissue_values,
                                                                                this_trait_tissue_values,
                                                                                self.corr_method)

                    trait.tissue_corr = result[0]
                    trait.tissue_pvalue = result[2]

    def do_lit_correlation_for_trait_list(self):
        # pylint: disable = E, W, R, C

        input_trait_mouse_gene_id = self.convert_to_mouse_gene_id(
            self.dataset.group.species.lower(), self.this_trait.geneid)

        for trait in self.correlation_results:

            if trait.geneid:
                trait.mouse_gene_id = self.convert_to_mouse_gene_id(
                    self.dataset.group.species.lower(), trait.geneid)
            else:
                trait.mouse_gene_id = None

            if trait.mouse_gene_id and str(trait.mouse_gene_id).find(";") == -1:
                result = g.db.execute(
                    """SELECT value
                       FROM LCorrRamin3
                       WHERE GeneId1='%s' and
                             GeneId2='%s'
                    """ % (escape(str(trait.mouse_gene_id)), escape(str(input_trait_mouse_gene_id)))
                ).fetchone()
                if not result:
                    result = g.db.execute("""SELECT value
                       FROM LCorrRamin3
                       WHERE GeneId2='%s' and
                             GeneId1='%s'
                    """ % (escape(str(trait.mouse_gene_id)), escape(str(input_trait_mouse_gene_id)))
                    ).fetchone()

                if result:
                    lit_corr = result.value
                    trait.lit_corr = lit_corr
                else:
                    trait.lit_corr = 0
            else:
                trait.lit_corr = 0

    def do_lit_correlation_for_all_traits(self):
        """method for lit_correlation for all traits"""
        # pylint: disable = E, W, R, C
        input_trait_mouse_gene_id = self.convert_to_mouse_gene_id(
            self.dataset.group.species.lower(), self.this_trait.geneid)

        lit_corr_data = {}
        for trait, gene_id in list(self.trait_geneid_dict.items()):
            mouse_gene_id = self.convert_to_mouse_gene_id(
                self.dataset.group.species.lower(), gene_id)

            if mouse_gene_id and str(mouse_gene_id).find(";") == -1:
                #print("gene_symbols:", input_trait_mouse_gene_id + " / " + mouse_gene_id)
                result = g.db.execute(
                    """SELECT value
                       FROM LCorrRamin3
                       WHERE GeneId1='%s' and
                             GeneId2='%s'
                    """ % (escape(mouse_gene_id), escape(input_trait_mouse_gene_id))
                ).fetchone()
                if not result:
                    result = g.db.execute("""SELECT value
                       FROM LCorrRamin3
                       WHERE GeneId2='%s' and
                             GeneId1='%s'
                    """ % (escape(mouse_gene_id), escape(input_trait_mouse_gene_id))
                    ).fetchone()
                if result:
                    #print("result:", result)
                    lit_corr = result.value
                    lit_corr_data[trait] = [gene_id, lit_corr]
                else:
                    lit_corr_data[trait] = [gene_id, 0]
            else:
                lit_corr_data[trait] = [gene_id, 0]

        lit_corr_data = collections.OrderedDict(sorted(list(lit_corr_data.items()),
                                                       key=lambda t: -abs(t[1][1])))

        return lit_corr_data

    def do_tissue_correlation_for_all_traits(self, tissue_dataset_id=1):
        # Gets tissue expression values for the primary trait
        # pylint: disable = E, W, R, C
        primary_trait_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values(
            symbol_list=[self.this_trait.symbol])

        if self.this_trait.symbol.lower() in primary_trait_tissue_vals_dict:
            primary_trait_tissue_values = primary_trait_tissue_vals_dict[self.this_trait.symbol.lower(
            )]

            #print("trait_gene_symbols: ", pf(trait_gene_symbols.values()))
            corr_result_tissue_vals_dict = correlation_functions.get_trait_symbol_and_tissue_values(
                symbol_list=list(self.trait_symbol_dict.values()))

            #print("corr_result_tissue_vals: ", pf(corr_result_tissue_vals_dict))

            #print("trait_gene_symbols: ", pf(trait_gene_symbols))

            tissue_corr_data = {}
            for trait, symbol in list(self.trait_symbol_dict.items()):
                if symbol and symbol.lower() in corr_result_tissue_vals_dict:
                    this_trait_tissue_values = corr_result_tissue_vals_dict[symbol.lower(
                    )]

                    result = correlation_functions.cal_zero_order_corr_for_tiss(primary_trait_tissue_values,
                                                                                this_trait_tissue_values,
                                                                                self.corr_method)

                    tissue_corr_data[trait] = [symbol, result[0], result[2]]

            tissue_corr_data = collections.OrderedDict(sorted(list(tissue_corr_data.items()),
                                                              key=lambda t: -abs(t[1][1])))

    def get_sample_r_and_p_values(self, trait, target_samples):
        """Calculates the sample r (or rho) and p-value

        Given a primary trait and a target trait's sample values,
        calculates either the pearson r or spearman rho and the p-value
        using the corresponding scipy functions.

        """
        # pylint: disable = E, W, R, C
        self.this_trait_vals = []
        target_vals = []

        for index, sample in enumerate(self.target_dataset.samplelist):
            if sample in self.sample_data:
                sample_value = self.sample_data[sample]
                target_sample_value = target_samples[index]
                self.this_trait_vals.append(sample_value)
                target_vals.append(target_sample_value)

        self.this_trait_vals, target_vals, num_overlap = normalize_values(
            self.this_trait_vals, target_vals)

        if num_overlap > 5:
            # ZS: 2015 could add biweight correlation, see http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3465711/
            if self.corr_method == 'bicor':
                sample_r, sample_p = do_bicor(
                    self.this_trait_vals, target_vals)

            elif self.corr_method == 'pearson':
                sample_r, sample_p = scipy.stats.pearsonr(
                    self.this_trait_vals, target_vals)

            else:
                sample_r, sample_p = scipy.stats.spearmanr(
                    self.this_trait_vals, target_vals)

            if numpy.isnan(sample_r):
                pass

            else:

                self.correlation_data[trait] = [
                    sample_r, sample_p, num_overlap]

    def convert_to_mouse_gene_id(self, species=None, gene_id=None):
        """If the species is rat or human, translate the gene_id to the mouse geneid

        If there is no input gene_id or there's no corresponding mouse gene_id, return None

        """
        if not gene_id:
            return None

        mouse_gene_id = None
        if "species" == "mouse":
            mouse_gene_id = gene_id

        elif species == 'rat':
            query = """SELECT mouse
                   FROM GeneIDXRef
                   WHERE rat='%s'""" % escape(gene_id)

            result = g.db.execute(query).fetchone()
            if result != None:
                mouse_gene_id = result.mouse

        elif species == "human":

            query = """SELECT mouse
                   FROM GeneIDXRef
                   WHERE human='%s'""" % escape(gene_id)

            result = g.db.execute(query).fetchone()
            if result != None:
                mouse_gene_id = result.mouse

        return mouse_gene_id

    def do_correlation(self, start_vars, create_dataset=create_dataset,
                       create_trait=create_trait,
                       get_species_dataset_trait=get_species_dataset_trait):
        # pylint: disable = E, W, R, C
        # probably refactor start_vars being passed twice
        # this method  aims to replace the do_correlation but also add dependendency injection
        # to enable testing

        # should maybe refactor below code more or less works the same
        if start_vars["dataset"] == "Temp":
            self.dataset = create_dataset(
                dataset_name="Temp", dataset_type="Temp", group_name=start_vars['group'])

            self.trait_id = start_vars["trait_id"]

            self.this_trait = create_trait(dataset=self.dataset,
                                           name=self.trait_id,
                                           cellid=None)

        else:

            get_species_dataset_trait(self, start_vars)

        corr_samples_group = start_vars['corr_samples_group']
        self.sample_data = {}
        self.corr_type = start_vars['corr_type']
        self.corr_method = start_vars['corr_sample_method']
        self.min_expr = float(
            start_vars["min_expr"]) if start_vars["min_expr"] != "" else None
        self.p_range_lower = float(
            start_vars["p_range_lower"]) if start_vars["p_range_lower"] != "" else -1.0
        self.p_range_upper = float(
            start_vars["p_range_upper"]) if start_vars["p_range_upper"] != "" else 1.0

        if ("loc_chr" in start_vars and "min_loc_mb" in start_vars and "max_loc_mb" in start_vars):
            self.location_type = str(start_vars['location_type'])
            self.location_chr = str(start_vars['loc_chr'])

            try:

                # the code is below is basically a temporary fix
                self.min_location_mb = int(start_vars['min_loc_mb'])
                self.max_location_mb = int(start_vars['max_loc_mb'])
            except Exception as e:
                self.min_location_mb = None
                self.max_location_mb = None

        else:
            self.location_type = self.location_chr = self.min_location_mb = self.max_location_mb = None

        self.get_formatted_corr_type()

        self.return_number = int(start_vars['corr_return_results'])

        primary_samples = self.dataset.group.samplelist


        # The two if statements below append samples to the sample list based upon whether the user
        # rselected Primary Samples Only, Other Samples Only, or All Samples

        if self.dataset.group.parlist != None:
            primary_samples += self.dataset.group.parlist

        if self.dataset.group.f1list != None:

            primary_samples += self.dataset.group.f1list

        # If either BXD/whatever Only or All Samples, append all of that group's samplelist

        if corr_samples_group != 'samples_other':
                
            # print("primary samples are *****",primary_samples)

            self.process_samples(start_vars, primary_samples)

        if corr_samples_group != 'samples_primary':
            if corr_samples_group == 'samples_other':
                primary_samples = [x for x in primary_samples if x not in (
                    self.dataset.group.parlist + self.dataset.group.f1list)]

            self.process_samples(start_vars, list(self.this_trait.data.keys()), primary_samples)

        self.target_dataset = create_dataset(start_vars['corr_dataset'])
        # when you add code to retrieve the trait_data for target dataset got gets very slow
        import time

        init_time = time.time()
        self.target_dataset.get_trait_data(list(self.sample_data.keys()))

        aft_time = time.time() - init_time

        self.header_fields = get_header_fields(
            self.target_dataset.type, self.corr_method)

        if self.target_dataset.type == "ProbeSet":
            self.filter_cols = [7, 6]

        elif self.target_dataset.type == "Publish":
            self.filter_cols = [6, 0]

        else:
            self.filter_cols = [4, 0]

        self.correlation_results = []

        self.correlation_data = {}

        if self.corr_type == "tissue":
            self.trait_symbol_dict = self.dataset.retrieve_genes("Symbol")

            tissue_corr_data = self.do_tissue_correlation_for_all_traits()
            if tissue_corr_data != None:
                for trait in list(tissue_corr_data.keys())[:self.return_number]:
                    self.get_sample_r_and_p_values(
                        trait, self.target_dataset.trait_data[trait])
            else:
                for trait, values in list(self.target_dataset.trait_data.items()):
                    self.get_sample_r_and_p_values(trait, values)

        elif self.corr_type == "lit":
            self.trait_geneid_dict = self.dataset.retrieve_genes("GeneId")
            lit_corr_data = self.do_lit_correlation_for_all_traits()

            for trait in list(lit_corr_data.keys())[:self.return_number]:
                self.get_sample_r_and_p_values(
                    trait, self.target_dataset.trait_data[trait])

        elif self.corr_type == "sample":
            for trait, values in list(self.target_dataset.trait_data.items()):
                self.get_sample_r_and_p_values(trait, values)

        self.correlation_data = collections.OrderedDict(sorted(list(self.correlation_data.items()),
                                                               key=lambda t: -abs(t[1][0])))

        # ZS: Convert min/max chromosome to an int for the location range option

        """
        took 20.79 seconds took compute all the above majority of time taken on retrieving target dataset trait
        info
        """

        initial_time_chr = time.time()

        range_chr_as_int = None
        for order_id, chr_info in list(self.dataset.species.chromosomes.chromosomes.items()):
            if 'loc_chr' in start_vars:
                if chr_info.name == self.location_chr:
                    range_chr_as_int = order_id

        for _trait_counter, trait in enumerate(list(self.correlation_data.keys())[:self.return_number]):
            trait_object = create_trait(
                dataset=self.target_dataset, name=trait, get_qtl_info=True, get_sample_info=False)
            if not trait_object:
                continue

            chr_as_int = 0
            for order_id, chr_info in list(self.dataset.species.chromosomes.chromosomes.items()):
                if self.location_type == "highest_lod":
                    if chr_info.name == trait_object.locus_chr:
                        chr_as_int = order_id
                else:
                    if chr_info.name == trait_object.chr:
                        chr_as_int = order_id

            if (float(self.correlation_data[trait][0]) >= self.p_range_lower and
                    float(self.correlation_data[trait][0]) <= self.p_range_upper):

                if (self.target_dataset.type == "ProbeSet" or self.target_dataset.type == "Publish") and bool(trait_object.mean):
                    if (self.min_expr != None) and (float(trait_object.mean) < self.min_expr):
                        continue

                if range_chr_as_int != None and (chr_as_int != range_chr_as_int):
                    continue
                if self.location_type == "highest_lod":
                    if (self.min_location_mb != None) and (float(trait_object.locus_mb) < float(self.min_location_mb)):
                        continue
                    if (self.max_location_mb != None) and (float(trait_object.locus_mb) > float(self.max_location_mb)):
                        continue
                else:
                    if (self.min_location_mb != None) and (float(trait_object.mb) < float(self.min_location_mb)):
                        continue
                    if (self.max_location_mb != None) and (float(trait_object.mb) > float(self.max_location_mb)):
                        continue

                (trait_object.sample_r,
                 trait_object.sample_p,
                 trait_object.num_overlap) = self.correlation_data[trait]

                # Set some sane defaults
                trait_object.tissue_corr = 0
                trait_object.tissue_pvalue = 0
                trait_object.lit_corr = 0
                if self.corr_type == "tissue" and tissue_corr_data != None:
                    trait_object.tissue_corr = tissue_corr_data[trait][1]
                    trait_object.tissue_pvalue = tissue_corr_data[trait][2]
                elif self.corr_type == "lit":
                    trait_object.lit_corr = lit_corr_data[trait][1]

                self.correlation_results.append(trait_object)

        """
        above takes time with respect to size of traits i.e n=100,500,.....t_size
        """

        if self.corr_type != "lit" and self.dataset.type == "ProbeSet" and self.target_dataset.type == "ProbeSet":
            # self.do_lit_correlation_for_trait_list()
            self.do_lit_correlation_for_trait_list()

        if self.corr_type != "tissue" and self.dataset.type == "ProbeSet" and self.target_dataset.type == "ProbeSet":
            self.do_tissue_correlation_for_trait_list()
            # self.do_lit_correlation_for_trait_list()

        self.json_results = generate_corr_json(
            self.correlation_results, self.this_trait, self.dataset, self.target_dataset)

        # org mode by bons

        # DVORAKS
        # klavaro for touch typing
        # archwiki for documentation
        # exwm for window manager ->13

        # will fit perfectly with genenetwork 2 with change of anything if return self

        # alternative for this
        return self.json_results
        # return {
        #     # "Results": "succeess",
        #     # "return_number": self.return_number,
        #     # "primary_samples": primary_samples,
        #     # "time_taken": 12,
        #     # "correlation_data": self.correlation_data,
        #     "correlation_json": self.json_results
        # }


def do_bicor(this_trait_vals, target_trait_vals):
    # pylint: disable = E, W, R, C
    r_library = ro.r["library"]             # Map the library function
    r_options = ro.r["options"]             # Map the options function

    r_library("WGCNA")
    r_bicor = ro.r["bicorAndPvalue"]        # Map the bicorAndPvalue function

    r_options(stringsAsFactors=False)

    this_vals = ro.Vector(this_trait_vals)
    target_vals = ro.Vector(target_trait_vals)

    the_r, the_p, _fisher_transform, _the_t, _n_obs = [
        numpy.asarray(x) for x in r_bicor(x=this_vals, y=target_vals)]

    return the_r, the_p


def get_header_fields(data_type, corr_method):
    """function to get header fields when doing correlation"""
    if data_type == "ProbeSet":
        if corr_method == "spearman":

            header_fields = ['Index',
                             'Record',
                             'Symbol',
                             'Description',
                             'Location',
                             'Mean',
                             'Sample rho',
                             'N',
                             'Sample p(rho)',
                             'Lit rho',
                             'Tissue rho',
                             'Tissue p(rho)',
                             'Max LRS',
                             'Max LRS Location',
                             'Additive Effect']

        else:
            header_fields = ['Index',
                             'Record',
                             'Abbreviation',
                             'Description',
                             'Mean',
                             'Authors',
                             'Year',
                             'Sample r',
                             'N',
                             'Sample p(r)',
                             'Max LRS',
                             'Max LRS Location',
                             'Additive Effect']

    elif data_type == "Publish":
        if corr_method == "spearman":

            header_fields = ['Index',
                             'Record',
                             'Abbreviation',
                             'Description',
                             'Mean',
                             'Authors',
                             'Year',
                             'Sample rho',
                             'N',
                             'Sample p(rho)',
                             'Max LRS',
                             'Max LRS Location',
                             'Additive Effect']

        else:
            header_fields = ['Index',
                             'Record',
                             'Abbreviation',
                             'Description',
                             'Mean',
                             'Authors',
                             'Year',
                             'Sample r',
                             'N',
                             'Sample p(r)',
                             'Max LRS',
                             'Max LRS Location',
                             'Additive Effect']

    else:
        if corr_method == "spearman":
            header_fields = ['Index',
                             'ID',
                             'Location',
                             'Sample rho',
                             'N',
                             'Sample p(rho)']

        else:
            header_fields = ['Index',
                             'ID',
                             'Location',
                             'Sample r',
                             'N',
                             'Sample p(r)']

    return header_fields


def generate_corr_json(corr_results, this_trait, dataset, target_dataset, for_api=False):
    """function to generate corr json data"""
    #todo refactor this function
    results_list = []
    for i, trait in enumerate(corr_results):
        if trait.view == False:
            continue
        results_dict = {}
        results_dict['index'] = i + 1
        results_dict['trait_id'] = trait.name
        results_dict['dataset'] = trait.dataset.name
        results_dict['hmac'] = hmac.data_hmac(
            '{}:{}'.format(trait.name, trait.dataset.name))
        if target_dataset.type == "ProbeSet":
            results_dict['symbol'] = trait.symbol
            results_dict['description'] = "N/A"
            results_dict['location'] = trait.location_repr
            results_dict['mean'] = "N/A"
            results_dict['additive'] = "N/A"
            if bool(trait.description_display):
                results_dict['description'] = trait.description_display
            if bool(trait.mean):
                results_dict['mean'] = f"{float(trait.mean):.3f}"
            try:
                results_dict['lod_score'] = f"{float(trait.LRS_score_repr) / 4.61:.1f}"
            except:
                results_dict['lod_score'] = "N/A"
            results_dict['lrs_location'] = trait.LRS_location_repr
            if bool(trait.additive):
                results_dict['additive'] = f"{float(trait.additive):.3f}"
            results_dict['sample_r'] = f"{float(trait.sample_r):.3f}"
            results_dict['num_overlap'] = trait.num_overlap
            results_dict['sample_p'] = f"{float(trait.sample_p):.3e}"
            results_dict['lit_corr'] = "--"
            results_dict['tissue_corr'] = "--"
            results_dict['tissue_pvalue'] = "--"
            if bool(trait.lit_corr):
                results_dict['lit_corr'] = f"{float(trait.lit_corr):.3f}"
            if bool(trait.tissue_corr):
                results_dict['tissue_corr'] = f"{float(trait.tissue_corr):.3f}"
                results_dict['tissue_pvalue'] = f"{float(trait.tissue_pvalue):.3e}"
        elif target_dataset.type == "Publish":
            results_dict['abbreviation_display'] = "N/A"
            results_dict['description'] = "N/A"
            results_dict['mean'] = "N/A"
            results_dict['authors_display'] = "N/A"
            results_dict['additive'] = "N/A"
            if for_api:
                results_dict['pubmed_id'] = "N/A"
                results_dict['year'] = "N/A"
            else:
                results_dict['pubmed_link'] = "N/A"
                results_dict['pubmed_text'] = "N/A"

            if bool(trait.abbreviation):
                results_dict['abbreviation_display'] = trait.abbreviation
            if bool(trait.description_display):
                results_dict['description'] = trait.description_display
            if bool(trait.mean):
                results_dict['mean'] = f"{float(trait.mean):.3f}"
            if bool(trait.authors):
                authors_list = trait.authors.split(',')
                if len(authors_list) > 6:
                    results_dict['authors_display'] = ", ".join(
                        authors_list[:6]) + ", et al."
                else:
                    results_dict['authors_display'] = trait.authors
            if bool(trait.pubmed_id):
                if for_api:
                    results_dict['pubmed_id'] = trait.pubmed_id
                    results_dict['year'] = trait.pubmed_text
                else:
                    results_dict['pubmed_link'] = trait.pubmed_link
                    results_dict['pubmed_text'] = trait.pubmed_text
            try:
                results_dict['lod_score'] = f"{float(trait.LRS_score_repr) / 4.61:.1f}"
            except:
                results_dict['lod_score'] = "N/A"
            results_dict['lrs_location'] = trait.LRS_location_repr
            if bool(trait.additive):
                results_dict['additive'] = f"{float(trait.additive):.3f}"
            results_dict['sample_r'] = f"{float(trait.sample_r):.3f}"
            results_dict['num_overlap'] = trait.num_overlap
            results_dict['sample_p'] = f"{float(trait.sample_p):.3e}"
        else:
            results_dict['location'] = trait.location_repr
            results_dict['sample_r'] = f"{float(trait.sample_r):.3f}"
            results_dict['num_overlap'] = trait.num_overlap
            results_dict['sample_p'] = f"{float(trait.sample_p):.3e}"

        results_list.append(results_dict)

    return json.dumps(results_list)