state-management.component.ts 9.39 KB
Newer Older
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
1
2
3
import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3';
import {StateService} from '../state.service';
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
4
5
import * as PlotlyJS from 'plotly.js/dist/plotly.js';

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
6
7
8
9
10
11
12
13
14
15
16

@Component({
  selector: 'app-state-management',
  templateUrl: './state-management.component.html',
  styleUrls: ['./state-management.component.css']
})
export class StateManagementComponent implements OnInit {

  private treeCreated = false;
  private selectedNode;
  private treemap;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
17
18
19
  private svg;
  private hoveredNode = 1;
  public plot;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
20
21
22
23
24
25

  constructor(private state: StateService) { }

  ngOnInit(): void {
    if (this.state.lshData) {
      this.createStateTree();
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
26
      this.initializePlot();
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
27
28
29
30
31
32
33
    }
    this.state.onNewLshData.subscribe(() => {
      if (!this.treeCreated) {
        this.createStateTree();
      } else {
        this.update();
      }
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
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
      this.initializePlot();
    });
  }

  initializePlot(): void {
    console.log('creating plot');
    console.log(this.hoveredNode);
    console.log(this.state.states);
    const subplots = [];
    const data = [];
    this.state.selection.forEach((channelIndex: number, index: number) => {
      const channel = this.state.states[this.hoveredNode.toString()].state.queryWindow[channelIndex];
      data.push({
        x: [...Array(channel.length).keys()],
        y: channel,
        type: 'line',
        xaxis: 'x',
        yaxis: `y${index + 2}`,
        line: {
          color: this.state.colors[channelIndex],
        }
      });
      subplots.push([`xy${index + 2}`]);
    });

    const plot = {
      data: data,
      layout: {
        grid: {
          rows: this.state.selection.length,
          columns: 1,
          subplots: subplots,
        },
        showlegend: false,
        hovermode: 'closest',
        autosize: true,
        margin: {
          l: 30,
          r: 30,
          t: 30,
          b: 0,
          pad: 4
        },
        height: 100 * this.state.selection.length,
        width: 300,
        titlefont: {
          size: 9
        },
        xaxis: {
          showgrid: false,
          zeroline: false,
          showticklabels: false,
        },
        yaxis: {
          zeroline: false,
          showticklabels: false,
        }
      }
    };
    this.state.selection.forEach((channel: number, index: number) => {
      plot.layout[`yaxis${index + 2}`] = {
        zeroline: false,
        showticklabels: false,
        annotations: [{
          xref: 'paper',
          yref: 'paper',
          x: 0,
          xanchor: 'right',
          y: 1,
          yanchor: 'bottom',
          text: 'X axis label',
          showarrow: false
        }]
        // title: this.state.rawData[channel].name
      };
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
109
    });
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
110
    this.plot = plot;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
111
112
113
114
115
  }

