123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260 |
- package api;
- import java.awt.BorderLayout;
- import java.awt.Component;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.image.BufferedImage;
- 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.ArrayList;
- import java.util.Collections;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.LinkedHashSet;
- import java.util.LinkedList;
- import java.util.List;
- import java.util.Locale;
- import java.util.Objects;
- import java.util.function.BiFunction;
- import java.util.function.Consumer;
- import java.util.function.Supplier;
- import java.util.stream.Collectors;
- import javax.swing.BorderFactory;
- import javax.swing.Box;
- import javax.swing.BoxLayout;
- import javax.swing.ImageIcon;
- import javax.swing.JButton;
- import javax.swing.JCheckBox;
- import javax.swing.JFileChooser;
- import javax.swing.JFormattedTextField;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JPanel;
- import javax.swing.JProgressBar;
- import javax.swing.JScrollPane;
- import javax.swing.JSplitPane;
- import javax.swing.text.NumberFormatter;
- import classes.AbstractCanvasObject;
- import classes.Category;
- import classes.Edge;
- import classes.GroupNode;
- import classes.Flexibility;
- import classes.HolonElement;
- import classes.HolonObject;
- import classes.HolonSwitch;
- import classes.HolonElement.Priority;
- import ui.controller.Control;
- import ui.controller.FlexManager.FlexState;
- import ui.controller.FlexManager.FlexWrapper;
- import ui.model.DecoratedGroupNode;
- import ui.model.DecoratedState;
- import ui.model.IntermediateCableWithState;
- import ui.model.Model;
- import ui.model.DecoratedCable.CableState;
- import ui.model.DecoratedHolonObject.HolonObjectState;
- import ui.model.DecoratedSwitch.SwitchState;
- import ui.model.DecoratedNetwork;
- import ui.view.Console;
- public abstract class TopologieAlgorithmFramework implements AddOn{
- //Algo
- protected int rounds = 1;
- protected int amountOfNewCables = 3;
-
-
- //Panel
- private JPanel content = new JPanel();
- protected Console console = new Console();
- private JPanel borderPanel = new JPanel();
-
-
- //Settings groupNode
- private DecoratedGroupNode dGroupNode = null;
-
-
- //access
- private ArrayList<AccessWrapper> accessWildcards = new ArrayList<AccessWrapper>();
- LinkedList<List<Integer>> resetChain = new LinkedList<List<Integer>>();
-
-
- private HashMap<Integer, AbstractCanvasObject> accessIntToObject = new HashMap<Integer, AbstractCanvasObject>();
- private HashMap<AbstractCanvasObject, Integer> accessObjectToInt = new HashMap<AbstractCanvasObject, Integer>();
- private HashMap<Integer, AbstractCanvasObject> accessIntegerToWildcard = new HashMap<Integer, AbstractCanvasObject>();
- private HashMap<AbstractCanvasObject, GroupNode> accessGroupNode = new HashMap<AbstractCanvasObject, GroupNode>();
-
- private HashSet<IndexCable> cableSet = new HashSet<IndexCable>();
- private ArrayList<IndexCable> cableList = new ArrayList<IndexCable>();
- private HashSet<IndexCable> addedIndexCable = new HashSet<IndexCable>();
- private int countForAccessMap = 0;
- private int amountOfExistingCables = 0;
- private ArrayList<HolonSwitch> switchList = new ArrayList<HolonSwitch>();
- private HashMap<HolonSwitch, GroupNode> accessSwitchGroupNode = new HashMap<HolonSwitch, GroupNode>();
- private ArrayList<Edge> edgeList = new ArrayList<Edge>();
-
-
- boolean algoUseElements = false, algoUseSwitches = true, algoUseFlexes = true;
-
- //time
- private long startTime;
-
-
- private RunProgressBar runProgressbar = new RunProgressBar();
-
-
-
- //concurrency
- private Thread runThread = new Thread();
- protected boolean cancel = false;
- //holeg interaction
- protected Control control;
-
- //printing
- private Printer runPrinter = new Printer(plottFileName());
- protected List<Double> runList = new LinkedList<Double>();
- //Parameter
- @SuppressWarnings("rawtypes")
- LinkedList<ParameterStepping> parameterSteppingList= new LinkedList<ParameterStepping>();
- protected boolean useStepping = false;
-
-
-
- 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("Parameter"));
- 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("Rounds", rounds, intInput -> rounds = intInput, () -> rounds, 1);
- addIntParameter("amountOfNewCables", amountOfNewCables, intInput -> amountOfNewCables = intInput, () -> amountOfNewCables, 0);
- 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 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 -> {
- Runnable task = () -> run();
- runThread = new Thread(task);
- runThread.start();
- });
- buttonPanel.add(runButton);
-
-
-
- return buttonPanel;
- }
-
-
-
- //ParameterImports
-
- //int
- protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter) {
- this.addIntParameter(parameterName, parameterValue, setter, getter, 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, parameterMinValue, Integer.MAX_VALUE);
- }
-
- protected void addIntParameter(String parameterName, int parameterValue, Consumer<Integer> setter, Supplier<Integer> getter, 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);
- });
-
- borderPanel.add(singleParameterPanel);
- }
-
-
- //double
- protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter) {
- this.addDoubleParameter(parameterName, parameterValue, setter, getter, 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, parameterMinValue, Double.MAX_VALUE);
- }
-
-
- protected void addDoubleParameter(String parameterName, double parameterValue, Consumer<Double> setter, Supplier<Double> getter, 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);
- });
-
- borderPanel.add(singleParameterPanel);
- }
- //boolean
- protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
- 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());
- JCheckBox useGroupNodeCheckBox = new JCheckBox();
- useGroupNodeCheckBox.setSelected(parameterValue);
- useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
- 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() {
- Category category = control.searchCategory("Wildcards");
- if(category == null) {
- try {
- control.addCategory("Wildcards");
- } catch (IOException e) {
- console.println("IO Exception - Creating WIldcards Category failed.");
- System.out.println("IO Exception - Creating WIldcards Category failed.");
- e.printStackTrace();
- }
- }
- }
-
- private void fitness() {
- if(runThread.isAlive()) {
- console.println("Run have to be cancelled First.");
- return;
- }
- double currentFitness = evaluateNetwork();
- console.println("Actual Fitnessvalue: " + currentFitness);
- }
-
-
- protected double evaluatePosition(List<Integer> positionToEvaluate) {
- runProgressbar.step();
- control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
-
- setState(positionToEvaluate); // execution time critical
- return evaluateNetwork();
- }
- private double evaluateNetwork() {
-
- // Not possible due exponentiak growing
- // double times = Math.pow(2, switchList.size());
- // double sum = 0;
- // for(int i = 0; i < times; i++) {
- // int positionInBitString = 0;
- // for(HolonSwitch hSwitch: switchList) {
- // boolean result = ((i >> positionInBitString++) & 1) != 0;
- // hSwitch.setManualState(result);
- // }
- // sum += evaluateNetwork() / times;
- // }
-
- System.out.println("-->");
- double sum = 0;
- double step = 0.1;
- int steppsDone = 0;
- for(double actual = 0; actual <= 1 ; actual += step) {
- for(HolonSwitch hSwitch: switchList) {
- hSwitch.setManualMode(true);
- hSwitch.setManualState(Random.nextDouble() < actual);
- }
- control.calculateStateOnlyForCurrentTimeStep();
- DecoratedState actualstate = control.getSimManager().getActualDecorState();
- sum += evaluateState(actualstate);
- steppsDone++;
- }
- System.out.println("<--");
-
- return sum /(double) steppsDone;
- }
-
-
- protected abstract double evaluateState(DecoratedState actualstate);
-
- private void run() {
- cancel = false;
- control.guiDisable(true);
- 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();
-
- }
- updateVisual();
- runProgressbar.finishedCancel();
- control.guiDisable(false);
- }
- @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());
- console.println(algoInformationToPrint());
- runPrinter.closeStream();
- runProgressbar.start();
- Individual runBest = new Individual();
- runBest.fitness = Double.MAX_VALUE;
- for(int r = 0; r < rounds; r++)
- {
-
- startTimer();
- Individual roundBest = executeAlgo();
- if(cancel)return;
- long executionTime = printElapsedTime();
- runPrinter.openStream();
- runPrinter.println(runList.stream().map(Object::toString).collect(Collectors.joining(", ")));
- runPrinter.println(stringStatFromActualState());
- runPrinter.println("Result: " + roundBest.fitness + " ExecutionTime:" + executionTime);
- runPrinter.closeStream();
- //resetState();
- if(roundBest.fitness < runBest.fitness) runBest = roundBest;
- }
-
- control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
- setState(runBest.position);
- updateVisual();
- 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());
- control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
- resetChain.clear();
- control.resetSimulation();
- control.setCurIteration(0);
- updateVisual();
- }else {
- console.println("No run inistialized.");
- }
- }
- /**
- * To let the User See the current state without touching the Canvas.
- */
- private void updateVisual() {
- control.calculateStateAndVisualForCurrentTimeStep();
- }
- /**
- * Sets the Model back to its original State before the LAST run.
- */
- private void resetState() {
- control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
- setState(resetChain.getLast());
- }
- /**
- * 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));
- }
- }
- /**
- * 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.
- * @param model
- * @return
- */
- protected List<Integer> extractPositionAndAccess() {
- Model model = control.getModel();
-
-
-
-
-
- //-->reset
- accessWildcards.clear();
- this.countForAccessMap = 0;
- amountOfExistingCables = 0;
- accessIntToObject.clear();
- accessObjectToInt.clear();
- cableSet.clear();
- cableList.clear();
- accessGroupNode.clear();
- //<---
- Category category = control.searchCategory("Wildcards");
- if(category != null) {
- for(int count = 0; count < category.getObjects().size(); count++ ) {
- accessIntegerToWildcard.put(count + 1, category.getObjects().get(count));
- }
- }else {
- console.println("No 'Wildcards' Category");
- }
-
-
-
- List<Integer> initialState = new ArrayList<Integer>();
- generateAccess(model.getObjectsOnCanvas(), 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;
- }
-
-
-
-
- /**
- * Method to extract the Informations recursively out of the Model.
- * @param nodes
- * @param positionToInit
- * @param timeStep
- */
- private void generateAccess(List<AbstractCanvasObject> nodes, GroupNode groupnode) {
- for(AbstractCanvasObject aCps : nodes) {
- if(aCps instanceof HolonObject) {
- HolonObject hO = (HolonObject) aCps;
- accessIntToObject.put(++countForAccessMap, hO);
- accessObjectToInt.put(hO, countForAccessMap);
- if(hO.getName().equals("Wildcard")) {
- accessWildcards.add(new AccessWrapper(hO));
- }
- if(groupnode != null) {
- accessGroupNode.put(hO, groupnode);
- }
- }
- else if(aCps instanceof GroupNode) {
- generateAccess(((GroupNode)aCps).getNodes(), (GroupNode) aCps);
- }
- }
- }
-
-
- protected void resetWildcards() {
- this.accessWildcards.forEach(wrapper -> wrapper.resetState());
- }
- /**
- * All Nodes have to be in the access map !!
- * @param cables
- */
- private void addCables(List<Edge> edges) {
-
- for (Edge edge : edges) {
- edge.setUnlimitedCapacity(true);
- edgeList.add(edge);
- //console.println("Cable from " + edge.getA().getName() + " to " + edge.getB().getName());
- if(!accessObjectToInt.containsKey(edge.getA())) {
- console.println("Node A from Edge[" + edge + "] not exist");
- continue;
- } else if (!accessObjectToInt.containsKey(edge.getB())) {
- console.println("Node B 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.contains(cable)) {
- return;
- }
- generateEdgeFromIndexCable(cable, switchBetween);
- addedIndexCable.add(cable);
- }
-
- 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().x + toObject.getPosition().x)/2;
- int middleY = (fromObject.getPosition().y + toObject.getPosition().y)/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.getNodes().add(newSwitch);
- accessSwitchGroupNode.put(newSwitch, groupnode);
- } else if(accessGroupNode.containsKey(toObject)) {
- GroupNode groupnode = accessGroupNode.get(toObject);
- groupnode.getNodes().add(newSwitch);
- accessSwitchGroupNode.put(newSwitch, groupnode);
- }else {
- control.getModel().getObjectsOnCanvas().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);
- edge1.setUnlimitedCapacity(true);
- control.getModel().getEdgesOnCanvas().add(edge1);
- edgeList.add(edge1);
-
- //Generate Cable From Object B To Switch
- Edge edge = new Edge(newSwitch, toObject);
- edge.setUnlimitedCapacity(true);
- control.getModel().getEdgesOnCanvas().add(edge);
- edgeList.add(edge);
- }else {
- Edge edge = new Edge(accessIntToObject.get(cable.first), accessIntToObject.get(cable.second));
- edge.setUnlimitedCapacity(true);
- 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).getNodes().remove(hSwitch);
- }
- else {
- control.getModel().getObjectsOnCanvas().remove(hSwitch);
- }
- }
- accessSwitchGroupNode.clear();
- switchList.clear();
- edgeList.clear();
- }
-
-
- private String stringStatFromActualState() {
- if(dGroupNode != null)
- {
- //GetActualDecoratedGroupNode
- dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
- int amountOfSupplier = dGroupNode.getAmountOfSupplier();
- int amountOfConsumer = dGroupNode.getAmountOfConsumer();
- int amountOfPassiv = dGroupNode.getAmountOfPassiv();
- int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
- int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
- int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
- int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
- int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-
-
- int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
- int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
- return "HolonObjects["
- + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
- + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
- + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
- + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
- + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
- + "]" + " HolonElemnts["
- + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
- + "]";
- }
- DecoratedState state = control.getSimManager().getActualDecorState();
- int amountOfSupplier = 0, amountOfConsumer = 0, amountOfPassiv = 0, unSuppliedConsumer = 0, partiallySuppliedConsumer = 0, suppliedConsumer = 0, overSuppliedConsumer = 0;
- int activeElements = 0, amountOfelements = 0;
- int totalConsumption = 0, totalProduction = 0;
- for(DecoratedNetwork net : state.getNetworkList()) {
- amountOfConsumer += net.getAmountOfConsumer();
- amountOfSupplier += net.getAmountOfSupplier();
- amountOfPassiv += net.getAmountOfPassiv();
- unSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
- partiallySuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
- suppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
- overSuppliedConsumer += net.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
- amountOfelements += net.getAmountOfElements();
- activeElements += net.getAmountOfActiveElements();
- totalConsumption += net.getTotalConsumption();
- totalProduction += net.getTotalProduction();
- }
- int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
- int difference = Math.abs(totalProduction - totalConsumption);
-
-
-
- List<Flexibility> flexActiveList = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE).stream().map(flex -> flex.getFlex()).collect(Collectors.toList());
- int amountActiveEssential = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Essential).count();
- int amountActiveHigh = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.High).count();
- int amountActiveMedium = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Medium).count();
- int amountActiveLow = (int)flexActiveList.stream().filter(flex -> flex.getElement().getPriority() == Priority.Low).count();
- int amountActiveFlexibilities = amountActiveEssential + amountActiveHigh + amountActiveMedium + amountActiveLow;
- int amountHolons = state.getNetworkList().size();
- int amountSwitch = state.getDecoratedSwitches().size();
- int amountActiveSwitch = (int)state.getDecoratedSwitches().stream().filter(dswitch -> (dswitch.getState() == SwitchState.Closed)).count();
-
-
- return "HolonObjects["
- + " Passiv: " + percentage(amountOfPassiv, amountOfObjects)
- + " Producer: " + percentage(amountOfSupplier, amountOfObjects)
- + " Consumer: " + percentage(amountOfConsumer, amountOfObjects)
- + " Unsupplied: " + percentage(unSuppliedConsumer, amountOfConsumer)
- + " PartiallySupplied: " + percentage(partiallySuppliedConsumer, amountOfObjects)
- + " Supplied: " + percentage(suppliedConsumer, amountOfConsumer)
- + " Over: " + percentage(overSuppliedConsumer, amountOfConsumer)
- + "]" + " HolonElemnts["
- + " Active: " + percentage(activeElements, amountOfelements)
- + "]" + "Flexibilities_active["
- + " Essential: " + percentage(amountActiveEssential, amountActiveFlexibilities)
- + " High: " + percentage(amountActiveHigh, amountActiveFlexibilities)
- + " Medium: " + percentage(amountActiveMedium, amountActiveFlexibilities)
- + " Low: " + percentage(amountActiveLow, amountActiveFlexibilities)
- + "]" + " activeSwitches:" + percentage(amountActiveSwitch,amountSwitch)
- + " Holons: " + amountHolons
- + " totalConsumption: " + totalConsumption
- + " totalProduction: " + totalProduction
- + " difference: " + difference;
-
- }
-
-
- private String percentage(int actual, int max) {
- return actual + "/" + max + "("+ (float)actual/(float)max * 100 + "%)";
- }
-
-
- @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 = accessWildcards.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 for Access HolonElement and HolonSwitch in one Element and not have to split the List.
- */
- 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;
- wildcard.getElements().clear();
- if(state > 0) {
- HolonObject hO = (HolonObject)accessIntegerToWildcard.get(state);
- if(hO == null) {
- console.println("null set state(" + state + ")");
- }else {
- wildcard.getElements().addAll(hO.getElements());
- }
- }
- }
- }
- public void resetState() {
- state = 0;
- wildcard.getElements().clear();
- }
-
- public String toString() {
- return wildcard + "have state: " + state;
- }
- }
-
-
-
-
- /**
- * To create Random and maybe switch the random generation in the future.
- */
- protected static class Random{
- private static java.util.Random random = new java.util.Random();
- /**
- * True or false
- * @return the random boolean.
- */
- public static boolean nextBoolean(){
- return random.nextBoolean();
- }
- /**
- * Between 0.0(inclusive) and 1.0 (exclusive)
- * @return the random double.
- */
- public static double nextDouble() {
- return random.nextDouble();
- }
-
- /**
- * Random Int in Range [min;max[ with UniformDistirbution
- * @param min
- * @param max
- * @return
- */
- public static int nextIntegerInRange(int min, int max) {
- int result = min;
- try {
- result = min + random.nextInt(max - min);
- }catch(java.lang.IllegalArgumentException e){
- System.err.println("min : " + min + " max : " + max);
- System.err.println("max should be more then min");
- }
- return result;
- }
- /**
- * Random Int in Range [min;max[ with UniformDistirbution
- * @param min
- * @param max
- * @param valueBetween a value between min and max
- * @return
- */
- public static int nextIntegerInRangeExcept(int min, int max,int valueBetween) {
- int result = min;
- if(max - min == 1) {
- return (valueBetween == min)? max:min;
- }
- try {
- result = min + random.nextInt((max - 1) - min);
- if(result >= valueBetween) {
- result++;
- }
- }catch(java.lang.IllegalArgumentException e){
- System.err.println("min : " + min + " max : " + max + " valueBetween:" + valueBetween);
- System.err.println("Except max should be more then min");
- }
- return result;
- }
- }
-
- private class Handle<T>{
- public T object;
- Handle(T object){
- this.object = object;
- }
- public String toString() {
- return object.toString();
- }
- }
- 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.compareTo(second) == 0) {
- 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)) {
- return false;
- }
- IndexCable p = (IndexCable) o;
- return Objects.equals(p.first, first) && Objects.equals(p.second, second);
- }
- @Override
- public int hashCode() {
- return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
- }
- @Override
- public String toString() {
- return "{" + first + "," + second + "}";
- }
- }
- }
|