CorrelationAnalysis.vue 19.6 KB
Newer Older
1
<template>
2
  <div :class="`fjs-vm-root fjs-vm-root-${this._uid}`">
3

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

17
    <div class="fjs-parameter-container">
18
      <button class="fjs-run-analysis-btn"
19
              type="button"
20
              @click="runAnalysisWrapper({init: true, args})"
21
              :disabled="disabled">&#9654;</button><br/>
22
23
24
      <br/>
      <span>{{ error }}</span>
    </div>
25

26
    <div class="fjs-vis-container">
27
      <svg :width="width"
28
           :height="height">
29
        <g :transform="`translate(${margin.left}, ${margin.top})`">
30
31
32
33
34
          <g class="fjs-corr-axis fjs-x-axis-1" :transform="`translate(0, ${padded.height})`"></g>
          <g class="fjs-corr-axis fjs-x-axis-2"></g>
          <g class="fjs-corr-axis fjs-y-axis-1"></g>
          <g class="fjs-corr-axis fjs-y-axis-2" :transform="`translate(${padded.width}, 0)`"></g>
          <g class="fjs-brush"></g>
35
36
37
38
39
40
41
42
43
44
45
46
47
          <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>
Sascha Herzinger's avatar
Sascha Herzinger committed
48
          <icon class="fjs-scatterplot-point"
49
                :shape="point.subset"
Sascha Herzinger's avatar
Sascha Herzinger committed
50
51
                :cx="scales.x(point.x)"
                :cy="scales.y(point.y)"
52
                :size="9"
53
54
                v-svgtooltip="point.tooltip"
                :fill="annotationColors[annotations.indexOf(point.annotation) % annotationColors.length]"
55
                :key="`${point.id}-${scales.x(point.x)}-${scales.y(point.y)}`"
56
                v-for="point in shownPoints.all">
Sascha Herzinger's avatar
Sascha Herzinger committed
57
          </icon>
58
          <line class="fjs-lin-reg-line"
59
60
61
                :x1="tweened.regLine.x1"
                :x2="tweened.regLine.x2"
                :y1="tweened.regLine.y1"
Sascha Herzinger's avatar
Sascha Herzinger committed
62
                :y2="tweened.regLine.y2"
63
                v-svgtooltip="regLine.tooltip">
64
          </line>
65
          <rect class="fjs-histogram-rect"
66
67
68
69
70
                :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
71
          </rect>
72
          <rect class="fjs-histogram-rect"
73
74
75
76
77
                :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
78
          </rect>
79
80
        </g>
      </svg>
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
      <div class="fjs-table-container">
        <table class="fjs-stats-table">
          <caption>Selected points</caption>
          <tr>
            <td>Corr. Coef.</td>
            <td>{{ tmpAnalysisResults.coef }}</td>
          </tr>
          <tr>
            <td>p-value</td>
            <td>{{ tmpAnalysisResults.p_value }}</td>
          </tr>
          <tr>
            <td>Correlation method</td>
            <td>{{ tmpAnalysisResults.method }}</td>
          </tr>
          <tr>
            <td>#Points</td>
            <td>{{ tmpPoints.all.length }}</td>
          </tr>
        </table>
        <table class="fjs-stats-table"
               v-for="(stats, i) in shownAnalysisResults.subsets">
          <caption>Subset: {{ i + 1 }}</caption>
          <tr>
            <td>Corr. Coef.</td>
            <td>{{ stats.coef }}</td>
          </tr>
          <tr>
            <td>p-value</td>
            <td>{{ stats.p_value }}</td>
          </tr>
          <tr>
            <td>Correlation method</td>
            <td>{{ tmpAnalysisResults.method }}</td>
          </tr>
          <tr>
            <td>#Points</td>
            <td>{{ tmpPoints.subsets.filter(d => d === i).length }}</td>
          </tr>
        </table>
      </div>
122
123
    </div>

124
  </div>
125
126
127
128
</template>


<script>
129
  import DataBox from '../DataBox.vue'
Sascha Herzinger's avatar
Sascha Herzinger committed
130
  import Icon from '../Icon.vue'
131
132
  import store from '../../store/store'
  import types from '../../store/mutation-types'
Sascha Herzinger's avatar
Sascha Herzinger committed
133
  import requestHandling from '../methods/request-handling'
134
  import * as d3 from 'd3'
Sascha Herzinger's avatar
Sascha Herzinger committed
135
  import svgtooltip from '../directives/v-svgtooltip'
