Best JavaScript code snippet using best
variance_chart.js
Source:variance_chart.js
1/**2 * Makes a variance chart from a file of variance data for principal components of one frequency3 * @param {string} variance_datafile_name The name of the variance datafile in the data folder4 * @param {string} dataset The name of the principal component datafile in the data folder5 * @param {string} freq_sing_val_file The name of the datafile in the data folder holding the frequency's singular value data6 * @param {array} selected_pca The array that will store selected principal components as they are selected. Begins empty.7 * @param {svg} varchart The D3 created SVG (on a div in the html) that will contain the variance chart.8 * @param {svg} heatmapsvg The D3 created SVG (on a div in the html) that will contain the heatmap for this variance chart's frequency9 * @param {svg} heatmapsvg2 The D3 created SVG (on a div in the html) that will contain the heatmap excluded selected pca low-rank approximation10 * @param {bool} lowrank Whether the heatmap this chart is tied to represents a low rank approx of data (if True) or multiple principal components side by side (if False)11 * @param {array} whole_pca The array that will store all pca elements12 * @return {None} Does not return anything, just manipulates svgs passed as parameters13 */14async function make_variance_chart(variance_datafile_name, dataset, freq_sing_val_file, selected_pca, varchart, heatmapsvg, heatmapsvg2, lowrank, whole_pca){15 // put loading label while data are loading16 /*17 const loading_message = varchart.append('text')18 .attr('id', 'var_loading_message')19 .attr('x', 100)20 .attr('y', 200)21 .attr('fill', '#ccc')22 .attr('font-family', 'Helvetica Neue, Arial')23 .attr('font-weight', 500)24 .attr('font-size', 60)25 .text("Loading...");26 */27 // Y label28 varchart.append("text")29 .attr("class", "y label")30 .attr("text-anchor", "start")31 .attr("y", -50)32 .attr("x", -150)33 .attr("dy", ".75em")34 .attr("font-size", 15)35 .attr("transform", "rotate(-90)")36 .text("% Variance Explained");37 // X label38 varchart.append("text")39 .attr("class", "x label")40 .attr("text-anchor", "end")41 .attr("x", width)42 .attr("y", height + 40)43 .attr("font-size", 15)44 .text("Component Number");45 // title46 varchart.append("text")47 .attr("x", (width / 2))48 .attr("y", 0 - (margin.top / 2))49 .attr("text-anchor", "middle")50 .style("font-size", 15)51 .attr("font-weight",700)52 .text("% Explained Variance Per Component");53 // Adding the second plot: explained variance54 d3.csv("data/"+ variance_datafile_name)55 .then(function (data) {56 data.forEach(function(d) {57 d.num = parseInt(d.num);58 d.variance = parseFloat(d.variance)});59 // Set x and y axis60 var var_x = d3.scaleLinear().domain([0, d3.max(data, function(d) { return d.num; })]).range([0, width]);61 var var_y = d3.scaleLinear().domain([0, d3.max(data, function(d) { return d.variance; })]).range([height, 0]);62 varchart.append("g")63 .attr("transform", "translate(0," + height + ")")64 .call(d3.axisBottom(var_x));65 varchart.append("g")66 .call(d3.axisLeft(var_y));67 var total_variance_captured = 0;68 // Add dots69 varchart.append('g')70 .selectAll("dot")71 .data(data)72 .enter()73 .append("circle")74 .attr("cx", function (d) { return var_x(d.num); } )75 .attr("cy", function (d) { return var_y(d.variance); } )76 .attr("r", 3.5)77 .style("fill", "#69b3a2")78 .on("mouseover", function(d,i) {79 d3.select(this).transition()80 .duration('10')81 .attr("r", 5)82 })83 .on('mouseout', function() {84 d3.select(this).transition()85 .duration('100')86 .attr("r", 3.5)87 })88 .on("click", function(d, i)89 {90 // get component number (stored in 0 indexed matrix so subtract 1)91 component = i.num - 1;92 // get variance93 component_variance = i.variance.toFixed(4);94 // get component data95 //pc_data = get_pc_data(component, 120);96 curr_color = d3.select(this).style("fill");97 if (document.querySelectorAll(".selected").length == 0){98 total_variance_captured = 099 selected_pca = []100 }101 if (document.querySelectorAll(".selected").length == 62){102 total_variance_captured = 1103 const range = (start, end, length = end - start + 1) =>104 Array.from({ length }, (_, i) => start + i)105 selected_pca = range(0, 61);106 }107 if (curr_color == "rgb(105, 179, 162)"){ // if point is being highlighted108 d3.select(this).style("fill", "rgb(254, 211, 72)");109 d3.select(this).attr("class","selected");110 total_variance_captured = parseFloat(total_variance_captured) + parseFloat(component_variance);111 selected_pca.push(component);112 } else if (curr_color == "rgb(254, 211, 72)"){ // if point is being de-selected113 d3.select(this).style("fill", "rgb(105, 179, 162)");114 d3.select(this).attr("class","");115 total_variance_captured = parseFloat(total_variance_captured) - parseFloat(component_variance);116 var index = selected_pca.indexOf(component);117 selected_pca.splice(index, 1);118 }119 // to make sure -0 never happens120 total_variance_captured = Math.abs(total_variance_captured);121 //clear heatmap122 d3.select(heatmapsvg.node())123 .selectAll("text")124 .remove();125 d3.select(heatmapsvg.node())126 .selectAll("rect")127 .remove();128 d3.select(heatmapsvg2.node())129 .selectAll("text")130 .remove();131 d3.select(heatmapsvg2.node())132 .selectAll("rect")133 .remove();134 // change heatmap135 if (selected_pca.length > 0) {136 rest_pca = whole_pca.filter( function( el ) {137 return selected_pca.indexOf( el ) < 0;138 });139 } else {140 rest_pca = [];141 }142 heatmap(dataset, freq_sing_val_file, selected_pca, heatmapsvg, lowrank, true, total_variance_captured);143 heatmap(dataset, freq_sing_val_file, rest_pca, heatmapsvg2, lowrank, false, total_variance_captured);144 // change variance explained label145 if (total_variance_captured == 0){146 variance_explained_label.text("0%");147 } else {148 variance_explained_label.text((total_variance_captured*100).toFixed(2) + "%");149 }150 })151 // total variance explained label152 const variance_explained_label = varchart.append('text')153 .attr('class', 'year')154 .attr('x', 200)155 .attr('y', 100)156 .attr('fill', '#ccc')157 .attr('font-family', 'Helvetica Neue, Arial')158 .attr('font-weight', 500)159 .attr('font-size', 60)160 .text(total_variance_captured + "%");161 });...
matrixMoments.js
Source:matrixMoments.js
1function columns2D(a,columns) {2 const {thread:{x},constants:{size}}=this,column=columns[x];3 let sum=0,sumSquared=0,sumCubed=0;4 for(let i=0;i<size; i++) {5 const v=a[i][column],v2=v*v,v3=v2*v;6 sum+=v;7 sumSquared+=v2;8 sumCubed+=v3;9 }10 const average=sum/size,11 variance=(sumSquared/size)-average**2,12 stdDev=Math.sqrt(variance),13 skew=(sumCubed-3*average*variance-average**3)/(variance*stdDev);14 return [average,variance,skew];15}16function columns3D(a) {17 const {thread:{x},constants:{size}}=this;18 let sum=0,sumSquared=0,sumCubed=0;19 for(let i=0;i<size; i++) {20 const v=a[i][x],v2=v*v,v3=v2*v;21 sum+=v;22 sumSquared+=v2;23 sumCubed+=v3;24 }25 const average=sum/size,26 variance=(sumSquared/size)-average**2,27 stdDev=Math.sqrt(variance),28 skew=(sumCubed-3*average*variance-average**3)/(variance*stdDev);29 return [average,variance,skew];30}31function rows2D(a,rows) {32 const {thread:{x},constants:{size}}=this,row=rows[x];33 let sum=0,sumSquared=0,sumCubed=0;34 for(let i=0;i<size; i++) {35 const v=a[row][i],v2=v*v,v3=v2*v;36 sum+=v;37 sumSquared+=v2;38 sumCubed+=v3;39 }40 const average=sum/size,41 variance=(sumSquared/size)-average**2,42 stdDev=Math.sqrt(variance),43 skew=(sumCubed-3*average*variance-average**3)/(variance*stdDev);44 return [average,variance,skew];45}46function rows3D(a) {47 const {thread:{x},constants:{size}}=this;48 let sum=0,sumSquared=0,sumCubed=0;49 for(let i=0;i<size; i++) {50 const v=a[x][i],v2=v*v,v3=v2*v;51 sum+=v;52 sumSquared+=v2;53 sumCubed+=v3;54 }55 const average=sum/size,56 variance=(sumSquared/size)-average**2,57 stdDev=Math.sqrt(variance),58 skew=(sumCubed-3*average*variance-average**3)/(variance*stdDev);59 return [average,variance,skew];60}61module.exports={62 columns2D:columns2D,63 columns3D:columns3D,64 rows2D:rows2D,65 rows3D:rows3D
...
variance-test.js
Source:variance-test.js
...5suite.addBatch({6 "variance": {7 topic: load("arrays/variance").expression("d3.variance"),8 "returns the variance value for numbers": function(variance) {9 assert.isUndefined(variance([1]));10 assert.equal(variance([5, 1, 2, 3, 4]), 2.5);11 assert.equal(variance([20, 3]), 144.5);12 assert.equal(variance([3, 20]), 144.5);13 },14 "ignores null, undefined and NaN": function(variance) {15 assert.equal(variance([NaN, 1, 2, 3, 4, 5]), 2.5);16 assert.equal(variance([1, 2, 3, 4, 5, NaN]), 2.5);17 assert.equal(variance([10, null, 3, undefined, 5, NaN]), 13);18 },19 "can handle large numbers without overflowing": function(variance) {20 assert.equal(variance([Number.MAX_VALUE, Number.MAX_VALUE]), 0);21 assert.equal(variance([-Number.MAX_VALUE, -Number.MAX_VALUE]), 0);22 },23 "returns undefined for empty array": function(variance) {24 assert.isUndefined(variance([]));25 assert.isUndefined(variance([null]));26 assert.isUndefined(variance([undefined]));27 assert.isUndefined(variance([NaN]));28 assert.isUndefined(variance([NaN, NaN]));29 },30 "applies the optional accessor function": function(variance) {31 assert.equal(variance([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], mean), 4.5);32 assert.equal(variance([1, 2, 3, 4, 5], function(d, i) { return i; }), 2.5);33 }34 }35});36function mean(array) {37 return array.reduce(function(p, v) { return p + v; }) / array.length;38}...
Using AI Code Generation
1var x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];2var y = [1, 3, 2, 5, 7, 8, 8, 9, 10, 12];3var n = 10;4var sumX = 0;5var sumY = 0;6var sumXY = 0;7var sumX2 = 0;8var sumY2 = 0;9var i = 0;10var meanX = 0;11var meanY = 0;12var slope = 0;13var intercept = 0;14var r = 0;15var r2 = 0;16for (i = 0; i < n; i++) {17 sumX += x[i];18 sumY += y[i];19 sumXY += x[i] * y[i];20 sumX2 += x[i] * x[i];21 sumY2 += y[i] * y[i];22}23meanX = sumX / n;24meanY = sumY / n;25slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);26intercept = meanY - slope * meanX;27r = (n * sumXY - sumX * sumY) / Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));28r2 = r * r;29console.log("slope: " + slope);30console.log("intercept: " + intercept);31console.log("r: " + r);32console.log("r2: " + r2);
Using AI Code Generation
1var BestFitLine = require('./test3.js');2var line = new BestFitLine();3line.addDataPoint(0,0);4line.addDataPoint(1,1);5line.addDataPoint(2,2);6line.addDataPoint(3,3);7line.addDataPoint(4,4);8line.addDataPoint(5,5);9line.addDataPoint(6,6);10line.addDataPoint(7,7);11line.addDataPoint(8,8);12line.addDataPoint(9,9);13console.log(line.slope);14console.log(line.intercept);15console.log(line.rSquared);16var BestFitLine = function() {17 this.n = 0;18 this.sumX = 0;19 this.sumY = 0;20 this.sumXX = 0;21 this.sumXY = 0;22 this.slope = 0;23 this.intercept = 0;24 this.rSquared = 0;25};26BestFitLine.prototype.addDataPoint = function(x, y) {27 this.n++;28 this.sumX += x;29 this.sumY += y;30 this.sumXX += x * x;31 this.sumXY += x * y;32 this.slope = (this.n * this.sumXY - this.sumX * this.sumY) /33 (this.n * this.sumXX - this.sumX * this.sumX);34 this.intercept = (this.sumY - this.slope * this.sumX) / this.n;35 this.rSquared = Math.pow((this.n * this.sumXY - this.sumX * this.sumY) /36 Math.sqrt((this.n * this.sumXX - this.sumX * this.sumX) *37 (this.n * this.sumYY - this.sumY * this.sumY)), 2);38};39BestFitLine.prototype.toString = function() {40 return 'y = ' + this.slope.toFixed(2) + 'x + ' + this.intercept.toFixed(2);41};42module.exports = BestFitLine;43var BestFitLine = require('./test3.js');44var line = new BestFitLine();45line.addDataPoint(0,0);46line.addDataPoint(1,1);47line.addDataPoint(2,2);48line.addDataPoint(3,3);49line.addDataPoint(4,4);50line.addDataPoint(5,5);51line.addDataPoint(6,6
Using AI Code Generation
1var BestFitLine = require("./BestFitLine");2var bfl = new BestFitLine();3bfl.readData("test4.dat");4console.log("Data read from file: ");5bfl.printData();6bfl.calcVariance();7bfl.printResults();8console.log("Best fit line: ");9bfl.printBestFitLine();
Using AI Code Generation
1var BFLV = require('./BFLV.js');2var BFLC = require('./BFLC.js');3var BFL = require('./BFL.js');4var x = [1, 2, 3, 4, 5];5var y = [1, 2, 3, 4, 5];6var bflv = new BFLV(x, y);7console.log(bflv.toString());8var bflc = new BFLC(x, y);9console.log(bflc.toString());10var bfl = new BFL(x, y);11console.log(bfl.toString());
Using AI Code Generation
1function bestFitLine(dataPoints, returnedValues) {2 var sumX = 0;3 var sumY = 0;4 var sumXY = 0;5 var sumX2 = 0;6 var n = dataPoints.length;7 for (var i = 0; i < n; i++) {8 sumX += dataPoints[i][0];9 sumY += dataPoints[i][1];10 sumXY += dataPoints[i][0] * dataPoints[i][1];11 sumX2 += dataPoints[i][0] * dataPoints[i][0];12 }13 var slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);14 var yIntercept = (sumY - slope * sumX) / n;15 returnedValues[0] = slope;16 returnedValues[1] = yIntercept;17}18];19var returnedValues = [];20bestFitLine(dataPoints, returnedValues);21document.write("slope: ", returnedValues[0], "<br>");22document.write("y-intercept: ", returnedValues[1], "<br>");
Using AI Code Generation
1var data = readFile("data.txt");2var line = getBestFitLine(data);3var y = line.predict(10);4var actualY = 100;5var error = y - actualY;6print("Predicted y value: " + y);7print("Actual y value: " + actualY);8print("Error: " + error);9var data = readFile("data.txt");10var line = getBestFitLine(data, "leastSquares");11var y = line.predict(10);12var actualY = 100;13var error = y - actualY;
Using AI Code Generation
1var dataSort = [];2for (var i = 0; i < data2.length; i++) {3 dataSort.push(data2[i]);4}5for (var i = 0; i < data3.length; i++) {6 dataSort.push(data3[i]);7}8dataSort.sort(function (a, b) {9 return a.independent - b.independent;10});11var sumX = 0;12var sumY = 0;13var sumXSquared = 0;14var sumYSquared = 0;15var sumXY = 0;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!