123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648 |
- package algo;
- import java.awt.*;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.LinkedList;
- import java.util.List;
- import javax.swing.*;
- import algo.StorageElement.Mode;
- import api.AddOn;
- import classes.*;
- import ui.controller.Control;
- public class TestAlgo implements AddOn {
- private boolean cancel = false;
- // Gui Part:
- private Control control;
- private JTextArea textArea;
- private JPanel content = new JPanel();
- // ProgressBar
- private JProgressBar progressBar = new JProgressBar();
- private long startTime;
- private Thread runThread;
- // Blackstart Resistance in Watt
- private HolonObject powerPlant;
- private TextField blackstartResistanceTextfield;
- private TextField blackstartSuccessTimeTextfield;
- private TextField powerplantMaxOutputTextfield;
- private TextField blackstartStartTimeTextfield;
- private TextField simulationDurationTextfield;
- private int blackstartSuccessTime;
- private int blackstartStartTime;
- private int blackstartRunningCounter;
- private float powerplantMaxOutput;
- private List<HolonObject> renewableProducers;
- private List<HolonObject> consumers;
- private StorageProductionController SPC;
- public static void main(String[] args) {
- JFrame newFrame = new JFrame("exampleWindow");
- TestAlgo instance = new TestAlgo();
- newFrame.setContentPane(instance.getPanel());
- newFrame.pack();
- newFrame.setVisible(true);
- newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- public TestAlgo() {
- content.setLayout(new BorderLayout());
- textArea = new JTextArea();
- textArea.setEditable(false);
- JScrollPane scrollPane = new JScrollPane(textArea);
- JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, createOptionPanel(), scrollPane);
- splitPane.setResizeWeight(0.0);
- content.add(splitPane, BorderLayout.CENTER);
- content.setPreferredSize(new Dimension(800, 800));
- }
- public JPanel createOptionPanel() {
- JPanel optionPanel = new JPanel(new BorderLayout());
- JScrollPane scrollPane = new JScrollPane(createParameterPanel());
- scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
- optionPanel.add(scrollPane, BorderLayout.CENTER);
- optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
- return optionPanel;
- }
- private Component createParameterPanel() {
- JPanel parameterPanel = new JPanel(null);
- parameterPanel.setPreferredSize(new Dimension(510, 300));
- blackstartResistanceTextfield = new TextField("5000000");
- blackstartResistanceTextfield.setBounds(10, 10, 170, 20);
- parameterPanel.add(blackstartResistanceTextfield);
- JLabel blackstartResistanceLabel = new JLabel("Blackstart resistance in Watt");
- blackstartResistanceLabel.setBounds(185, 10, 300, 20);
- parameterPanel.add(blackstartResistanceLabel);
- blackstartSuccessTimeTextfield = new TextField("30");
- blackstartSuccessTimeTextfield.setBounds(10, 35, 170, 20);
- parameterPanel.add(blackstartSuccessTimeTextfield);
- JLabel blackstartSuccessTimeLabel = new JLabel("Time for successfull blackstart in minutes(iterations)");
- blackstartSuccessTimeLabel.setBounds(185, 35, 300, 20);
- parameterPanel.add(blackstartSuccessTimeLabel);
- blackstartStartTimeTextfield = new TextField("15");
- blackstartStartTimeTextfield.setBounds(10, 60, 170, 20);
- parameterPanel.add(blackstartStartTimeTextfield);
- JLabel blackstartStartTimeLabel = new JLabel("Starttime for the blackstart");
- blackstartStartTimeLabel.setBounds(185, 60, 300, 20);
- parameterPanel.add(blackstartStartTimeLabel);
- simulationDurationTextfield = new TextField("500");// TODO:!
- simulationDurationTextfield.setBounds(10, 85, 170, 20);
- parameterPanel.add(simulationDurationTextfield);
- JLabel simulationDurationLabel = new JLabel("How long should the simulation run?");
- simulationDurationLabel.setBounds(185, 85, 300, 20);
- parameterPanel.add(simulationDurationLabel);
- powerplantMaxOutputTextfield = new TextField("40000000");
- powerplantMaxOutputTextfield.setBounds(10, 110, 170, 20);
- parameterPanel.add(powerplantMaxOutputTextfield);
- JLabel powerplantMaxOutputLabel = new JLabel("Powerplant Output afer Blackstart");
- powerplantMaxOutputLabel.setBounds(185, 110, 300, 20);
- parameterPanel.add(powerplantMaxOutputLabel);
- // JButton selectGroupNodeButton = new JButton("Select GroupNode");
- // selectGroupNodeButton.setEnabled(false);
- // selectGroupNodeButton.setBounds(10, 25, 165, 20);
- // selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
- // borderPanel.add(selectGroupNodeButton);
- // JCheckBox useGroupNodeCheckBox = new JCheckBox();
- // useGroupNodeCheckBox.setSelected(false);
- // useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
- // useGroupNodeCheckBox.addActionListener(actionEvent -> {
- // useGroupNode = useGroupNodeCheckBox.isSelected();
- // selectGroupNodeButton.setEnabled(useGroupNode);
- // });
- // borderPanel.add(useGroupNodeCheckBox);
- return parameterPanel;
- }
- public JPanel createButtonPanel() {
- JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
- JButton cancelButton = new JButton("Cancel Run");
- cancelButton.addActionListener(actionEvent -> cancel());
- buttonPanel.add(cancelButton);
- JButton clearButton = new JButton("Clear Console");
- clearButton.addActionListener(actionEvent -> clear());
- buttonPanel.add(clearButton);
- JButton resetButton = new JButton("Reset");
- resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
- resetButton.addActionListener(actionEvent -> reset());
- buttonPanel.add(resetButton);
- JButton runButton = new JButton("Run");
- runButton.addActionListener(actionEvent -> {
- Runnable task = () -> run();
- runThread = new Thread(task);
- runThread.start();
- });
- buttonPanel.add(runButton);
- return buttonPanel;
- }
- private void cancel() {
- if (runThread.isAlive()) {
- println("");
- println("Cancel run.");
- cancel = true;
- progressBar.setValue(0);
- } else {
- println("Nothing to cancel.");
- }
- }
- private void run() {
- cancel = false;
- disableGuiInput(true);
- startTimer();
- initAlgo();
- if (cancel) {
- reset();
- disableGuiInput(false);
- return;
- }
- printElapsedTime();
- disableGuiInput(false);
- }
- private void reset() {
- println("RESET DOES NOTHING platzhalter");
- }
- private void disableGuiInput(boolean bool) {
- control.guiDisable(bool);
- }
- @Override
- public JPanel getPanel() {
- return content;
- }
- @Override
- public void setController(Control control) {
- this.control = control;
- }
- private void clear() {
- textArea.setText("");
- }
- private void print(String message) {
- textArea.append(message);
- }
- private void println(String message) {
- textArea.append(message + "\n");
- }
- private void startTimer() {
- startTime = System.currentTimeMillis();
- }
- private void printElapsedTime() {
- long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
- println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
- }
- ///////////////////////////////////////////////////////////////////////////////////
- /**
- *
- */
- private void initAlgo() {
- try {
- // init
- SPC = new StorageProductionController(getStorageElements());// DANGER DONT GIVE NULL
- renewableProducers = getRenewableProducers();
- consumers = getConsumers();
- powerPlant = getPowerPlant();// DANGER DONT GIVE NULL
- if(powerPlant == null){
- println("No Power Plant in Model");
- return;
- }
- calcResistance();
- blackstartRunningCounter = 0;
- deactivateBlackstart();
- control.getModel().setCurIteration(0);
- // prepare model
- /////////
- setPowerplantProduction(0);
- enableAllConsumers();
- SPC.disableStorageProduction(-1); //disable all storage production
- for (StorageElement se :
- getStorageElements()) {
- se.setStateOfCharge(10000);
- }
- // StorageElement ele = new StorageElement("Storage", 1, 0, control.getModel());
- // ele.setStatusAndSetEnergy(Mode.EMIT, 5000);
- //
- // System.out.println(""+ele.getEnergyPerElement());
- // powerPlant.addElement(ele);
-
- // for (HolonElement elem : powerPlant.getElements()) {
- // if(elem instanceof StorageElement) {
- // println("boom");
- // }
- // }
- // TODO: prios?
- /////////
- // Get parameters from textfields
- setPowerPlantBlackstartResistance(-Float.parseFloat(blackstartResistanceTextfield.getText()));
- blackstartSuccessTime = Integer.parseInt(blackstartSuccessTimeTextfield.getText());
- powerplantMaxOutput = Float.parseFloat(powerplantMaxOutputTextfield.getText());
- blackstartStartTime = Integer.parseInt(blackstartStartTimeTextfield.getText());
- control.getModel().setIterations(Integer.parseInt(simulationDurationTextfield.getText()));
- updateVisual();
- if (blackstartStartTime + blackstartSuccessTime > control.getModel().getIterations() - 1) {
- println("No Time for the blackstart, use working numbers");
- } else {
- blackstartMain(control.getModel().getCurIteration());
- }
- } catch (NumberFormatException e) {
- println("Worng Input, only numbers please");
- }
- }
- /**
- *
- * @param curIteration
- */
- private void blackstartMain(int curIteration) {
- // try {
- // Thread.sleep(1000);
- // } catch (InterruptedException e) {
- // // TODO Auto-generated catch block
- // e.printStackTrace();
- // }
- control.getModel().setCurIteration(curIteration);
- if (blackstartRunning()) {
- if (!blackstartAlgo(curIteration)) {
- // blackstart for this iteration was not successfull
- deactivateBlackstart();
- updateVisual();
- println("Simulation of blackstart failed in Iteration: " + curIteration);
- } else {
- // blackstart for this iteration was successfull
- blackstartRunningCounter++;
- if (blackstartRunningCounter == blackstartSuccessTime) {
- // blackstart was successfull for the needed iterations
- deactivateBlackstart();
- enableAllConsumers();
- updateVisual();
- println("Simulation of blackstart Successfull in Iteration: " + curIteration);
- } else {
- // blackstart not finished yet
- updateVisual();
- blackstartMain(curIteration + 1);
- }
- }
- } else {
- // blackstart has not started yet
- if (curIteration == blackstartStartTime) {
- activateBlackstart();
- disableConsumers();
- blackstartMain(curIteration);
- } else {
- updateVisual();
- blackstartMain(curIteration + 1);
- }
- }
- }
- /**
- * TODO:HOLEG UNTERVERSORGUNG CHECKEN
- *
- * @param curIteration
- * @return true or false depending on whether the blackstart was successful for
- * this iteration
- */
- private boolean blackstartAlgo(int curIteration) {
- if (currentRenewableProduction() < getPowerPlantBlackstartResistance()) {
- // renewable energy production is not sufficient for the blackstart
- if (SPC.currentPossibleStorageProduction() >= getPowerPlantBlackstartResistance()
- - currentRenewableProduction()) {// is there currently enough power available from storage?
- SPC.enableStorageProduction(getPowerPlantBlackstartResistance() - currentRenewableProduction());
- rampUpPowerplant();
- enableConsumers(getPowerplantProduction());
- return true;
- } else {
- // blackstart has failed
- SPC.disableStorageProduction(-1);//TODO:disable all
- println("Not enough storage energy available");
- return false;
- }
- } else {
- //TODO: disable storage?
- // renewable energy production is sufficient for the blackstart
- rampUpPowerplant();
- enableConsumers(
- currentRenewableProduction() - getPowerPlantBlackstartResistance() + getPowerplantProduction());
- return true;
- }
- }
- private HolonObject getPowerPlant() {
- for (AbstractCpsObject cps : control.getModel().getObjectsOnCanvas()) {
- // geht nur wenn nur ein power plant vorhanden ist
- if (cps instanceof HolonObject) {
- if (cps.getObjName().equals("Power Plant")) {
- return (HolonObject) cps;
- }
- }
- }
- return null;
- }
- private ArrayList<StorageElement> getStorageElements() {
- ArrayList<StorageElement> storageElements = new ArrayList<StorageElement>();
- for (HolonObject holonObject : control.getModel().getAllHolonObjectsOnCanvas()) {
- // if(holonObject.getName().contentEquals("House")) {
- // holonObject.addElement(new StorageElement("Storage", 1, 0, control.getModel()));
- // }
- for (HolonElement ele : holonObject.getElements()) {
- if(ele instanceof StorageElement){
- storageElements.add((StorageElement) ele);
- }
- // if (ele.getEleName().equals("Storage")) {
- // println(ele.getEleName() + "is : " + ele.getClass());
- // if (ele instanceof StorageElement) {
- // println("boomboomboomboom");
- // }
- // }
- }
- }
- return storageElements;
- }
- private void calcResistance() {
- if (powerPlant != null) {
- // println("Powerplant Energy @"+powerPlant.getEnergyAtTimeStep(1));
- // println("" + getPowerplantProduction());
- // travers
- if (powerPlant.getConnectedTo().size() > 0) {
- for (CpsEdge edge : powerPlant.getConnectedTo()) {
- // println(edge.toString());
- if (powerPlant.getId() == edge.getA().getId()) {
- traversEdges(edge.getB(), powerPlant, calcEdgeLength(edge));
- } else {
- traversEdges(edge.getA(), powerPlant, calcEdgeLength(edge));
- }
- }
- } else {
- println("Nothing connected to powerplant");
- }
- } else {
- println("No powerplant connected");
- }
- }
- private void traversEdges(AbstractCpsObject currentObject, AbstractCpsObject last, double distance) {
- if (currentObject.getConnectedTo().size() > 1) { // recursive call for all edges
- for (CpsEdge edge : currentObject.getConnectedTo()) {
- if (currentObject.getId() == edge.getA().getId()) { // look at which way the edge points
- if (last.getId() != edge.getB().getId()) {
- traversEdges(edge.getB(), currentObject, distance + calcEdgeLength(edge));
- }
- } else {
- if (last.getId() != edge.getA().getId()) {
- traversEdges(edge.getA(), currentObject, distance + calcEdgeLength(edge));
- }
- }
- }
- } else { // at leaf
- // println("Distance to " + currentObject.getId() + ": " + distance);
- // ((HolonObject) currentObject).addElement(new StorageElement("Storage", 1, 0, control.getModel()));
- for (HolonElement ele : ((HolonObject) currentObject).getElements()) {
- if (ele.getEleName() == "Solar Panels") {
- ele.setEnergyPerElement(5000);// TODO: das wollen wir ja so nicht
- // println("Energy: " + ele.getEnergyPerElement());
- // set how much energy is left after resistance22
- ele.setEnergyPerElement(calcEnergyAfterResistance(ele.getEnergyPerElement(), distance));// TODO: das
- // wollen
- // wir ja so
- // auch
- // nicht
- // println("Energy after resistance: " + ele.getEnergyPerElement());
- }
- }
- }
- }
- private float calcEnergyAfterResistance(float currentEnergy, double distance) {
- // 230v kupfer 30mm durchmesser
- int volatage = 230;
- int diameter = 30;
- // kupfer
- double specificMaterialResistance = 0.017;
- double blackstartResistance = Math.pow(volatage, 2) / getPowerPlantBlackstartResistance();
- double cableResistance = specificMaterialResistance * (distance / (0.25 * Math.PI * Math.pow(diameter, 2)));
- return (float) (1 - (cableResistance / (cableResistance + blackstartResistance))) * currentEnergy;
- }
- private double calcEdgeLength(CpsEdge edge) {
- Position aPos = edge.getA().getPosition();
- Position bPos = edge.getB().getPosition();
- double xDiff = Math.abs(aPos.x - bPos.x);
- double yDiff = Math.abs(aPos.y - bPos.y);
- return Math.sqrt(Math.pow(xDiff, 2) + Math.pow(yDiff, 2));
- }
- private void disableConsumers() {
- // TODO: disableBatteryLoading? will ich das wirklich?
- // SPC.disableStorageProduction();
- for (HolonObject consumer : consumers) {
- for (HolonElement ele : consumer.getElements()) {
- if (ele.isActive() && ele.isConsumer()) {
- ele.setActive(false);
- }
- }
- }
- }
- private void enableConsumers(float energyAvailable) {
- println("currenctrenewable: " + currentRenewableProduction());
- println("currenctpossiblestorage: " + SPC.currentPossibleStorageProduction());
- println("blackstart resi: " + getPowerPlantBlackstartResistance());
- println("current pp production: " + getPowerplantProduction());
- println("energy available for consumers" + energyAvailable);
- // Damit wir immer die gleiche ausgangslage haben //TODO: wirklich?
- disableConsumers();
- // TODO: das ganze lieber mit prirotaeten
- for (HolonObject consumer : consumers) {
- for (HolonElement ele : consumer.getElements()) {
- if (energyAvailable > 0
- && energyAvailable - Math.abs(ele.getEnergyPerElement() * ele.getAmount()) >= 0) {
- if (!ele.isActive()) {
- ele.setActive(true);
- energyAvailable = energyAvailable - Math.abs(ele.getEnergyPerElement() * ele.getAmount());// +
- // since
- // its
- // negative
- // System.out.println("Element " + ele.getId() + " was enabled Energy left: "+ energyAvailable);
- }
- } else {
- return;
- }
- }
- }
- // if (!SPC.batteriesFull()) {
- // // TODO: load unused batteries
- // } else {
- //
- // }
- }
- private void enableAllConsumers() {
- for (HolonObject consumer : consumers) {
- for (HolonElement ele : consumer.getElements()) {
- if (!ele.isActive() && ele.isConsumer()) {
- ele.setActive(true);
- }
- }
- }
- }
- private float currentRenewableProduction() {
- float production = 0;
- for (HolonObject house : renewableProducers) {
- for (HolonElement ele : house.getElements()) {
- if (ele.getEleName().equals("Solar Panels")) {// TODO: hier muss noch mehr dazu
- production = production + ele.getEnergyAtTimeStep(control.getModel().getCurIteration());
- }
- }
- }
- return production;
- }
- private void rampUpPowerplant() {
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Power")) {
- ele.setEnergyPerElement(ele.getEnergyPerElement() + powerplantMaxOutput / blackstartSuccessTime);
- }
- }
- }
- private float getPowerplantProduction() {
- float totalProduction = 0;
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Power")) {
- totalProduction = ele.getEnergyPerElement();
- }
- }
- return totalProduction;
- }
- private float setPowerplantProduction(float power) {
- float totalProduction = 0;
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Power")) {
- ele.setEnergyPerElement(power);
- }
- }
- return totalProduction;
- }
- private float getPowerPlantBlackstartResistance() {
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Blackstart")) {
- return -ele.getEnergyPerElement();
- }
- }
- return 0;
- }
- private void setPowerPlantBlackstartResistance(float resistance) {
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Blackstart")) {
- ele.setEnergyPerElement(resistance);
- }
- }
- }
- private boolean blackstartRunning() {
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Blackstart")) {
- if (ele.isActive()) {
- return true;
- } else {
- return false;
- }
- }
- }
- return false;
- }
- private void activateBlackstart() {
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Blackstart")) {
- ele.setActive(true);
- }
- }
- }
- private void deactivateBlackstart() {
- for (HolonElement ele : powerPlant.getElements()) {
- if (ele.getEleName().equals("Blackstart")) {
- ele.setActive(false);
- }
- }
- }
- private LinkedList<HolonObject> getRenewableProducers() {
- LinkedList<HolonObject> list = new LinkedList<HolonObject>();
- for (HolonObject holonObject : control.getModel().getAllHolonObjectsOnCanvas()) {
- if (holonObject.getObjName().contentEquals("House")) {// TODO: das reicht so nicht da muss noch gecheckt
- // werden ob es renewables gibt
- list.add(holonObject);
- }
- }
- return list;
- }
- private LinkedList<HolonObject> getConsumers() {
- LinkedList<HolonObject> list = new LinkedList<HolonObject>();
- for (HolonObject holonObject : control.getModel().getAllHolonObjectsOnCanvas()) {
- if (holonObject.getObjName().contentEquals("House")) {// TODO: das reicht so nicht da muss noch gecheckt
- // werden ob es consumer gibt
- list.add(holonObject);
- }
- }
- return list;
- }
- /**
- * To let the User See the current state without touching the Canvas.
- */
- private void updateVisual() {
- System.out.println("Start updateVisual in Iteration: " + control.getModel().getCurIteration());
- control.calculateStateAndVisualForCurrentTimeStep();
- control.updateCanvas();
- System.out.println("Finish updateVisual in Iteration: " + control.getModel().getCurIteration());
- }
- }
|