AlgorithmFrameworkFlex.java 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. package api;
  2. import java.awt.BorderLayout;
  3. import java.awt.Component;
  4. import java.awt.Dimension;
  5. import java.awt.FlowLayout;
  6. import java.awt.image.BufferedImage;
  7. import java.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import java.io.OutputStreamWriter;
  12. import java.math.RoundingMode;
  13. import java.text.NumberFormat;
  14. import java.util.ArrayList;
  15. import java.util.LinkedList;
  16. import java.util.List;
  17. import java.util.Locale;
  18. import java.util.function.Consumer;
  19. import java.util.function.DoubleConsumer;
  20. import java.util.function.IntConsumer;
  21. import java.util.stream.Collectors;
  22. import javax.swing.BorderFactory;
  23. import javax.swing.Box;
  24. import javax.swing.BoxLayout;
  25. import javax.swing.ImageIcon;
  26. import javax.swing.JButton;
  27. import javax.swing.JCheckBox;
  28. import javax.swing.JFileChooser;
  29. import javax.swing.JFormattedTextField;
  30. import javax.swing.JLabel;
  31. import javax.swing.JOptionPane;
  32. import javax.swing.JPanel;
  33. import javax.swing.JProgressBar;
  34. import javax.swing.JScrollPane;
  35. import javax.swing.JSplitPane;
  36. import javax.swing.text.NumberFormatter;
  37. import classes.AbstractCpsObject;
  38. import classes.CpsUpperNode;
  39. import classes.Flexibility;
  40. import classes.HolonElement;
  41. import classes.HolonObject;
  42. import classes.HolonSwitch;
  43. import ui.controller.Control;
  44. import ui.controller.FlexManager.FlexState;
  45. import ui.controller.FlexManager.FlexWrapper;
  46. import ui.model.DecoratedGroupNode;
  47. import ui.model.DecoratedState;
  48. import ui.model.Model;
  49. import ui.model.DecoratedHolonObject.HolonObjectState;
  50. import ui.view.Console;
  51. public abstract class AlgorithmFrameworkFlex implements AddOn{
  52. //Algo
  53. protected int rounds = 3;
  54. //Panel
  55. private JPanel content = new JPanel();
  56. protected Console console = new Console();
  57. private JPanel borderPanel = new JPanel();
  58. //Settings groupNode
  59. private DecoratedGroupNode dGroupNode = null;
  60. //access
  61. private ArrayList<AccessWrapper> access;
  62. LinkedList<List<Boolean>> resetChain = new LinkedList<List<Boolean>>();
  63. boolean algoUseElements = true, algoUseSwitches = true, algoUseFlexes = true;
  64. //time
  65. private long startTime;
  66. private RunProgressBar runProgressbar = new RunProgressBar();
  67. //concurrency
  68. private Thread runThread = new Thread();
  69. protected boolean cancel = false;
  70. //holeg interaction
  71. protected Control control;
  72. //printing
  73. protected RunDataBase db;
  74. private RunPrinter printer = new RunPrinter(plottFileName(), true);
  75. public AlgorithmFrameworkFlex(){
  76. content.setLayout(new BorderLayout());
  77. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  78. createOptionPanel() , console);
  79. splitPane.setResizeWeight(0.0);
  80. content.add(splitPane, BorderLayout.CENTER);
  81. content.setPreferredSize(new Dimension(800,800));
  82. }
  83. private JPanel createOptionPanel() {
  84. JPanel optionPanel = new JPanel(new BorderLayout());
  85. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  86. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  87. optionPanel.add(scrollPane, BorderLayout.CENTER);
  88. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  89. return optionPanel;
  90. }
  91. private Component createParameterPanel() {
  92. JPanel parameterPanel = new JPanel(null);
  93. parameterPanel.setPreferredSize(new Dimension(510,300));
  94. borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
  95. addIntParameter("Rounds", rounds, intInput -> rounds = intInput, 1);
  96. JScrollPane scrollPane = new JScrollPane(borderPanel);
  97. scrollPane.setBounds(10, 0, 450, 292);
  98. scrollPane.setBorder(BorderFactory.createEmptyBorder());
  99. parameterPanel.add(scrollPane);
  100. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  101. selectGroupNodeButton.setBounds(500, 0, 185, 30);
  102. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  103. parameterPanel.add(selectGroupNodeButton);
  104. JProgressBar progressBar = runProgressbar.getJProgressBar();
  105. progressBar.setBounds(500, 35, 185, 20);
  106. progressBar.setStringPainted(true);
  107. parameterPanel.add(progressBar);
  108. JCheckBox useElements = new JCheckBox("Elements");
  109. useElements.setSelected(algoUseElements);
  110. useElements.setBounds(500, 70, 185, 20);
  111. useElements.addActionListener(actionEvent -> algoUseElements = useElements.isSelected());
  112. parameterPanel.add(useElements);
  113. JCheckBox useSwitches = new JCheckBox("Switches");
  114. useSwitches.setSelected(algoUseSwitches);
  115. useSwitches.setBounds(500, 90, 185, 20);
  116. useSwitches.addActionListener(actionEvent -> algoUseSwitches = useSwitches.isSelected());
  117. parameterPanel.add(useSwitches);
  118. JCheckBox useFlexes = new JCheckBox("Flexibilities");
  119. useFlexes.setSelected(algoUseFlexes);
  120. useFlexes.setBounds(500, 110, 185, 20);
  121. useFlexes.addActionListener(actionEvent -> algoUseFlexes = useFlexes.isSelected());
  122. parameterPanel.add(useFlexes);
  123. return parameterPanel;
  124. }
  125. private JPanel createButtonPanel() {
  126. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  127. JButton resetButton = new JButton("Reset");
  128. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  129. resetButton.addActionListener(actionEvent -> reset());
  130. buttonPanel.add(resetButton);
  131. JButton cancelButton = new JButton("Cancel Run");
  132. cancelButton.addActionListener(actionEvent -> cancel());
  133. buttonPanel.add(cancelButton);
  134. JButton plottButton = new JButton("Plott");
  135. plottButton.addActionListener(actionEvent -> plott());
  136. buttonPanel.add(plottButton);
  137. JButton fitnessButton = new JButton("Fitness");
  138. fitnessButton.setToolTipText("Fitness for the current state.");
  139. fitnessButton.addActionListener(actionEvent -> fitness());
  140. buttonPanel.add(fitnessButton);
  141. JButton runButton = new JButton("Run");
  142. runButton.addActionListener(actionEvent -> {
  143. Runnable task = () -> run();
  144. runThread = new Thread(task);
  145. runThread.start();
  146. });
  147. buttonPanel.add(runButton);
  148. return buttonPanel;
  149. }
  150. //ParameterImports
  151. //int
  152. protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter) {
  153. this.addIntParameter(parameterName, parameterValue, setter, Integer.MIN_VALUE, Integer.MAX_VALUE);
  154. }
  155. protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter, int parameterMinValue) {
  156. this.addIntParameter(parameterName, parameterValue, setter, parameterMinValue, Integer.MAX_VALUE);
  157. }
  158. protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter, int parameterMinValue, int parameterMaxValue) {
  159. JPanel singleParameterPanel = new JPanel();
  160. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  161. singleParameterPanel.setAlignmentX(0.0f);
  162. singleParameterPanel.add(new JLabel(parameterName + ": "));
  163. singleParameterPanel.add(Box.createHorizontalGlue());
  164. NumberFormat format = NumberFormat.getIntegerInstance();
  165. format.setGroupingUsed(false);
  166. format.setParseIntegerOnly(true);
  167. NumberFormatter integerFormatter = new NumberFormatter(format);
  168. integerFormatter.setMinimum(parameterMinValue);
  169. integerFormatter.setMaximum(parameterMaxValue);
  170. integerFormatter.setCommitsOnValidEdit(true);
  171. JFormattedTextField singleParameterTextField = new JFormattedTextField(integerFormatter);
  172. singleParameterTextField.setValue(parameterValue);
  173. String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
  174. String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
  175. singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
  176. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
  177. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  178. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  179. singleParameterPanel.add(singleParameterTextField);
  180. borderPanel.add(singleParameterPanel);
  181. }
  182. //double
  183. protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter) {
  184. this.addDoubleParameter(parameterName, parameterValue, setter, Double.MIN_VALUE, Double.MAX_VALUE);
  185. }
  186. protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter, double parameterMinValue) {
  187. this.addDoubleParameter(parameterName, parameterValue, setter, parameterMinValue, Double.MAX_VALUE);
  188. }
  189. protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter, double parameterMinValue, double parameterMaxValue) {
  190. JPanel singleParameterPanel = new JPanel();
  191. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  192. singleParameterPanel.setAlignmentX(0.0f);
  193. singleParameterPanel.add(new JLabel(parameterName + ": "));
  194. singleParameterPanel.add(Box.createHorizontalGlue());
  195. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  196. doubleFormat.setMinimumFractionDigits(1);
  197. doubleFormat.setMaximumFractionDigits(10);
  198. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  199. NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
  200. doubleFormatter.setMinimum(parameterMinValue);
  201. doubleFormatter.setMaximum(parameterMaxValue);
  202. JFormattedTextField singleParameterTextField = new JFormattedTextField(doubleFormatter);
  203. singleParameterTextField.setValue(parameterValue);
  204. String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
  205. String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
  206. singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
  207. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
  208. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  209. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  210. singleParameterPanel.add(singleParameterTextField);
  211. borderPanel.add(singleParameterPanel);
  212. }
  213. //boolean
  214. protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
  215. JPanel singleParameterPanel = new JPanel();
  216. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  217. singleParameterPanel.setAlignmentX(0.0f);
  218. singleParameterPanel.add(new JLabel(parameterName + ": "));
  219. singleParameterPanel.add(Box.createHorizontalGlue());
  220. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  221. useGroupNodeCheckBox.setSelected(parameterValue);
  222. useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
  223. singleParameterPanel.add(useGroupNodeCheckBox);
  224. borderPanel.add(singleParameterPanel);
  225. }
  226. private void startTimer(){
  227. startTime = System.currentTimeMillis();
  228. }
  229. private void printElapsedTime(){
  230. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  231. db.executionTime = elapsedMilliSeconds;
  232. console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  233. }
  234. private void plott() {
  235. if(db!=null) {
  236. console.println("Plott..");
  237. printer.print(algoInformationToPrint());
  238. }else {
  239. console.println("No run inistialized.");
  240. }
  241. }
  242. private void cancel() {
  243. if(runThread.isAlive()) {
  244. console.println("Cancel run.");
  245. cancel = true;
  246. runProgressbar.stop();
  247. } else {
  248. console.println("Nothing to cancel.");
  249. }
  250. }
  251. private void fitness() {
  252. if(runThread.isAlive()) {
  253. console.println("Run have to be cancelled First.");
  254. return;
  255. }
  256. double currentFitness = evaluatePosition(extractPositionAndAccess());
  257. resetChain.removeLast();
  258. console.println("Actual Fitnessvalue: " + currentFitness);
  259. }
  260. private void selectGroupNode() {
  261. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  262. @SuppressWarnings("unchecked")
  263. Handle<DecoratedGroupNode> selected = (Handle<DecoratedGroupNode>) JOptionPane.showInputDialog(content, "Select GroupNode:", "GroupNode?", JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
  264. if(selected != null) {
  265. console.println("Selected: " + selected);
  266. dGroupNode = selected.object;
  267. }
  268. }
  269. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  270. runProgressbar.step();
  271. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  272. setState(positionToEvaluate);
  273. control.calculateStateOnlyForCurrentTimeStep();
  274. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  275. return evaluateState(actualstate);
  276. }
  277. protected abstract double evaluateState(DecoratedState actualstate);
  278. private void run() {
  279. cancel = false;
  280. control.guiDisable(true);
  281. executeAlgoWithParameter();
  282. updateVisual();
  283. control.guiDisable(false);
  284. }
  285. private void executeAlgoWithParameter(){
  286. runProgressbar.start();
  287. int actualIteration = control.getModel().getCurIteration();
  288. db = new RunDataBase();
  289. db.startInfo = stringStatFromActualState();
  290. console.println("TimeStep:" + actualIteration);
  291. startTimer();
  292. Individual runBest = new Individual();
  293. runBest.fitness = Double.MAX_VALUE;
  294. for(int r = 0; r < rounds; r++)
  295. {
  296. Individual roundBest = executeAlgo();
  297. if(cancel)return;
  298. resetState();
  299. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  300. }
  301. printElapsedTime();
  302. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  303. this.extractPositionAndAccess();
  304. setState(runBest.position);
  305. updateVisual();
  306. db.endInfo = stringStatFromActualState();
  307. console.println("AlgoResult:" + runBest.fitness);
  308. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
  309. runProgressbar.stop();
  310. }
  311. private void calculateAndPrintFlexInfos(DecoratedState state) {
  312. int amountOfUsedFlex = 0;
  313. int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
  314. float cost = 0;
  315. int consumingFlex = 0;
  316. float consumingFlexEnergy = 0.0f;
  317. int producingFlex = 0;
  318. float producingFlexEnergy = 0.0f;
  319. int maxCooldown = 0;
  320. for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
  321. amountOfUsedFlex++;
  322. cost += flexWrapper.getFlex().cost;
  323. float energy = flexWrapper.getFlex().bringtmir();
  324. if(energy < 0) {
  325. consumingFlex++;
  326. consumingFlexEnergy += -energy;
  327. }else {
  328. producingFlex++;
  329. producingFlexEnergy += energy;
  330. }
  331. if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
  332. }
  333. //Total Flexibilities:
  334. //Used Flexibilities:
  335. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  336. //Consuming Flexibilities:
  337. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  338. //Producing Flexibilities
  339. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  340. //Total cost:
  341. console.println("Total Cost: "+ cost);
  342. //Longest Cooldown
  343. console.println("Max Cooldown: "+ maxCooldown);
  344. //
  345. }
  346. protected abstract Individual executeAlgo();
  347. private void reset() {
  348. if(runThread.isAlive()) {
  349. console.println("Run have to be cancelled First.");
  350. return;
  351. }
  352. if(!resetChain.isEmpty()) {
  353. console.println("Resetting..");
  354. setState(resetChain.getFirst());
  355. resetChain.clear();
  356. control.resetSimulation();
  357. control.setCurIteration(0);
  358. updateVisual();
  359. }else {
  360. console.println("No run inistialized.");
  361. }
  362. }
  363. /**
  364. * To let the User See the current state without touching the Canvas.
  365. */
  366. private void updateVisual() {
  367. control.calculateStateAndVisualForCurrentTimeStep();
  368. }
  369. /**
  370. * Sets the Model back to its original State before the LAST run.
  371. */
  372. private void resetState() {
  373. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  374. setState(resetChain.getLast());
  375. }
  376. /**
  377. * Sets the State out of the given position for calculation or to show the user.
  378. * @param position
  379. */
  380. private void setState(List<Boolean> position) {
  381. int i = 0;
  382. for(Boolean bool: position) {
  383. access.get(i++).setState(bool);
  384. }
  385. }
  386. /**
  387. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  388. * Also initialize the Access Hashmap to swap faster positions.
  389. * @param model
  390. * @return
  391. */
  392. protected List<Boolean> extractPositionAndAccess() {
  393. Model model = control.getModel();
  394. access= new ArrayList<AccessWrapper>();
  395. List<Boolean> initialState = new ArrayList<Boolean>();
  396. rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  397. resetChain.add(initialState);
  398. if(algoUseFlexes) {
  399. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  400. access.add(new AccessWrapper(flex.getFlex()));
  401. initialState.add(false);
  402. }
  403. }
  404. //console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  405. return initialState;
  406. }
  407. /**
  408. * Method to extract the Informations recursively out of the Model.
  409. * @param nodes
  410. * @param positionToInit
  411. * @param timeStep
  412. */
  413. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  414. for(AbstractCpsObject aCps : nodes) {
  415. if (aCps instanceof HolonObject && algoUseElements) {
  416. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  417. positionToInit.add(hE.isActive());
  418. access.add(new AccessWrapper(hE));
  419. }
  420. }
  421. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  422. HolonSwitch sw = (HolonSwitch) aCps;
  423. positionToInit.add(sw.getState(timeStep));
  424. access.add(new AccessWrapper(sw));
  425. }
  426. else if(aCps instanceof CpsUpperNode) {
  427. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  428. }
  429. }
  430. }
  431. private String stringStatFromActualState() {
  432. console.println(" (dGroupNode != null):" + (dGroupNode != null));
  433. if(dGroupNode != null)
  434. {
  435. //GetActualDecoratedGroupNode
  436. dGroupNode = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(dGroupNode.getModel());
  437. int amountOfSupplier = dGroupNode.getAmountOfSupplier();
  438. int amountOfConsumer = dGroupNode.getAmountOfConsumer();
  439. int amountOfPassiv = dGroupNode.getAmountOfPassiv();
  440. int amountOfObjects = amountOfSupplier + amountOfConsumer + amountOfPassiv;
  441. int unSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
  442. int partiallySuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
  443. int suppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
  444. int overSuppliedConsumer = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
  445. int activeElements = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
  446. int elements = dGroupNode.getAmountOfElemntsFromHolonObjects();
  447. return "HolonObjects["
  448. + " Producer: " + amountOfSupplier + "/" + amountOfObjects + "("+ (float)amountOfSupplier/(float)amountOfObjects * 100 + "%)"
  449. + " Unsupplied: " + unSuppliedConsumer + "/" + amountOfObjects + "("+ (float)unSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  450. + " PartiallySupplied: " + partiallySuppliedConsumer + "/" + amountOfObjects + "("+ (float)partiallySuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  451. + " Supplied: " + suppliedConsumer + "/" + amountOfObjects + "("+ (float)suppliedConsumer/(float)amountOfObjects * 100 + "%)"
  452. + " Passiv: " + overSuppliedConsumer + "/" + amountOfObjects + "("+ (float)overSuppliedConsumer/(float)amountOfObjects * 100 + "%)"
  453. + "]" + " HolonElemnts["
  454. + " Active: " + activeElements + "/" + elements + "("+ (float)activeElements/(float)elements * 100 + "%)"
  455. + "]";
  456. }
  457. return "[No GroupMode Use == No detailed Info]";
  458. }
  459. @Override
  460. public JPanel getPanel() {
  461. return content;
  462. }
  463. @Override
  464. public void setController(Control control) {
  465. this.control = control;
  466. }
  467. private class RunProgressBar{
  468. //progressbar
  469. private JProgressBar progressBar = new JProgressBar();
  470. private int count = 0;
  471. private boolean isActive = false;
  472. public void step() {
  473. if(isActive) progressBar.setValue(count++);
  474. progressBar.setMaximum(getProgressBarMaxCount());
  475. }
  476. public void start() {
  477. isActive = true;
  478. progressBar.setValue(0);
  479. }
  480. public void stop() {
  481. isActive = false;
  482. }
  483. public JProgressBar getJProgressBar(){
  484. return progressBar;
  485. }
  486. }
  487. protected abstract int getProgressBarMaxCount();
  488. protected abstract String algoInformationToPrint();
  489. protected abstract String plottFileName();
  490. public class RunDataBase{
  491. String startInfo, endInfo;
  492. long executionTime = 1;
  493. List<List<Double>> allRuns = new ArrayList<List<Double>>();
  494. public void insertNewRun(List<Double> newRun){
  495. allRuns.add(newRun);
  496. }
  497. }
  498. public class RunPrinter{
  499. //Fields
  500. private JFileChooser fileChooser = new JFileChooser();
  501. private boolean append = false;
  502. //Constructor
  503. public RunPrinter(String filename) {
  504. this(filename, false);
  505. }
  506. public RunPrinter(String filename, boolean append){
  507. this.append = append;
  508. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  509. setFilename(filename);
  510. }
  511. //public methods
  512. public void enableAppend(boolean enable) {
  513. append = enable;
  514. }
  515. public void setFilename(String filename) {
  516. fileChooser.setSelectedFile(new File(filename));
  517. }
  518. public void print(String info) {
  519. File file = fileChooser.getSelectedFile();
  520. try {
  521. file.createNewFile();
  522. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  523. new FileOutputStream(file, append), "UTF-8"));
  524. printToStream(out, info);
  525. out.close();
  526. } catch (IOException e) {
  527. System.out.println(e.getMessage());
  528. }
  529. }
  530. //private methods
  531. private void printToStream(BufferedWriter out, String info) throws IOException {
  532. out.write(info);
  533. out.newLine();
  534. if(db != null)
  535. out.write(db.allRuns.stream().map(list -> list.stream().map(Object::toString).collect(Collectors.joining(","))).collect(Collectors.joining(System.lineSeparator())));
  536. out.newLine();
  537. out.write("ExecutionTime for all rounds[milliseconds]:" + db.executionTime);
  538. out.newLine();
  539. out.write("StartStats: " + db.startInfo);
  540. out.newLine();
  541. out.write("EndStats: " + db.endInfo);
  542. out.newLine();
  543. out.newLine();
  544. }
  545. }
  546. /**
  547. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  548. */
  549. private class AccessWrapper {
  550. public static final int HOLONELEMENT = 0;
  551. public static final int SWITCH = 1;
  552. public static final int FLEXIBILITY = 2;
  553. private int type;
  554. private HolonSwitch hSwitch;
  555. private HolonElement hElement;
  556. private Flexibility flex;
  557. public AccessWrapper(HolonSwitch hSwitch){
  558. type = SWITCH;
  559. this.hSwitch = hSwitch;
  560. }
  561. public AccessWrapper(HolonElement hElement){
  562. type = HOLONELEMENT;
  563. this.hElement = hElement;
  564. }
  565. public AccessWrapper(Flexibility flex){
  566. type = FLEXIBILITY;
  567. this.flex = flex;
  568. }
  569. public void setState(boolean state) {
  570. switch(type) {
  571. case HOLONELEMENT:
  572. hElement.setActive(state);
  573. break;
  574. case SWITCH:
  575. hSwitch.setManualMode(true);
  576. hSwitch.setManualState(state);
  577. break;
  578. case FLEXIBILITY:
  579. if(state) {
  580. control.getSimManager().getActualFlexManager().orderFlex(flex);
  581. }
  582. break;
  583. default:
  584. }
  585. }
  586. public String typeString() {
  587. switch(type) {
  588. case HOLONELEMENT:
  589. return "HOLONELEMENT";
  590. case SWITCH:
  591. return "SWITCH";
  592. case FLEXIBILITY:
  593. return "FLEXIBILITY";
  594. default:
  595. return "unknown";
  596. }
  597. }
  598. public String toString() {
  599. return "[" + typeString() + "]";
  600. }
  601. }
  602. /**
  603. * To create Random and maybe switch the random generation in the future.
  604. */
  605. protected static class Random{
  606. private static java.util.Random random = new java.util.Random();
  607. /**
  608. * True or false
  609. * @return the random boolean.
  610. */
  611. public static boolean nextBoolean(){
  612. return random.nextBoolean();
  613. }
  614. /**
  615. * Between 0.0(inclusive) and 1.0 (exclusive)
  616. * @return the random double.
  617. */
  618. public static double nextDouble() {
  619. return random.nextDouble();
  620. }
  621. /**
  622. * Random Int in Range [min;max[ with UniformDistirbution
  623. * @param min
  624. * @param max
  625. * @return
  626. */
  627. public static int nextIntegerInRange(int min, int max) {
  628. return min + random.nextInt(max - min);
  629. }
  630. }
  631. private class Handle<T>{
  632. public T object;
  633. Handle(T object){
  634. this.object = object;
  635. }
  636. public String toString() {
  637. return object.toString();
  638. }
  639. }
  640. public class Individual {
  641. public double fitness;
  642. public List<Boolean> position;
  643. public Individual(){};
  644. /**
  645. * Copy Constructor
  646. */
  647. public Individual(Individual c){
  648. position = c.position.stream().collect(Collectors.toList());
  649. fitness = c.fitness;
  650. }
  651. }
  652. }