fixed network

master
parent 877575a375
commit ba8ddb2831
  1. BIN
      __pycache__/run.cpython-37.pyc
  2. 2
      cachedir/joblib/run/executeModel/72a755383fba437e4dead6ff3e3d81e3/metadata.json
  3. 4
      cachedir/joblib/run/executeModel/func_code.py
  4. 22
      frontend/package-lock.json
  5. 1
      frontend/package.json
  6. 2
      frontend/src/components/DataSetExecController.vue
  7. 391
      frontend/src/components/FeatureSpace2.vue
  8. 96
      frontend/src/components/Main.vue
  9. 99
      frontend/src/components/Slider.vue
  10. 379
      frontend/src/greadability.js
  11. 73
      run.py

Binary file not shown.

@ -1 +1 @@
{"duration": 4.569021940231323, "input_args": {}}
{"duration": 7.80327582359314, "input_args": {}}

@ -7,11 +7,9 @@ def executeModel():
params = {"C": (0.0001, 10000), "gamma": (0.0001, 10000)}
svc_bayesopt = BayesianOptimization(estimator, params)
svc_bayesopt.maximize(init_points=5, n_iter=20, acq='ucb')
svc_bayesopt.maximize(init_points=10, n_iter=25, acq='ucb')
bestParams = svc_bayesopt.max['params']
estimator = SVC(C=bestParams.get('C'), gamma=bestParams.get('gamma'), probability=True)
estimator.fit(XData, yData)
yPredict = estimator.predict(XData)
yPredictProb = cross_val_predict(estimator, XData, yData, cv=crossValidation, method='predict_proba')
return 'Everything Okay'

