aboutsummaryrefslogtreecommitdiff
path: root/wqflask/wqflask/static/new/javascript/lod_chart.coffee
blob: 777aac2a35c63db338d3927f28d83b5e1e05ea66 (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
lodchart = () ->
    width = 800
    height = 500
    margin = {left:60, top:40, right:40, bottom: 40, inner:5}
    axispos = {xtitle:25, ytitle:30, xlabel:5, ylabel:5}
    titlepos = 20
    ylim = null
    additive_ylim = null
    nyticks = 5
    yticks = null
    additive_yticks = null
    chrGap = 8
    darkrect = "#F1F1F9"
    lightrect = "#FBFBFF" 
    lodlinecolor = "darkslateblue"
    additivelinecolor = "red"
    linewidth = 2
    suggestivecolor = "gainsboro"
    significantcolor = "#EBC7C7"
    pointcolor = "#E9CFEC" # pink
    pointsize = 0 # default = no visible points at markers
    pointstroke = "black"
    title = ""
    xlab = "Chromosome"
    ylab = "LRS score"
    additive_ylab = "Additive Effect"
    rotate_ylab = null
    yscale = d3.scale.linear()
    additive_yscale = d3.scale.linear()
    xscale = null
    pad4heatmap = false
    lodcurve = null
    lodvarname = null
    markerSelect = null
    chrSelect = null
    pointsAtMarkers = true
  
    ## the main function
    chart = (selection) ->
      selection.each (data) ->
        
        console.log("data:", data)
        
        lodvarname = lodvarname ? data.lodnames[0]
        data[lodvarname] = (Math.abs(x) for x in data[lodvarname]) # take absolute values
        data['additive'] = (Math.abs(x) for x in data['additive'])
        ylim = ylim ? [0, d3.max(data[lodvarname])]
        if data['additive'].length > 0
            additive_ylim = additive_ylim ? [0, d3.max(data['additive'])]
        lodvarnum = data.lodnames.indexOf(lodvarname)
  
        # Select the svg element, if it exists.
        svg = d3.select(this).selectAll("svg").data([data])
  
        # Otherwise, create the skeletal chart.
        gEnter = svg.enter().append("svg").append("g")
  
        # Update the outer dimensions.
        svg.attr("width", width+margin.left+margin.right)
           .attr("height", height+margin.top+margin.bottom)
  
        # Update the inner dimensions.
        g = svg.select("g")
  
        # box
        g.append("rect")
         .attr("x", margin.left)
         .attr("y", margin.top)
         .attr("height", height)
         .attr("width", width)
         .attr("fill", darkrect)
         .attr("stroke", "none")
  
        yscale.domain(ylim)
              .range([height+margin.top, margin.top+margin.inner])
        
        if data['additive'].length > 0
            additive_yscale.domain(additive_ylim)
                  .range([height+margin.top, margin.top+margin.inner + height/2])
  
        # if yticks not provided, use nyticks to choose pretty ones
        yticks = yticks ? yscale.ticks(nyticks)
        if data['additive'].length > 0
            additive_yticks = additive_yticks ? additive_yscale.ticks(nyticks)
  
        # reorganize lod,pos by chromosomes
        data = reorgLodData(data, lodvarname)
  
        # add chromosome scales (for x-axis)
        data = chrscales(data, width, chrGap, margin.left, pad4heatmap)
        xscale = data.xscale
  
        # chr rectangles
        chrSelect =
                  g.append("g").attr("class", "chrRect")
                   .selectAll("empty")
                   .data(data.chrnames)
                   .enter()
                   .append("rect")
                   .attr("id", (d) -> "chrrect#{d[0]}")
                   .attr("x", (d,i) ->
                     return data.chrStart[i] if i==0 and pad4heatmap
                     data.chrStart[i]-chrGap/2)
                   .attr("width", (d,i) ->
                      return data.chrEnd[i] - data.chrStart[i]+chrGap/2 if (i==0 or i+1 == data.chrnames.length) and pad4heatmap
                      data.chrEnd[i] - data.chrStart[i]+chrGap)
                   .attr("y", margin.top)
                   .attr("height", height)
                   .attr("fill", (d,i) ->
                      return darkrect if i % 2
                      lightrect)
                   .attr("stroke", "none")
                   .on("click", (d) ->
                      redraw_plot(d)
                    )   
  
        # x-axis labels
        xaxis = g.append("g").attr("class", "x axis")
        xaxis.selectAll("empty")
             .data(data.chrnames)
             .enter()
             .append("text")
             .text((d) -> d[0])
             .attr("x", (d,i) -> (data.chrStart[i]+data.chrEnd[i])/2)
             .attr("y", margin.top+height+axispos.xlabel)
             .attr("cursor", "pointer")
             .on("click", (d) ->
                 redraw_plot(d)
              )   
             
        xaxis.append("text").attr("class", "title")
             .attr("y", margin.top+height+axispos.xtitle)
             .attr("x", margin.left+width/2)
             .text(xlab)

  
        redraw_plot = (chr_ob) ->
             console.log("chr_name is:", chr_ob[0])
             console.log("chr_length is:", chr_ob[1])
             $('#topchart').remove()
             $('#chart_container').append('<div class="qtlcharts" id="topchart"></div>')
             chr_plot = new Chr_Interval_Map(600, 1200, chr_ob)
  
        # y-axis
        rotate_ylab = rotate_ylab ? (ylab.length > 1)
        yaxis = g.append("g").attr("class", "y axis")
        yaxis.selectAll("empty")
             .data(yticks)
             .enter()
             .append("line")
             .attr("y1", (d) -> yscale(d))
             .attr("y2", (d) -> yscale(d))
             .attr("x1", margin.left)
             .attr("x2", margin.left+7)
             .attr("fill", "none")
             .attr("stroke", "white")
             .attr("stroke-width", 1)
             .style("pointer-events", "none")
             
        yaxis.selectAll("empty")
             .data(yticks)
             .enter()
             .append("text")
             .attr("y", (d) -> yscale(d))
             .attr("x", margin.left-axispos.ylabel)
             .attr("fill", "blue")
             .text((d) -> formatAxis(yticks)(d))
             
        yaxis.append("text").attr("class", "title")
             .attr("y", margin.top+height/2)
             .attr("x", margin.left-axispos.ytitle)
             .text(ylab)
             .attr("transform", if rotate_ylab then "rotate(270,#{margin.left-axispos.ytitle},#{margin.top+height/2})" else "")
  
        if data['additive'].length > 0
            rotate_additive_ylab = rotate_additive_ylab ? (additive_ylab.length > 1)
            additive_yaxis = g.append("g").attr("class", "y axis")
            additive_yaxis.selectAll("empty")
                 .data(additive_yticks)
                 .enter()
                 .append("line")
                 .attr("y1", (d) -> additive_yscale(d))
                 .attr("y2", (d) -> additive_yscale(d))
                 .attr("x1", margin.left + width)
                 .attr("x2", margin.left + width - 7)
                 .attr("fill", "none")
                 .attr("stroke", "white")
                 .attr("stroke-width", 1)
                 .style("pointer-events", "none")
        
            additive_yaxis.selectAll("empty")
                 .data(additive_yticks)
                 .enter()
                 .append("text")
                 .attr("y", (d) -> additive_yscale(d))
                 .attr("x", (d) -> margin.left + width + axispos.ylabel + 20)
                 .attr("fill", "green")
                 .text((d) -> formatAxis(additive_yticks)(d))
                 
            additive_yaxis.append("text").attr("class", "title")
                 .attr("y", margin.top+1.5*height)
                 .attr("x", margin.left + width + axispos.ytitle)
                 .text(additive_ylab)
                 .attr("transform", if rotate_additive_ylab then "rotate(270,#{margin.left + width + axispos.ytitle}, #{margin.top+height*1.5})" else "")
  
  
        suggestive_bar = g.append("g").attr("class", "suggestive")
        suggestive_bar.selectAll("empty")
             .data([data.suggestive])
             .enter()
             .append("line")
             .attr("y1", (d) -> yscale(d))
             .attr("y2", (d) -> yscale(d))
             .attr("x1", margin.left)
             .attr("x2", margin.left+width)
             .attr("fill", "none")
             .attr("stroke", suggestivecolor)
             .attr("stroke-width", 5)
             .style("pointer-events", "none")

        suggestive_bar = g.append("g").attr("class", "significant")
        suggestive_bar.selectAll("empty")
             .data([data.significant])
             .enter()
             .append("line")
             .attr("y1", (d) -> yscale(d))
             .attr("y2", (d) -> yscale(d))
             .attr("x1", margin.left)
             .attr("x2", margin.left+width)
             .attr("fill", "none")
             .attr("stroke", significantcolor)
             .attr("stroke-width", 5)
             .style("pointer-events", "none")
  
        # lod curves by chr
        lodcurve = (chr, lodcolumn) ->
            d3.svg.line()
              .x((d) -> xscale[chr](d))
              .y((d,i) -> yscale(data.lodByChr[chr][i][lodcolumn]))
              
        if data['additive'].length > 0
            additivecurve = (chr, lodcolumn) ->
                d3.svg.line()
                  .x((d) -> xscale[chr](d))
                  .y((d,i) -> additive_yscale(data.additiveByChr[chr][i][lodcolumn]))
  
        curves = g.append("g").attr("id", "curves")
  
        for chr in data.chrnames
          curves.append("path")
                .datum(data.posByChr[chr[0]])
                .attr("d", lodcurve(chr[0], lodvarnum))
                .attr("stroke", lodlinecolor)
                .attr("fill", "none")
                .attr("stroke-width", linewidth)
                .style("pointer-events", "none")
        
        if data['additive'].length > 0
            for chr in data.chrnames
                curves.append("path")
                      .datum(data.posByChr[chr[0]])
                      .attr("d", additivecurve(chr[0], lodvarnum))
                      .attr("stroke", additivelinecolor)
                      .attr("fill", "none")
                      .attr("stroke-width", 1)
                      .style("pointer-events", "none")
  
        # points at markers
        if pointsize > 0
          markerpoints = g.append("g").attr("id", "markerpoints_visible")
          markerpoints.selectAll("empty")
                      .data(data.markers)
                      .enter()
                      .append("circle")
                      .attr("cx", (d) -> xscale[d.chr](d.pos))
                      .attr("cy", (d) -> yscale(d.lod))
                      .attr("r", pointsize)
                      .attr("fill", pointcolor)
                      .attr("stroke", pointstroke)
                      .attr("pointer-events", "hidden")
  
        # title
        titlegrp = g.append("g").attr("class", "title")
         .append("text")
         .attr("x", margin.left+width/2)
         .attr("y", margin.top-titlepos)
         .text(title)
  
        # another box around edge
        g.append("rect")
         .attr("x", margin.left)
         .attr("y", margin.top)
         .attr("height", height)
         .attr("width", () ->
            return(data.chrEnd[-1..][0]-margin.left) if pad4heatmap
            data.chrEnd[-1..][0]-margin.left+chrGap/2)
         .attr("fill", "none")
         .attr("stroke", "black")
         .attr("stroke-width", "none")
  
        if pointsAtMarkers
          # these hidden points are what gets selected...a bit larger
          hiddenpoints = g.append("g").attr("id", "markerpoints_hidden")
  
          markertip = d3.tip()
                        .attr('class', 'd3-tip')
                        .html((d) ->
                          [d.name, " LRS = #{d3.format('.2f')(d.lod)}"])
                        .direction("e")
                        .offset([0,10])
          svg.call(markertip)
  
          markerSelect =
            hiddenpoints.selectAll("empty")
                        .data(data.markers)
                        .enter()
                        .append("circle")
                        .attr("cx", (d) -> xscale[d.chr](d.pos))
                        .attr("cy", (d) -> yscale(d.lod))
                        .attr("id", (d) -> d.name)
                        .attr("r", d3.max([pointsize*2, 3]))
                        .attr("opacity", 0)
                        .attr("fill", pointcolor)
                        .attr("stroke", pointstroke)
                        .attr("stroke-width", "1")
                        .on "mouseover.paneltip", (d) ->
                           d3.select(this).attr("opacity", 1)
                           markertip.show(d)
                        .on "mouseout.paneltip", ->
                           d3.select(this).attr("opacity", 0)
                                          .call(markertip.hide)
  

  
    ## configuration parameters
    chart.width = (value) ->
      return width unless arguments.length
      width = value
      chart
  
    chart.height = (value) ->
      return height unless arguments.length
      height = value
      chart
  
    chart.margin = (value) ->
      return margin unless arguments.length
      margin = value
      chart
  
    chart.titlepos = (value) ->
      return titlepos unless arguments.length
      titlepos
      chart
  
    chart.axispos = (value) ->
      return axispos unless arguments.length
      axispos = value
      chart
  
    chart.ylim = (value) ->
      return ylim unless arguments.length
      ylim = value
      chart
      
    #if data['additive'].length > 0
    chart.additive_ylim = (value) ->
      return additive_ylim unless arguments.length
      additive_ylim = value
      chart
      
    chart.nyticks = (value) ->
      return nyticks unless arguments.length
      nyticks = value
      chart
  
    chart.yticks = (value) ->
      return yticks unless arguments.length
      yticks = value
      chart
  
    chart.chrGap = (value) ->
      return chrGap unless arguments.length
      chrGap = value
      chart
  
    chart.darkrect = (value) ->
      return darkrect unless arguments.length
      darkrect = value
      chart
  
    chart.lightrect = (value) ->
      return lightrect unless arguments.length
      lightrect = value
      chart
  
    chart.linecolor = (value) ->
      return linecolor unless arguments.length
      linecolor = value
      chart
  
    chart.linewidth = (value) ->
      return linewidth unless arguments.length
      linewidth = value
      chart
  
    chart.pointcolor = (value) ->
      return pointcolor unless arguments.length
      pointcolor = value
      chart
  
    chart.pointsize = (value) ->
      return pointsize unless arguments.length
      pointsize = value
      chart
  
    chart.pointstroke = (value) ->
      return pointstroke unless arguments.length
      pointstroke = value
      chart
  
    chart.title = (value) ->
      return title unless arguments.length
      title = value
      chart
  
    chart.xlab = (value) ->
      return xlab unless arguments.length
      xlab = value
      chart
  
    chart.ylab = (value) ->
      return ylab unless arguments.length
      ylab = value
      chart
  
    chart.rotate_ylab = (value) ->
      return rotate_ylab if !arguments.length
      rotate_ylab = value
      chart
  
    chart.lodvarname = (value) ->
      return lodvarname unless arguments.length
      lodvarname = value
      chart
  
    chart.pad4heatmap = (value) ->
      return pad4heatmap unless arguments.length
      pad4heatmap = value
      chart
  
    chart.pointsAtMarkers = (value) ->
      return pointsAtMarkers unless arguments.length
      pointsAtMarkers = value
      chart
  
    chart.yscale = () ->
      return yscale
    
    #if data['additive'].length > 0
    chart.additive_yscale = () ->
      return additive_yscale
  
    chart.xscale = () ->
      return xscale
  
    chart.lodcurve = () ->
      return lodcurve
    
    #if data['additive'].length > 0
    chart.additivecurve = () ->
      return additivecurve
  
    chart.markerSelect = () ->
      return markerSelect
  
    chart.chrSelect = () ->
      return chrSelect
  
    # return the chart function
    chart

# reorganize lod/pos by chromosome
# lodvarname==null    -> case for multiple LOD columns (lodheatmap)
# lodvarname provided -> case for one LOD column (lodchart)
reorgLodData = (data, lodvarname=null) ->
    data.posByChr = {}
    data.lodByChr = {}
    data.additiveByChr = {}
    
    for chr,i in data.chrnames
      data.posByChr[chr[0]] = []
      data.lodByChr[chr[0]] = []
      data.additiveByChr[chr[0]] = []
      for pos, j in data.pos
        if data.chr[j] == chr[0]
          data.posByChr[chr[0]].push(pos)
          data.lodnames = [data.lodnames] unless Array.isArray(data.lodnames)
          if data['additive'].length > 0
            additiveval = (data['additive'][j] for lodcolumn in data.lodnames)
          lodval = (data[lodcolumn][j] for lodcolumn in data.lodnames)
          data.additiveByChr[chr[0]].push(additiveval)
          data.lodByChr[chr[0]].push(lodval)

    
    if lodvarname?
      data.markers = []
      for marker,i in data.markernames
        if marker != ""
          data.markers.push({name:marker, chr:data.chr[i], pos:data.pos[i], lod:data[lodvarname][i]})
    
    data


# calculate chromosome start/end + scales, for heat map
chrscales = (data, width, chrGap, leftMargin, pad4heatmap) ->
    # start and end of chromosome positions
    chrStart = []
    chrEnd = []
    chrLength = []
    totalChrLength = 0
    maxd = 0
    for chr in data.chrnames
      d = maxdiff(data.posByChr[chr[0]])
      maxd = d if d > maxd
  
      rng = d3.extent(data.posByChr[chr[0]])
      chrStart.push(rng[0])
      chrEnd.push(rng[1])
      L = rng[1] - rng[0]
      chrLength.push(L)
      totalChrLength += L
  
    # adjust lengths for heatmap
    if pad4heatmap
      data.recwidth = maxd
      chrStart = chrStart.map (x) -> x-maxd/2
      chrEnd = chrEnd.map (x) -> x+maxd/2
      chrLength = chrLength.map (x) -> x+maxd
      totalChrLength += (chrLength.length*maxd)
  
    # break up x axis into chromosomes by length, with gaps
    data.chrStart = []
    data.chrEnd = []
    cur = leftMargin
    cur += chrGap/2 unless pad4heatmap
    data.xscale = {}
    for chr,i in data.chrnames
      data.chrStart.push(cur)
      w = Math.round((width-chrGap*(data.chrnames.length-pad4heatmap))/totalChrLength*chrLength[i])
      data.chrEnd.push(cur + w)
      cur = data.chrEnd[i] + chrGap
      # x-axis scales, by chromosome
      data.xscale[chr[0]] = d3.scale.linear()
                           .domain([chrStart[i], chrEnd[i]])
                           .range([data.chrStart[i], data.chrEnd[i]])
  
    # return data with new stuff added
    data
    
# maximum difference between adjacent values in a vector
maxdiff = (x) ->
    return null if x.length < 2
    result = x[1] - x[0]
    return result if x.length < 3
    for i in [2...x.length]
      d = x[i] - x[i-1]
      result = d if d > result
    result
    
# determine rounding of axis labels
formatAxis = (d) ->
    d = d[1] - d[0]
    ndig = Math.floor( Math.log(d % 10) / Math.log(10) )
    ndig = 0 if ndig > 0
    ndig = Math.abs(ndig)
    d3.format(".#{ndig}f")