  createStateTree() {
    console.log('Creating tree!');

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
116
    const margin = {top: 20, right: 10, bottom: 30, left: 10};
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
117
118
119
    const width = 960 - margin.left - margin.right;
    const height = 500 - margin.top - margin.bottom;

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
120
    this.svg = d3.select('.state').append('svg')
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
121
122
123
124
125
126
127
128
129
      .attr("width", width + margin.right + margin.left)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate("
        + margin.left + "," + margin.top + ")");

    let root;
    const data = this.state.states;
    this.selectedNode = d3.hierarchy(data[1], function(d) { return d.children ? d.children.map(function(child) {return data[child]}) : undefined });
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
130
131
    this.selectedNode.x0 = width / 8;
    this.selectedNode.y0 = 0;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
132
133
134
135
136

    this.treeCreated = true;
    this.update();
  }

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
137
  async update() {
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
138
139
140
141
142
143
144
145
146
147
148
149
    const margin = {top: 20, right: 90, bottom: 30, left: 90};
    const width = 960 - margin.left - margin.right;
    const height = 500 - margin.top - margin.bottom;

    if (!this.treemap) {
      this.treemap = d3.tree().size([height, width]);
    }
    let i = 0;
    const duration = 750;

    const data = this.state.states;
    const currIndex = this.state.currStateIndex;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
150
    this.hoveredNode = currIndex;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
151
152
153
154
155
156
    const root = d3.hierarchy(data[1], function(d) { return d.children ? d.children.map(function(child) {return data[child]}) : undefined });
    const source = this.selectedNode;

    const loadState = (id) => {
      this.state.loadState(id);
    };
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
157
158
159
160
161

    const setHover = (id) => {
      this.hoveredNode = id;
      this.initializePlot();
    };
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    // // Assigns the x and y position for the nodes
    // let root;
    // const data = this.state.states;
    // root = d3.hierarchy(data[1], function(d) { return d.children ? d.children.map(function(child) {return data[child]}) : undefined });

    const treeData = this.treemap(root);

    // Compute the new tree layout.
    const nodes = treeData.descendants();
    console.log('descendants');
    console.log(nodes);
    const links = treeData.descendants().slice(1);

    // Normalize for fixed-depth.
    nodes.forEach(function(d) {
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
177
      d.y = d.depth * 180;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
178
179
180
181
    });

    // ****************** Nodes section ***************************

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
182
    this.svg.selectAll('g.node').select('circle').style("fill", "#fff");
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
183
    // Update the nodes...
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
184
    const node = this.svg.selectAll('g.node')
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
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
      .data(nodes, function(d: any) {
        return d.id;
      });



    // Enter any new modes at the parent's previous position.
    const nodeEnter = node.enter().append('g')
      .attr('class',function(d) {
        console.log('new nodes');
        return 'node';
      })
      // .attr("transform", function(d) {
      //   console.log('new nodes');
      //   return "translate(" + source.y0 + "," + source.x0 + ")";
      // })
      .on('click', function(d: any) {
        loadState(d.data.id);
      });

    // Add Circle for the nodes
    nodeEnter.append('circle')
      .attr('class', 'node')
      .attr('r', 1e-6)
      .style("fill", function(d:any) {
        return d.data.id === currIndex ? "lightsteelblue" : "#fff";
      });

    // Add labels for the nodes
    nodeEnter.append('text')
      .attr("dy", ".35em")
      .attr("x", function(d:any) {
        return d.children ? -13 : 13;
      })
      .attr("text-anchor", function(d:any) {
        return d.children ? "end" : "start";
      })
      .text(function(d: any) {
        return d.data.id;
      });

    // // UPDATE
    const nodeUpdate = nodeEnter.merge(node as any);

    // Transition to the proper position for the node
    nodeUpdate.transition()
      .duration(duration)
      .attr("transform", function(d: any) {
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
233
        return "translate(" + d.x + "," + d.y + ")";
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
234
235
236
237
238
239
240
241
      });

    // Update the node attributes and style
    nodeUpdate.select('circle.node')
      .attr('r', 10)
      .style("fill", function(d:any) {
        return d.data.id === currIndex ? "lightsteelblue" : "#fff";
      })
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
242
243
244
245
246
247
248
249
250
251
252
253
    .attr('cursor', 'pointer')
    .on("mouseover", function(d) {
      d3.select(this).style("fill", function(d:any) {
        return "orange";
      });
      setHover(d.data.id);
    })
    .on('mouseout', function(d) {
      d3.select(this).style("fill", function(d:any) {
        return d.data.id === currIndex ? "lightsteelblue" : "#fff";
      });
    });
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274


    // Remove any exiting nodes
    const nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) {
        return "translate(" + source.y + "," + source.x + ")";
      })
      .remove();

    // On exit reduce the node circles size to 0
    nodeExit.select('circle')
      .attr('r', 1e-6);

    // On exit reduce the opacity of text labels
    nodeExit.select('text')
      .style('fill-opacity', 1e-6);

    // ****************** links section ***************************

    // Update the links...
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
275
    const link = this.svg.selectAll('path.link')
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
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
      .data(links, function(d: any) {
        return d.id;
      });

    // // Enter any new links at the parent's previous position.
    const linkEnter = link.enter().insert('path', "g")
      .attr("class", "link")
      .attr('d', function(d) {
        const o = {x: source.x0, y: source.y0}
        return diagonal(o, o);
      });

    // UPDATE
    const linkUpdate = linkEnter.merge(link as any);

    // Transition back to the parent element position
    linkUpdate.transition()
      .duration(duration)
      .attr('d', function(d: any) {
        return diagonal(d, d.parent)
      });

    // Remove any exiting links
    const linkExit = link.exit().transition()
      .duration(duration)
      .attr('d', function(d) {
        var o = {x: source.x, y: source.y};
        return diagonal(o, o);
      })
      .remove();

    // Store the old positions for transition.
    nodes.forEach(function(d: any) {
      d.x0 = d.x;
      d.y0 = d.y;
    });

    // Creates a curved (diagonal) path from parent to the child nodes
    function diagonal(s, d) {

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
316
317
318
319
      const path = `M ${s.x} ${s.y}
            C ${(s.x + d.x) / 2} ${s.y},
              ${(s.x + d.x) / 2} ${d.y},
              ${d.x} ${d.y}`;
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
320
321
322
323

      return path;
    }

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
324
325
326
327
328
329
330
331
332
333
334
335
    // for (const state of Object.values(this.state.states)) {
    //   const trace ={x:[3,9,8,10,4,6,5],y:[5,7,6,7,8,9,8],type:"scatter"};
    //   const trace1 ={x:[3,4,1,6,8,9,5],y:[4,2,5,2,1,7,3],type:"scatter"};
    //   const dataa = [trace, trace1];
    //   const layout = {title : "Simple JavaScript Graph"};
    //   const gd = await PlotlyJS.newPlot('graph', dataa, layout);
    //   console.log(gd);
    //   const plot = d3.select('.cartesianlayer').node();
    //   console.log(plot);
    //   this.svg.node().appendChild(plot);
    //   // const image = await PlotlyJS.toImage(gd,{format: 'svg', height:300,width:300});
    // }
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
336
337
338
339
340
  }

  // Toggle children on click

}