AlgorithmFrameworkFlex.java 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. setState(runBest.position);
  302. updateVisual();
  303. console.println("AlgoResult:" + runBest.fitness);
  304. runProgressbar.stop();
  305. }
  306. protected abstract Individual executeAlgo();
  307. private void reset() {
  308. if(runThread.isAlive()) {
  309. console.println("Run have to be cancelled First.");
  310. return;
  311. }
  312. if(!resetChain.isEmpty()) {
  313. console.println("Resetting..");
  314. setState(resetChain.getFirst());
  315. resetChain.clear();
  316. control.resetSimulation();
  317. control.setCurIteration(0);
  318. updateVisual();
  319. }else {
  320. console.println("No run inistialized.");
  321. }
  322. }
  323. /**
  324. * To let the User See the current state without touching the Canvas.
  325. */
  326. private void updateVisual() {
  327. control.calculateStateAndVisualForCurrentTimeStep();
  328. }
  329. /**
  330. * Sets the Model back to its original State before the LAST run.
  331. */
  332. private void resetState() {
  333. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  334. setState(resetChain.getLast());
  335. }
  336. /**
  337. * Sets the State out of the given position for calculation or to show the user.
  338. * @param position
  339. */
  340. private void setState(List<Boolean> position) {
  341. int i = 0;
  342. for(Boolean bool: position) {
  343. access.get(i++).setState(bool);
  344. }
  345. }
  346. /**
  347. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  348. * Also initialize the Access Hashmap to swap faster positions.
  349. * @param model
  350. * @return
  351. */
  352. protected List<Boolean> extractPositionAndAccess() {
  353. Model model = control.getModel();
  354. access= new ArrayList<AccessWrapper>();
  355. List<Boolean> initialState = new ArrayList<Boolean>();
  356. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  357. resetChain.add(initialState);
  358. if(algoUseFlexes) {
  359. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  360. access.add(new AccessWrapper(flex.getFlex()));
  361. initialState.add(false);
  362. }
  363. }
  364. console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  365. return initialState;
  366. }
  367. /**
  368. * Method to extract the Informations recursively out of the Model.
  369. * @param nodes
  370. * @param positionToInit
  371. * @param timeStep
  372. */
  373. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  374. for(AbstractCpsObject aCps : nodes) {
  375. if (aCps instanceof HolonObject && algoUseElements) {
  376. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  377. positionToInit.add(hE.isActive());
  378. access.add(new AccessWrapper(hE));
  379. }
  380. }
  381. else if (aCps instanceof HolonSwitch&& algoUseSwitches) {
  382. HolonSwitch sw = (HolonSwitch) aCps;
  383. positionToInit.add(sw.getState(timeStep));
  384. access.add(new AccessWrapper(sw));
  385. }
  386. else if(aCps instanceof CpsUpperNode) {
  387. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  388. }
  389. }
  390. }
  391. @Override
  392. public JPanel getPanel() {
  393. return content;
  394. }
  395. @Override
  396. public void setController(Control control) {
  397. this.control = control;
  398. }
  399. private class RunProgressBar{
  400. //progressbar
  401. private JProgressBar progressBar = new JProgressBar();
  402. private int count = 0;
  403. private boolean isActive = false;
  404. public void step() {
  405. if(isActive) progressBar.setValue(count++);
  406. progressBar.setMaximum(getProgressBarMaxCount());
  407. }
  408. public void start() {
  409. isActive = true;
  410. progressBar.setValue(0);
  411. }
  412. public void stop() {
  413. isActive = false;
  414. }
  415. public JProgressBar getJProgressBar(){
  416. return progressBar;
  417. }
  418. }
  419. protected abstract int getProgressBarMaxCount();
  420. public class RunDataBase{
  421. List<List<Double>> allRuns = new ArrayList<List<Double>>();
  422. public void insertNewRun(List<Double> newRun){
  423. allRuns.add(newRun);
  424. }
  425. }
  426. public class RunPrinter{
  427. //Fields
  428. private JFileChooser fileChooser = new JFileChooser();
  429. private boolean append = false;
  430. //Constructor
  431. public RunPrinter(String filename) {
  432. this(filename, false);
  433. }
  434. public RunPrinter(String filename, boolean append){
  435. this.append = append;
  436. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  437. setFilename(filename);
  438. }
  439. //public methods
  440. public void enableAppend(boolean enable) {
  441. append = enable;
  442. }
  443. public void setFilename(String filename) {
  444. fileChooser.setSelectedFile(new File(filename));
  445. }
  446. public void print(String info) {
  447. File file = fileChooser.getSelectedFile();
  448. try {
  449. file.createNewFile();
  450. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  451. new FileOutputStream(file, append), "UTF-8"));
  452. printToStream(out, info);
  453. out.close();
  454. } catch (IOException e) {
  455. System.out.println(e.getMessage());
  456. }
  457. }
  458. //private methods
  459. private void printToStream(BufferedWriter out, String info) throws IOException {
  460. out.write(info);
  461. out.newLine();
  462. if(db != null)
  463. out.write(db.allRuns.stream().map(list -> list.stream().map(Object::toString).collect(Collectors.joining(","))).collect(Collectors.joining(System.lineSeparator())));
  464. }
  465. }
  466. /**
  467. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  468. */
  469. private class AccessWrapper {
  470. public static final int HOLONELEMENT = 0;
  471. public static final int SWITCH = 1;
  472. public static final int FLEXIBILITY = 2;
  473. private int type;
  474. private HolonSwitch hSwitch;
  475. private HolonElement hElement;
  476. private Flexibility flex;
  477. public AccessWrapper(HolonSwitch hSwitch){
  478. type = SWITCH;
  479. this.hSwitch = hSwitch;
  480. }
  481. public AccessWrapper(HolonElement hElement){
  482. type = HOLONELEMENT;
  483. this.hElement = hElement;
  484. }
  485. public AccessWrapper(Flexibility flex){
  486. type = FLEXIBILITY;
  487. this.flex = flex;
  488. }
  489. public void setState(boolean state) {
  490. switch(type) {
  491. case HOLONELEMENT:
  492. hElement.setActive(state);
  493. break;
  494. case SWITCH:
  495. hSwitch.setManualMode(true);
  496. hSwitch.setManualState(state);
  497. break;
  498. case FLEXIBILITY:
  499. if(state) {
  500. // if(control.getSimManager() == null) console.println("control.getSimManager() == null");
  501. // if(control.getSimManager().getActualFlexManager() == null) console.println("control.getSimManager().getActualFlexManager() == null");
  502. control.getSimManager().getActualFlexManager().orderFlex(flex);
  503. }
  504. break;
  505. default:
  506. }
  507. }
  508. public String typeString() {
  509. switch(type) {
  510. case HOLONELEMENT:
  511. return "HOLONELEMENT";
  512. case SWITCH:
  513. return "SWITCH";
  514. case FLEXIBILITY:
  515. return "FLEXIBILITY";
  516. default:
  517. return "unknown";
  518. }
  519. }
  520. public String toString() {
  521. return "[" + typeString() + "]";
  522. }
  523. }
  524. /**
  525. * To create Random and maybe switch the random generation in the future.
  526. */
  527. protected static class Random{
  528. private static java.util.Random random = new java.util.Random();
  529. /**
  530. * True or false
  531. * @return the random boolean.
  532. */
  533. public static boolean nextBoolean(){
  534. return random.nextBoolean();
  535. }
  536. /**
  537. * Between 0.0(inclusive) and 1.0 (exclusive)
  538. * @return the random double.
  539. */
  540. public static double nextDouble() {
  541. return random.nextDouble();
  542. }
  543. /**
  544. * Random Int in Range [min;max[ with UniformDistirbution
  545. * @param min
  546. * @param max
  547. * @return
  548. */
  549. public static int nextIntegerInRange(int min, int max) {
  550. return min + random.nextInt(max - min);
  551. }
  552. }
  553. private class Handle<T>{
  554. public T object;
  555. Handle(T object){
  556. this.object = object;
  557. }
  558. public String toString() {
  559. return object.toString();
  560. }
  561. }
  562. public class Individual {
  563. public double fitness;
  564. public List<Boolean> position;
  565. public Individual(){};
  566. /**
  567. * Copy Constructor
  568. */
  569. public Individual(Individual c){
  570. position = c.position.stream().collect(Collectors.toList());
  571. fitness = c.fitness;
  572. }
  573. }
  574. }