CorrelationAnalysis.vue 16.9 KB
Newer Older
1
<template>
2
  <div id="root">
3

4
    <div id="data-box-section">
5
6
7
8
9
10
11
12
      <data-box header="X and Y variables"
                dataType="numerical"
                v-on:update="update_xyData">
      </data-box>
      <data-box header="Annotations"
                dataType="categorical"
                v-on:update="update_annotationData">
      </data-box>
13
    </div>
14

15
    <div id="controls-section">
16
17
18
      <button id="run-analysis-btn"
              type="button"
              @click="runAnalysisWrapper({init: true})"
19
              :disabled="disabled">&#9654;</button><br/>
20
21
22
      <br/>
      <span>{{ error }}</span>
    </div>
23
24

    <div id="visualisation-section">
25
      <table class="stats-table" v-show="!shownAnalysisResults.init">
26
27
28
29
30
31
32
33
        <tr>
          <td>Corr. Coef.</td>
          <td>{{ tmpAnalysisResults.coef }}</td>
        </tr>
        <tr>
          <td>p-value</td>
          <td>{{ tmpAnalysisResults.p_value }}</td>
        </tr>
Sascha Herzinger's avatar
Sascha Herzinger committed
34
35
36
37
38
39
40
41
42
        <tr>
          <td>Correlation statistic</td>
          <td>{{ tmpAnalysisResults.method }}</td>
        </tr>
        <tr>
          <td>#Selected points</td>
          <td>{{ tmpPoints.all.length }}</td>
        </tr>
        <tr>
Sascha Herzinger's avatar
Sascha Herzinger committed
43
          <td>#Displayed points</td>
Sascha Herzinger's avatar
Sascha Herzinger committed
44
45
          <td>{{ shownPoints.all.length }}</td>
        </tr>
46
      </table>
47
48
49
      <svg :width="width"
           :height="height"
           v-show="!shownAnalysisResults.init">
50
51
        <g :transform="`translate(${margin.left}, ${margin.top})`">
          <g id="x-axis-1" class="fjs-corr-axis" :transform="`translate(0, ${padded.height})`"></g>
52
53
          <g id="x-axis-2" class="fjs-corr-axis"></g>
          <g id="y-axis-1" class="fjs-corr-axis"></g>
54
          <g id="y-axis-2" class="fjs-corr-axis" :transform="`translate(${padded.width}, 0)`"></g>
55
56
57
58
59
60
61
62
63
64
65
66
67
68
          <g id="brush"></g>
          <text :x="padded.width / 2"
                y="-10"
                text-anchor="middle"
                font-size="16">
            {{ shownAnalysisResults.x_label }}
          </text>
          <text :x="padded.width + 10"
                :y="padded.height / 2"
                text-anchor="middle"
                font-size="16"
                :transform="`rotate(90 ${padded.width + 10} ${padded.height / 2})`">
            {{ shownAnalysisResults.y_label }}
          </text>
69
70
          <circle class="scatterplot-point"
                  :cx="scales.x(point.x)"
71
72
73
                  :cy="scales.y(point.y)"
                  r="4"
                  :data-idx="idx"
Sascha Herzinger's avatar
Sascha Herzinger committed
74
                  v-for="(point, idx) in shownPoints.all"
75
                  v-svgtooltip="point.tooltip">
76
          </circle>
77
          <line id="lin-reg-line"
78
79
80
                :x1="tweened.regLine.x1"
                :x2="tweened.regLine.x2"
                :y1="tweened.regLine.y1"
Sascha Herzinger's avatar
Sascha Herzinger committed
81
                :y2="tweened.regLine.y2"
82
                v-svgtooltip="regLine.tooltip">
83
          </line>
84
85
86
87
88
89
          <rect class="histogram-rect"
                :x="attr.x"
                :y="attr.y"
                :width="attr.width"
                :height="attr.height"
                v-for="attr in tweened.histogramAttr.xAttr">
Sascha Herzinger's avatar
Sascha Herzinger committed
90
          </rect>
91
92
93
94
95
96
          <rect class="histogram-rect"
                :x="attr.x"
                :y="attr.y"
                :width="attr.width"
                :height="attr.height"
                v-for="attr in tweened.histogramAttr.yAttr">
Sascha Herzinger's avatar
Sascha Herzinger committed
97
          </rect>