@ -9418,6 +9418,28 @@
"d3-path": "1"
}
},
"d3-simple-slider": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/d3-simple-slider/-/d3-simple-slider-1.7.0.tgz",
"integrity": "sha512-8Vjxdxc8CXohlKYwdjw2J7/uzxOq6njvdBZflK/cn9XT0bZ4ydVLEXr4BM37306hj7FqLFZ8QSakCiHEukmTtQ==",
"requires": {
"d3-array": "^1.0.0",
"d3-axis": "^1.0.8",
"d3-dispatch": "^1.0.0",
"d3-drag": "^1.0.0",
"d3-ease": "^1.0.0",
"d3-scale": "^2.0.0",
"d3-selection": "^1.0.0",
"d3-transition": "^1.0.0"
},
"dependencies": {
"d3-array": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-1.2.4.tgz",
"integrity": "sha512-KHW6M86R+FUPYGb3R5XiYjXPq7VzwxZ22buHhAEVG5ztoEcZZMLov530mmccaqA1GghZArjQV46fuc8kUqhhHw=="
}
}
},
"d3-svg-legend": {
"version": "1.13.0",
"resolved": "https://registry.npmjs.org/d3-svg-legend/-/d3-svg-legend-1.13.0.tgz",

@ -43,6 +43,7 @@
"d3-loom": "^1.0.2",
"d3-selection": "^1.4.1",
"d3-selection-multi": "^1.0.1",
"d3-simple-slider": "^1.7.0",
"d3-svg-legend": "^1.13.0",
"d3_exploding_boxplot": "^0.2.1",
"file-saver": "^2.0.2",

@ -35,7 +35,7 @@ export default {
data () {
return {
defaultDataSet: 'HeartC', // default value for the first data set
searchText: 'Hyper-parameter search',
searchText: 'Exploration of Features',
resetText: 'Reset',
dataset: 'Data set'
}

@ -1,30 +1,13 @@
<template>
<div>
<label id="data" for="param-dataset" data-toggle="tooltip" data-placement="right" title="Tip: use one of the data sets already provided or upload a new file.">{{ dataset }}</label>
<select id="selectFile" @change="selectDataSet()">
<option value="HeartC.csv" selected>Heart Disease</option>
<option value="IrisC.csv">Iris</option>
<option value="local">Upload New File</option>
</select>
<button class="btn-outline-success"
id="initializeID"
v-on:click="initialize">
<font-awesome-icon icon="search" />
{{ searchText }}
</button>
<button class="btn-outline-danger"
id="resetID"
v-on:click="reset">
<font-awesome-icon icon="trash" />
{{ resetText }}
</button>
<div class="column">
<svg class="chart"></svg>
<div id="FeatureGraph2"></div>
</div>
</template>
<script>
import Papa from 'papaparse'
import { EventBus } from '../main.js'
import {$,jQuery} from 'jquery';
import * as greadability from '../greadability.js'
import * as d3Base from 'd3'
// attach all d3 plugins to the d3 library
@ -34,53 +17,335 @@ export default {
name: 'FeatureSpace2',
data () {
return {
defaultDataSet: 'HeartC', // default value for the first data set
searchText: 'Hyper-parameter search',
resetText: 'Reset',
dataset: 'Data set'
dataFS2: [],
jsonData: [],
}
},
methods: {
selectDataSet () {
const fileName = document.getElementById('selectFile')
this.defaultDataSet = fileName.options[fileName.selectedIndex].value
this.defaultDataSet = this.defaultDataSet.split('.')[0]
if (this.defaultDataSet == "DiabetesC" || this.defaultDataSet == "HeartC" || this.defaultDataSet == "IrisC" || this.defaultDataSet == "StanceC") { // This is a function that handles a new file, which users can upload.
this.dataset = "Data set"
d3.select("#data").select("input").remove(); // Remove the selection field.
EventBus.$emit('SendToServerDataSetConfirmation', this.defaultDataSet)
} else {
EventBus.$emit('SendToServerDataSetConfirmation', this.defaultDataSet)
d3.select("#data").select("input").remove();
this.dataset = ""
var data
d3.select("#data")
.append("input")
.attr("type", "file")
.style("font-size", "18.5px")
.style("width", "200px")
.on("change", function() {
var file = d3.event.target.files[0];
Papa.parse(file, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
complete: function(results) {
data = results.data;
EventBus.$emit('SendToServerLocalFile', data)
}
});
initializeNetwork () {
var dataLoc = JSON.parse(this.dataFS2[1])
var listofNodes = this.dataFS2[4]
var nodes = []
listofNodes.forEach(element => nodes.push({"name": element}))
var links = []
Object.entries(dataLoc).forEach(
function ([feature, value]) {
Object.entries(value).forEach( function ([featureInside, value]) {
if (feature != featureInside) {
if (value >= 0) {
links.push({"source": listofNodes.indexOf(feature), "target": listofNodes.indexOf(featureInside), "value": Math.abs(value) * 30, "group": 1})
} else {
links.push({"source": listofNodes.indexOf(feature), "target": listofNodes.indexOf(featureInside), "value": Math.abs(value) * 30, "group": 2})
}
}
})
})
this.jsonData = {"nodes": nodes, "links": links};
this.graphVizualization()
},
graphVizualization () {
var width = 600;
var height = 500;
var chartWidth = 600;
var chartHeight = 60;
var margin = {left: 10, right: 10, top: 10, bottom: 40};
var numTicks = 200;
var selectedParams;
var bestParams;
var dispatch = d3.dispatch('layoutend');
var svg = d3.select("#FeatureGraph2").append("svg")
.attr("width", width)
.attr("height", height);
var chartSvg = d3.select('svg.chart')
.attr('width', chartWidth)
.attr('height', chartHeight)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
chartWidth = chartWidth - margin.left - margin.right;
chartHeight = chartHeight - margin.top - margin.bottom;
var x = d3.scaleLinear()
.domain([0, 1])
.range([0, chartWidth]);
chartSvg.append('g')
.attr('transform', 'translate(0,' + chartHeight + ')')
.call(d3.axisBottom(x).ticks(7))
.append("text")
.attr("fill", "#000")
.attr('transform', 'translate(' + chartWidth/2 + ',' + 0 + ')')
.attr("y", chartHeight + 10)
.attr("dy", "0.71em")
.attr("text-anchor", "middle")
.text("Average readability score");
var readabilityCircles = chartSvg.append('g').selectAll('circle');
var graph = this.jsonData
var link = svg.append('g')
.attr('class', 'links')
.selectAll('line')
.data(graph.links)
.enter().append('line')
.attr("stroke-width", function(d) { return Math.sqrt(d.value); });
var node = svg.append('g')
.attr('class', 'nodes')
.selectAll('g')
.data(graph.nodes)
.enter().append('g')
var circles = node.append("circle")
.attr("r", 5);
console.log(node)
var labels = node.append("text")
.text(function(d) {
console.log(d)
return d.name;
})
}
},
reset () {
EventBus.$emit('reset')
EventBus.$emit('alternateFlagLock')
.attr('x', 6)
.attr('y', 3);
node.append('title').text(function (d) { return d.name; });
var paramGroups = [
{name: 'chargeStrength', values: [-30, -80]},
{name: 'linkDistance', values: [30, -80]},
{name: 'linkStrength', values: [0, 1]},
{name: 'gravity', values: [0, 0.5]},
{name: 'iterations', values: [1, 2]},
{name: 'alphaDecay', values: [0, 0.0228, 0.05]},
{name: 'velocityDecay', values: [0.4, 0.8]}
];
var paramList = generateParams(paramGroups);
var bestSoFar = d3.select('.best').selectAll('li')
.data(paramGroups.map(function (d) { return d.name; }))
.enter().append('li')
.text(function (d) { return d; });
dispatch.on('layoutend', function (params, i) {
if (!bestParams || params.graphReadability > bestParams.graphReadability) {
bestParams = params;
selectedParams = bestParams;
bestSoFar
.data(d3.map(bestParams).keys().filter(function (d) { return d !== 'positions' && d !== 'graphReadability'; }))
.text(function (d) { return d + ' = ' + bestParams[d]; });
}
d3.select('.progress').text('Testing ' + (i + 1) + ' of ' + paramList.length + ' parameter settings');
// Plot the number line.
readabilityCircles = readabilityCircles
.data(readabilityCircles.data().concat(params))
.enter().append('circle')
.attr('cx', function (d) { return x(d.graphReadability); })
.attr('cy', 5)
.attr('r', 4)
.on('click', function (d) {
selectedParams = d;
readabilityCircles.classed('selected', false);
d3.select(this).classed('selected', true).raise();
bestSoFar
.data(d3.map(selectedParams).keys().filter(function (d) { return d !== 'positions' && d !== 'graphReadability'; }))
.text(function (d) { return d + ' = ' + selectedParams[d]; });
drawGraph();
})
.merge(readabilityCircles)
.classed('selected', function (d) { return d === selectedParams; });
readabilityCircles.filter(function (d) { return d === selectedParams; })
.raise();
drawGraph();
});
var i = 0;
var stepper = d3.timer(function () {
var p = paramList[i];
var forceSim = getForceSimFromParams(p);
// Reset node attributes.
graph.nodes.forEach(function (n) {
n.x = n.y = n.vx = n.vy = 0;
});
forceSim.nodes(graph.nodes)
.stop();
forceSim.force('link')
.links(graph.links);
for (var t = 0; t < numTicks; ++t) {
forceSim.tick();
}
p.graphReadability = greadability.greadability(graph.nodes, graph.links);
p.graphReadability = (p.graphReadability.crossing + p.graphReadability.crossingAngle +
p.graphReadability.angularResolutionMin + p.graphReadability.angularResolutionDev) / 4
p.positions = graph.nodes.map(function (n) { return {x: n.x, y: n.y}; });
dispatch.call('layoutend', forceSim, p, i);
++i;
if (i >= paramList.length) {
stepper.stop();
}
});
function drawGraph () {
graph.nodes.forEach(function (n, i) {
n.x = selectedParams.positions[i].x;
n.y = selectedParams.positions[i].y;
});
var xDistance = d3.extent(graph.nodes, function (n) { return n.x; });
var xMin = xDistance[0];
xDistance = xDistance[1] - xDistance[0];
var yDistance = d3.extent(graph.nodes, function (n) { return n.y; });
var yMin = yDistance[0];
yDistance = yDistance[1] - yDistance[0];
graph.nodes.forEach(function (n, i) {
n.x = (height - 10) * (n.x - xMin) / Math.max(xDistance, yDistance);
n.y = (height - 10) * (n.y - yMin) / Math.max(xDistance, yDistance);
});
xDistance = d3.extent(graph.nodes, function (n) { return n.x; });
var xMid = (xDistance[1] + xDistance[0]) / 2;
yDistance = d3.extent(graph.nodes, function (n) { return n.y; });
var yMid = (yDistance[1] - yDistance[0]) / 2;
graph.nodes.forEach(function (n, i) {
n.x = n.x + width/2 - xMid;
n.y = n.y + height/2 - yMid;
});
link
.attr('x1', function (d) { return d.source.x; })
.attr('x2', function (d) { return d.target.x; })
.attr('y1', function (d) { return d.source.y; })
.attr('y2', function (d) { return d.target.y; });
node
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
})
}
function generateParams (paramGroups, paramList, currParam) {
var p = paramGroups[0];
if (!paramList) paramList = [];
if (!currParam) currParam = {};
p.values.forEach(function (v) {
var setting = {};
setting[p.name] = v;
if (paramGroups.length === 1) {
paramList.push(Object.assign(setting, currParam));
} else {
generateParams(paramGroups.slice(1), paramList, Object.assign(setting, currParam));
}
});
return paramList;
}
function getForceSimFromParams (params) {
var forceSim = d3.forceSimulation()
.force('link', d3.forceLink().iterations(params.iterations))
.force('charge', d3.forceManyBody().strength(params.chargeStrength))
.force('x', d3.forceX(0).strength(params.gravity))
.force('y', d3.forceY(0).strength(params.gravity))
.force('center', d3.forceCenter(0, 0))
.alphaDecay(params.alphaDecay)
.velocityDecay(params.velocityDecay);
if (params.linkStrength !== null) {
forceSim.force('link').strength(params.linkStrength);
}
return forceSim;
}
},
reset () {
var svg = d3.select("#FeatureSpaceVisual");
svg.selectAll("*").remove();
},
},
initialize () {
EventBus.$emit('ConfirmDataSet')
}
mounted () {
EventBus.$on('quad', data => { this.dataFS2 = data })
EventBus.$on('quad', this.initializeNetwork)
}
}
</script>
<style>
text {
font-family: sans-serif;
font-size: 10px;
}
svg {
display: block;
}
.links line {
stroke: #999;
stroke-opacity: 0.6;
}
.nodes circle {
fill: #000000;
stroke: #fff;
stroke-width: 1px;
}
.chart circle {
fill: #aaa;
fill-opacity: 0.1;
stroke: #aaa;
stroke-opacity: 0.4;
cursor: pointer;
}
.chart circle.selected {
fill: #d30000;
fill-opacity: 0.6;
stroke: #d30000;
stroke-opacity: 0.8;
}
.column {
float: left;
margin: 0 10px;
}
</style>

@ -10,6 +10,7 @@
<mdb-card-body>
<mdb-card-text class="text-left" style="font-size: 18.5px;">
<DataSetExecController/>
<Slider/>
</mdb-card-text>
</mdb-card-body>
</mdb-card>
@ -170,6 +171,7 @@
import Vue from 'vue'
import DataSetExecController from './DataSetExecController.vue'
import Slider from './Slider.vue'
import FeatureSpace1 from './FeatureSpace1.vue'
import FeatureSpace2 from './FeatureSpace2.vue'
import FeatureSpace3 from './FeatureSpace3.vue'
@ -192,6 +194,7 @@ export default Vue.extend({
name: 'Main',
components: {
DataSetExecController,
Slider,
FeatureSpace1,
FeatureSpace2,
FeatureSpace3,
@ -203,6 +206,8 @@ export default Vue.extend({
},
data () {
return {
PositiveValue: 75,
NegativeValue: 25,
unselectedRemainingPoints: [],
Collection: 0,
OverviewResults: 0,
@ -385,30 +390,12 @@ export default Vue.extend({
axios.post(path, postData, axiosConfig)
.then(response => {
console.log('File name was sent successfully!')
this.SendAlgorithmsToServer()
this.threshold()
})
.catch(error => {
console.log(error)
})
},
SendAlgorithmsToServer () {
const path = `http://127.0.0.1:5000/data/ServerRequestResults`
const axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS'
}
}
axios.post(path, postData, axiosConfig)
.then(response => {
console.log('Send request to server! Algorithm name was sent successfully!')
})
.catch(error => {
console.log(error)
})
},
Reset () {
const path = `http://127.0.0.1:5000/data/Reset`
this.reset = true
@ -470,6 +457,50 @@ export default Vue.extend({
console.log(error)
})
},
threshold () {
const path = `http://127.0.0.1:5000/data/thresholdDataSpace`
const postData = {
PositiveValue: this.PositiveValue,
NegativeValue: this.NegativeValue
}
const axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS'
}
}
axios.post(path, postData, axiosConfig)
.then(response => {
console.log('Sent the thresholds to the server side!')
this.returnCorrel()
})
.catch(error => {
console.log(error)
})
},
returnCorrel () {
const path = `http://127.0.0.1:5000/data/returnCorrelations`
const axiosConfig = {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token',
'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS'
}
}
axios.get(path, axiosConfig)
.then(response => {
console.log('Server successfully send the correlation matrices!')
this.correlResul = response.data.correlResul
EventBus.$emit('quad', this.correlResul)
})
.catch(error => {
console.log(error)
})
}
},
created () {
// does the browser support the Navigation Timing API?
@ -531,12 +562,6 @@ export default Vue.extend({
EventBus.$on('SendToServerLocalFile', data => { this.localFile = data })
EventBus.$on('SendToServerLocalFile', this.SendToServerData)
EventBus.$on('PCPCall', data => { this.selectedAlgorithm = data })
EventBus.$on('toggle1', data => { this.toggle1 = data })
EventBus.$on('toggle2', data => { this.toggle2 = data })
EventBus.$on('toggle3', data => { this.toggle3 = data })
EventBus.$on('toggle1', this.updateToggle)
EventBus.$on('toggle2', this.updateToggle)
EventBus.$on('toggle3', this.updateToggle)
EventBus.$on('PCPCall', this.CallPCP)
EventBus.$on('PCPCallDB', this.SendBrushedParameters)
EventBus.$on('UpdateBoxPlot', data => { this.brushedBoxPlotUpdate = data })
@ -554,24 +579,11 @@ export default Vue.extend({
EventBus.$on('AllSelModels', data => {this.valueSel = data})
EventBus.$on('RemoveFromStack', data => { this.ClassifierIDsListRemaining = data })
EventBus.$on('RemoveFromStack', this.RemoveFromStackModels)
EventBus.$on('OpenModal', this.openModalFun)
EventBus.$on('SendSelectedPointsToServerEventfromData', data => {this.dataPointsSelfromDataSpace = data})
EventBus.$on('SendSelectedPointsToServerEventfromData', this.DataSpaceFun)
EventBus.$on('SendFilter', data => {this.filterData = data})
EventBus.$on('SendFilter', this.FilterFun)
EventBus.$on('SendAction', data => {this.actionData = data})
EventBus.$on('SendAction', this.ActionFun)
EventBus.$on('SendProvenance', data => {this.provenanceData = data})
EventBus.$on('SendProvenance', this.ProvenanceControlFun)
EventBus.$on('SendtheChangeinRangePos', data => {this.PositiveValue = data})
EventBus.$on('SendtheChangeinRangeNeg', data => {this.NegativeValue = data})
EventBus.$on('SendtheChangeinRangePos', this.threshold)
EventBus.$on('SendtheChangeinRangeNeg', this.threshold)
EventBus.$on('toggleDeep', data => {this.toggleDeepMain = data})
//Prevent double click to search for a word.
document.addEventListener('mousedown', function (event) {

@ -0,0 +1,99 @@
<template>
<div>
<div class="row align-items-center">
<div class="col-lg-2"><p>Positive</p></div>
<div class="col-lg-8"><div id="slider-stepPos"></div></div>
<div class="col-lg-2"><p id="value-stepPos"></p></div>
</div>
<div class="row align-items-center">
<div class="col-lg-2"><p>Negative</p></div>
<div class="col-lg-8"><div id="slider-stepNeg"></div></div>
<div class="col-lg-2"><p id="value-stepNeg"></p></div>
</div>
</div>
</template>
<script>
import { EventBus } from '../main.js'
import { sliderBottom } from 'd3-simple-slider'
import * as d3Base from 'd3'
// attach all d3 plugins to the d3 library
const d3 = Object.assign(d3Base, { sliderBottom })
export default {
name: 'Slider',
data () {
return {
}
},
methods: {
InitSliders () {
var dataCorrect = [55.0, 60.0, 65.0, 70.0, 75.0, 80.0, 85.0, 90.0, 95.0];
var dataWrong = [5.0, 10.0, 15.0, 20.0, 25.0, 30.0, 35.0, 40.0, 45.0];
var sliderStepPos = d3
.sliderBottom()
.min(d3.min(dataCorrect))
.max(d3.max(dataCorrect))
.width(300)
.tickFormat(d3.format(".0f"))
.ticks(9)
.step(5)
.default(75.0)
.on('onchange', val => {
d3.select('p#value-stepPos').text(d3.format(".0f")(val));
EventBus.$emit('SendtheChangeinRangePos', d3.format(".0f")(val))
});
var gStepPos = d3
.select('div#slider-stepPos')
.append('svg')
.attr('width', 500)
.attr('height', 100)
.append('g')
.attr('transform', 'translate(30,30)');
gStepPos.call(sliderStepPos);
d3.select('p#value-stepPos').text(d3.format(".0f")(sliderStepPos.value()));
var sliderStepNeg = d3
.sliderBottom()
.min(d3.min(dataWrong))
.max(d3.max(dataWrong))
.width(300)
.tickFormat(d3.format(".0f"))
.ticks(9)
.step(5)
.default(25.0)
.on('onchange', val => {
d3.select('p#value-stepNeg').text(d3.format(".0f")(val));
EventBus.$emit('SendtheChangeinRangeNeg', d3.format(".0f")(val))
});
var gStepNeg = d3
.select('div#slider-stepNeg')
.append('svg')
.attr('width', 500)
.attr('height', 100)
.append('g')
.attr('transform', 'translate(30,30)');
gStepNeg.call(sliderStepNeg);
d3.select('p#value-stepNeg').text(d3.format(".0f")(sliderStepNeg.value()));
},
reset () {
EventBus.$emit('reset')
EventBus.$emit('alternateFlagLock')
},
initialize () {
EventBus.$emit('ConfirmDataSet')
}
},
mounted () {
this.InitSliders()
},
}
</script>

@ -0,0 +1,379 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.greadability = global.greadability || {})));
}(this, (function (exports) { 'use strict';
var greadability = function (nodes, links, id) {
var i,
j,
n = nodes.length,
m,
degree = new Array(nodes.length),
cMax,
idealAngle = 70,
dMax;
/*
* Tracks the global graph readability metrics.
*/
var graphStats = {
crossing: 0, // Normalized link crossings
crossingAngle: 0, // Normalized average dev from 70 deg
angularResolutionMin: 0, // Normalized avg dev from ideal min angle
angularResolutionDev: 0, // Normalized avg dev from each link
};
var getSumOfArray = function (numArray) {
var i = 0, n = numArray.length, sum = 0;
for (; i < n; ++i) sum += numArray[i];
return sum;
};
var initialize = function () {
var i, j, link;
var nodeById = {};
// Filter out self loops
links = links.filter(function (l) {
return l.source !== l.target;
});
m = links.length;
if (!id) {
id = function (d) { return d.index; };
}
for (i = 0; i < n; ++i) {
nodes[i].index = i;
degree[i] = [];
nodeById[id(nodes[i], i, nodeById)] = nodes[i];
}
// Make sure source and target are nodes and not indices.
for (i = 0; i < m; ++i) {
link = links[i];
if (typeof link.source !== "object") link.source = nodeById[link.source];
if (typeof link.target !== "object") link.target = nodeById[link.target];
}
// Filter out duplicate links
var filteredLinks = [];
links.forEach(function (l) {
var s = l.source, t = l.target;
if (s.index > t.index) {
filteredLinks.push({source: t, target: s});
} else {
filteredLinks.push({source: s, target: t});
}
});
links = filteredLinks;
links.sort(function (a, b) {
if (a.source.index < b.source.index) return -1;
if (a.source.index > b.source.index) return 1;
if (a.target.index < b.target.index) return -1;
if (a.target.index > b.target.index) return 1;
return 0;
});
i = 1;
while (i < links.length) {
if (links[i-1].source.index === links[i].source.index &&
links[i-1].target.index === links[i].target.index) {
links.splice(i, 1);
}
else ++i;
}
// Update length, if a duplicate was deleted.
m = links.length;
// Calculate degree.
for (i = 0; i < m; ++i) {
link = links[i];
link.index = i;
degree[link.source.index].push(link);
degree[link.target.index].push(link);
};
}
// Assume node.x and node.y are the coordinates
function direction (pi, pj, pk) {
var p1 = [pk[0] - pi[0], pk[1] - pi[1]];
var p2 = [pj[0] - pi[0], pj[1] - pi[1]];
return p1[0] * p2[1] - p2[0] * p1[1];
}
// Is point k on the line segment formed by points i and j?
// Inclusive, so if pk == pi or pk == pj then return true.
function onSegment (pi, pj, pk) {
return Math.min(pi[0], pj[0]) <= pk[0] &&
pk[0] <= Math.max(pi[0], pj[0]) &&
Math.min(pi[1], pj[1]) <= pk[1] &&
pk[1] <= Math.max(pi[1], pj[1]);
}
function linesCross (line1, line2) {
var d1, d2, d3, d4;
// CLRS 2nd ed. pg. 937
d1 = direction(line2[0], line2[1], line1[0]);
d2 = direction(line2[0], line2[1], line1[1]);
d3 = direction(line1[0], line1[1], line2[0]);
d4 = direction(line1[0], line1[1], line2[1]);
if (((d1 > 0 && d2 < 0) || (d1 < 0 && d2 > 0)) &&
((d3 > 0 && d4 < 0) || (d3 < 0 && d4 > 0))) {
return true;
} else if (d1 === 0 && onSegment(line2[0], line2[1], line1[0])) {
return true;
} else if (d2 === 0 && onSegment(line2[0], line2[1], line1[1])) {
return true;
} else if (d3 === 0 && onSegment(line1[0], line1[1], line2[0])) {
return true;
} else if (d4 === 0 && onSegment(line1[0], line1[1], line2[1])) {
return true;
}
return false;
}
function linksCross (link1, link2) {
// Self loops are not intersections
if (link1.index === link2.index ||
link1.source === link1.target ||
link2.source === link2.target) {
return false;
}
// Links cannot intersect if they share a node
if (link1.source === link2.source ||
link1.source === link2.target ||
link1.target === link2.source ||
link1.target === link2.target) {
return false;
}
var line1 = [
[link1.source.x, link1.source.y],
[link1.target.x, link1.target.y]
];
var line2 = [
[link2.source.x, link2.source.y],
[link2.target.x, link2.target.y]
];
return linesCross(line1, line2);
}
function linkCrossings () {
var i, j, c = 0, d = 0, link1, link2, line1, line2;;
// Sum the upper diagonal of the edge crossing matrix.
for (i = 0; i < m; ++i) {
for (j = i + 1; j < m; ++j) {
link1 = links[i], link2 = links[j];
// Check if link i and link j intersect
if (linksCross(link1, link2)) {
line1 = [
[link1.source.x, link1.source.y],
[link1.target.x, link1.target.y]
];
line2 = [
[link2.source.x, link2.source.y],
[link2.target.x, link2.target.y]
];
++c;
d += Math.abs(idealAngle - acuteLinesAngle(line1, line2));
}
}
}
return {c: 2*c, d: 2*d};
}
function linesegmentsAngle (line1, line2) {
// Finds the (counterclockwise) angle from line segement line1 to
// line segment line2. Assumes the lines share one end point.
// If both endpoints are the same, or if both lines have zero
// length, then return 0 angle.
// Param order matters:
// linesegmentsAngle(line1, line2) != linesegmentsAngle(line2, line1)
var temp, len, angle1, angle2, sLine1, sLine2;
// Re-orient so that line1[0] and line2[0] are the same.
if (line1[0][0] === line2[1][0] && line1[0][1] === line2[1][1]) {
temp = line2[1];
line2[1] = line2[0];
line2[0] = temp;
} else if (line1[1][0] === line2[0][0] && line1[1][1] === line2[0][1]) {
temp = line1[1];
line1[1] = line1[0];
line1[0] = temp;
} else if (line1[1][0] === line2[1][0] && line1[1][1] === line2[1][1]) {
temp = line1[1];
line1[1] = line1[0];
line1[0] = temp;
temp = line2[1];
line2[1] = line2[0];
line2[0] = temp;
}
// Shift the line so that the first point is at (0,0).
sLine1 = [
[line1[0][0] - line1[0][0], line1[0][1] - line1[0][1]],
[line1[1][0] - line1[0][0], line1[1][1] - line1[0][1]]
];
// Normalize the line length.
len = Math.hypot(sLine1[1][0], sLine1[1][1]);
if (len === 0) return 0;
sLine1[1][0] /= len;
sLine1[1][1] /= len;
// If y < 0, angle = acos(x), otherwise angle = 360 - acos(x)
angle1 = Math.acos(sLine1[1][0]) * 180 / Math.PI;
if (sLine1[1][1] < 0) angle1 = 360 - angle1;
// Shift the line so that the first point is at (0,0).
sLine2 = [
[line2[0][0] - line2[0][0], line2[0][1] - line2[0][1]],
[line2[1][0] - line2[0][0], line2[1][1] - line2[0][1]]
];
// Normalize the line length.
len = Math.hypot(sLine2[1][0], sLine2[1][1]);
if (len === 0) return 0;
sLine2[1][0] /= len;
sLine2[1][1] /= len;
// If y < 0, angle = acos(x), otherwise angle = 360 - acos(x)
angle2 = Math.acos(sLine2[1][0]) * 180 / Math.PI;
if (sLine2[1][1] < 0) angle2 = 360 - angle2;
return angle1 <= angle2 ? angle2 - angle1 : 360 - (angle1 - angle2);
}
function acuteLinesAngle (line1, line2) {
// Acute angle of intersection, in degrees. Assumes these lines
// intersect.
var slope1 = (line1[1][1] - line1[0][1]) / (line1[1][0] - line1[0][0]);
var slope2 = (line2[1][1] - line2[0][1]) / (line2[1][0] - line2[0][0]);
// If these lines are two links incident on the same node, need
// to check if the angle is 0 or 180.
if (slope1 === slope2) {
// If line2 is not on line1 and line1 is not on line2, then
// the lines share only one point and the angle must be 180.
if (!(onSegment(line1[0], line1[1], line2[0]) && onSegment(line1[0], line1[1], line2[1])) ||
!(onSegment(line2[0], line2[1], line1[0]) && onSegment(line2[0], line2[1], line1[1])))
return 180;
else return 0;
}
var angle = Math.abs(Math.atan(slope1) - Math.atan(slope2));
return (angle > Math.PI / 2 ? Math.PI - angle : angle) * 180 / Math.PI;
}
function angularRes () {
var j,
resMin = 0,
resDev = 0,
nonZeroDeg,
node,
minAngle,
idealMinAngle,
incident,
line0,
line1,
line2,
incidentLinkAngles,
nextLink;
nonZeroDeg = degree.filter(function (d) { return d.length >= 1; }).length;
for (j = 0; j < n; ++j) {
node = nodes[j];
line0 = [[node.x, node.y], [node.x+1, node.y]];
// Links that are incident to this node (already filtered out self loops)
incident = degree[j];
if (incident.length <= 1) continue;
idealMinAngle = 360 / incident.length;
// Sort edges by the angle they make from an imaginary vector
// emerging at angle 0 on the unit circle.
// Necessary for calculating angles of incident edges correctly
incident.sort(function (a, b) {
line1 = [
[a.source.x, a.source.y],
[a.target.x, a.target.y]
];
line2 = [
[b.source.x, b.source.y],
[b.target.x, b.target.y]
];
var angleA = linesegmentsAngle(line0, line1);
var angleB = linesegmentsAngle(line0, line2);
return angleA < angleB ? -1 : angleA > angleB ? 1 : 0;
});
incidentLinkAngles = incident.map(function (l, i) {
nextLink = incident[(i + 1) % incident.length];
line1 = [
[l.source.x, l.source.y],
[l.target.x, l.target.y]
];
line2 = [
[nextLink.source.x, nextLink.source.y],
[nextLink.target.x, nextLink.target.y]
];
return linesegmentsAngle(line1, line2);
});
minAngle = Math.min.apply(null, incidentLinkAngles);
resMin += Math.abs(idealMinAngle - minAngle) / idealMinAngle;
resDev += getSumOfArray(incidentLinkAngles.map(function (angle) {
return Math.abs(idealMinAngle - angle) / idealMinAngle;
})) / (2 * incident.length - 2);
}
// Divide by number of nodes with degree != 0
resMin = resMin / nonZeroDeg;
// Divide by number of nodes with degree != 0
resDev = resDev / nonZeroDeg;
return {resMin: resMin, resDev: resDev};
}
initialize();
cMax = (m * (m - 1) / 2) - getSumOfArray(degree.map(function (d) { return d.length * (d.length - 1); })) / 2;
var crossInfo = linkCrossings();
dMax = crossInfo.c * idealAngle;
graphStats.crossing = 1 - (cMax > 0 ? crossInfo.c / cMax : 0);
graphStats.crossingAngle = 1 - (dMax > 0 ? crossInfo.d / dMax : 0);
var angularResInfo = angularRes();
graphStats.angularResolutionMin = 1 - angularResInfo.resMin;
graphStats.angularResolutionDev = 1 - angularResInfo.resDev;
return graphStats;
};
exports.greadability = greadability;
Object.defineProperty(exports, '__esModule', { value: true });
})));

@ -447,26 +447,85 @@ def create_global_function():
# initialize model
model = SVC(C=C, gamma=gamma, degree=1, random_state=RANDOM_SEED)
# set in cross-validation
result = cross_validate(model, XData, yData, cv=crossValidation)
result = cross_validate(model, XData, yData, cv=crossValidation, scoring='accuracy')
# result is mean of test_score
return np.mean(result['test_score'])
location = './cachedir'
memory = Memory(location, verbose=0)
@memory.cache
# check this issue later because we are getting the same results
def executeModel():
create_global_function()
global estimator
global yPredictProb
params = {"C": (0.0001, 10000), "gamma": (0.0001, 10000)}
svc_bayesopt = BayesianOptimization(estimator, params)
svc_bayesopt.maximize(init_points=5, n_iter=20, acq='ucb')
svc_bayesopt.maximize(init_points=5, n_iter=25, acq='ucb')
bestParams = svc_bayesopt.max['params']
estimator = SVC(C=bestParams.get('C'), gamma=bestParams.get('gamma'), probability=True)
estimator.fit(XData, yData)
yPredict = estimator.predict(XData)
yPredictProb = cross_val_predict(estimator, XData, yData, cv=crossValidation, method='predict_proba')
return 'Everything Okay'
@cross_origin(origin='localhost',headers=['Content-Type','Authorization'])
@app.route('/data/thresholdDataSpace', methods=["GET", "POST"])
def Seperation():
thresholds = request.get_data().decode('utf8').replace("'", '"')
thresholds = json.loads(thresholds)
thresholdsPos = thresholds['PositiveValue']
thresholdsNeg = thresholds['NegativeValue']
getCorrectPrediction = []
for index, value in enumerate(yPredictProb):
getCorrectPrediction.append(value[yData[index]]*100)
quadrant1 = []
quadrant2 = []
quadrant3 = []
quadrant4 = []
for index, value in enumerate(getCorrectPrediction):
if (value > 50 and value > thresholdsPos):
quadrant1.append(index)
elif (value > 50 and value <= thresholdsPos):
quadrant2.append(index)
elif (value <= 50 and value > thresholdsNeg):
quadrant3.append(index)
else:
quadrant4.append(index)
Datarows1 = XData.iloc[quadrant1, :]
Datarows2 = XData.iloc[quadrant2, :]
Datarows3 = XData.iloc[quadrant3, :]
Datarows4 = XData.iloc[quadrant4, :]
global packCorr
packCorr = []
corrMatrix1 = Datarows1.corr()
corrMatrix2 = Datarows2.corr()
corrMatrix3 = Datarows3.corr()
corrMatrix4 = Datarows4.corr()
packCorr.append(corrMatrix1.to_json())
packCorr.append(corrMatrix2.to_json())
packCorr.append(corrMatrix3.to_json())
packCorr.append(corrMatrix4.to_json())
packCorr.append(list(XData.columns.values.tolist()))
return 'Everything Okay'
@app.route('/data/returnCorrelations', methods=["GET", "POST"])
def SendCorrel():
global packCorr
return 'Everything Okay'
response = {
'correlResul': packCorr
}
return jsonify(response)
Loading…
Cancel
Save