Debian Codegraph @

bqplot/js/src/HistModel.ts

raw
1 /* Copyright 2015 Bloomberg Finance L.P.
2 *
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 import * as d3 from 'd3';
17 // var d3 =Object.assign({}, require("d3-array"), require("d3-scale"), require("d3-scale-chromatic"));
18 import { MarkModel } from './MarkModel';
19 import * as serialize from './serialize';
20
21 export interface BinData {
22 index: number;
23 bin: d3.Bin<number, number>;
24 }
25
26 export class HistModel extends MarkModel {
27 defaults() {
28 return {
29 ...MarkModel.prototype.defaults(),
30 _model_name: 'HistModel',
31 _view_name: 'Hist',
32 sample: [],
33 count: [],
34 scales_metadata: {
35 sample: { orientation: 'horizontal', dimension: 'x' },
36 count: { orientation: 'vertical', dimension: 'y' },
37 },
38 bins: 10,
39 midpoints: [],
40 colors: ['steelblue'],
41 stroke: null,
42 opacities: [],
43 normalized: false,
44 };
45 }
46
47 initialize(attributes, options) {
48 super.initialize(attributes, options);
49
50 this.mark_data = [];
51 // For the histogram, changing the "sample" scale changes the "count" values being plotted.
52 // Hence, on change of the value of "preserve_domain", we must call the "update_data"
53 // function, and not merely "update_domains".
54 this.on_some_change(
55 ['bins', 'sample', 'preserve_domain'],
56 this.update_data,
57 this
58 );
59 this.update_data();
60 this.on('change:normalized', () => {
61 this.normalizeData(true);
62 });
63 this.normalizeData(true);
64 }
65
66 update_data() {
67 const xScale = this.get('scales').sample;
68
69 // TODO: This potentially triggers domain_changed and therefore a
70 // Draw, while update_data is generally followed by a Draw.
71 if (this.sample.length == 0) {
72 this.mark_data = [];
73 this.xMid = [];
74 this.count = [];
75 this.xBins = [];
76 } else {
77 if (!this.get('preserve_domain').sample) {
78 xScale.compute_and_set_domain(this.sample, this.model_id + '_sample');
79 } else {
80 xScale.del_domain([], this.model_id + '_sample');
81 }
82
83 this.minX = xScale.domain[0];
84 this.maxX = xScale.domain[1];
85
86 const filtered_sample = this.sample.filter(
87 (d) => d <= this.maxX && d >= this.minX
88 );
89 // since x_data may be a TypedArray, explicitly use Array.map
90 const x_data_ind = Array.prototype.map.call(filtered_sample, (d, i) => {
91 return { index: i, value: d };
92 });
93
94 this.xBins = d3.range(
95 this.minX,
96 this.maxX,
97 (this.maxX - this.minX) / this.bins
98 );
99 this.xMid = this.xBins
100 .map((d, i) => {
101 return 0.5 * (d + this.xBins[i - 1]);
102 })
103 .slice(1);
104
105 const bins = d3
106 .histogram()
107 .thresholds(this.xBins)
108 .value((d: any) => {
109 return d.value;
110 })(x_data_ind);
111
112 this.mark_data = bins.map((bin, index) => {
113 return { bin, index };
114 });
115 }
116 this.normalizeData(false);
117
118 this.set('midpoints', this.xMid);
119 this.set('count', new Float64Array(this.count));
120
121 this.update_domains();
122 this.save_changes();
123 this.trigger('data_updated');
124 }
125
126 private normalizeData(save_and_update: boolean) {
127 this.count = this.mark_data.map((d: BinData) => d.bin.length);
128
129 if (this.get('normalized')) {
130 let x_width = 1;
131 if (this.mark_data.length > 0) {
132 x_width = this.mark_data[0].bin.x1 - this.mark_data[0].bin.x0;
133 }
134
135 const sum = this.count.reduce((a, b) => {
136 return a + b;
137 }, 0);
138
139 if (sum != 0) {
140 this.count = this.count.map((a) => {
141 return a / (sum * x_width);
142 });
143 }
144 }
145
146 if (save_and_update) {
147 this.set('count', new Float64Array(this.count));
148 this.update_domains();
149 this.save_changes();
150 this.trigger('data_updated');
151 }
152 }
153
154 get_data_dict(data: BinData, index: number) {
155 const return_dict: any = {};
156 return_dict.midpoint = this.xMid[index];
157 return_dict.bin_start = this.xBins[index];
158 return_dict.bin_end = this.xBins[index + 1];
159 return_dict.index = index;
160 return_dict.count = this.count[index];
161 return return_dict;
162 }
163
164 update_domains() {
165 if (!this.mark_data) return;
166
167 // For histogram, changing the x-scale domain changes a lot of
168 // things including the data which is to be plotted. So the x-domain
169 // change is handled by the update_data function and only the
170 // y-domain change is handled by this function.
171 const y_scale = this.get('scales').count;
172 if (!this.get('preserve_domain').count) {
173 y_scale.set_domain(
174 [0, d3.max(this.count) * 1.05],
175 this.model_id + '_count'
176 );
177 }
178 }
179
180 private get sample(): number[] {
181 return this.get('sample');
182 }
183
184 get bins(): number {
185 return this.get('bins');
186 }
187
188 static serializers = {
189 ...MarkModel.serializers,
190 sample: serialize.array_or_json_serializer,
191 count: serialize.array_or_json_serializer,
192 };
193
194 xBins: number[];
195 xMid: number[];
196 count: number[];
197 minX: number;
198 maxX: number;
199
200 mark_data: BinData[];
201 }