AlgorithmFrameworkFlex.java 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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.view.Console;
  50. public abstract class AlgorithmFrameworkFlex implements AddOn{
  51. //Algo
  52. protected int rounds = 3;
  53. //Panel
  54. private JPanel content = new JPanel();
  55. protected Console console = new Console();
  56. private JPanel borderPanel = new JPanel();
  57. //Settings groupNode
  58. private boolean useGroupNode = false;
  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. private Control control;
  72. //printing
  73. protected RunDataBase db;
  74. private RunPrinter printer = new RunPrinter("plott.txt");
  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. console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  232. }
  233. private void plott() {
  234. if(db!=null) {
  235. console.println("Plott..");
  236. printer.print("");
  237. }else {
  238. console.println("No run inistialized.");
  239. }
  240. }
  241. private void cancel() {
  242. if(runThread.isAlive()) {
  243. console.println("Cancel run.");
  244. cancel = true;
  245. runProgressbar.stop();
  246. } else {
  247. console.println("Nothing to cancel.");
  248. }
  249. }
  250. private void fitness() {
  251. if(runThread.isAlive()) {
  252. console.println("Run have to be cancelled First.");
  253. return;
  254. }
  255. double currentFitness = evaluatePosition(extractPositionAndAccess());
  256. resetChain.removeLast();
  257. console.println("Actual Fitnessvalue: " + currentFitness);
  258. }
  259. private void selectGroupNode() {
  260. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  261. @SuppressWarnings("unchecked")
  262. 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, "");
  263. if(selected != null) {
  264. console.println("Selected: " + selected);
  265. dGroupNode = selected.object;
  266. }
  267. }
  268. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  269. runProgressbar.step();
  270. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  271. setState(positionToEvaluate);
  272. control.calculateStateOnlyForCurrentTimeStep();
  273. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  274. return evaluateState(actualstate);
  275. }
  276. protected abstract double evaluateState(DecoratedState actualstate);
  277. private void run() {
  278. cancel = false;
  279. control.guiDisable(true);
  280. executeAlgoWithParameter();
  281. updateVisual();
  282. control.guiDisable(false);
  283. }
  284. private void executeAlgoWithParameter(){
  285. runProgressbar.start();
  286. int actualIteration = control.getModel().getCurIteration();
  287. console.println("TimeStep:" + actualIteration);
  288. startTimer();
  289. Individual runBest = new Individual();
  290. runBest.fitness = Double.MAX_VALUE;
  291. db = new RunDataBase();
  292. for(int r = 0; r < rounds; r++)
  293. {
  294. Individual roundBest = executeAlgo();
  295. if(cancel)return;
  296. resetState();
  297. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  298. }
  299. printElapsedTime();
  300. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  301. this.extractPositionAndAccess();
  302. setState(runBest.position);
  303. updateVisual();
  304. console.println("AlgoResult:" + runBest.fitness);
  305. if(this.algoUseFlexes)calculateAndPrintFlexInfos(control.getSimManager().getActualDecorState());
  306. runProgressbar.stop();
  307. }
  308. private void calculateAndPrintFlexInfos(DecoratedState state) {
  309. int amountOfUsedFlex = 0;
  310. int amountOfFlex = state.getFlexManager().getAllFlexWrapper().size();
  311. float cost = 0;
  312. int consumingFlex = 0;
  313. float consumingFlexEnergy = 0.0f;
  314. int producingFlex = 0;
  315. float producingFlexEnergy = 0.0f;
  316. int maxCooldown = 0;
  317. for(FlexWrapper flexWrapper :state.getFlexManager().getAllFlexWrapperWithState(FlexState.IN_USE)) {
  318. amountOfUsedFlex++;
  319. cost += flexWrapper.getFlex().cost;
  320. float energy = flexWrapper.getFlex().bringtmir();
  321. if(energy < 0) {
  322. consumingFlex++;
  323. consumingFlexEnergy += -energy;
  324. }else {
  325. producingFlex++;
  326. producingFlexEnergy += energy;
  327. }
  328. if(flexWrapper.getFlex().getCooldown() > maxCooldown) maxCooldown = flexWrapper.getFlex().getCooldown();
  329. }
  330. //Total Flexibilities:
  331. //Used Flexibilities:
  332. console.println("Used Flex [" + amountOfUsedFlex + "/" + amountOfFlex + "]");
  333. //Consuming Flexibilities:
  334. console.println(consumingFlex + " consuimg flexibilities that consumed " + consumingFlexEnergy + "Energy.");
  335. //Producing Flexibilities
  336. console.println(producingFlex + " producing flexibilities that produce " + producingFlexEnergy + "Energy.");
  337. //Total cost:
  338. console.println("Total Cost: "+ cost);
  339. //Longest Cooldown
  340. console.println("Max Cooldown: "+ maxCooldown);
  341. //
  342. }
  343. protected abstract Individual executeAlgo();
  344. private void reset() {
  345. if(runThread.isAlive()) {
  346. console.println("Run have to be cancelled First.");
  347. return;
  348. }
  349. if(!resetChain.isEmpty()) {
  350. console.println("Resetting..");
  351. setState(resetChain.getFirst());
  352. resetChain.clear();
  353. control.resetSimulation();
  354. control.setCurIteration(0);
  355. updateVisual();
  356. }else {
  357. console.println("No run inistialized.");
  358. }
  359. }
  360. /**
  361. * To let the User See the current state without touching the Canvas.
  362. */
  363. private void updateVisual() {
  364. control.calculateStateAndVisualForCurrentTimeStep();
  365. }
  366. /**
  367. * Sets the Model back to its original State before the LAST run.
  368. */
  369. private void resetState() {
  370. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  371. setState(resetChain.getLast());
  372. }
  373. /**
  374. * Sets the State out of the given position for calculation or to show the user.
  375. * @param position
  376. */
  377. private void setState(List<Boolean> position) {
  378. int i = 0;
  379. for(Boolean bool: position) {
  380. access.get(i++).setState(bool);
  381. }
  382. }
  383. /**
  384. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  385. * Also initialize the Access Hashmap to swap faster positions.
  386. * @param model
  387. * @return
  388. */
  389. protected List<Boolean> extractPositionAndAccess() {
  390. Model model = control.getModel();
  391. access= new ArrayList<AccessWrapper>();
  392. List<Boolean> initialState = new ArrayList<Boolean>();
  393. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  394. resetChain.add(initialState);
  395. if(algoUseFlexes) {
  396. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  397. access.add(new AccessWrapper(flex.getFlex()));
  398. initialState.add(false);
  399. }
  400. }
  401. console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  402. return initialState;
  403. }
  404. /**
  405. * Method to extract the Informations recursively out of the Model.
  406. * @param nodes
  407. * @param positionToInit
  408. * @param timeStep
  409. */
  410. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  411. for(AbstractCpsObject aCps : nodes) {
  412. if (aCps instanceof HolonObject && algoUseElements) {
  413. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  414. positionToInit.add(hE.isActive());
  415. access.add(new AccessWrapper(hE));
  416. }
  417. }
  418. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  419. HolonSwitch sw = (HolonSwitch) aCps;
  420. positionToInit.add(sw.getState(timeStep));
  421. access.add(new AccessWrapper(sw));
  422. }
  423. else if(aCps instanceof CpsUpperNode) {
  424. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  425. }
  426. }
  427. }
  428. @Override
  429. public JPanel getPanel() {
  430. return content;
  431. }
  432. @Override
  433. public void setController(Control control) {
  434. this.control = control;
  435. }
  436. private class RunProgressBar{
  437. //progressbar
  438. private JProgressBar progressBar = new JProgressBar();
  439. private int count = 0;
  440. private boolean isActive = false;
  441. public void step() {
  442. if(isActive) progressBar.setValue(count++);
  443. progressBar.setMaximum(getProgressBarMaxCount());
  444. }
  445. public void start() {
  446. isActive = true;
  447. progressBar.setValue(0);
  448. }
  449. public void stop() {
  450. isActive = false;
  451. }
  452. public JProgressBar getJProgressBar(){
  453. return progressBar;
  454. }
  455. }
  456. protected abstract int getProgressBarMaxCount();
  457. public class RunDataBase{
  458. List<List<Double>> allRuns = new ArrayList<List<Double>>();
  459. public void insertNewRun(List<Double> newRun){
  460. allRuns.add(newRun);
  461. }
  462. }
  463. public class RunPrinter{
  464. //Fields
  465. private JFileChooser fileChooser = new JFileChooser();
  466. private boolean append = false;
  467. //Constructor
  468. public RunPrinter(String filename) {
  469. this(filename, false);
  470. }
  471. public RunPrinter(String filename, boolean append){
  472. this.append = append;
  473. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  474. setFilename(filename);
  475. }
  476. //public methods
  477. public void enableAppend(boolean enable) {
  478. append = enable;
  479. }
  480. public void setFilename(String filename) {
  481. fileChooser.setSelectedFile(new File(filename));
  482. }
  483. public void print(String info) {
  484. File file = fileChooser.getSelectedFile();
  485. try {
  486. file.createNewFile();
  487. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  488. new FileOutputStream(file, append), "UTF-8"));
  489. printToStream(out, info);
  490. out.close();
  491. } catch (IOException e) {
  492. System.out.println(e.getMessage());
  493. }
  494. }
  495. //private methods
  496. private void printToStream(BufferedWriter out, String info) throws IOException {
  497. out.write(info);
  498. out.newLine();
  499. if(db != null)
  500. out.write(db.allRuns.stream().map(list -> list.stream().map(Object::toString).collect(Collectors.joining(","))).collect(Collectors.joining(System.lineSeparator())));
  501. }
  502. }
  503. /**
  504. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  505. */
  506. private class AccessWrapper {
  507. public static final int HOLONELEMENT = 0;
  508. public static final int SWITCH = 1;
  509. public static final int FLEXIBILITY = 2;
  510. private int type;
  511. private HolonSwitch hSwitch;
  512. private HolonElement hElement;
  513. private Flexibility flex;
  514. public AccessWrapper(HolonSwitch hSwitch){
  515. type = SWITCH;
  516. this.hSwitch = hSwitch;
  517. }
  518. public AccessWrapper(HolonElement hElement){
  519. type = HOLONELEMENT;
  520. this.hElement = hElement;
  521. }
  522. public AccessWrapper(Flexibility flex){
  523. type = FLEXIBILITY;
  524. this.flex = flex;
  525. }
  526. public void setState(boolean state) {
  527. switch(type) {
  528. case HOLONELEMENT:
  529. hElement.setActive(state);
  530. break;
  531. case SWITCH:
  532. hSwitch.setManualMode(true);
  533. hSwitch.setManualState(state);
  534. break;
  535. case FLEXIBILITY:
  536. if(state) {
  537. // if(control.getSimManager() == null) console.println("control.getSimManager() == null");
  538. // if(control.getSimManager().getActualFlexManager() == null) console.println("control.getSimManager().getActualFlexManager() == null");
  539. control.getSimManager().getActualFlexManager().orderFlex(flex);
  540. }
  541. break;
  542. default:
  543. }
  544. }
  545. public String typeString() {
  546. switch(type) {
  547. case HOLONELEMENT:
  548. return "HOLONELEMENT";
  549. case SWITCH:
  550. return "SWITCH";
  551. case FLEXIBILITY:
  552. return "FLEXIBILITY";
  553. default:
  554. return "unknown";
  555. }
  556. }
  557. public String toString() {
  558. return "[" + typeString() + "]";
  559. }
  560. }
  561. /**
  562. * To create Random and maybe switch the random generation in the future.
  563. */
  564. protected static class Random{
  565. private static java.util.Random random = new java.util.Random();
  566. /**
  567. * True or false
  568. * @return the random boolean.
  569. */
  570. public static boolean nextBoolean(){
  571. return random.nextBoolean();
  572. }
  573. /**
  574. * Between 0.0(inclusive) and 1.0 (exclusive)
  575. * @return the random double.
  576. */
  577. public static double nextDouble() {
  578. return random.nextDouble();
  579. }
  580. /**
  581. * Random Int in Range [min;max[ with UniformDistirbution
  582. * @param min
  583. * @param max
  584. * @return
  585. */
  586. public static int nextIntegerInRange(int min, int max) {
  587. return min + random.nextInt(max - min);
  588. }
  589. }
  590. private class Handle<T>{
  591. public T object;
  592. Handle(T object){
  593. this.object = object;
  594. }
  595. public String toString() {
  596. return object.toString();
  597. }
  598. }
  599. public class Individual {
  600. public double fitness;
  601. public List<Boolean> position;
  602. public Individual(){};
  603. /**
  604. * Copy Constructor
  605. */
  606. public Individual(Individual c){
  607. position = c.position.stream().collect(Collectors.toList());
  608. fitness = c.fitness;
  609. }
  610. }
  611. }