136
  import { TweenLite } from 'gsap'
137
138
  export default {
    name: 'correlation-analysis',
139
    data () {
140
      return {
141
        error: '',
142
143
        width: 0,
        height: 0,
144
145
        xyData: [],
        annotationData: [],
146
        annotationColors: d3.schemeCategory10,
147
        shownAnalysisResults: {
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
            return {
              id: [],
              [this.x_label]: [],
              [this.y_label]: []
            }
          }
163
        },
164
        tmpAnalysisResults: {
165
          init: true,  // will disappear after being initially set
166
167
168
169
170
171
172
          coef: 0,
          p_value: 0,
          slope: 0,
          intercept: 0,
          method: '',
          x_label: '',
          y_label: '',
Sascha Herzinger's avatar
Sascha Herzinger committed
173
          get data () {
174
175
176
177
178
179
180
            return {
              id: [],
              [this.x_label]: [],
              [this.y_label]: []
            }
          }
        },
181
        selectedPoints: [],
182
183
184
185
186
        tweened: {
          regLine: {},
          histogramAttr: {
            xAttr: [],
            yAttr: []
187
          }
188
        }
189
190
      }
    },
191
    computed: {
192
193
194
      idFilter () {
        return store.getters.filter('ids')
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
195
196
197
      subsets () {
        return store.getters.subsets
      },
198
199
      disabled () {
        return this.xyData.length !== 2
200
      },
201
202
203
204
      args () {
        return {
          x: `$${this.xyData[0]}$`,
          y: `$${this.xyData[1]}$`,
205
          id_filter: this.selectedPoints.map(d => d.id),
206
207
          method: 'pearson',
          annotations: this.annotationData.map(d => `$${d}$`)
208
209
        }
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
210
211
      margin () {
        const left = this.width / 3
212
213
        const top = 50
        const right = 50
Sascha Herzinger's avatar
Sascha Herzinger committed
214
215
216
        const bottom = this.height / 3
        return { left, top, right, bottom }
      },
217
218
219
220
      padded () {
        const width = this.width - this.margin.left - this.margin.right
        const height = this.height - this.margin.top - this.margin.bottom
        return { width, height }
221
      },
222
223
224
      annotations () {
        return this.shownPoints.annotations.filter((d, i, arr) => arr.indexOf(d) === i)  // make unique
      },
225
      shownPoints () {
226
227
228
        const xs = []
        const ys = []
        const ids = []
229
        const subsets = []
230
        const annotations = []
231
        let all = []
232
        if (!this.shownAnalysisResults.init) {
233
234
235
236
237
238
          all = this.shownAnalysisResults.data.map(d => {
            const x = d[this.shownAnalysisResults.x_label]
            const y = d[this.shownAnalysisResults.y_label]
            const id = d.id
            const subset = d.subset
            const annotation = d.annotation
239
240
241
            const tooltip = {
              [this.shownAnalysisResults.x_label]: x,
              [this.shownAnalysisResults.y_label]: y,
242
243
244
245
              subset
            }
            if (typeof annotation !== 'undefined') {
              tooltip.annotation = annotation
246
            }
247
248
249
            xs.push(x)
            ys.push(y)
            ids.push(id)
250
            subsets.push(subset)
251
252
            annotations.push(annotation)
            return {x, y, id, subset, annotation, tooltip}
253
254
          })
        }
255
        return { xs, ys, ids, subsets, annotations, all }
256
      },
Sascha Herzinger's avatar
Sascha Herzinger committed
257
      tmpPoints () {
258
259
        const xs = []
        const ys = []
260
261
262
263
        const ids = []
        const subsets = []
        const annotations = []
        let all = []
264
        if (!this.tmpAnalysisResults.init) {
265
266
267
268
269
270
          all = this.tmpAnalysisResults.data.map(d => {
            const x = d[this.tmpAnalysisResults.x_label]
            const y = d[this.tmpAnalysisResults.y_label]
            const id = d.id
            const subset = d.subset
            const annotation = d.annotation
271
272
            xs.push(x)
            ys.push(y)
273
274
275
276
            ids.push(id)
            subsets.push(subset)
            annotations.push(annotation)
            return {x, y, id, subset, annotation}
277
278
          })
        }
279
        return { xs, ys, ids, subsets, annotations, all }
280
      },
281
282
      scales () {
        const x = d3.scaleLinear()
Sascha Herzinger's avatar
Sascha Herzinger committed
283
284
285
286
287
          .domain((() => {
            const xExtent = d3.extent(this.shownPoints.xs)
            const xPadding = (xExtent[1] - xExtent[0]) / 10
            return [xExtent[0] - xPadding, xExtent[1] + xPadding]
          })())
288
289
          .range([0, this.padded.width])
        const y = d3.scaleLinear()
Sascha Herzinger's avatar
Sascha Herzinger committed
290
291
292
293
294
          .domain((() => {
            const yExtent = d3.extent(this.shownPoints.ys)
            const yPadding = (yExtent[1] - yExtent[0]) / 10
            return [yExtent[0] - yPadding, yExtent[1] + yPadding]
          })())
295
296
297
298
299
300
301
302
303
304
305
306
307
308
          .range([this.padded.height, 0])
        return { x, y }
      },
      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 }
      },
309
      regLine () {
310
        if (this.tmpAnalysisResults.init) {
311
312
          return { x1: 0, x2: 0, y1: 0, y2: 0 }
        }
313
314
        const minX = d3.min(this.tmpPoints.xs)
        const maxX = d3.max(this.tmpPoints.xs)
315
        let x1 = this.scales.x(minX)
316
        let y1 = this.scales.y(this.tmpAnalysisResults.intercept + this.tmpAnalysisResults.slope * minX)
317
        let x2 = this.scales.x(maxX)
318
        let y2 = this.scales.y(this.tmpAnalysisResults.intercept + this.tmpAnalysisResults.slope * maxX)
319

320
321
        x1 = x1 < 0 ? 0 : x1
        x1 = x1 > this.width ? this.width : x1
322

323
324
        x2 = x2 < 0 ? 0 : x2
        x2 = x2 > this.width ? this.width : x2
325

326
327
        y1 = y1 < 0 ? 0 : y1
        y1 = y1 > this.height ? this.height : y1
328

329
330
        y2 = y2 < 0 ? 0 : y2
        y2 = y2 > this.height ? this.height : y2
331

Sascha Herzinger's avatar
Sascha Herzinger committed
332
333
334
        const tooltip = {Slope: this.tmpAnalysisResults.slope, Intercept: this.tmpAnalysisResults.intercept}

        return { x1, x2, y1, y2, tooltip }
335
336
337
338
      },
      brush () {
        return d3.brush()
          .extent([[0, 0], [this.padded.width, this.padded.height]])
339
          .on('end', () => {
340
            this.error = ''
341
            if (!d3.event.selection) {
342
              this.selectedPoints = []
343
              this.runAnalysisWrapper({init: false, args: this.args})
344
            } else {
345
346
347
348
349
350
351
352
              const [[x0, y0], [x1, y1]] = d3.event.selection
              this.selectedPoints = this.shownPoints.all.filter(d => {
                const x = this.scales.x(d.x)
                const y = this.scales.y(d.y)
                return x0 <= x && x <= x1 && y0 <= y && y <= y1
              })
              if (this.selectedPoints.length > 0 && this.selectedPoints.length < 3) {
                this.error = 'Selection must be zero (everything is selected) or greater than two.'
Sascha Herzinger's avatar
Sascha Herzinger committed
353
                return
354
355
356
              } else {
                this.runAnalysisWrapper({init: false, args: this.args})
              }
357
            }
358
            store.commit(types.SET_FILTER, {filter: 'ids', value: this.selectedPoints.map(d => d.id)})
359
          })
Sascha Herzinger's avatar
Sascha Herzinger committed
360
361
      },
      histograms () {
362
        const BINS = 14
363
364
365
        let xBins = []
        let yBins = []
        if (!this.tmpAnalysisResults.init) {
366
367
          const [xMin, xMax] = d3.extent(this.tmpPoints.xs)
          const [yMin, yMax] = d3.extent(this.tmpPoints.ys)
368
369
370
          const xThresholds = d3.range(xMin, xMax, (xMax - xMin) / BINS)
          const yThresholds = d3.range(yMin, yMax, (yMax - yMin) / BINS)
          xBins = d3.histogram()
371
            .domain([xMin, xMax])
372
373
            .thresholds(xThresholds)(this.tmpPoints.xs)
          yBins = d3.histogram()
374
            .domain([yMin, yMax])
375
376
            .thresholds(yThresholds)(this.tmpPoints.ys)
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
377
378
379
        return { xBins, yBins }
      },
      histogramScales () {
380
381
        const xExtent = d3.extent(this.histograms.xBins.map(d => d.length))
        const yExtent = d3.extent(this.histograms.yBins.map(d => d.length))
382
        // no, I didn't mix up x and y.
Sascha Herzinger's avatar
Sascha Herzinger committed
383
        const x = d3.scaleLinear()
384
385
          .domain(yExtent)
          .range([yExtent[0] ? 10 : 0, this.margin.left])
Sascha Herzinger's avatar
Sascha Herzinger committed
386
        const y = d3.scaleLinear()
387
388
          .domain(xExtent)
          .range([xExtent[0] ? 10 : 0, this.margin.bottom])
Sascha Herzinger's avatar
Sascha Herzinger committed
389
390
        return { x, y }
      },
391
392
393
394
      histogramAttr () {
        const xAttr = this.histograms.xBins.map(d => {
          return {
            x: this.scales.x(d.x0),
Sascha Herzinger's avatar
Sascha Herzinger committed
395
            y: this.padded.height + 1,
396
397
398
399
400
401
            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 {
402
            x: -this.histogramScales.x(d.length),
403
404
405
406
407
408
409
410
            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 }
      }
411
412
    },
    watch: {
413
      'axis': {
414
        handler: function (newAxis) {
415
416
417
418
          d3.select(`.fjs-vm-root-${this._uid} .fjs-x-axis-1`).call(newAxis.x1)
          d3.select(`.fjs-vm-root-${this._uid} .fjs-x-axis-2`).call(newAxis.x2)
          d3.select(`.fjs-vm-root-${this._uid} .fjs-y-axis-1`).call(newAxis.y1)
          d3.select(`.fjs-vm-root-${this._uid} .fjs-y-axis-2`).call(newAxis.y2)
419
        }
420
421
      },
      'brush': {
422
        handler: function (newBrush) {
423
          d3.select(`.fjs-vm-root-${this._uid} .fjs-brush`).call(newBrush)
424
        }
425
426
      },
      'regLine': {
427
        handler: function (newRegLine, oldRegLine) {
428
429
430
431
432
433
434
          const coords = oldRegLine
          const targetCoords = newRegLine
          targetCoords.onUpdate = () => { this.tweened.regLine = coords }
          TweenLite.to(coords, 0.5, targetCoords)
        }
      },
      'histogramAttr': {
435
        handler: function (newHistogramAttr, oldHistogramAttr) {
436
437
438
          let i = Math.max.apply(null, [newHistogramAttr.xAttr.length, oldHistogramAttr.xAttr.length])
          let j = Math.max.apply(null, [newHistogramAttr.yAttr.length, oldHistogramAttr.yAttr.length])

439
          while (i--) {
440
            const ii = i
441
            let xAttr = oldHistogramAttr.xAttr[i] ? oldHistogramAttr.xAttr[i]
Sascha Herzinger's avatar
Sascha Herzinger committed
442
              : { x: this.padded.width / 2, y: this.padded.height, width: 0, height: 0 }
443
444
445
            const xAttrTarget = newHistogramAttr.xAttr[i] ? newHistogramAttr.xAttr[i] : { width: 0 }
            xAttrTarget.onUpdate = () => { this.tweened.histogramAttr.xAttr[ii] = xAttr }
            TweenLite.to(xAttr, 0.5, xAttrTarget)
446
447
          }

448
          while (j--) {
449
            const jj = j
450
            const yAttr = oldHistogramAttr.yAttr[j] ? oldHistogramAttr.yAttr[j]
Sascha Herzinger's avatar
Sascha Herzinger committed
451
              : { x: 0, y: this.padded.height / 2, width: 0, height: 0 }
452
453
454
            const yAttrTarget = newHistogramAttr.yAttr[j] ? newHistogramAttr.yAttr[j] : { height: 0 }
            yAttrTarget.onUpdate = () => { this.tweened.histogramAttr.yAttr[jj] = yAttr }
            TweenLite.to(yAttr, 0.5, yAttrTarget)
455
456
          }
        }
457
458
459
460
461
462
463
      },
      'idFilter': {
        handler: function (newIDFilter) {
          const isFiltered = (newIDFilter.length === this.selectedPoints.length) &&
            this.selectedPoints.map(d => d.id).every(id => newIDFilter.indexOf(id) !== -1)
          if (!isFiltered) {
            const args = this.args
464
            args.id_filter = newIDFilter
465
466
467
            this.runAnalysisWrapper({init: false, args})
          }
        }
Sascha Herzinger's avatar
Sascha Herzinger committed
468
469
470
471
472
      },
      'subsets': {
        handler: function () {
          this.runAnalysisWrapper({init: false, args: this.args})
        }
473
474
      }
    },
Sascha Herzinger's avatar
Sascha Herzinger committed
475
    mounted () {
476
      this.handleResize()
477
    },
Sascha Herzinger's avatar
Sascha Herzinger committed
478
    beforeDestroy () {
479
480
      const svg = this.$el.querySelector(`.fjs-vm-root-${this._uid} .fjs-vis-container svg`)
      svg.removeEventListener('resize', this.handleResize)
481
    },
482
    components: {
Sascha Herzinger's avatar
Sascha Herzinger committed
483
484
      DataBox,
      Icon
485
486
    },
    mixins: [
Sascha Herzinger's avatar
Sascha Herzinger committed
487
      requestHandling,
488
      svgtooltip
489
490
    ],
    methods: {
491
      runAnalysisWrapper ({init, args}) {
492
        args['subsets'] = store.getters.subsets
493
        // function made available via requestHandling mixin
494
        this.runAnalysis({task_name: 'compute-correlation', args})
495
          .then(response => {
496
            const results = JSON.parse(response)
497
498
            const data = JSON.parse(results.data)
            results.data = Object.keys(data).map(key => data[key])
499
500
501
502
503
504
            if (init) {
              this.shownAnalysisResults = results
              this.tmpAnalysisResults = results
            } else {
              this.tmpAnalysisResults = results
            }
505
          })
506
          .catch(error => console.error(error))
507
          .then(this.handleResize)  // FIXME: it would be better to listen to the svg size directly.
508
      },
509
510
      handleResize () {
        const container = this.$el.querySelector(`.fjs-vm-root-${this._uid} .fjs-vis-container svg`)
511
        // noinspection JSSuspiciousNameCombination
512
513
        this.height = container.clientWidth
        this.width = container.clientWidth
514
515
516
517
518
519
      },
      update_xyData (ids) {
        this.xyData = ids
      },
      update_annotationData (ids) {
        this.annotationData = ids
520
      }
521
522
523
524
525
    }
  }
</script>


526
527
528
529
530
531
<style lang="sass" scoped>
  @import './src/assets/base.sass'

  *
    font-family: Roboto, sans-serif

532
  .fjs-vm-root
533
534
    height: 100%
    width: 100%
535
536
    display: flex
    flex-direction: column
537

538
539
540
541
542
543
544
545
546
    .fjs-data-box-container
      width: 70%
      height: 160px
      overflow: hidden
      margin: 0 auto
      .fjs-data-box:nth-child(1)
        float: left
      .fjs-data-box:nth-child(2)
        float: right
547

548
    .fjs-parameter-container
549
550
551
552
553
554
555
556
557
      text-align: center
      .fjs-run-analysis-btn
        margin: 10px
        width: 100px
        height: 30px
        box-shadow: 2px 2px 4px 0 #999
        font-size: 20px
      .fjs-run-analysis-btn:not([disabled]):hover
        cursor: pointer
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
    .fjs-vis-container
      flex: 1
      display: flex
      justify-content: center
      svg
        float: left
        flex: 1
        .fjs-lin-reg-line
          stroke: #ff5e00
          stroke-width: 4px
        .fjs-lin-reg-line:hover
          opacity: 0.4
        .fjs-histogram-rect
          stroke: #fff
          shape-rendering: crispEdges
          stroke-width: 0px
          fill: #ffd100
        .fjs-scatterplot-point
          stroke-width: 0
          shape-rendering: crispEdges
        .fjs-scatterplot-point:hover
          fill: #f00
        .fjs-brush
          stroke-width: 0
      .fjs-table-container
        float: left
        display: flex
        flex-direction: column
        .fjs-stats-table
          margin: 5px
          border-spacing: 0
          border-collapse: collapse
          font-size: 14px
          float: right
        .fjs-stats-table tr:nth-child(even)
          background-color: #ddd
        .fjs-stats-table, .fjs-stats-table td, .fjs-stats-table th
          border: 1px #ccc solid
          border-collapse: collapse
          padding: 5px
599
600
601
</style>

<!--CSS for dynamically created components-->
602
603
604
605
606
607
608
609
610
<style lang="sass">
  @import './src/assets/svgtooltip.sass'

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