98
99
100
101
        </g>
      </svg>
    </div>

102
  </div>
103
104
105
106
</template>


<script>
107
108
  import DataBox from '../DataBox.vue'
  import requestHandling from '../mixins/request-handling'
109
  import * as d3 from 'd3'
110
  import svgtooltip from '../mixins/v-svgtooltip'
111
  import { TweenLite } from 'gsap'
112
  import $ from 'jquery'
113
114
  export default {
    name: 'correlation-analysis',
115
    data () {
116
      return {
117
        error: '',
118
119
        width: 0,
        height: 0,
120
121
122
123
124
        xyData: [],
        annotationData: [],
        get args () {
          return {
            x: `$${this.xyData[0]}$`,
125
126
            y: `$${this.xyData[1]}$`,
            ids: this.selectedPoints.map(d => d.id)
127
          }
128
        },
129

130
        shownAnalysisResults: {
131
          init: true,  // will disappear after being initially set
132
133
134
135
136
137
138
          coef: 0,
          p_value: 0,
          slope: 0,
          intercept: 0,
          method: '',
          x_label: '',
          y_label: '',
Sascha Herzinger's avatar
Sascha Herzinger committed
139
          get data () {
140
141
142
143
144
145
            return {
              id: [],
              [this.x_label]: [],
              [this.y_label]: []
            }
          }
146
        },
147
        tmpAnalysisResults: {
148
          init: true,  // will disappear after being initially set
149
150
151
152
153
154
155
          coef: 0,
          p_value: 0,
          slope: 0,
          intercept: 0,
          method: '',
          x_label: '',
          y_label: '',
Sascha Herzinger's avatar
Sascha Herzinger committed
156
          get data () {
157
158
159
160
161
162
163
            return {
              id: [],
              [this.x_label]: [],
              [this.y_label]: []
            }
          }
        },
164
        selectedPoints: [],
165
166
167
168
169
        tweened: {
          regLine: {},
          histogramAttr: {
            xAttr: [],
            yAttr: []
170
          }
171
        }
172
173
      }
    },
174
175
176
    computed: {
      disabled () {
        return this.xyData.length !== 2
177
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
178
179
      margin () {
        const left = this.width / 3
180
181
        const top = 50
        const right = 50
Sascha Herzinger's avatar
Sascha Herzinger committed
182
183
184
        const bottom = this.height / 3
        return { left, top, right, bottom }
      },
185
186
187
188
      padded () {
        const width = this.width - this.margin.left - this.margin.right
        const height = this.height - this.margin.top - this.margin.bottom
        return { width, height }
189
      },
190
      shownPoints () {
191
192
193
        const xs = []
        const ys = []
        const ids = []
194
        let all = []
195
        if (!this.shownAnalysisResults.init) {
196
197
198
199
          all = Object.keys(this.shownAnalysisResults.data.id).map(key => {
            const x = this.shownAnalysisResults.data[this.shownAnalysisResults.x_label][key]
            const y = this.shownAnalysisResults.data[this.shownAnalysisResults.y_label][key]
            const id = this.shownAnalysisResults.data.id[key]
Sascha Herzinger's avatar
Sascha Herzinger committed
200
            const tooltip = {[this.shownAnalysisResults.x_label]: x, [this.shownAnalysisResults.y_label]: y}
201
202
203
            xs.push(x)
            ys.push(y)
            ids.push(id)
Sascha Herzinger's avatar
Sascha Herzinger committed
204
            return {x, y, id, tooltip}
205
206
          })
        }
207
208
        return { xs, ys, ids, all }
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
209
      tmpPoints () {
210
211
212
        const xs = []
        const ys = []
        const ids = []
213
        let all = []
214
        if (!this.tmpAnalysisResults.init) {
Sascha Herzinger's avatar
Sascha Herzinger committed
215
          all = Object.keys(this.tmpAnalysisResults.data.id).map(key => {
216
217
218
219
220
221
222
223
224
            const x = this.tmpAnalysisResults.data[this.tmpAnalysisResults.x_label][key]
            const y = this.tmpAnalysisResults.data[this.tmpAnalysisResults.y_label][key]
            const id = this.tmpAnalysisResults.data.id[key]
            xs.push(x)
            ys.push(y)
            ids.push(id)
            return {x, y, id}
          })
        }
225
        return { xs, ys, ids, all }
226
      },
227
228
      scales () {
        const x = d3.scaleLinear()
Sascha Herzinger's avatar
Sascha Herzinger committed
229
230
231
232
233
          .domain((() => {
            const xExtent = d3.extent(this.shownPoints.xs)
            const xPadding = (xExtent[1] - xExtent[0]) / 10
            return [xExtent[0] - xPadding, xExtent[1] + xPadding]
          })())
234
235
          .range([0, this.padded.width])
        const y = d3.scaleLinear()
Sascha Herzinger's avatar
Sascha Herzinger committed
236
237
238
239
240
          .domain((() => {
            const yExtent = d3.extent(this.shownPoints.ys)
            const yPadding = (yExtent[1] - yExtent[0]) / 10
            return [yExtent[0] - yPadding, yExtent[1] + yPadding]
          })())
241
242
243
          .range([this.padded.height, 0])
        return { x, y }
      },
244
245
246
247
248
249
250
251
252
      tmpScales () {
        const x = d3.scaleLinear()
          .domain(d3.extent(this.tmpPoints.xs))
          .range([this.scales.x(d3.min(this.tmpPoints.xs)), this.scales.x(d3.max(this.tmpPoints.xs))])
        const y = d3.scaleLinear()
          .domain(d3.extent(this.tmpPoints.ys))
          .range([this.scales.y(this.tmpPoints.max), this.scales.x(this.tmpPoints.min)])
        return { x, y }
      },
253
254
255
256
257
258
259
260
261
262
263
      axis () {
        const x1 = d3.axisTop(this.scales.x)
        const y1 = d3.axisRight(this.scales.y)
        const x2 = d3.axisBottom(this.scales.x)
          .tickSizeInner(this.padded.height - 23)
          .tickFormat('')
        const y2 = d3.axisLeft(this.scales.y)
          .tickSizeInner(this.padded.width - 23)
          .tickFormat('')
        return { x1, x2, y1, y2 }
      },
264
      regLine () {
265
        if (this.tmpAnalysisResults.init) {
266
267
          return { x1: 0, x2: 0, y1: 0, y2: 0 }
        }
268
269
        const minX = d3.min(this.tmpPoints.xs)
        const maxX = d3.max(this.tmpPoints.xs)
270
        let x1 = this.scales.x(minX)
271
        let y1 = this.scales.y(this.tmpAnalysisResults.intercept + this.tmpAnalysisResults.slope * minX)
272
        let x2 = this.scales.x(maxX)
273
        let y2 = this.scales.y(this.tmpAnalysisResults.intercept + this.tmpAnalysisResults.slope * maxX)
274

275
276
        x1 = x1 < 0 ? 0 : x1
        x1 = x1 > this.width ? this.width : x1
277

278
279
        x2 = x2 < 0 ? 0 : x2
        x2 = x2 > this.width ? this.width : x2
280

281
282
        y1 = y1 < 0 ? 0 : y1
        y1 = y1 > this.height ? this.height : y1
283

284
285
        y2 = y2 < 0 ? 0 : y2
        y2 = y2 > this.height ? this.height : y2
286

Sascha Herzinger's avatar
Sascha Herzinger committed
287
288
289
        const tooltip = {Slope: this.tmpAnalysisResults.slope, Intercept: this.tmpAnalysisResults.intercept}

        return { x1, x2, y1, y2, tooltip }
290
291
292
293
      },
      brush () {
        return d3.brush()
          .extent([[0, 0], [this.padded.width, this.padded.height]])
294
          .on('end', () => {
295
            this.error = ''
296
            if (!d3.event.selection) {
297
298
299
300
              this.selectedPoints = []
              this.runAnalysisWrapper({init: false})
              return
            }
301
            const [[x0, y0], [x1, y1]] = d3.event.selection
302
            this.selectedPoints = this.shownPoints.all.filter(d => {
303
304
              const x = this.scales.x(d.x)
              const y = this.scales.y(d.y)
305
              return x0 <= x && x <= x1 && y0 <= y && y <= y1
306
            })
307
308
309
310
311
            if (this.selectedPoints.length > 0 && this.selectedPoints.length < 3) {
              this.error = 'Selection must be zero (everything is selected) or greater than two.'
            } else {
              this.runAnalysisWrapper({init: false})
            }
312
          })
Sascha Herzinger's avatar
Sascha Herzinger committed
313
314
      },
      histograms () {
315
        const BINS = 14
316
317
318
        let xBins = []
        let yBins = []
        if (!this.tmpAnalysisResults.init) {
319
320
321
322
323
324
325
326
327
328
329
          const [xMin, xMax] = this.tmpScales.x.domain()
          const [yMin, yMax] = this.tmpScales.y.domain()
          const xThresholds = d3.range(xMin, xMax, (xMax - xMin) / BINS)
          const yThresholds = d3.range(yMin, yMax, (yMax - yMin) / BINS)
          xBins = d3.histogram()
            .domain(this.tmpScales.x.domain())
            .thresholds(xThresholds)(this.tmpPoints.xs)
          yBins = d3.histogram()
            .domain(this.tmpScales.y.domain())
            .thresholds(yThresholds)(this.tmpPoints.ys)
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
330
331
332
        return { xBins, yBins }
      },
      histogramScales () {
333
334
        const xExtent = d3.extent(this.histograms.xBins.map(d => d.length))
        const yExtent = d3.extent(this.histograms.yBins.map(d => d.length))
Sascha Herzinger's avatar
Sascha Herzinger committed
335
336
        // no, I didn't mix up xBins and yBins.
        const x = d3.scaleLinear()
337
338
          .domain(yExtent)
          .range([yExtent[0] ? 10 : 0, this.margin.left])
Sascha Herzinger's avatar
Sascha Herzinger committed
339
        const y = d3.scaleLinear()
340
341
          .domain(xExtent)
          .range([xExtent[0] ? 10 : 0, this.margin.bottom])
Sascha Herzinger's avatar
Sascha Herzinger committed
342
343
        return { x, y }
      },
344
345
346
347
      histogramAttr () {
        const xAttr = this.histograms.xBins.map(d => {
          return {
            x: this.scales.x(d.x0),
Sascha Herzinger's avatar
Sascha Herzinger committed
348
            y: this.padded.height + 1,
349
350
351
352
353
354
            width: this.scales.x(d.x1) - this.scales.x(d.x0),
            height: this.histogramScales.y(d.length)
          }
        })
        const yAttr = this.histograms.yBins.map(d => {
          return {
355
            x: -this.histogramScales.x(d.length),
356
357
358
359
360
361
362
363
            y: this.scales.y(d.x1),
            width: this.histogramScales.x(d.length),
            height: this.scales.y(d.x0) - this.scales.y(d.x1)
          }
        })

        return { xAttr, yAttr }
      }
364
365
    },
    watch: {
366
      'axis': {
367
        handler: function (newAxis) {
368
369
370
371
          d3.select('#x-axis-1').call(newAxis.x1)
          d3.select('#x-axis-2').call(newAxis.x2)
          d3.select('#y-axis-1').call(newAxis.y1)
          d3.select('#y-axis-2').call(newAxis.y2)
372
        }
373
374
      },
      'brush': {
375
        handler: function (newBrush) {
376
          d3.select('#brush').call(newBrush)
377
        }
378
379
      },
      'regLine': {
380
        handler: function (newRegLine, oldRegLine) {
381
382
383
384
385
386
387
          const coords = oldRegLine
          const targetCoords = newRegLine
          targetCoords.onUpdate = () => { this.tweened.regLine = coords }
          TweenLite.to(coords, 0.5, targetCoords)
        }
      },
      'histogramAttr': {
388
        handler: function (newHistogramAttr, oldHistogramAttr) {
389
390
391
          let i = Math.max.apply(null, [newHistogramAttr.xAttr.length, oldHistogramAttr.xAttr.length])
          let j = Math.max.apply(null, [newHistogramAttr.yAttr.length, oldHistogramAttr.yAttr.length])

392
          while (i--) {
393
            const ii = i
394
395
396
397
398
            let xAttr = oldHistogramAttr.xAttr[i] ? oldHistogramAttr.xAttr[i]
: { x: this.padded.width / 2, y: this.padded.height, width: 0, height: 0 }
            const xAttrTarget = newHistogramAttr.xAttr[i] ? newHistogramAttr.xAttr[i] : { width: 0 }
            xAttrTarget.onUpdate = () => { this.tweened.histogramAttr.xAttr[ii] = xAttr }
            TweenLite.to(xAttr, 0.5, xAttrTarget)
399
400
          }

401
          while (j--) {
402
            const jj = j
403
404
405
406
407
            const yAttr = oldHistogramAttr.yAttr[j] ? oldHistogramAttr.yAttr[j]
: { x: 0, y: this.padded.height / 2, width: 0, height: 0 }
            const yAttrTarget = newHistogramAttr.yAttr[j] ? newHistogramAttr.yAttr[j] : { height: 0 }
            yAttrTarget.onUpdate = () => { this.tweened.histogramAttr.yAttr[jj] = yAttr }
            TweenLite.to(yAttr, 0.5, yAttrTarget)
408
409
          }
        }
410
411
      }
    },
Sascha Herzinger's avatar
Sascha Herzinger committed
412
    mounted () {
413
      window.addEventListener('resize', this.onResize)
414
415
416
      this.onResize()  // initial call
      // saves us one manual initialization
      this.tmpAnalysisResults = JSON.parse(JSON.stringify(this.shownAnalysisResults))
417
    },
Sascha Herzinger's avatar
Sascha Herzinger committed
418
    beforeDestroy () {
419
420
      window.removeEventListener('resize', this.onResize)
    },
421
422
423
424
    components: {
      DataBox
    },
    mixins: [
Sascha Herzinger's avatar
Sascha Herzinger committed
425
      requestHandling,
426
      svgtooltip
427
428
    ],
    methods: {
429
      runAnalysisWrapper ({init}) {
430
431
432
433
        let args = this.args
        if (init) {
          args.ids = []
        }
434
        // function made available via requestHandling mixin
435
        this.runAnalysis({job_name: 'compute-correlation', args: args})
436
          .then(response => {
437
438
            const results = JSON.parse(response)
            results.data = JSON.parse(results.data)
439
440
441
442
443
444
            if (init) {
              this.shownAnalysisResults = results
              this.tmpAnalysisResults = results
            } else {
              this.tmpAnalysisResults = results
            }
445
          })
446
447
448
          .catch(error => console.error(error))
      },
      onResize () {
449
        const tableHeight = $(this.$el.querySelector('table')).outerHeight(true)
450
        const section = this.$el.querySelector('#visualisation-section')
451
452
453
454
455
        const height = section.clientHeight - tableHeight
        const width = section.clientWidth
        this.height = height > width ? width : height // we want to have a square
        // noinspection JSSuspiciousNameCombination
        this.width = this.height
456
457
458
459
460
461
      },
      update_xyData (ids) {
        this.xyData = ids
      },
      update_annotationData (ids) {
        this.annotationData = ids
462
      }
463
464
465
466
467
    }
  }
</script>


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
<style lang="sass" scoped>
  @import './src/assets/base.sass'

  *
    font-family: Roboto, sans-serif

  #root
    height: 100%
    width: 100%

  #data-box-section
    text-align: center
    height: 15%
    > *
      display: inline-block

  #controls-section
    height: 5%
    text-align: center
    #run-analysis-btn
      margin: 10px
      width: 100px
      height: 30px
      box-shadow: 2px 2px 4px 0 #999
      font-size: 20px
    #run-analysis-btn:not([disabled]):hover
      cursor: pointer

  #visualisation-section
    height: 80%
    #lin-reg-line
      stroke: #ff5e00
      stroke-width: 4px
    #lin-reg-line:hover
      opacity: 0.4
    .histogram-rect
      stroke: #fff
      shape-rendering: crispEdges
      stroke-width: 0px
      fill: #ffd100
    .stats-table
      margin: 5px
      border-spacing: 0
      border-collapse: collapse
      font-size: 14px
      float: right
    .stats-table tr:nth-child(even)
      background-color: #ddd
    .stats-table, .stats-table td, .stats-table th
      border: 1px #ccc solid
      border-collapse: collapse
      padding: 5px
    .scatterplot-point:hover
      fill: #f00
      opacity: 0.4
    #brush
      stroke-width: 0
525
526
527
</style>

<!--CSS for dynamically created components-->
528
529
530
531
532
533
534
535
536
<style lang="sass">
  @import './src/assets/svgtooltip.sass'

  .fjs-corr-axis
    shape-rendering: crispEdges
    .tick
      shape-rendering: crispEdges
    line
      stroke: #999
537
</style>