financeBalance = function (gen) {
if (gen === 0) {
d3.selectAll(".budget").remove();
d3.selectAll(".fixedCost").remove();
d3.selectAll(".variableCost").remove();
}
let stationCost = addStationCount * 1;
let capacityCost = increaseCapacity * 0.1 * history.stations.length;
let evCost = replaceEv * 0.05;
let fixedCost = stationCost + capacityCost + evCost;
let initialValue = 0;
history.upgradeNumber.forEach(
(d) =>
(d.upgradeTotal = d.upgradeNumber.reduce((totalValue, currentValue) => {
return totalValue + currentValue;
}, initialValue))
);
let upgradeCost = upgradePercentage * 0.1;
let initialCost = 0;
history.subsidy.forEach(
(d) =>
(d.sum = d.subsidizedMoney.reduce((totalCost, currentCost) => {
return totalCost + currentCost;
}, initialCost))
);
let variableCost =
upgradeCost * history.upgradeNumber[gen].upgradeTotal +
history.subsidy[gen].sum;
history.finance[gen].fixedCost = -fixedCost / 1000;
history.finance[gen].totalVariableCost = -variableCost / 1000;
if (gen >= 1) {
history.finance[gen].variableCost =
history.finance[gen].totalVariableCost -
history.finance[gen - 1].totalVariableCost;
} else if (gen == 0) {
history.finance[gen].variableCost = history.finance[gen].totalVariableCost;
}
// calculate budget balance
history.finance[gen].budgetBalance =
cityBudget * 1000 + fixedCost + history.finance[gen].totalVariableCost;
const xScale = d3
.scaleLinear()
.domain([0, simulationSteps - 1])
.range([margin, budgetWidth - margin]);
const yScale = d3
.scaleLinear()
.domain([-10000, 10000])
.range([budgetHeight - margin, margin]);
let lineGen = d3
.line()
.x((d) => xScale(d.generationNumber))
.y((d) => yScale(d.budgetBalance));
d3.select("#budgetChart")
.append("rect")
.attr("x", margin)
.attr("y", yScale(Math.max(0, cityBudget * 1000)))
.attr("width", (budgetWidth - margin) / simulationSteps)
.attr("height", Math.abs(yScale(cityBudget * 1000) - yScale(0)))
.attr("fill", "red")
.attr("class", "budget");
d3.select("#budgetChart")
.append("rect")
.attr("x", margin)
.attr("y", budgetHeight / 2 + history.finance[0].totalVariableCost)
.attr("width", (budgetWidth - margin) / simulationSteps)
.attr("height", -yScale(fixedCost))
.attr("fill", "green")
.attr("class", "fixedCost");
d3.select("#budgetChart")
.selectAll(".variableCost")
.data(history.finance)
.enter()
.append("rect")
.attr(
"x",
(d, i) => margin + (i * (budgetWidth - margin)) / simulationSteps
)
.attr("y", (d) => yScale(0))
.attr("width", (budgetWidth - margin) / simulationSteps)
.attr("height", (d) => Math.abs(yScale(d.variableCost) - yScale(0)))
.attr("fill", "blue")
.attr("stroke", "white")
.attr("stroke-width", 1)
.attr("class", "variableCost");
d3.select("#budgetChart")
.select("#budgetBalancePath")
.datum(history.finance)
.transition()
.attr("d", lineGen);
}