1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213 |
- package holeg.api;
- import java.awt.BorderLayout;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.math.RoundingMode;
- import java.text.NumberFormat;
- import java.util.*;
- import java.util.function.BiFunction;
- import java.util.function.Consumer;
- import java.util.function.Supplier;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- import javax.swing.BorderFactory;
- import javax.swing.Box;
- import javax.swing.BoxLayout;
- import javax.swing.JButton;
- import javax.swing.JCheckBox;
- import javax.swing.JFileChooser;
- import javax.swing.JFormattedTextField;
- import javax.swing.JLabel;
- import javax.swing.JPanel;
- import javax.swing.JProgressBar;
- import javax.swing.JScrollPane;
- import javax.swing.JSeparator;
- import javax.swing.JSplitPane;
- import javax.swing.text.NumberFormatter;
- import holeg.algorithm.objective_function.TopologieObjectiveFunction;
- import holeg.model.*;
- import holeg.model.HolonSwitch.SwitchMode;
- import holeg.model.HolonSwitch.SwitchState;
- import holeg.preferences.ImagePreference;
- import holeg.ui.controller.Control;
- import holeg.ui.view.component.Console;
- import holeg.ui.view.category.Category;
- public abstract class TopologieAlgorithmFramework implements AddOn{
- //Algo
- protected int rounds = 1;
- protected int amountOfNewCables = 20;
-
-
- //Panel
- private JPanel content = new JPanel();
- protected Console console = new Console();
- private JPanel borderPanel = new JPanel();
- private HashMap<String, JPanel> panelMap = new HashMap<String, JPanel>();
-
-
-
-
- //Settings groupNode
- private Optional<GroupNode> groupNode = Optional.empty();
-
-
- //access
- private ArrayList<AccessWrapper> accessWildcards = new ArrayList<>();
- LinkedList<List<Integer>> resetChain = new LinkedList<>();
-
-
- private final HashMap<Integer, AbstractCanvasObject> accessIntToObject = new HashMap<>();
- private final HashMap<AbstractCanvasObject, Integer> accessObjectToInt = new HashMap<>();
- private final HashMap<Integer, AbstractCanvasObject> accessIntegerToWildcard = new HashMap<>();
- private final HashMap<AbstractCanvasObject, GroupNode> accessGroupNode = new HashMap<>();
-
- private final HashSet<IndexCable> cableSet = new HashSet<>();
- private final ArrayList<IndexCable> cableList = new ArrayList<>();
- private final HashMap<IndexCable, Double> addedIndexCable = new HashMap<>();
- private int countForAccessMap = 0;
- private int amountOfExistingCables = 0;
- private final ArrayList<HolonSwitch> switchList = new ArrayList<>();
- private final HashMap<HolonSwitch, GroupNode> accessSwitchGroupNode = new HashMap<>();
- private final ArrayList<Edge> edgeList = new ArrayList<>();
-
- boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true;
-
- //time
- private long startTime;
-
-
- private final RunProgressBar runProgressbar = new RunProgressBar();
-
-
-
- //concurrency
- private Thread runThread = new Thread();
- protected boolean cancel = false;
- //holeg interaction
- protected Control control;
-
- //printing
- private final Printer runPrinter = new Printer(plottFileName());
- protected List<Double> runList = new LinkedList<>();
- //Parameter
- @SuppressWarnings("rawtypes")
- LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
- protected boolean useStepping = false;
- //SwitchButton
-
-
-
- public TopologieAlgorithmFramework(){
- content.setLayout(new BorderLayout());
- JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
- createOptionPanel() , console);
- splitPane.setResizeWeight(0.0);
- content.add(splitPane, BorderLayout.CENTER);
- content.setPreferredSize(new Dimension(1200,800));
- }
-
-
-
-
-
-
- private JPanel createOptionPanel() {
- JPanel optionPanel = new JPanel(new BorderLayout());
- JScrollPane scrollPane = new JScrollPane(createParameterPanel());
- scrollPane.setBorder(BorderFactory.createTitledBorder("Parameters"));
- optionPanel.add(scrollPane, BorderLayout.CENTER);
- optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
- return optionPanel;
- }
-
- private JPanel createParameterPanel() {
- JPanel parameterPanel = new JPanel(null);
- parameterPanel.setPreferredSize(new Dimension(510,300));
- borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
- addIntParameter("Number of New Cables", amountOfNewCables, intInput -> amountOfNewCables = intInput, () -> amountOfNewCables, 0);
- addSeperator();
- addIntParameter("Repetitions", rounds, intInput -> rounds = intInput, () -> rounds, 1);
- JScrollPane scrollPane = new JScrollPane(borderPanel);
- scrollPane.setBounds(10, 0, 850, 292);
- scrollPane.setBorder(BorderFactory.createEmptyBorder());
- parameterPanel.add(scrollPane);
-
-
- JProgressBar progressBar = runProgressbar.getJProgressBar();
- progressBar.setBounds(900, 35, 185, 20);
- progressBar.setStringPainted(true);
- parameterPanel.add(progressBar);
-
- JButton addCategoryButton = new JButton("Add Category");
- addCategoryButton.setBounds(900, 65, 185, 30);
- addCategoryButton.addActionListener(clicked -> createWildcardsCategory());
- parameterPanel.add(addCategoryButton);
- return parameterPanel;
- }
- private JPanel createButtonPanel() {
- JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-
- JButton toggleSwitchesButton = new JButton("Toggle Switches");
- toggleSwitchesButton.setToolTipText("Set all switches active or inactive.");
- toggleSwitchesButton.addActionListener(actionEvent -> toggleSwitches());
- buttonPanel.add(toggleSwitchesButton);
-
-
-
- JButton resetButton = new JButton("Reset");
- resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
- resetButton.addActionListener(actionEvent -> reset());
- buttonPanel.add(resetButton);
-
- JButton cancelButton = new JButton("Cancel Run");
- cancelButton.addActionListener(actionEvent -> cancel());
- buttonPanel.add(cancelButton);
-
- JButton fitnessButton = new JButton("Fitness");
- fitnessButton.setToolTipText("Fitness for the current state.");
- fitnessButton.addActionListener(actionEvent -> fitness());
- buttonPanel.add(fitnessButton);
-
- JButton runButton = new JButton("Run");
- runButton.addActionListener(actionEvent -> {
- if(runThread.isAlive()) {
- return;
- }
- reset();
- this.resetAllList();
- resetChain.clear();
- Runnable task = () -> run();
- runThread = new Thread(task);
- runThread.start();
- });
- buttonPanel.add(runButton);
-
-
-
- return buttonPanel;
- }
-
-
-
- //ParameterImports
-
- private void toggleSwitches() {
- List<HolonSwitch> allSwitchList = control.getModel().getCanvas().getAllSwitchObjectsRecursive().toList();
- if(allSwitchList.isEmpty()) return;
- SwitchState set = allSwitchList.get(0).getManualState();
- allSwitchList.forEach(hSwitch -> {
- hSwitch.setMode(SwitchMode.Manual);
- hSwitch.setManualState(SwitchState.opposite(set));
- });
- updateVisual();
- }
- //addSeperator
- protected void addSeperator() {
- borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
- borderPanel.add(new JSeparator());
- borderPanel.add(Box.createRigidArea(new Dimension(5, 5)));
- }
- //int
- protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
- this.addIntParameter(parameterName, parameterValue, setter, getter, true, Integer.MIN_VALUE, Integer.MAX_VALUE);
- }
-
- protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, int parameterMinValue) {
- this.addIntParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Integer.MAX_VALUE);
- }
-
- protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, boolean visible, int parameterMinValue, int parameterMaxValue) {
- JPanel singleParameterPanel = new JPanel();
- singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
- singleParameterPanel.setAlignmentX(0.0f);
- singleParameterPanel.add(new JLabel(parameterName + ": "));
- singleParameterPanel.add(Box.createHorizontalGlue());
- NumberFormat format = NumberFormat.getIntegerInstance();
- format.setGroupingUsed(false);
- format.setParseIntegerOnly(true);
- NumberFormatter integerFormatter = new NumberFormatter(format);
- integerFormatter.setMinimum(parameterMinValue);
- integerFormatter.setMaximum(parameterMaxValue);
- integerFormatter.setCommitsOnValidEdit(true);
- JFormattedTextField singleParameterTextField = new JFormattedTextField(integerFormatter);
- singleParameterTextField.setValue(parameterValue);
- String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
- String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
- singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
- singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
- singleParameterTextField.setMaximumSize(new Dimension(200, 30));
- singleParameterTextField.setPreferredSize(new Dimension(200, 30));
- singleParameterPanel.add(singleParameterTextField);
-
-
- ParameterStepping<Integer> intParameterStepping = new ParameterStepping<Integer>(setter, getter, Integer::sum , (a,b) -> a * b, 1, 1);
- intParameterStepping.useThisParameter = false;
- parameterSteppingList.add(intParameterStepping);
-
- JCheckBox useSteppingCheckBox = new JCheckBox();
- useSteppingCheckBox.setSelected(false);
- singleParameterPanel.add(useSteppingCheckBox);
-
-
-
- JLabel stepsLabel = new JLabel("Steps: ");
- stepsLabel.setEnabled(false);
- singleParameterPanel.add(stepsLabel);
-
- NumberFormatter stepFormatter = new NumberFormatter(format);
- stepFormatter.setMinimum(1);
- stepFormatter.setMaximum(Integer.MAX_VALUE);
- stepFormatter.setCommitsOnValidEdit(true);
-
-
- JFormattedTextField stepsTextField = new JFormattedTextField(stepFormatter);
- stepsTextField.setEnabled(false);
- stepsTextField.setValue(1);
- stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
- stepsTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
- stepsTextField.setMaximumSize(new Dimension(40, 30));
- stepsTextField.setPreferredSize(new Dimension(40, 30));
- singleParameterPanel.add(stepsTextField);
-
- JLabel stepsSizeLabel = new JLabel("StepsSize: ");
- stepsSizeLabel.setEnabled(false);
- singleParameterPanel.add(stepsSizeLabel);
-
- JFormattedTextField stepsSizeTextField = new JFormattedTextField(stepFormatter);
- stepsSizeTextField.setEnabled(false);
- stepsSizeTextField.setValue(1);
- stepsSizeTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
- stepsSizeTextField.addPropertyChangeListener(actionEvent -> intParameterStepping.stepSize = Integer.parseInt(stepsSizeTextField.getValue().toString()));
- stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
- stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
- singleParameterPanel.add(stepsSizeTextField);
-
- useSteppingCheckBox.addActionListener(actionEvent -> {
- boolean enabled = useSteppingCheckBox.isSelected();
- intParameterStepping.useThisParameter = enabled;
- this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
- stepsLabel.setEnabled(enabled);
- stepsTextField.setEnabled(enabled);
- stepsSizeLabel.setEnabled(enabled);
- stepsSizeTextField.setEnabled(enabled);
- });
- panelMap.put(parameterName, singleParameterPanel);
- singleParameterPanel.setVisible(visible);
- borderPanel.add(singleParameterPanel);
- }
-
-
- //double
- protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
- this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, Double.MIN_VALUE, Double.MAX_VALUE);
- }
-
-
- protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, double parameterMinValue) {
- this.addDoubleParameter(parameterName, parameterValue, setter, getter, true, parameterMinValue, Double.MAX_VALUE);
- }
-
-
- protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, boolean visible, double parameterMinValue, double parameterMaxValue) {
- JPanel singleParameterPanel = new JPanel();
- singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
- singleParameterPanel.setAlignmentX(0.0f);
- singleParameterPanel.add(new JLabel(parameterName + ": "));
- singleParameterPanel.add(Box.createHorizontalGlue());
- NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
- doubleFormat.setMinimumFractionDigits(1);
- doubleFormat.setMaximumFractionDigits(10);
- doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
- NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
- doubleFormatter.setMinimum(parameterMinValue);
- doubleFormatter.setMaximum(parameterMaxValue);
- doubleFormatter.setCommitsOnValidEdit(true);
- JFormattedTextField singleParameterTextField = new JFormattedTextField(doubleFormatter);
- singleParameterTextField.setValue(parameterValue);
- String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
- String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
- singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
- singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
- singleParameterTextField.setMaximumSize(new Dimension(200, 30));
- singleParameterTextField.setPreferredSize(new Dimension(200, 30));
- singleParameterPanel.add(singleParameterTextField);
-
- ParameterStepping<Double> doubleParameterStepping = new ParameterStepping<Double>(setter, getter, (a,b) -> a+b , (a,b) -> a * b, 1.0, 1);
- doubleParameterStepping.useThisParameter = false;
- parameterSteppingList.add(doubleParameterStepping);
-
- JCheckBox useSteppingCheckBox = new JCheckBox();
- useSteppingCheckBox.setSelected(false);
- singleParameterPanel.add(useSteppingCheckBox);
-
-
-
- JLabel stepsLabel = new JLabel("Steps: ");
- stepsLabel.setEnabled(false);
- singleParameterPanel.add(stepsLabel);
- NumberFormat format = NumberFormat.getIntegerInstance();
- format.setGroupingUsed(false);
- format.setParseIntegerOnly(true);
- NumberFormatter integerFormatter = new NumberFormatter(format);
- integerFormatter.setMinimum(1);
- integerFormatter.setMaximum(Integer.MAX_VALUE);
- integerFormatter.setCommitsOnValidEdit(true);
-
-
-
- JFormattedTextField stepsTextField = new JFormattedTextField(integerFormatter);
- stepsTextField.setEnabled(false);
- stepsTextField.setValue(1);
- stepsTextField.setToolTipText("Only integer \u2208 [" + 1 + "," + Integer.MAX_VALUE + "]");
- stepsTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepps = Integer.parseInt(stepsTextField.getValue().toString()));
- stepsTextField.setMaximumSize(new Dimension(40, 30));
- stepsTextField.setPreferredSize(new Dimension(40, 30));
- singleParameterPanel.add(stepsTextField);
-
- JLabel stepsSizeLabel = new JLabel("StepsSize: ");
- stepsSizeLabel.setEnabled(false);
- singleParameterPanel.add(stepsSizeLabel);
-
- NumberFormatter doubleFormatterForStepping = new NumberFormatter(doubleFormat);
- doubleFormatterForStepping.setCommitsOnValidEdit(true);
- JFormattedTextField stepsSizeTextField = new JFormattedTextField(doubleFormatterForStepping);
- stepsSizeTextField.setEnabled(false);
- stepsSizeTextField.setValue(1.0);
- stepsSizeTextField.setToolTipText("Only double");
- stepsSizeTextField.addPropertyChangeListener(actionEvent -> doubleParameterStepping.stepSize = Double.parseDouble(stepsSizeTextField.getValue().toString()));
- stepsSizeTextField.setMaximumSize(new Dimension(40, 30));
- stepsSizeTextField.setPreferredSize(new Dimension(40, 30));
- singleParameterPanel.add(stepsSizeTextField);
-
- useSteppingCheckBox.addActionListener(actionEvent -> {
- boolean enabled = useSteppingCheckBox.isSelected();
- doubleParameterStepping.useThisParameter = enabled;
- this.useStepping = this.parameterSteppingList.stream().anyMatch(parameter -> parameter.useThisParameter);
- stepsLabel.setEnabled(enabled);
- stepsTextField.setEnabled(enabled);
- stepsSizeLabel.setEnabled(enabled);
- stepsSizeTextField.setEnabled(enabled);
- });
- panelMap.put(parameterName, singleParameterPanel);
- singleParameterPanel.setVisible(visible);
- borderPanel.add(singleParameterPanel);
- }
- //boolean
- protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter, List<String> showParameterNames, List<String> hideParameterNames){
- JPanel singleParameterPanel = new JPanel();
- panelMap.put(parameterName, singleParameterPanel);
- singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
- singleParameterPanel.setAlignmentX(0.0f);
- singleParameterPanel.add(new JLabel(parameterName + ": "));
- singleParameterPanel.add(Box.createHorizontalGlue());
- JCheckBox useGroupNodeCheckBox = new JCheckBox();
- useGroupNodeCheckBox.addActionListener(actionEvent -> {
- setter.accept(useGroupNodeCheckBox.isSelected());
- showParameterNames.forEach(string -> panelMap.get(string).setVisible(useGroupNodeCheckBox.isSelected()));
- hideParameterNames.forEach(string -> panelMap.get(string).setVisible(!useGroupNodeCheckBox.isSelected()));
- });
- useGroupNodeCheckBox.setSelected(parameterValue);
- singleParameterPanel.add(useGroupNodeCheckBox);
- borderPanel.add(singleParameterPanel);
- }
-
- private void startTimer(){
- startTime = System.currentTimeMillis();
- }
- private long printElapsedTime(){
- long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
- console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
- return elapsedMilliSeconds;
- }
-
-
-
- private void cancel() {
- if(runThread.isAlive()) {
- console.println("Cancel run.");
- cancel = true;
- runProgressbar.cancel();
- } else {
- console.println("Nothing to cancel.");
- }
- }
- private void createWildcardsCategory() {
- Optional<Category> category = control.findCategoryWithName("Wildcards");
- if(category.isEmpty()) {
- control.createCategoryWithName("Wildcards");
- }
- }
-
- private void fitness() {
- if(runThread.isAlive()) {
- console.println("Run have to be cancelled First.");
- return;
- }
- // reset();
- // this.extractPositionAndAccess();
- double currentFitness = evaluateNetworkAndPrint();
- console.println("Actual Fitnessvalue: " + currentFitness);
- }
-
-
- protected double evaluatePosition(List<Integer> positionToEvaluate) {
- setState(positionToEvaluate); // execution time critical
- return evaluateNetwork();
- }
- private double evaluateNetwork() {
- runProgressbar.step();
- return evaluateState(control.getModel(), calculateAmountOfAddedSwitches(), addedCableMeter(), false);
- }
- private double evaluateNetworkAndPrint() {
- runProgressbar.step();
- openAllSwitchInSwitchList();
- control.calculateStateForCurrentIteration();
- return evaluateState(control.getModel() ,calculateAmountOfAddedSwitches(), addedCableMeter(), true);
- }
-
- private void openAllSwitchInSwitchList() {
- for(HolonSwitch hSwitch: switchList) {
- hSwitch.setMode(SwitchMode.Manual);
- hSwitch.setManualState(SwitchState.Open);
- }
- }
-
-
-
- private double addedCableMeter() {
- return addedIndexCable.values().stream().reduce(0.0, Double::sum);
- }
- private int calculateAmountOfAddedSwitches() {
- return (int)this.switchList.stream().filter(sw -> sw.getName().contains("AddedSwitch")).count();
- }
-
- protected abstract double evaluateState(Model model, int amountOfAddedSwitch, double addedCableMeter, boolean moreInfromation);
-
- private void run() {
- cancel = false;
- control.guiSetEnabled(false);
- runPrinter.openStream();
- runPrinter.println("");
- runPrinter.println("Start:" + stringStatFromActualState());
- runPrinter.closeStream();
- if(this.useStepping) {
- initParameterStepping();
- do {
- executeAlgoWithParameter();
- if(cancel) break;
- resetState();
- }while(updateOneParameter());
- resetParameterStepping();
- }else {
- executeAlgoWithParameter();
-
- }
- TopologieObjectiveFunction.averageLog.clear();
- updateVisual();
- runProgressbar.finishedCancel();
- control.guiSetEnabled(true);
- }
- @SuppressWarnings("rawtypes")
- private void initParameterStepping() {
- for(ParameterStepping param :this.parameterSteppingList) {
- param.init();
- }
-
- }
- @SuppressWarnings("rawtypes")
- private void resetParameterStepping() {
- for(ParameterStepping param :this.parameterSteppingList) {
- param.reset();
- }
-
- }
- @SuppressWarnings("rawtypes")
- private boolean updateOneParameter() {
- List<ParameterStepping> parameterInUseList = this.parameterSteppingList.stream().filter(param -> param.useThisParameter).collect(Collectors.toList());
- Collections.reverse(parameterInUseList);
- int lastParameter = parameterInUseList.size() - 1 ;
- int actualParameter = 0;
- for(ParameterStepping param : parameterInUseList) {
-
- if(param.canUpdate()) {
- param.update();
- return true;
- }else {
- if(actualParameter == lastParameter) break;
- param.reset();
- }
- actualParameter++;
- }
- //No Param can be updated
- return false;
- }
- private void executeAlgoWithParameter(){
- double startFitness = evaluatePosition(extractPositionAndAccess());
- resetChain.removeLast();
- runPrinter.openStream();
- runPrinter.println("");
- runPrinter.println(algoInformationToPrint());
- runPrinter.closeStream();
- console.println(algoInformationToPrint());
- runProgressbar.start();
- Individual runBest = new Individual();
- runBest.fitness = Double.MAX_VALUE;
- for(int r = 0; r < rounds; r++)
- {
-
- resetState();
- startTimer();
- Individual roundBest = executeAlgo();
- if(cancel)return;
- long executionTime = printElapsedTime();
- setState(roundBest.position);
- runPrinter.openStream();
- runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
- runPrinter.println(stringStatFromActualState());
- runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
- runPrinter.closeStream();
-
- if(roundBest.fitness < runBest.fitness) runBest = roundBest;
- }
-
- setState(runBest.position);
- openAllSwitchInSwitchList();
- updateVisual();
- evaluateNetworkAndPrint();
- console.println("Start: " + startFitness);
- console.println("AlgoResult: " + runBest.fitness);
- }
-
-
- protected abstract Individual executeAlgo();
- private void reset() {
- if(runThread.isAlive()) {
- console.println("Run have to be cancelled First.");
- return;
- }
- if(!resetChain.isEmpty()) {
- console.println("Resetting..");
- setState(resetChain.getFirst());
- resetChain.clear();
- control.resetSimulation();
- control.getModel().setCurrentIteration(0);
- updateVisual();
- }else {
- console.println("No run inistialized.");
- }
- }
- /**
- * To let the User See the current state without touching the Canvas.
- */
- private void updateVisual() {
- control.calculateStateForCurrentIteration();
- }
- /**
- * Sets the Model back to its original State before the LAST run.
- */
- private void resetState() {
- if(!resetChain.isEmpty()) {
- setState(resetChain.removeLast());
- }
- resetAllList();
- }
- /**
- * Sets the State out of the given position for calculation or to show the user.
- * @param position
- */
- private void setState(List<Integer> position) {
- this.removeAllAddedObjects();
- for(int i = 0; i < this.amountOfNewCables; i++) {
- generateCable(position.get(2 * i), position.get(2 * i + 1), position.get(2 * amountOfNewCables + i) == 1);
- }
- //Switches new Cable
- //Switches existing cable
- int count = 0;
- for(int i = 3 * amountOfNewCables; i < 3 * this.amountOfNewCables + this.amountOfExistingCables; i++) {
- generateEdgeFromIndexCable(cableList.get(count++), position.get(i) == 1);
- }
- //WildCards
- count = 0;
- for(int i = 3 * amountOfNewCables + amountOfExistingCables; i < position.size(); i++) {
- accessWildcards.get(count++).setState(position.get(i));
- }
- openAllSwitchInSwitchList();
- control.calculateStateForCurrentIteration();
- }
- /**
- * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
- * Also initialize the Access Hashmap to swap faster positions.
- */
- protected List<Integer> extractPositionAndAccess() {
- Model model = control.getModel();
-
- resetAllList();
- Optional<Category> category = control.findCategoryWithName("Wildcards");
- category.ifPresentOrElse(cat -> {
- int count = 1;
- for(AbstractCanvasObject obj : cat.getObjects()) {
- accessIntegerToWildcard.put(count, obj);
- count++;
- }
- }, () -> {
- console.println("No 'Wildcards' Category");
- });
-
- List<Integer> initialState = new ArrayList<Integer>();
- generateAccess(model.getCanvas().getObjectsInThisLayer(), null);
- addCables(model.getEdgesOnCanvas());
- model.getEdgesOnCanvas().clear();
- //New Cables
- for(int i = 0; i < this.amountOfNewCables; i++) {
- initialState.add(0);
- initialState.add(0);
- }
- //switch in new Cables
- for(int i = 0; i < this.amountOfNewCables; i++) {
- initialState.add(0);
- }
- //Switch in initial Cable
- cableSet.stream().forEach(indexCale -> initialState.add(0));
- amountOfExistingCables = cableSet.size();
- //wildcards
- for(int i = 0; i < accessWildcards.size(); i++) {
- initialState.add(0);
- }
- resetChain.add(initialState);
- //console.println(accessIntToObject.values().stream().map(hO -> hO.getName()).collect(Collectors.joining(", ")));
- //console.println(cableSet.stream().map(Object::toString).collect(Collectors.f(", ")));
- return initialState;
- }
- private void resetAllList() {
- accessWildcards.clear();
- this.countForAccessMap = 0;
- amountOfExistingCables = 0;
- accessIntToObject.clear();
- accessObjectToInt.clear();
- cableSet.clear();
- cableList.clear();
- accessGroupNode.clear();
- accessIntegerToWildcard.clear();
- addedIndexCable.clear();
- switchList.clear();
- accessSwitchGroupNode.clear();
- edgeList.clear();
- }
-
-
-
-
- /**
- * Method to extract the Informations recursively out of the Model.
- * @param nodes
- */
- private void generateAccess(Stream<AbstractCanvasObject> nodes, GroupNode groupnode) {
- nodes.forEach(aCps -> {
- if(aCps instanceof HolonObject hO) {
- accessIntToObject.put(++countForAccessMap, hO);
- accessObjectToInt.put(hO, countForAccessMap);
- if(hO.getName().contains("Wildcard")) {
- accessWildcards.add(new AccessWrapper(hO));
- }
- if(groupnode != null) {
- accessGroupNode.put(hO, groupnode);
- }
- }
- if(aCps instanceof HolonSwitch hSwitch) {
- accessIntToObject.put(++countForAccessMap, hSwitch);
- accessObjectToInt.put(hSwitch, countForAccessMap);
- if(groupnode != null) {
- accessGroupNode.put(hSwitch, groupnode);
- }
- }
- if(aCps instanceof Node node) {
- accessIntToObject.put(++countForAccessMap, node);
- accessObjectToInt.put(node, countForAccessMap);
- if(groupnode != null) {
- accessGroupNode.put(node, groupnode);
- }
- }
- else if(aCps instanceof GroupNode groupNode) {
- generateAccess(groupNode.getObjectsInThisLayer(), groupNode);
- }
- });
- }
-
-
- protected void resetWildcards() {
- this.accessWildcards.forEach(AccessWrapper::resetState);
- }
- /**
- * All Nodes have to be in the access map !!
- */
- private void addCables(Set<Edge> edges) {
-
- for (Edge edge : edges) {
- edge.mode = Edge.EdgeMode.Unlimited;
- edgeList.add(edge);
- //console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
- if(!accessObjectToInt.containsKey(edge.getA())) {
- console.println("Node A [" + edge.getA() + "] from Edge[" + edge + "] not exist");
- continue;
- } else if (!accessObjectToInt.containsKey(edge.getB())) {
- console.println("Node B [" + edge.getB() + "]from Edge[" + edge + "] not exist");
- continue;
- }
- IndexCable cable = new IndexCable(accessObjectToInt.get(edge.getA()), accessObjectToInt.get(edge.getB()));
- boolean success = cableSet.add(cable);
- if(success) {
- cableList.add(cable);
- }
-
- }
- }
-
-
-
- private void generateCable(int index0, int index1, boolean switchBetween) {
- //If cable isnt valid
- if(index0 == 0 || index1 == 0 || index0 == index1) {
- //console.println("Cable("+index1+","+index2+ ") isn't valid");
- return;
- }
- IndexCable cable = new IndexCable(index0, index1);
- //if cable is in existing cables
- if(cableSet.contains(cable) || addedIndexCable.keySet().contains(cable)) {
- return;
- }
- generateEdgeFromIndexCable(cable, switchBetween);
- addedIndexCable.put(cable, cable.getLength());
- }
-
- private void generateEdgeFromIndexCable(IndexCable cable, boolean switchBetween){
- if(switchBetween) {
- //generate Switch
- AbstractCanvasObject fromObject = accessIntToObject.get(cable.first);
- AbstractCanvasObject toObject = accessIntToObject.get(cable.second);
- int middleX = (fromObject.getPosition().getX() + toObject.getPosition().getX())/2;
- int middleY = (fromObject.getPosition().getY() + toObject.getPosition().getY())/2;
- HolonSwitch newSwitch = new HolonSwitch("AddedSwitch");
- newSwitch.setPosition(middleX, middleY);
- //If fromObject is in Group
- if(accessGroupNode.containsKey(fromObject)) {
- GroupNode groupnode = accessGroupNode.get(fromObject);
- groupnode.add(newSwitch);
- accessSwitchGroupNode.put(newSwitch, groupnode);
- } else if(accessGroupNode.containsKey(toObject)) {
- GroupNode groupnode = accessGroupNode.get(toObject);
- groupnode.add(newSwitch);
- accessSwitchGroupNode.put(newSwitch, groupnode);
- }else {
- control.getModel().getCanvas().add(newSwitch);
- }
- //else if toObject is in Group
- this.switchList.add(newSwitch);
- //Generate Cable From Object A To Switch
- Edge edge1 = new Edge(fromObject, newSwitch, 0);
- edge1.mode = Edge.EdgeMode.Unlimited;
- control.getModel().getEdgesOnCanvas().add(edge1);
- edgeList.add(edge1);
-
- //Generate Cable From Object B To Switch
- Edge edge = new Edge(newSwitch, toObject, 0);
- edge.mode = Edge.EdgeMode.Unlimited;
- control.getModel().getEdgesOnCanvas().add(edge);
- edgeList.add(edge);
- }else {
- Edge edge = new Edge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second), 0);
- edge.mode = Edge.EdgeMode.Unlimited;
- control.getModel().getEdgesOnCanvas().add(edge);
- edgeList.add(edge);
- }
- }
- private void removeAllAddedObjects() {
- control.getModel().getEdgesOnCanvas().removeAll(edgeList);
- addedIndexCable.clear();
- //control.getModel().getObjectsOnCanvas().removeAll(switchList);
- for(HolonSwitch hSwitch: switchList) {
- if(this.accessSwitchGroupNode.containsKey(hSwitch)) {
- accessSwitchGroupNode.get(hSwitch).remove(hSwitch);
- }
- else {
- control.getModel().getCanvas().remove(hSwitch);
- }
- }
- accessSwitchGroupNode.clear();
- switchList.clear();
- edgeList.clear();
- }
- private String stringStatFromActualState() {
- AlgorithmFrameworkFlex.RunValues val = new AlgorithmFrameworkFlex.RunValues();
- GroupNode canvas = control.getModel().getCanvas();
- List<HolonObject> holonObjectList = canvas.getAllHolonObjectsRecursive().toList();
- Map<HolonObject.HolonObjectState, Long> stateMap = holonObjectList.stream().collect(Collectors.groupingBy(HolonObject::getState, Collectors.counting()));
- // UPDATE SUPPLY STATE
- val.producer = Math.toIntExact(stateMap.getOrDefault(HolonObject.HolonObjectState.PRODUCER, 0L));
- val.overSupplied = Math.toIntExact(stateMap.getOrDefault(HolonObject.HolonObjectState.OVER_SUPPLIED, 0L));
- val.supplied = Math.toIntExact(stateMap.getOrDefault(HolonObject.HolonObjectState.SUPPLIED, 0L));
- val.partiallySupplied = Math.toIntExact(stateMap.getOrDefault(HolonObject.HolonObjectState.PARTIALLY_SUPPLIED, 0L));
- val.unsupplied = Math.toIntExact(stateMap.getOrDefault(HolonObject.HolonObjectState.NOT_SUPPLIED, 0L));
- val.passiv = Math.toIntExact(stateMap.getOrDefault(HolonObject.HolonObjectState.NO_ENERGY, 0L));
- val.consumer = val.overSupplied + val.supplied + val.partiallySupplied + val.unsupplied;
- val.objects = val.consumer + val.producer + val.passiv;
- List<HolonElement> holonElementList = canvas.getAllHolonElements().toList();
- val.elements = holonElementList.size();
- // UPDATE ActiveInActive
- val.activeElements = holonElementList.stream().filter(HolonElement::isOn).count();
- val.consumption = canvas.getTotalConsumption();
- val.production = canvas.getTotalProduction();
- val.difference= Math.abs(val.production - val.consumption);
- List<Flexibility> activeFlex = holonElementList.stream().flatMap(ele -> ele.flexList.stream()).filter(flex -> flex.getState().equals(Flexibility.FlexState.IN_USE)).toList();
- Map<HolonElement.Priority, Long> priorityCounts = activeFlex.stream().collect(Collectors.groupingBy(flex -> flex.getElement().priority, Collectors.counting()));
- val.essentialFlex = priorityCounts.getOrDefault(HolonElement.Priority.Essential, 0L);
- val.highFlex = priorityCounts.getOrDefault(HolonElement.Priority.High, 0L);
- val.mediumFlex = priorityCounts.getOrDefault(HolonElement.Priority.Medium, 0L);
- val.lowFlex = priorityCounts.getOrDefault(HolonElement.Priority.Low, 0L);
- val.flexebilities = activeFlex.size();
- val.holon = control.getModel().holons.size();
- List<HolonSwitch> switchList = canvas.getAllSwitchObjectsRecursive().toList();
- val.switches = switchList.size();
- val.activeSwitches = (int)switchList.stream().filter(HolonSwitch::isClosed).count();
- DoubleSummaryStatistics overStat = holonObjectList.stream().filter(con -> con.getState().equals(HolonObject.HolonObjectState.OVER_SUPPLIED))
- .mapToDouble(HolonObject::getSupplyBarPercentage).summaryStatistics();
- DoubleSummaryStatistics partiallyStat = holonObjectList.stream().filter(con -> con.getState().equals(HolonObject.HolonObjectState.PARTIALLY_SUPPLIED))
- .mapToDouble(HolonObject::getSupplyBarPercentage).summaryStatistics();
- val.partiallyMin = AlgorithmFrameworkFlex.RunValues.filterInf(partiallyStat.getMin());
- val.partiallyMax = AlgorithmFrameworkFlex.RunValues.filterInf(partiallyStat.getMax());
- val.partiallyAverage = AlgorithmFrameworkFlex.RunValues.filterInf(partiallyStat.getAverage());
- val.overMin = AlgorithmFrameworkFlex.RunValues.filterInf(overStat.getMin());
- val.overMax = AlgorithmFrameworkFlex.RunValues.filterInf(overStat.getMax());
- val.overAverage = AlgorithmFrameworkFlex.RunValues.filterInf(overStat.getAverage());
- int addedSwitches = calculateAmountOfAddedSwitches();
- double addedCableMeters = addedCableMeter();
- double wildcardCost = TopologieObjectiveFunction.calculateWildcardCost(control.getModel());
- double cableCost = TopologieObjectiveFunction.calculateAddedCableCost(addedCableMeters);
- double switchCost = TopologieObjectiveFunction.calculateAddedSwitchCost(addedSwitches);
- double totalCost = wildcardCost + cableCost + switchCost;
- return val.stringStatFromRunValues("")
- + " Topology["
- + " addedCableMeters:" + addedCableMeters
- + " addedSwitches: " + addedSwitches
- + " totalCost: " + totalCost + "("
- + " wildcardCost: " + wildcardCost
- + " cableCost: " + cableCost
- + " switchCost: " + switchCost
- + ")]";
- }
-
-
- @Override
- public JPanel getPanel() {
- return content;
- }
- @Override
- public void setController(Control control) {
- this.control = control;
- }
-
- // | New Cable | Switches | Wildcards |
- //return index: | countForAccessMap | 1 | accessWildcards.size()|
- public int getMaximumIndexObjects(int index) {
- int maximumIndex = -1;
- //New Cables
- if(index < 2 * amountOfNewCables) {
- maximumIndex = this.countForAccessMap;
- }
- //Switches in existing and in new Cables
- else if (index < 3 * amountOfNewCables + this.amountOfExistingCables) {
- maximumIndex = 1;
- }
- //wildcards
- else {
- maximumIndex = this.accessIntegerToWildcard.size();
- }
- return maximumIndex;
- }
-
-
- private class RunProgressBar{
- //progressbar
- private JProgressBar progressBar = new JProgressBar();
- private int count = 0;
- private boolean isActive = false;
-
- public void step() {
- if(isActive) progressBar.setValue(count++);
- }
- public void start() {
- progressBar.setIndeterminate(false);
- count = 0;
- isActive = true;
- progressBar.setValue(0);
- progressBar.setMaximum(getProgressBarMaxCount());
- }
- public void cancel() {
- isActive = false;
- progressBar.setIndeterminate(true);
- }
- public void finishedCancel() {
- progressBar.setIndeterminate(false);
- progressBar.setValue(0);
- }
- public JProgressBar getJProgressBar(){
- return progressBar;
- }
- }
-
- protected abstract int getProgressBarMaxCount();
-
- protected abstract String algoInformationToPrint();
- protected abstract String plottFileName();
-
-
-
- public class Printer{
- private JFileChooser fileChooser = new JFileChooser();
- private BufferedWriter out;
- public Printer(String filename){
- fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
- fileChooser.setSelectedFile(new File(filename));
- }
- public void openStream() {
- File file = fileChooser.getSelectedFile();
- try {
- file.createNewFile();
- out = new BufferedWriter(new OutputStreamWriter(
- new FileOutputStream(file, true), "UTF-8"));
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
-
-
- public void println(String stringToPrint) {
- try {
- out.write(stringToPrint);
- out.newLine();
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
- public void closeStream() {
- try {
- out.close();
- } catch (IOException e) {
- System.out.println(e.getMessage());
- }
- }
- }
-
-
- /**
- * A Wrapper Class to access wildcards
- */
- private class AccessWrapper {
- int state = 0;
- HolonObject wildcard;
- public AccessWrapper(HolonObject wildcard) {
- this.wildcard = wildcard;
- }
-
- public void setState(int state) {
- if(this.state != state) {
- this.state = state;
- if(state > 0) {
- wildcard.clearElements();
- HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
- if(hO == null) {
- console.println("null set state(" + state + ")");
- }else {
- if(hO.getName().contains(":")) {
- wildcard.setName("Wildcard" + hO.getName().substring(hO.getName().lastIndexOf(":")));
- }else {
- wildcard.setName("Wildcard");
- }
- wildcard.add(hO.elementsStream().toList());
- wildcard.setImagePath(hO.getImagePath());
- }
- }else {
- resetState();
- }
- }
- }
- public void resetState() {
- state = 0;
- wildcard.setName("Wildcard");
- wildcard.setImagePath(ImagePreference.Canvas.DefaultObject.House);
- wildcard.clearElements();
- }
-
- public String toString() {
- return wildcard + "have state: " + state;
- }
- }
-
-
- public class Individual {
- public double fitness;
- public List<Integer> position;
-
- public Individual(){};
- /**
- * Copy Constructor
- */
- public Individual(Individual c){
- position = c.position.stream().collect(Collectors.toList());
- fitness = c.fitness;
- }
- }
-
- protected class ParameterStepping<T>{
- boolean useThisParameter = false;
- String paramaterName;
- private int count = 0;
- int stepps;
- T stepSize;
- T startValue;
- Consumer<T> setter;
- Supplier<T> getter;
- BiFunction<Integer,T,T> multyply;
- BiFunction<T,T,T> add;
- ParameterStepping(Consumer<T> setter, Supplier<T> getter, BiFunction<T,T,T> add, BiFunction<Integer,T,T> multyply, T stepSize, int stepps){
- this.setter = setter;
- this.getter = getter;
- this.multyply = multyply;
- this.add = add;
- this.stepSize = stepSize;
- this.stepps = stepps;
- }
-
- void init() {
- startValue = getter.get();
- }
-
- boolean canUpdate() {
- return count < stepps;
- }
-
- void update(){
- if(canUpdate()) {
- setter.accept(add.apply(startValue, multyply.apply(count + 1, stepSize)));
- count ++;
- }
- }
-
- void reset() {
- setter.accept(startValue);
- count = 0;
- }
- }
-
-
-
-
-
- public class IndexCable{
- public final Integer first;
- public final Integer second;
- public IndexCable(Integer first, Integer second) {
- if(first.equals(second)) {
- throw new IllegalArgumentException("(" + first + "==" + second + ")"
- + "Two ends of the cable are at the same Object");
- } else if(first.compareTo(second) < 0) {
- this.first = first;
- this.second = second;
- }else {
- this.first = second;
- this.second = first;
- }
- }
- @Override
- public boolean equals(Object o) {
- if(o instanceof IndexCable cable) {
- return Objects.equals(cable.first, first) && Objects.equals(cable.second, second);
- }
- return false;
- }
- @Override
- public int hashCode() {
- return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
- }
- @Override
- public String toString() {
- return "{" + first + "," + second + "}";
- }
- public double getLength() {
- return accessIntToObject.get(first).getPosition().getDistance(accessIntToObject.get(second).getPosition());
- }
- }
- }
|