<!DOCTYPE html>
<meta charset="utf-8">
<title>Sankey Diagram</title>
<style>
#chart {
height: 500px;
}
.node rect {
cursor: move;
fill-opacity: .9;
shape-rendering: crispEdges;
}
.node text {
pointer-events: none;
text-shadow: 0 1px 0 #fff;
}
.link {
fill: none;
stroke: #000;
stroke-opacity: .2;
}
.link:hover {
stroke-opacity: .5;
}
</style>
<body>
<h1>Voters transfers during Czech presidential elections 2013 using hypothetical instant runoff voting system</h1>
<p id="chart">
<p>The data is from research conducted among users of voting advice application <a href="//volebnikalkulacka.cz">Volební kalkulačka</a>. It is weighted so the 1st round of the real elections and the 2nd round of the real elections match the 1st and last round of the potentional <a href="//en.wikipedia.org/wiki/Instant-runoff_voting">instant-runoff voting (alternative vote) electoral system</a>.</p>
<p>The analysis flow:
<ol><li>extract.py (from research.txt, not present because of the size) -> responses0</li>
<li>calc2.py -> groups18.csv</li>
<li>weights.R</li>
<li>calc3.py -> sankey.json</li>
</ol>
</p>
<script src="//d3js.org/d3.v2.min.js?2.9.1"></script>
<script src="sankey.js"></script>
<script>
var margin = {top: 1, right: 1, bottom: 6, left: 1},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatNumber = d3.format(",.0f"),
format = function(d) { return formatNumber(d); },
color = function(d){ return d.color; };//d3.scale.category20();
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var sankey = d3.sankey()
.nodeWidth(15)
.nodePadding(10)
.size([width, height]);
var path = sankey.link();
d3.json("sankey.json", function(energy) {
sankey
.nodes(energy.nodes)
.links(energy.links)
.layout(32);
var link = svg.append("g").selectAll(".link")
.data(energy.links)
.enter().append("path")
.attr("class", "link")
.attr("d", path)
.style("stroke-width", function(d) { return Math.max(1, d.dy); })
.sort(function(a, b) { return b.dy - a.dy; });
link.append("title")
.text(function(d) { return d.source.name + " → " + d.target.name + "\n" + format(d.value/11525*100) + ' %'; });
var node = svg.append("g").selectAll(".node")
.data(energy.nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
.call(d3.behavior.drag()
.origin(function(d) { return d; })
.on("dragstart", function() { this.parentNode.appendChild(this); })
.on("drag", dragmove));
node.append("rect")
.attr("height", function(d) { return d.dy; })
.attr("width", sankey.nodeWidth())
.style("fill", function(d) { return d.color; })
.style("stroke", function(d) { return d3.rgb(d.color).darker(2); })
.append("title")
.text(function(d) { return d.name + "\n" + format(d.value/11525*100) + ' %'; });
node.append("text")
.attr("x", -6)
.attr("y", function(d) { return d.dy / 2; })
.attr("dy", ".35em")
.attr("text-anchor", "end")
.attr("transform", null)
.text(function(d) { return d.name; })
.filter(function(d) { return d.x < width / 2; })
.attr("x", 6 + sankey.nodeWidth())
.attr("text-anchor", "start");
function dragmove(d) {
d3.select(this).attr("transform", "translate(" + d.x + "," + (d.y = Math.max(0, Math.min(height - d.dy, d3.event.y))) + ")");
sankey.relayout();
link.attr("d", path);
}
});
</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-8592359-13', 'ocks.org');
ga('send', 'pageview');
</script>
# -*- coding: utf-8 -*-
# calculates 18 groups
import pickle
import csv
with open("responses0", 'rb') as f:
responses = pickle.load(f)
out = {}
sums = {}
for jsonvar in responses:
i = i + 1
count = 0
for key in jsonvar:
try:
if (jsonvar[key] == 1):
count = count + 1
except:
nothing = 1
for key in jsonvar:
try:
if (jsonvar[key] == 1):
if jsonvar['zeman'] < jsonvar['schwarzenberg']:
if key in sums:
if 'zeman' in sums[key]:
sums[key]['zeman'] = sums[key]['zeman'] + 1/count
else:
sums[key]['zeman'] = 1/count
else:
#print(jsonvar)
sums[key] = {}
sums[key]['zeman'] = 1/count
else:
if (jsonvar['schwarzenberg'] < jsonvar['zeman']):
if key in sums:
if 'schwarzenberg' in sums[key]:
sums[key]['schwarzenberg'] = sums[key]['schwarzenberg'] + 1/count
else:
sums[key]['schwarzenberg'] = 1/count
else:
sums[key] = {}
sums[key]['schwarzenberg'] = 1/count
except:
#del jsonvar[key]
nothing = 1
print(sums)
writer = csv.writer(open('groups18.csv', 'wb'))
for key, value in sums.items():
if 'zeman' not in value:
value['zeman'] = 0
if 'schwarzenberg' not in value:
value['schwarzenberg'] = 0
writer.writerow([key, value['zeman'], value['schwarzenberg']])
print [key, value['zeman'], value['schwarzenberg']]
# -*- coding: utf-8 -*-
# calculates the transfers
# using weights from R (manually entered)
import json
import pickle
with open("responses0", 'rb') as f:
responses = pickle.load(f)
out = {}
out["nodes"] = []
out["links"] = []
prevj = {}
i = 0
j = 0
people = {
"zeman": {"name":"Zeman","color":"#FF0000"},
"schwarzenberg":{"name":"Schwarzenberg","color":"#880088"},
"fischer":{"name":"Fischer","color":"#0000FF"},
"dienstbier":{"name":"Dienstbier","color":"#FFA500"},
"franz":{"name":"Franz","color":"#000000"},
"roithova":{"name":"Roithová","color":"#FFFF00"},
"fischerova":{"name":"Fischerová","color":"#00AA00"},
"sobotka":{"name":"Sobotka","color":"#000088"},
"bobosikova":{"name":"Bobošíková","color":"#FFFF44"}
}
weights = {
'zeman': {'zeman': 1.6800465},
'fischer': {'zeman': 1.4850209, 'schwarzenberg': 1.6041692},
'sobotka': {'zeman': 0.8815094, 'schwarzenberg': 0.5447683},
'fischerova': { 'zeman': 0.7513741, 'schwarzenberg': 0.4237004},
'schwarzenberg': {'schwarzenberg': 0.7202682},
'dienstbier': {'zeman': 2.6144173, 'schwarzenberg': 0.7212448},
'roithova': {'zeman': 1.4540868, 'schwarzenberg': 0.5347517},
'bobosikova': {'zeman': 1.1143363, 'schwarzenberg': 1.1098767},
'franz': {'zeman': 0.7372130, 'schwarzenberg': 0.3176280}}
wresponses = []
for jsonvar in responses:
minkey = min(jsonvar, key=jsonvar.get)
if jsonvar['zeman'] < jsonvar['schwarzenberg']:
weight = weights[minkey]['zeman']
else:
if jsonvar['zeman'] > jsonvar['schwarzenberg']:
weight = weights[minkey]['schwarzenberg']
else:
weight = 1
wresponses.append({
'values': jsonvar,
'weight': weight
})
#print(wresponses)
#raise Exception("diepy")
for n in range(1, 9):
sums = {}
for jsonvar in wresponses:
i = i + 1
count = 0
for key in jsonvar['values']:
try:
if (jsonvar['values'][key] == 1):
count = count + 1
except:
nothing = 1
for key in jsonvar['values']:
try:
if (jsonvar['values'][key] == 1):
if key in sums:
sums[key] = sums[key] + jsonvar['weight']/count
else:
sums[key] = jsonvar['weight']/count
except:
#del jsonvar[key]
nothing = 1
print(sums)
print sum(sums.itervalues())
print len(responses)
outkey = min(sums, key=sums.get)
print(outkey)
for item in sums:
out["nodes"].append({"color":people[item]["color"],"name":people[item]["name"], "j": j})
if (item == outkey):
currentj = j
if (n > 1):
tmp = sums[item] - last[item]
out["links"].append({"source":lastj,"target":j,"value":tmp})
out["links"].append({"source":prevj[item],"target":j,"value":last[item]})
prevj[item] = j
j = j + 1
lastj = currentj
for jsonvar in responses:
for key in jsonvar:
if (jsonvar[key] > jsonvar[outkey]):
jsonvar[key] = jsonvar[key] - 1
del jsonvar[outkey]
last = sums
#raise Exception("diepy")
#raise Exception("diepy")
with open('sankey.json', 'w') as outfile:
json.dump(out, outfile)
# -*- coding: utf-8 -*-
# extracts inputs
# only the correct ones
import json
import pickle
#fin = open('workfile.html', 'w')
responses = []
i = 0
with open("research.txt","r") as fin:
for row in fin:
ar = row.split("\t")
#print(ar)
jsonvar = json.loads(ar[3])
newvar = {}
try:
if "input-sort-bobosikova" in jsonvar:
newvar["bobosikova"] = int(jsonvar["input-sort-bobosikova"])
if "input-sort-dienstbier" in jsonvar:
newvar["dienstbier"] = int(jsonvar["input-sort-dienstbier"])
if "input-sort-fischer" in jsonvar:
newvar["fischer"] = int(jsonvar["input-sort-fischer"])
if "input-sort-fischerova" in jsonvar:
newvar["fischerova"] = int(jsonvar["input-sort-fischerova"])
if "input-sort-franz" in jsonvar:
newvar["franz"] = int(jsonvar["input-sort-franz"])
if "input-sort-roithova" in jsonvar:
newvar["roithova"] = int(jsonvar["input-sort-roithova"])
if "input-sort-schwarzenberg" in jsonvar:
newvar["schwarzenberg"] = int(jsonvar["input-sort-schwarzenberg"])
if "input-sort-sobotka" in jsonvar:
newvar["sobotka"] = int(jsonvar["input-sort-sobotka"])
if "input-sort-zeman" in jsonvar:
newvar["zeman"] = int(jsonvar["input-sort-zeman"])
cc = 0
for n in range(1, 10):
if n in newvar.values():
cc = cc + 1
if (cc == 9):
responses.append(newvar)
i = i + 1
except:
nothing = 1
print (i)
with open("responses0", 'wb') as f:
pickle.dump(responses, f)
#print(responses)
#raise Exception('diePy')
zeman,1673,0
fischer,553,658
sobotka,141,369
fischerova,201,528
schwarzenberg,0,3749
dienstbier,582,442
roithova,183,550
bobosikova,163,73
franz,603,1066
d3.sankey = function() {
var sankey = {},
nodeWidth = 24,
nodePadding = 8,
size = [1, 1],
nodes = [],
links = [];
sankey.nodeWidth = function(_) {
if (!arguments.length) return nodeWidth;
nodeWidth = +_;
return sankey;
};
sankey.nodePadding = function(_) {
if (!arguments.length) return nodePadding;
nodePadding = +_;
return sankey;
};
sankey.nodes = function(_) {
if (!arguments.length) return nodes;
nodes = _;
return sankey;
};
sankey.links = function(_) {
if (!arguments.length) return links;
links = _;
return sankey;
};
sankey.size = function(_) {
if (!arguments.length) return size;
size = _;
return sankey;
};
sankey.layout = function(iterations) {
computeNodeLinks();
computeNodeValues();
computeNodeBreadths();
computeNodeDepths(iterations);
computeLinkDepths();
return sankey;
};
sankey.relayout = function() {
computeLinkDepths();
return sankey;
};
sankey.link = function() {
var curvature = .5;
function link(d) {
var x0 = d.source.x + d.source.dx,
x1 = d.target.x,
xi = d3.interpolateNumber(x0, x1),
x2 = xi(curvature),
x3 = xi(1 - curvature),
y0 = d.source.y + d.sy + d.dy / 2,
y1 = d.target.y + d.ty + d.dy / 2;
return "M" + x0 + "," + y0
+ "C" + x2 + "," + y0
+ " " + x3 + "," + y1
+ " " + x1 + "," + y1;
}
link.curvature = function(_) {
if (!arguments.length) return curvature;
curvature = +_;
return link;
};
return link;
};
// Populate the sourceLinks and targetLinks for each node.
// Also, if the source and target are not objects, assume they are indices.
function computeNodeLinks() {
nodes.forEach(function(node) {
node.sourceLinks = [];
node.targetLinks = [];
});
links.forEach(function(link) {
var source = link.source,
target = link.target;
if (typeof source === "number") source = link.source = nodes[link.source];
if (typeof target === "number") target = link.target = nodes[link.target];
source.sourceLinks.push(link);
target.targetLinks.push(link);
});
}
// Compute the value (size) of each node by summing the associated links.
function computeNodeValues() {
nodes.forEach(function(node) {
node.value = Math.max(
d3.sum(node.sourceLinks, value),
d3.sum(node.targetLinks, value)
);
});
}
// Iteratively assign the breadth (x-position) for each node.
// Nodes are assigned the maximum breadth of incoming neighbors plus one;
// nodes with no incoming links are assigned breadth zero, while
// nodes with no outgoing links are assigned the maximum breadth.
function computeNodeBreadths() {
var remainingNodes = nodes,
nextNodes,
x = 0;
while (remainingNodes.length) {
nextNodes = [];
remainingNodes.forEach(function(node) {
node.x = x;
node.dx = nodeWidth;
node.sourceLinks.forEach(function(link) {
nextNodes.push(link.target);
});
});
remainingNodes = nextNodes;
++x;
}
//
moveSinksRight(x);
scaleNodeBreadths((width - nodeWidth) / (x - 1));
}
function moveSourcesRight() {
nodes.forEach(function(node) {
if (!node.targetLinks.length) {
node.x = d3.min(node.sourceLinks, function(d) { return d.target.x; }) - 1;
}
});
}
function moveSinksRight(x) {
nodes.forEach(function(node) {
if (!node.sourceLinks.length) {
node.x = x - 1;
}
});
}
function scaleNodeBreadths(kx) {
nodes.forEach(function(node) {
node.x *= kx;
});
}
function computeNodeDepths(iterations) {
var nodesByBreadth = d3.nest()
.key(function(d) { return d.x; })
.sortKeys(d3.ascending)
.entries(nodes)
.map(function(d) { return d.values; });
//
initializeNodeDepth();
resolveCollisions();
for (var alpha = 1; iterations > 0; --iterations) {
relaxRightToLeft(alpha *= .99);
resolveCollisions();
relaxLeftToRight(alpha);
resolveCollisions();
}
function initializeNodeDepth() {
var ky = d3.min(nodesByBreadth, function(nodes) {
return (size[1] - (nodes.length - 1) * nodePadding) / d3.sum(nodes, value);
});
nodesByBreadth.forEach(function(nodes) {
nodes.forEach(function(node, i) {
node.y = i;
node.dy = node.value * ky;
});
});
links.forEach(function(link) {
link.dy = link.value * ky;
});
}
function relaxLeftToRight(alpha) {
nodesByBreadth.forEach(function(nodes, breadth) {
nodes.forEach(function(node) {
if (node.targetLinks.length) {
var y = d3.sum(node.targetLinks, weightedSource) / d3.sum(node.targetLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedSource(link) {
return center(link.source) * link.value;
}
}
function relaxRightToLeft(alpha) {
nodesByBreadth.slice().reverse().forEach(function(nodes) {
nodes.forEach(function(node) {
if (node.sourceLinks.length) {
var y = d3.sum(node.sourceLinks, weightedTarget) / d3.sum(node.sourceLinks, value);
node.y += (y - center(node)) * alpha;
}
});
});
function weightedTarget(link) {
return center(link.target) * link.value;
}
}
function resolveCollisions() {
nodesByBreadth.forEach(function(nodes) {
var node,
dy,
y0 = 0,
n = nodes.length,
i;
// Push any overlapping nodes down.
nodes.sort(ascendingDepth);
for (i = 0; i < n; ++i) {
node = nodes[i];
dy = y0 - node.y;
if (dy > 0) node.y += dy;
y0 = node.y + node.dy + nodePadding;
}
// If the bottommost node goes outside the bounds, push it back up.
dy = y0 - nodePadding - size[1];
if (dy > 0) {
y0 = node.y -= dy;
// Push any overlapping nodes back up.
for (i = n - 2; i >= 0; --i) {
node = nodes[i];
dy = node.y + node.dy + nodePadding - y0;
if (dy > 0) node.y -= dy;
y0 = node.y;
}
}
});
}
function ascendingDepth(a, b) {
return a.y - b.y;
}
}
function computeLinkDepths() {
nodes.forEach(function(node) {
node.sourceLinks.sort(ascendingTargetDepth);
node.targetLinks.sort(ascendingSourceDepth);
});
nodes.forEach(function(node) {
var sy = 0, ty = 0;
node.sourceLinks.forEach(function(link) {
link.sy = sy;
sy += link.dy;
});
node.targetLinks.forEach(function(link) {
link.ty = ty;
ty += link.dy;
});
});
function ascendingSourceDepth(a, b) {
return a.source.y - b.source.y;
}
function ascendingTargetDepth(a, b) {
return a.target.y - b.target.y;
}
}
function center(node) {
return node.y + node.dy / 2;
}
function value(link) {
return link.value;
}
return sankey;
};
{"nodes": [{"color": "#FF0000", "j": 0, "name": "Zeman"}, {"color": "#0000FF", "j": 1, "name": "Fischer"}, {"color": "#000088", "j": 2, "name": "Sobotka"}, {"color": "#00AA00", "j": 3, "name": "Fischerov\u00e1"}, {"color": "#880088", "j": 4, "name": "Schwarzenberg"}, {"color": "#FFA500", "j": 5, "name": "Dienstbier"}, {"color": "#FFFF00", "j": 6, "name": "Roithov\u00e1"}, {"color": "#FFFF44", "j": 7, "name": "Bobo\u0161\u00edkov\u00e1"}, {"color": "#000000", "j": 8, "name": "Franz"}, {"color": "#FF0000", "j": 9, "name": "Zeman"}, {"color": "#0000FF", "j": 10, "name": "Fischer"}, {"color": "#000088", "j": 11, "name": "Sobotka"}, {"color": "#00AA00", "j": 12, "name": "Fischerov\u00e1"}, {"color": "#880088", "j": 13, "name": "Schwarzenberg"}, {"color": "#FFA500", "j": 14, "name": "Dienstbier"}, {"color": "#FFFF00", "j": 15, "name": "Roithov\u00e1"}, {"color": "#000000", "j": 16, "name": "Franz"}, {"color": "#FF0000", "j": 17, "name": "Zeman"}, {"color": "#0000FF", "j": 18, "name": "Fischer"}, {"color": "#00AA00", "j": 19, "name": "Fischerov\u00e1"}, {"color": "#880088", "j": 20, "name": "Schwarzenberg"}, {"color": "#FFA500", "j": 21, "name": "Dienstbier"}, {"color": "#FFFF00", "j": 22, "name": "Roithov\u00e1"}, {"color": "#000000", "j": 23, "name": "Franz"}, {"color": "#FF0000", "j": 24, "name": "Zeman"}, {"color": "#0000FF", "j": 25, "name": "Fischer"}, {"color": "#880088", "j": 26, "name": "Schwarzenberg"}, {"color": "#FFA500", "j": 27, "name": "Dienstbier"}, {"color": "#FFFF00", "j": 28, "name": "Roithov\u00e1"}, {"color": "#000000", "j": 29, "name": "Franz"}, {"color": "#000000", "j": 30, "name": "Franz"}, {"color": "#FF0000", "j": 31, "name": "Zeman"}, {"color": "#880088", "j": 32, "name": "Schwarzenberg"}, {"color": "#0000FF", "j": 33, "name": "Fischer"}, {"color": "#FFA500", "j": 34, "name": "Dienstbier"}, {"color": "#FF0000", "j": 35, "name": "Zeman"}, {"color": "#880088", "j": 36, "name": "Schwarzenberg"}, {"color": "#0000FF", "j": 37, "name": "Fischer"}, {"color": "#FFA500", "j": 38, "name": "Dienstbier"}, {"color": "#FF0000", "j": 39, "name": "Zeman"}, {"color": "#880088", "j": 40, "name": "Schwarzenberg"}, {"color": "#FFA500", "j": 41, "name": "Dienstbier"}, {"color": "#FF0000", "j": 42, "name": "Zeman"}, {"color": "#880088", "j": 43, "name": "Schwarzenberg"}], "links": [{"source": 7, "target": 9, "value": 52.37380610000628}, {"source": 0, "target": 9, "value": 2790.5572364999857}, {"source": 7, "target": 10, "value": 33.37657380000087}, {"source": 1, "target": 10, "value": 1868.7390452999919}, {"source": 7, "target": 11, "value": 17.807082799999932}, {"source": 2, "target": 11, "value": 325.31232809999784}, {"source": 7, "target": 12, "value": 31.170199199999445}, {"source": 3, "target": 12, "value": 374.3163048999973}, {"source": 7, "target": 13, "value": 15.538273800003935}, {"source": 4, "target": 13, "value": 2683.719313200099}, {"source": 7, "target": 14, "value": 63.42797710000218}, {"source": 5, "target": 14, "value": 1828.4809114000159}, {"source": 7, "target": 15, "value": 18.908040300000152}, {"source": 6, "target": 15, "value": 558.2224809000054}, {"source": 7, "target": 16, "value": 30.055862899999852}, {"source": 8, "target": 16, "value": 780.38594900001}, {"source": 11, "target": 17, "value": 85.37318130000813}, {"source": 9, "target": 17, "value": 2842.931042599992}, {"source": 11, "target": 18, "value": 40.63936929999841}, {"source": 10, "target": 18, "value": 1902.1156190999927}, {"source": 11, "target": 19, "value": 9.518488899999852}, {"source": 12, "target": 19, "value": 405.48650409999675}, {"source": 11, "target": 20, "value": 129.7158757000393}, {"source": 13, "target": 20, "value": 2699.257587000103}, {"source": 11, "target": 21, "value": 19.29014479999978}, {"source": 14, "target": 21, "value": 1891.908888500018}, {"source": 11, "target": 22, "value": 29.877830200000062}, {"source": 15, "target": 22, "value": 577.1305212000055}, {"source": 11, "target": 23, "value": 28.70452069999999}, {"source": 16, "target": 23, "value": 810.4418119000098}, {"source": 19, "target": 24, "value": 47.26021920000085}, {"source": 17, "target": 24, "value": 2928.3042239}, {"source": 19, "target": 25, "value": 38.53484149999849}, {"source": 18, "target": 25, "value": 1942.7549883999911}, {"source": 19, "target": 26, "value": 90.22844320002196}, {"source": 20, "target": 26, "value": 2828.973462700142}, {"source": 19, "target": 27, "value": 70.06245629999921}, {"source": 21, "target": 27, "value": 1911.1990333000178}, {"source": 19, "target": 28, "value": 95.50842990000069}, {"source": 22, "target": 28, "value": 607.0083514000056}, {"source": 19, "target": 29, "value": 73.41060290000087}, {"source": 23, "target": 29, "value": 839.1463326000098}, {"source": 28, "target": 30, "value": 93.96038650000162}, {"source": 29, "target": 30, "value": 912.5569355000107}, {"source": 28, "target": 31, "value": 135.1911677000021}, {"source": 24, "target": 31, "value": 2975.564443100001}, {"source": 28, "target": 32, "value": 223.31917030005525}, {"source": 26, "target": 32, "value": 2919.201905900164}, {"source": 28, "target": 33, "value": 122.2523849000006}, {"source": 25, "target": 33, "value": 1981.2898298999896}, {"source": 28, "target": 34, "value": 127.79367189999425}, {"source": 27, "target": 34, "value": 1981.261489600017}, {"source": 30, "target": 35, "value": 321.53513540001313}, {"source": 31, "target": 35, "value": 3110.755610800003}, {"source": 30, "target": 36, "value": 304.6977566000137}, {"source": 32, "target": 36, "value": 3142.5210762002193}, {"source": 30, "target": 37, "value": 168.1380768000031}, {"source": 33, "target": 37, "value": 2103.5422147999902}, {"source": 30, "target": 38, "value": 212.14635319998752}, {"source": 34, "target": 38, "value": 2109.0551615000113}, {"source": 37, "target": 39, "value": 698.3490870000483}, {"source": 35, "target": 39, "value": 3432.290746200016}, {"source": 37, "target": 40, "value": 874.7979950999561}, {"source": 36, "target": 40, "value": 3447.218832800233}, {"source": 37, "target": 41, "value": 698.5332094999558}, {"source": 38, "target": 41, "value": 2321.201514699999}, {"source": 41, "target": 42, "value": 2156.931807399893}, {"source": 39, "target": 42, "value": 4130.6398332000645}, {"source": 41, "target": 43, "value": 862.8029167996992}, {"source": 40, "target": 43, "value": 4322.016827900189}]}
# Optimization of weights
# optimization function
fn = function(w) {
# results of 1st round should match:
50000 * sum( (apply(X * w,1,sum) - results1)^2 ) +
# results of the 2nd round should match:
50000 * sum( (apply(X * w,2,sum) - results2)^2 ) +
# loss function 1, the weights should not be far from 1:
sum( c(t(w-1) %*% (w-1)) ) +
# loss function 2, the rate shall be similar to zeman / schwarzenberg in 1st round
# w[,1] - w[,2] did not work in optim, so workaround:
#1.669086312/0.719913577 is rate of respondents for zeman / schwarzenberg in 1st round
sum( (apply(w*onezero,1,sum) / apply(w*zeroone,1,sum) - 1.669086312/0.719913577)^2 )
}
# number of respondents
respondents = t(matrix(c(1661,0,553,653,141,369,201,527,0,3726,578,440,182,549,163,73,601,1062),nrow=2))
rownames(respondents) = c('zeman','fischer','sobotka','fischerova','schwarzenberg','dienstbier','roithova','bobosikova','franz')
colnames(respondents) = c('zeman2','schwarzenberg2')
#official election results
results1 = c(0.2421,0.1635,0.0246,0.0323,0.234,0.1612,0.0495,0.0239,0.0684)
results2 = c(0.5480,0.4519)
X = respondents/sum(c(respondents))
# help matrices:
onezero = matrix(c(1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0),nrow=9)
zeroone = matrix(c(0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1),nrow=9)
# starting values:
S = matrix(1,9,2)
S[1,2] = 0.1
S[5,1] = 0.1
# optimization:
optim(S,fn,control=list(maxit=20000))