Browse Source

Spelling

AddOrRemoveEdge
TomTroppmann 2 years ago
parent
commit
cd5515b4a6

+ 9 - 24
src/holeg/model/Holon.java

@@ -37,13 +37,6 @@ public class Holon {
     }
 
 
-    public void merge(Holon other) {
-        holonObjects.addAll(other.holonObjects);
-        edges.addAll(other.edges);
-        objects.addAll(other.objects);
-        other.clear();
-    }
-
     public void clear() {
         holonObjects.clear();
         edges.clear();
@@ -56,14 +49,11 @@ public class Holon {
     }
 
 
-    public void calculate(int timeStep) {
+    public void calculate() {
         Map<Boolean, List<HolonObject>> partition = holonObjects.stream().collect(Collectors.partitioningBy(hO -> hO.getActualEnergy() > 0));
         List<HolonObject> supplierList = partition.get(true);
         List<HolonObject> consumerList = partition.get(false);
         supplierList.sort((a, b) -> -Float.compare(a.getActualEnergy(), b.getActualEnergy()));
-        log.info("Supplier [" + supplierList.stream().map(hO -> hO.getName() + hO.getActualEnergy()).collect(Collectors.joining(", ")) + "]" + System.lineSeparator() +
-                "Consumer [" + consumerList.stream().map(hO -> hO.getName() + hO.getMinimumConsumingElementEnergy()).collect(Collectors.joining(", ")) + "]" + System.lineSeparator()
-        );
 
         float energyToSupplyInTheNetwork = supplierList.stream()
                 .map(HolonObject::getActualEnergy)
@@ -101,10 +91,6 @@ public class Holon {
             break;
         }
 
-        log.info("Supplier [" + supplierList.stream().map(hO -> hO.getName() + hO.getActualEnergy()).collect(Collectors.joining(", ")) + "]" + System.lineSeparator() +
-                "Consumer [" + consumerList.stream().map(hO -> hO.getName() + hO.getActualEnergy()).collect(Collectors.joining(", ")) + "]" + System.lineSeparator()
-        );
-
 
         // STEP 2:
         // Supply consumer fully
@@ -213,7 +199,7 @@ public class Holon {
         return (amount > 0) ? getFlexibilityConsumptionCapacity() / (float) amount : 0.f;
     }
 
-    public float getVarianzInFlexibilitiesConsumption() {
+    public float getVarianceInFlexibilitiesConsumption() {
         float average = getAverageFlexibilityConsumption();
         float sum = getListOfEnergyInConsumptionThatIsOfferedByFlexibilitiesInThisNetwork()
                 .map(energy -> squared(energy - average)).reduce(0.f, Float::sum);
@@ -221,7 +207,7 @@ public class Holon {
         return (amountOfFlexibilities > 0) ? sum / (float) amountOfFlexibilities : 0.f;
     }
 
-    public float getVarianzInFlexibilityProduction() {
+    public float getVarianceInFlexibilityProduction() {
         float average = getAverageFlexibilityProduction();
         float sum = getListOfEnergyInProductionThatIsOfferedByFlexibilitiesInThisNetwork()
                 .map(energy -> squared(energy - average)).reduce(0.f, Float::sum);
@@ -230,11 +216,11 @@ public class Holon {
     }
 
     public float getDeviationInFlexibilityConsumption() {
-        return (float) Math.sqrt(getVarianzInFlexibilitiesConsumption());
+        return (float) Math.sqrt(getVarianceInFlexibilitiesConsumption());
     }
 
     public float getDeviationInFlexibilityProduction() {
-        return (float) Math.sqrt(getVarianzInFlexibilityProduction());
+        return (float) Math.sqrt(getVarianceInFlexibilityProduction());
     }
 
     public float getTotalConsumption() {
@@ -256,26 +242,25 @@ public class Holon {
     /**
      * returns the Varianz in Poduction
      *
-     * @return
      */
-    public float getVarianzInProductionInNetworkForHolonObjects() {
+    public float getVarianceInProductionInNetworkForHolonObjects() {
         float average = getAverageProductionInNetworkForHolonObject();
         float sum = holonObjects.stream().map(hO -> squared(hO.getProduction() - average)).reduce(0.f, Float::sum);
         return sum / (float) holonObjects.size();
     }
 
     public float getDeviationInProductionInNetworkForHolonObjects() {
-        return (float) Math.sqrt(getVarianzInProductionInNetworkForHolonObjects());
+        return (float) Math.sqrt(getVarianceInProductionInNetworkForHolonObjects());
     }
 
-    public float getVarianzInConsumptionInNetworkForHolonObjects() {
+    public float getVarianceInConsumptionInNetworkForHolonObjects() {
         float average = getAverageConsumptionInNetworkForHolonObject();
         float sum = holonObjects.stream().map(hO -> squared(hO.getConsumption() - average)).reduce(0.f, Float::sum);
         return sum / (float) holonObjects.size();
     }
 
     public float getDeviationInConsumptionInNetworkForHolonObjects() {
-        return (float) Math.sqrt(getVarianzInConsumptionInNetworkForHolonObjects());
+        return (float) Math.sqrt(getVarianceInConsumptionInNetworkForHolonObjects());
     }
 
 

+ 35 - 17
src/holeg/ui/controller/Control.java

@@ -150,7 +150,7 @@ public class Control {
 
     public void addObjectOnCanvas(GroupNode node, AbstractCanvasObject object) {
         canvasController.addObject(node, object);
-        calculateStateForCurrentIterationAndBroadcastCanvasUpdate(model.getCurrentIteration());
+        updateStateForIteration(model.getCurrentIteration());
     }
 
 
@@ -191,10 +191,7 @@ public class Control {
      * @param edge the edge
      */
     public boolean addEdgeOnCanvas(Edge edge) {
-        boolean connectsItSelf = edge.getA() == edge.getB();
-        boolean connectionExist = model.getEdgesOnCanvas().stream().anyMatch(e -> (e.getA() == edge.getA() && e.getB() == edge.getB())
-                || (e.getB() == edge.getA() && e.getA() == edge.getB()));
-        if (connectsItSelf || connectionExist) {
+        if (doesEdgeExist(edge)) {
             return false;
         }
         canvasController.addEdgeOnCanvas(edge);
@@ -202,6 +199,31 @@ public class Control {
         return true;
     }
 
+    private boolean doesEdgeExist(Edge edge){
+        boolean connectsToSelf = edge.getA() == edge.getB();
+        return !connectsToSelf && model.getEdgesOnCanvas().stream().anyMatch(e -> (e.getA() == edge.getA() && e.getB() == edge.getB())
+                || (e.getB() == edge.getA() && e.getA() == edge.getB()));
+    }
+
+
+    /**
+     * Add an edge to the Canvas.
+     *
+     * @param edge the edge
+     */
+    public void addEdgeOnCanvasOrRemoveExisting(Edge edge) {
+        boolean connectsToSelf = edge.getA() == edge.getB();
+        if(connectsToSelf){
+            return;
+        }
+        Optional<Edge> edgeToRemove = model.getEdgesOnCanvas().stream().filter(e -> (e.getA() == edge.getA() && e.getB() == edge.getB())
+                || (e.getB() == edge.getA() && e.getA() == edge.getB())).findAny();
+        edgeToRemove.ifPresentOrElse(canvasController::removeEdgesOnCanvas, () -> canvasController.addEdgeOnCanvas(edge));
+        updateStateForCurrentIteration();
+    }
+
+
+
     /**
      * Removes an Edge from the Canvas.
      *
@@ -215,7 +237,11 @@ public class Control {
 
 
     public void calculateStateForCurrentIteration() {
-        calculateStateForCurrentIteration(model.getCurrentIteration());
+        simulationManager.calculateStateForIteration(model.getCurrentIteration());
+    }
+    public void updateStateForCurrentIteration() {
+        simulationManager.calculateStateForIteration(model.getCurrentIteration());
+        OnCanvasUpdate.broadcast();
     }
 
     /**
@@ -223,19 +249,11 @@ public class Control {
      *
      * @param x current Iteration
      */
-    public void calculateStateForCurrentIterationAndBroadcastCanvasUpdate(int x) {
-        simulationManager.calculateStateForTimeStep(x);
-        log.info("OnCanvasUpdate");
+    public void updateStateForIteration(int x) {
+        simulationManager.calculateStateForIteration(x);
         OnCanvasUpdate.broadcast();
     }
 
-    /**
-     * calculates the flow of the edges and the supply for objects.
-     */
-    public void calculateStateForCurrentIteration(int x) {
-        simulationManager.calculateStateForTimeStep(x);
-    }
-
     /**
      * resets the whole State of the simulation including a reset of all Edges to
      * the default "is working" state
@@ -279,7 +297,7 @@ public class Control {
             obj.getPosition().clampY(0, GuiSettings.canvasSize.getY());
         });
         groupNode.addAll(copies);
-        calculateStateForCurrentIterationAndBroadcastCanvasUpdate(model.getCurrentIteration());
+        updateStateForIteration(model.getCurrentIteration());
         OnSelectionChanged.broadcast();
     }
 

+ 2 - 10
src/holeg/ui/controller/SimulationManager.java

@@ -22,26 +22,18 @@ public class SimulationManager {
         this.control = control;
     }
 
-    public void calculateStateForTimeStep(int timeStep) {
-        log.fine("Calculate");
-        long start = System.currentTimeMillis();
+    public void calculateStateForIteration(int timeStep) {
         Model model =  control.getModel();
         model.getCanvas().getAllSwitchObjectsRecursive().forEach(sw -> sw.calculateState(timeStep));
         List<HolonObject> holonObjectList = model.getCanvas().getAllHolonObjectsRecursive().collect(Collectors.toList());
         List<Edge> edgeList = new ArrayList<>(model.getEdgesOnCanvas());
         Set<Holon> holons = getHolons(holonObjectList, edgeList, timeStep);
-        holons.forEach(holon -> holon.calculate(timeStep));
+        holons.forEach(Holon::calculate);
         model.holons = holons;
-        log.info("Holons:" + holons.stream().map(Object::toString).collect(Collectors.joining("\n")));
-        long end = System.currentTimeMillis();
-        log.finer("Simulation: " + (end - start) + "ms");
     }
 
 
     private Set<Holon> getHolons(List<HolonObject> holonObjectList, List<Edge> edgeList, int timeStep) {
-        log.info(System.lineSeparator() + "Supplier [" + holonObjectList.stream().map(AbstractCanvasObject::getName).collect(Collectors.joining(", ")) + "]" + System.lineSeparator() +
-                "Consumer [" + edgeList.stream().map(Object::toString).collect(Collectors.joining(", ")) + "]" + System.lineSeparator()
-        );
         Set<Holon> holons = new HashSet<>();
         for (Holon holon : calculateHolonStructure(holonObjectList, edgeList)) {
             final float energyOnCables = holon.holonObjects.stream().map(hO -> {

+ 2 - 2
src/holeg/ui/view/canvas/Canvas.java

@@ -214,8 +214,8 @@ public class Canvas extends JPanel {
                 }
                 case EdgeCreation -> getObjectAtPosition(lastPosition).ifPresentOrElse(obj -> {
                     boolean isGroupNode = obj instanceof GroupNode;
-                    if (!isGroupNode && control.addEdgeOnCanvas(new Edge(selectedOnPressed, obj, GuiSettings.maxCapacityForNewCreatedEdges))) {
-                        control.calculateStateForCurrentIteration();
+                    if (!isGroupNode) {
+                        control.addEdgeOnCanvasOrRemoveExisting(new Edge(selectedOnPressed, obj, GuiSettings.maxCapacityForNewCreatedEdges));
                     }
                 }, () -> {
                     Node node = new Node("Node");

+ 0 - 11
src/holeg/ui/view/information/HolonInformationPanel.java

@@ -18,7 +18,6 @@ import org.knowm.xchart.style.PieStyler;
 import org.knowm.xchart.style.PieStyler.LabelType;
 
 import javax.swing.*;
-import javax.swing.border.EmptyBorder;
 import javax.swing.event.PopupMenuEvent;
 import javax.swing.event.PopupMenuListener;
 import java.awt.*;
@@ -29,8 +28,6 @@ import java.util.stream.Collectors;
 
 public class HolonInformationPanel extends JPanel {
 	private static final Logger log = Logger.getLogger(HolonInformationPanel.class.getName());
-	//private Predicate<DecoratedHolonObject> stateFilter = (object) -> true;// = (object) -> object.getState() ==
-																			// HolonObjectState.PRODUCER;
 	private final int defaultWidth = 50;
 	private final int defaultHeight = 200;
 
@@ -57,7 +54,6 @@ public class HolonInformationPanel extends JPanel {
 	private final PieChart activeChart = createActiveChart();
 
 	private final JPanel graphPanel = new JPanel(new GridLayout(0, 2));
-	private final JPanel titlePanel = new JPanel(new BorderLayout(0, 0));
 
 	private final JCheckBoxMenuItem producerCheckBox = new JCheckBoxMenuItem("Producer", true);
 	private final JCheckBoxMenuItem overSuppliedCheckBox = new JCheckBoxMenuItem("Over supplied", true);
@@ -91,9 +87,7 @@ public class HolonInformationPanel extends JPanel {
 		this.control = control;
 		this.setLayout(new BorderLayout());
 		initGraphPanel();
-		initTitlePanel();
 		this.setBackground(ColorPreference.Panel.Background);
-		this.add(titlePanel, BorderLayout.PAGE_START);
 		this.add(graphPanel, BorderLayout.CENTER);
 	}
 	
@@ -398,11 +392,6 @@ public class HolonInformationPanel extends JPanel {
 		return panel;
 	}
 
-	public void initTitlePanel() {
-		titlePanel.setBackground(ColorPreference.Panel.Background);
-		titlePanel.setBorder(new EmptyBorder(5, 5, 2, 0));
-	}
-
 	public void setDefaultPieChartSettings(PieChart chart) {
 		PieStyler styler = chart.getStyler();
 		styler.setChartTitleVisible(true);

+ 32 - 55
src/holeg/ui/view/inspector/InspectorTable.java

@@ -53,7 +53,7 @@ import holeg.utility.pooling.Pool;
 import net.miginfocom.swing.MigLayout;
 
 public class InspectorTable extends JPanel {
-	private Pool<ElementRow> rowPool = new Pool<ElementRow>() {
+	private final Pool<ElementRow> rowPool = new Pool<>() {
 		@Override
 		public ElementRow create() {
 			return new ElementRow();
@@ -63,7 +63,7 @@ public class InspectorTable extends JPanel {
 	private final int maxDisplayedRowsNumber = 100;
 	private int actualPage = 0;
 	private int maxPageNumberForThisSelection = 0;
-	private Control control;
+	private final Control control;
 	private final int columnHeight = 20;
 	// UI
 	private final TrippleCheckBox selectAllCheckBox = new TrippleCheckBox();
@@ -76,7 +76,7 @@ public class InspectorTable extends JPanel {
 	private final JButton pageDecreaseButton = new JButton();
 	private final JLabel pageInformationLabel = new JLabel();
 	private final JPanel pageSelectionPanel = new JPanel();
-	private ArrayList<SortButton<ElementRow>> headerButtonList = new ArrayList<>();
+	private final ArrayList<SortButton<ElementRow>> headerButtonList = new ArrayList<>();
 	private final static NumberFormatter doubleFormatter = generateNumberFormatter();
 
 	// sorting
@@ -91,7 +91,7 @@ public class InspectorTable extends JPanel {
 	private boolean abortThread = false;
 
 	public InspectorTable(Control control) {
-		control.OnSelectionChanged.addListener(() -> updateInspectorUi());
+		control.OnSelectionChanged.addListener(this::updateInspectorUi);
 		this.control = control;
 		init();
 		addHeader();
@@ -136,16 +136,10 @@ public class InspectorTable extends JPanel {
 	};
 
 	private void performPageAction(PageAction action) {
-		int newPageNumber;
-		switch (action) {
-		case Decrease:
-			newPageNumber = Math.max(actualPage - 1, 0);
-			break;
-		case Increase:
-		default:
-			newPageNumber = Math.min(actualPage + 1, maxPageNumberForThisSelection);
-			break;
-		}
+		int newPageNumber = switch (action) {
+			case Decrease -> Math.max(actualPage - 1, 0);
+			default -> Math.min(actualPage + 1, maxPageNumberForThisSelection);
+		};
 		if (newPageNumber != actualPage) {
 			actualPage = newPageNumber;
 			updateTableUi();
@@ -172,26 +166,22 @@ public class InspectorTable extends JPanel {
 	}
 
 	private void initHeaderButtons() {
-		Comparator<ElementRow> objectComp = (ElementRow a, ElementRow b) -> a.element.parentObject.getName()
-				.compareTo(b.element.parentObject.getName());
-		Comparator<ElementRow> idComp = (ElementRow a, ElementRow b) -> Integer.compare(a.element.parentObject.getId(),
-				b.element.parentObject.getId());
-		Comparator<ElementRow> deviceComp = (ElementRow a, ElementRow b) -> a.element.getName()
-				.compareTo(b.element.getName());
+		Comparator<ElementRow> objectComp = Comparator.comparing((ElementRow a) -> a.element.parentObject.getName());
+		Comparator<ElementRow> idComp = Comparator.comparingInt((ElementRow a) -> a.element.parentObject.getId());
+		Comparator<ElementRow> deviceComp = Comparator.comparing((ElementRow a) -> a.element.getName());
 		Comparator<ElementRow> energyComp = (ElementRow a, ElementRow b) -> Float.compare(a.element.getEnergy(),
 				b.element.getEnergy());
-		Comparator<ElementRow> priorityComp = (ElementRow a, ElementRow b) -> a.element.getPriority()
-				.compareTo(b.element.getPriority());
+		Comparator<ElementRow> priorityComp = Comparator.comparing((ElementRow a) -> a.element.getPriority());
 		Comparator<ElementRow> activeComp = (ElementRow a, ElementRow b) -> Boolean.compare(a.element.active,
 				b.element.active);
 		;
 
-		headerButtonList.add(new SortButton<ElementRow>("Object", objectComp));
-		headerButtonList.add(new SortButton<ElementRow>("Id", idComp));
-		headerButtonList.add(new SortButton<ElementRow>("Device", deviceComp));
-		headerButtonList.add(new SortButton<ElementRow>("Energy", energyComp));
-		headerButtonList.add(new SortButton<ElementRow>("Priority", priorityComp));
-		headerButtonList.add(new SortButton<ElementRow>("Activ", activeComp));
+		headerButtonList.add(new SortButton<>("Object", objectComp));
+		headerButtonList.add(new SortButton<>("Id", idComp));
+		headerButtonList.add(new SortButton<>("Device", deviceComp));
+		headerButtonList.add(new SortButton<>("Energy", energyComp));
+		headerButtonList.add(new SortButton<>("Priority", priorityComp));
+		headerButtonList.add(new SortButton<>("Active", activeComp));
 	}
 
 	private void addHeader() {
@@ -273,7 +263,6 @@ public class InspectorTable extends JPanel {
 		buttonPanel.add(deleteButton);
 
 		pageIncreaseButton.setIcon(new ImageIcon(Import.loadImage("images/buttons/page_increase.png", 16, 16)));
-		;
 		pageIncreaseButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
 		pageIncreaseButton.addActionListener(clicked -> this.performPageAction(PageAction.Increase));
 
@@ -320,10 +309,8 @@ public class InspectorTable extends JPanel {
 			int numberOfRows = rowPool.getBorrowedCount();
 			this.removeAll();
 			addHeader();
-			rowPool.getBorrowedStream().sorted(actual_comp).skip(actualPage * maxDisplayedRowsNumber)
-					.limit(maxDisplayedRowsNumber).takeWhile(row -> !abortThread).forEach(row -> {
-						row.addContainerToInspector();
-					});
+			rowPool.getBorrowedStream().sorted(actual_comp).skip((long) actualPage * maxDisplayedRowsNumber)
+					.limit(maxDisplayedRowsNumber).takeWhile(row -> !abortThread).forEach(ElementRow::addContainerToInspector);
 			if (numberOfRows > maxDisplayedRowsNumber) {
 				int lastDisplayedElementNumber = Math.min(numberOfRows, (actualPage + 1) * maxDisplayedRowsNumber);
 				pageInformationLabel.setText(String.format("%d - %d from %d", 1 + actualPage * maxDisplayedRowsNumber,
@@ -340,7 +327,7 @@ public class InspectorTable extends JPanel {
 			selectAllCheckBox.setSelectionState(State.unselected);
 			revalidate();
 			repaint();
-			this.OnElementSelectionChanged.broadcast(new HashSet<HolonElement>());
+			this.OnElementSelectionChanged.broadcast(new HashSet<>());
 		});
 		populateRowsThread.start();
 
@@ -375,7 +362,7 @@ public class InspectorTable extends JPanel {
 	// Extract elements from a list of AbstractCanvasObjects
 	static Stream<HolonElement> extractElements(Collection<AbstractCanvasObject> toInspect) {
 		Stream<HolonElement> recursiveLayer = toInspect.stream().filter(object -> object instanceof GroupNode).flatMap(
-				obj -> ((GroupNode) obj).getAllHolonObjectsRecursive().flatMap(hO -> hO.elementsStream()));
+				obj -> ((GroupNode) obj).getAllHolonObjectsRecursive().flatMap(HolonObject::elementsStream));
 		Stream<HolonElement> thisLayer = toInspect.stream().filter(obj -> obj instanceof HolonObject).flatMap(obj -> {
 			HolonObject ho = (HolonObject) obj;
 			return ho.elementsStream();
@@ -385,7 +372,7 @@ public class InspectorTable extends JPanel {
 
 	private class ElementRow {
 		private HolonElement element = null;
-		private Container[] cellsInRow = new Container[7];
+		private final Container[] cellsInRow = new Container[7];
 		// TextBoxes
 		private JTextField elementNameTextField;
 		private JCheckBox selectionBox;
@@ -493,6 +480,7 @@ public class InspectorTable extends JPanel {
 			comboBox.setEditable(false);
 			comboBox.addActionListener(ae -> {
 				this.element.setPriority((Priority) comboBox.getSelectedItem());
+				control.updateStateForCurrentIteration();
 			});
 			cellsInRow[5] = comboBox;
 
@@ -507,7 +495,7 @@ public class InspectorTable extends JPanel {
 			activeCheckBox.setOpaque(false);
 			activeCheckBox.addActionListener(actionEvent -> {
 				this.element.active = activeCheckBox.isSelected();
-				control.calculateStateForCurrentIteration();
+				control.updateStateForCurrentIteration();
 			});
 			checkBoxWrapperPanel.add(activeCheckBox, BorderLayout.CENTER);
 			cellsInRow[6] = checkBoxWrapperPanel;
@@ -550,28 +538,17 @@ public class InspectorTable extends JPanel {
 			text = text.replaceAll("\u25bc|\u25b2", "");
 			// update text
 			switch (state) {
-			case Descending:
-				this.setText(text + "\u25bc");
-				break;
-			case Ascending:
-				this.setText(text + "\u25b2");
-				break;
-			case None:
-			default:
-				this.setText(text);
-				break;
+				case Descending -> this.setText(text + "\u25bc");
+				case Ascending -> this.setText(text + "\u25b2");
+				default -> this.setText(text);
 			}
 		}
 
 		public Comparator<T> getComp() {
-			switch (state) {
-			case Descending:
-				return comp.reversed();
-			case Ascending:
-			case None:
-			default:
-				return comp;
-			}
+			return switch (state) {
+				case Descending -> comp.reversed();
+				default -> comp;
+			};
 		}
 	}
 }

+ 1 - 1
src/holeg/ui/view/main/TimePanel.java

@@ -121,7 +121,7 @@ public class TimePanel extends JPanel implements ActionListener {
 
 		this.setBorder(null);
 		timeSlider.addChangeListener(changeEvent -> {
-			control.calculateStateForCurrentIterationAndBroadcastCanvasUpdate(timeSlider.getValue());
+			control.updateStateForIteration(timeSlider.getValue());
 		});
 
 		timeSlider.addMouseListener(new MouseAdapter() {