123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463 |
- package ui.controller;
- import classes.*;
- import classes.comparator.EnergyMinToMaxComparator;
- import classes.comparator.MinEnergyComparator;
- import classes.comparator.WeakestBattery;
- import ui.model.IntermediateCableWithState;
- import ui.model.DecoratedCable;
- import ui.model.DecoratedCable.CableState;
- import ui.model.DecoratedSwitch.SwitchState;
- import ui.model.DecoratedNetwork;
- import ui.model.DecoratedState;
- import ui.model.DecoratedSwitch;
- import ui.model.MinimumModel;
- import ui.model.MinimumNetwork;
- import ui.model.Model;
- import ui.model.Model.FairnessModel;
- import ui.model.VisualRepresentationalState;
- import ui.view.FlexiblePane;
- import ui.view.GUI;
- import ui.view.MyCanvas;
- import ui.view.Outliner;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.LinkedList;
- import java.util.ListIterator;
- import javax.swing.JPanel;
- /**
- * Controller for Simulation.
- *
- * @author Gruppe14
- */
- public class SimulationManager {
- int global = 0;
- private Model model;
- private ArrayList<AbstractCpsObject> objectsToHandle;
- private ArrayList<SubNet> subNets;
- private ArrayList<CpsEdge> brokenEdges;
- private HashMap<Integer, DecoratedState> saves = new HashMap<Integer, DecoratedState>();
- private HashMap<Integer, VisualRepresentationalState> savesVisual = new HashMap<Integer, VisualRepresentationalState>();
- private MyCanvas canvas;
- private int timeStep;
- private HashMap<Integer, Float> tagTable = new HashMap<>();
- private FlexiblePane flexPane;
- private GUI gui;
- private HashMap<HolonElement, Float> flexDevicesTurnedOnThisTurn = new HashMap<>();
- /**
- * Constructor.
- *
- * @param m
- * Model
- */
- SimulationManager(Model m) {
- canvas = null;
- model = m;
- subNets = new ArrayList<>();
- brokenEdges = new ArrayList<>();
- }
- /**
- * calculates the flow of the edges and the supply for objects and consider old timesteps for burned cables.
- *
- * @param timestep
- * current Iteration
- */
- void calculateStateForTimeStep(int timestep) {
-
-
- HashMap<CpsEdge, CableState> map = new HashMap<CpsEdge, CableState>();
- if(timestep > 0 && saves.containsKey(timestep-1)) //if the state before exist
- {
- //make cable hastmap
- DecoratedState theStateBefore = saves.get(timestep-1);
- for(DecoratedCable edge : theStateBefore.getLeftOverEdges())
- {
- map.put(edge.getModel(), edge.getState());
- }
- }
- timeStep = timestep;
- ArrayList<MinimumNetwork> list = new ArrayList<MinimumNetwork>();
- MinimumModel minimumModel = new MinimumModel(model.getObjectsOnCanvas(), model.getEdgesOnCanvas());
- //set all working:
- for(IntermediateCableWithState cable : minimumModel.getEdgeList()) {
- if(map.containsKey(cable.getModel())) cable.setState(map.get(cable.getModel()));
- }
- ArrayList<IntermediateCableWithState> leftOver = new ArrayList<IntermediateCableWithState>();
- boolean doAnotherLoop = true;
- while(doAnotherLoop) {
- doAnotherLoop = false;
- list = calculateNetworks(minimumModel, timestep, leftOver);
- for(MinimumNetwork net : list) {
- float energyOnCables = net.getHolonObjectList().stream().filter(object -> object.getEnergyAtTimeStep(timestep) > 0.0f).map(object -> object.getEnergyAtTimeStep(timestep)).reduce(0.0f, ((a,b) -> a + b));
- //find the cable with the energy supplied from his two connected objects are the biggest, from all cables that the network give more energy than the cablecapacity.
- IntermediateCableWithState cable = net.getEdgeList().stream().filter(aCable -> energyOnCables > aCable.getModel().getCapacity()).max((lhs,rhs) -> Float.compare(lhs.getEnergyFromConnetedAtTimestep(timestep), rhs.getEnergyFromConnetedAtTimestep(timestep))).orElse(null);
- if(cable != null) {
- cable.setState(CableState.Burned);
- doAnotherLoop = true;
- }
- }
- }
- ArrayList<DecoratedNetwork> decorNetworks = new ArrayList<DecoratedNetwork>();
- FairnessModel actualFairnessModel = model.getFairnessModel();
- for (MinimumNetwork net : list) {
- decorNetworks.add(new DecoratedNetwork(net, timestep, actualFairnessModel));
- }
- ArrayList<DecoratedCable> leftOverDecoratedCables = new ArrayList<DecoratedCable>();
-
- for(IntermediateCableWithState cable: leftOver) {
- leftOverDecoratedCables.add(new DecoratedCable(cable.getModel(), cable.getState(), 0.0f));
- }
- ArrayList<DecoratedSwitch> listOfDecoratedSwitches = decorateSwitches(minimumModel, timestep);
- DecoratedState stateFromThisTimestep = new DecoratedState(decorNetworks, leftOverDecoratedCables, listOfDecoratedSwitches, timestep);
- saves.put(timestep, stateFromThisTimestep);
- savesVisual.put(timestep, new VisualRepresentationalState(stateFromThisTimestep, minimumModel));
- canvas.repaint();
- gui.updateOutliners(getActualDecorState());//saves.getOrDefault(timestep, null);
-
- }
- /**
- * Decorate a switch
- * @param minModel
- * @param iteration
- * @return
- */
- public static ArrayList<DecoratedSwitch> decorateSwitches(MinimumModel minModel, int iteration) {
- ArrayList<DecoratedSwitch> aListOfDecoratedSwitches = new ArrayList<DecoratedSwitch>();
- for(HolonSwitch hSwitch: minModel.getSwitchList()) {
- aListOfDecoratedSwitches.add(new DecoratedSwitch(hSwitch, hSwitch.getState(iteration) ? SwitchState.Closed : SwitchState.Open));
- }
- return aListOfDecoratedSwitches;
- }
- /**
- * SubFunction to calculate the Networks from the model.
- * @param minModel
- * @param Iteration
- * @param leftOver
- * @return
- */
- ArrayList<MinimumNetwork> calculateNetworks(MinimumModel minModel, int Iteration, ArrayList<IntermediateCableWithState> leftOver){
- //Copy minModel ObjectList
- ArrayList<HolonObject> holonObjectList = new ArrayList<HolonObject>();
- for(HolonObject holonObject: minModel.getHolonObjectList()) {
- holonObjectList.add(holonObject);
- }
- //Copy minModelEdgeList
- ArrayList<IntermediateCableWithState> edgeList = new ArrayList<IntermediateCableWithState>();
- for(IntermediateCableWithState cable: minModel.getEdgeList()) {
- edgeList.add(cable);
- }
-
- ArrayList<MinimumNetwork> listOfNetworks = new ArrayList<MinimumNetwork>();
- while(!holonObjectList.isEmpty()) {
- //lookAt the first holonObject and find his neighbors
- HolonObject lookAtObject = holonObjectList.get(0);
- //delete out of list
- holonObjectList.remove(0);
- //create a new Network
- MinimumNetwork actualNetwork = new MinimumNetwork(new ArrayList<HolonObject>(), new ArrayList<IntermediateCableWithState>());
- actualNetwork.getHolonObjectList().add(lookAtObject);
- //create List of neighbors
- LinkedList<AbstractCpsObject> neighbors = new LinkedList<AbstractCpsObject>();
- populateListOfNeighbors(edgeList, lookAtObject, actualNetwork, neighbors);
- while(!neighbors.isEmpty()) {
- AbstractCpsObject lookAtNeighbor = neighbors.getFirst();
- if(lookAtNeighbor instanceof HolonObject) {
- actualNetwork.getHolonObjectList().add((HolonObject) lookAtNeighbor);
- holonObjectList.remove(lookAtNeighbor);
- }
- //When HolonSwitch Check if closed
- if(!(lookAtNeighbor instanceof HolonSwitch) || ((HolonSwitch)lookAtNeighbor).getState(Iteration)) {
- populateListOfNeighbors(edgeList, lookAtNeighbor, actualNetwork, neighbors);
- }
-
- neighbors.removeFirst();
- }
- listOfNetworks.add(actualNetwork);
- }
- if(leftOver!= null) {
- leftOver.clear();
- for(IntermediateCableWithState cable: edgeList) {
- leftOver.add(cable);
- }
- }
- return listOfNetworks;
- }
- /**
- * Adds the neighbors.
- * @param edgeList
- * @param lookAtObject
- * @param actualNetwork
- * @param neighbors
- */
- void populateListOfNeighbors(ArrayList<IntermediateCableWithState> edgeList, AbstractCpsObject lookAtObject,
- MinimumNetwork actualNetwork, LinkedList<AbstractCpsObject> neighbors) {
- ListIterator<IntermediateCableWithState> iter = edgeList.listIterator();
- while(iter.hasNext())
- {
- IntermediateCableWithState lookAtEdge = iter.next();
- if(lookAtEdge.getState() == CableState.Working && lookAtEdge.getModel().isConnectedTo(lookAtObject)) {
- iter.remove();
- actualNetwork.getEdgeList().add(lookAtEdge);
-
- //Add neighbar
- AbstractCpsObject edgeNeighbor;
- if(lookAtEdge.getModel().getA().equals(lookAtObject)) {
- edgeNeighbor = lookAtEdge.getModel().getB();
-
- }else {
- edgeNeighbor = lookAtEdge.getModel().getA();
- }
- if(!neighbors.contains(edgeNeighbor)) {
- neighbors.add(edgeNeighbor);
- }
- }
- }
- }
- /**
- * add all battries.getOut() from a list of battries and return them
- * @param aL a List of HolonBattries likely from subnet.getBatteries()
- * @param x TimeStep
- * @return
- *
- */
- private float GetOutAllBatteries(ArrayList<HolonBattery> aL, int x)
- {
- float OutEnergy = 0;
- for(HolonBattery hB : aL)
- {
- //System.out.println("Iteration: "+ x +"OutBattery: "+ hB.getOutAtTimeStep(x-1));
- OutEnergy += hB.getOutAtTimeStep(x-1);
- }
- //System.out.println("Iteration: "+ x +"GetOutAllBatteries: "+ OutEnergy);
- return OutEnergy;
- }
- /**
- * search for all flexible devices in the network and turn them on, until
- * energy surplus = 0 or all devices have been examined.
- *
- * This code could be compressed (cases inside over- and underproduction are
- * the same), but we decided that it is better readable this way
- *
- * @param subNet
- * the subnet
- * @param energySurplus
- * the current surplus of energy
- */
- private void turnOnFlexibleDevices(SubNet subNet, float energySurplus,
- int timestep) {
- for (HolonObject holonOb : subNet.getObjects()) {
- for (HolonElement holonEl : holonOb.getElements()) {
- // if this element is flexible and active (can be considered for
- // calculations)
- if (holonEl.isFlexible() && holonEl.isActive()) {
- float energyAvailableSingle = holonEl
- .getEnergyAtTimeStep(timestep);
- float energyAvailableMultiple = energyAvailableSingle
- * holonEl.getAmount();
- // ------------- flexible consumer / OVERPRODUCTION
- // -------------
- if (energyAvailableMultiple < 0 && energySurplus > 0) {
- // if there is more wasted energy than energy that this
- // device can give, give all energy available
- if (Math.abs(energyAvailableMultiple) <= Math
- .abs(energySurplus)) {
- energySurplus += energyAvailableMultiple;
- // set the new energy consumption to the maximum
- holonEl.setEnergyPerElement(energyAvailableSingle);
- flexDevicesTurnedOnThisTurn.put(holonEl,
- energyAvailableMultiple);
- }
- // else: we just need to turn on part of the flexible
- // energy available
- else {
- float energyNeeded = -energySurplus;
- energySurplus += energyNeeded; // should give 0, but
- // was kept this was
- // for consistency
- // the energy needed divided through the amount of
- // elements
- holonEl.setEnergyPerElement(energyNeeded
- / holonEl.getAmount());
- flexDevicesTurnedOnThisTurn.put(holonEl,
- energyNeeded);
- }
- }
- // ------------- flexible producer / UNDERPRODUCTION
- // -------------
- else if (energyAvailableMultiple > 0 && energySurplus < 0) {
- // if there is more energy needed than this device can
- // give, give all the energy available
- if (Math.abs(energyAvailableMultiple) <= Math
- .abs(energySurplus)) {
- energySurplus += energyAvailableMultiple;
- // set the new energy consumption to the maximum
- holonEl.setEnergyPerElement(energyAvailableSingle);
- flexDevicesTurnedOnThisTurn.put(holonEl,
- energyAvailableMultiple);
- }
- // else: we just need to turn on part of the flexible
- // energy available
- else {
- float energyNeeded = -energySurplus;
- int i = 0;
- energySurplus += energyNeeded; // should give 0, but
- // was kept this was
- // for consistency
- // the energy needed divided through the amount of
- // elements
- holonEl.setEnergyPerElement(energyNeeded
- / holonEl.getAmount());
- flexDevicesTurnedOnThisTurn.put(holonEl,
- energyNeeded);
- }
- }
- }
- if (energySurplus == 0) {
- break;
- }
- }
- if (energySurplus == 0) {
- break;
- }
- }
- }
- /**
- * Set Flow Simulation.
- *
- * @param sN
- * Subnet
- */
-
- /**
- * Set the Pseudo Tags.
- *
- * @param nodes
- * Array of AbstractCpsObjects
- */
- private void setPseudoTags(ArrayList<AbstractCpsObject> nodes,
- ArrayList<CpsEdge> edges) {
- for (AbstractCpsObject node : nodes) {
- node.recalculateTags();
- node.setPseudoTags(new ArrayList<>());
- }
- for (CpsEdge edge : edges) {
- edge.recalculateTags();
- edge.setPseudoTag(new ArrayList<>());
- }
- }
- /**
- * copies the data of an array of Objects.
- *
- * @param toCopy
- * the ArrayList of CpsObjects co Copy
- */
- private void copyObjects(ArrayList<AbstractCpsObject> toCopy) {
- for (AbstractCpsObject cps : toCopy) {
- if (cps instanceof CpsUpperNode) {
- copyObjects(((CpsUpperNode) cps).getNodes());
- } else {
- objectsToHandle.add(cps);
- }
- }
- }
- /**
- * Set the Canvas.
- *
- * @param can
- * the Canvas
- */
- public void setCanvas(MyCanvas can) {
- canvas = can;
- }
- /**
- * Should be a better way to update the canvas -.-
- * @param can
- */
- public void updateCanvas() {
- canvas.repaint();
- }
- /**
- * Reset all Data to the current state of the Model.
- */
- public void reset() {
- objectsToHandle = new ArrayList<>();
- copyObjects(model.getObjectsOnCanvas());
- flexDevicesTurnedOnThisTurn = new HashMap<>();
- }
- /**
- * Get all Subnets.Not functional.
- *
- * @return all Subnets
- */
- @Deprecated
- public ArrayList<SubNet> getSubNets() {
- return subNets;
- }
- /**
- * Get broken Edges
- */
- // public ArrayList<CpsEdge> getBrokenEdges() {
- // return brokenEdges;
- // }
- public FlexiblePane getFlexiblePane() {
- return flexPane;
- }
- void setFlexiblePane(FlexiblePane fp) {
- flexPane = fp;
- }
-
- public DecoratedState getActualDecorStateWithOffSet(int offSet) {
- return getDecorState(timeStep + offSet);
- }
- public DecoratedState getActualDecorState() {
- return getDecorState(timeStep);
- }
- public VisualRepresentationalState getActualVisualRepresentationalState(){
- return savesVisual.getOrDefault(timeStep, null);
- }
- public DecoratedState getDecorState(int timestep) {
- return saves.getOrDefault(timestep, null);
- }
- public void setGui(GUI gui) {
- this.gui = gui;
- }
- public HashMap<Integer, VisualRepresentationalState> getSavesVisual() {
- return savesVisual;
- }
- }
|