AlgorithmFrameworkFlex.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. //time
  64. private long startTime;
  65. private RunProgressBar runProgressbar = new RunProgressBar();
  66. //concurrency
  67. private Thread runThread = new Thread();
  68. protected boolean cancel = false;
  69. //holeg interaction
  70. private Control control;
  71. //printing
  72. protected RunDataBase db;
  73. private RunPrinter printer = new RunPrinter("plott.txt");
  74. public AlgorithmFrameworkFlex(){
  75. content.setLayout(new BorderLayout());
  76. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  77. createOptionPanel() , console);
  78. splitPane.setResizeWeight(0.0);
  79. content.add(splitPane, BorderLayout.CENTER);
  80. content.setPreferredSize(new Dimension(800,800));
  81. }
  82. private JPanel createOptionPanel() {
  83. JPanel optionPanel = new JPanel(new BorderLayout());
  84. JScrollPane scrollPane = new JScrollPane(createParameterPanel());
  85. scrollPane.setBorder(BorderFactory.createTitledBorder("Parameter"));
  86. optionPanel.add(scrollPane, BorderLayout.CENTER);
  87. optionPanel.add(createButtonPanel(), BorderLayout.PAGE_END);
  88. return optionPanel;
  89. }
  90. private Component createParameterPanel() {
  91. JPanel parameterPanel = new JPanel(null);
  92. parameterPanel.setPreferredSize(new Dimension(510,300));
  93. borderPanel.setLayout(new BoxLayout(borderPanel, BoxLayout.PAGE_AXIS));
  94. addIntParameter("Rounds", rounds, intInput -> rounds = intInput, 1);
  95. JScrollPane scrollPane = new JScrollPane(borderPanel);
  96. scrollPane.setBounds(10, 0, 450, 292);
  97. scrollPane.setBorder(BorderFactory.createEmptyBorder());
  98. parameterPanel.add(scrollPane);
  99. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  100. selectGroupNodeButton.setBounds(500, 0, 185, 30);
  101. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  102. parameterPanel.add(selectGroupNodeButton);
  103. JProgressBar progressBar = runProgressbar.getJProgressBar();
  104. progressBar.setBounds(500, 35, 185, 20);
  105. progressBar.setStringPainted(true);
  106. parameterPanel.add(progressBar);
  107. return parameterPanel;
  108. }
  109. private JPanel createButtonPanel() {
  110. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  111. JButton resetButton = new JButton("Reset");
  112. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  113. resetButton.addActionListener(actionEvent -> reset());
  114. buttonPanel.add(resetButton);
  115. JButton cancelButton = new JButton("Cancel Run");
  116. cancelButton.addActionListener(actionEvent -> cancel());
  117. buttonPanel.add(cancelButton);
  118. JButton plottButton = new JButton("Plott");
  119. plottButton.addActionListener(actionEvent -> plott());
  120. buttonPanel.add(plottButton);
  121. JButton fitnessButton = new JButton("Fitness");
  122. fitnessButton.setToolTipText("Fitness for the current state.");
  123. fitnessButton.addActionListener(actionEvent -> fitness());
  124. buttonPanel.add(fitnessButton);
  125. JButton runButton = new JButton("Run");
  126. runButton.addActionListener(actionEvent -> {
  127. Runnable task = () -> run();
  128. runThread = new Thread(task);
  129. runThread.start();
  130. });
  131. buttonPanel.add(runButton);
  132. return buttonPanel;
  133. }
  134. //ParameterImports
  135. //int
  136. protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter) {
  137. this.addIntParameter(parameterName, parameterValue, setter, Integer.MIN_VALUE, Integer.MAX_VALUE);
  138. }
  139. protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter, int parameterMinValue) {
  140. this.addIntParameter(parameterName, parameterValue, setter, parameterMinValue, Integer.MAX_VALUE);
  141. }
  142. protected void addIntParameter(String parameterName, int parameterValue, IntConsumer setter, int parameterMinValue, int parameterMaxValue) {
  143. JPanel singleParameterPanel = new JPanel();
  144. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  145. singleParameterPanel.setAlignmentX(0.0f);
  146. singleParameterPanel.add(new JLabel(parameterName + ": "));
  147. singleParameterPanel.add(Box.createHorizontalGlue());
  148. NumberFormat format = NumberFormat.getIntegerInstance();
  149. format.setGroupingUsed(false);
  150. format.setParseIntegerOnly(true);
  151. NumberFormatter integerFormatter = new NumberFormatter(format);
  152. integerFormatter.setMinimum(parameterMinValue);
  153. integerFormatter.setMaximum(parameterMaxValue);
  154. integerFormatter.setCommitsOnValidEdit(true);
  155. JFormattedTextField singleParameterTextField = new JFormattedTextField(integerFormatter);
  156. singleParameterTextField.setValue(parameterValue);
  157. String minValue = (parameterMinValue == Integer.MIN_VALUE)?"Integer.MIN_VALUE":String.valueOf(parameterMinValue);
  158. String maxValue = (parameterMaxValue == Integer.MAX_VALUE)?"Integer.MAX_VALUE":String.valueOf(parameterMaxValue);
  159. singleParameterTextField.setToolTipText("Only integer \u2208 [" + minValue + "," + maxValue + "]");
  160. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Integer.parseInt(singleParameterTextField.getValue().toString())));
  161. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  162. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  163. singleParameterPanel.add(singleParameterTextField);
  164. borderPanel.add(singleParameterPanel);
  165. }
  166. //double
  167. protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter) {
  168. this.addDoubleParameter(parameterName, parameterValue, setter, Double.MIN_VALUE, Double.MAX_VALUE);
  169. }
  170. protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter, double parameterMinValue) {
  171. this.addDoubleParameter(parameterName, parameterValue, setter, parameterMinValue, Double.MAX_VALUE);
  172. }
  173. protected void addDoubleParameter(String parameterName, double parameterValue, DoubleConsumer setter, double parameterMinValue, double parameterMaxValue) {
  174. JPanel singleParameterPanel = new JPanel();
  175. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  176. singleParameterPanel.setAlignmentX(0.0f);
  177. singleParameterPanel.add(new JLabel(parameterName + ": "));
  178. singleParameterPanel.add(Box.createHorizontalGlue());
  179. NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
  180. doubleFormat.setMinimumFractionDigits(1);
  181. doubleFormat.setMaximumFractionDigits(10);
  182. doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
  183. NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
  184. doubleFormatter.setMinimum(parameterMinValue);
  185. doubleFormatter.setMaximum(parameterMaxValue);
  186. JFormattedTextField singleParameterTextField = new JFormattedTextField(doubleFormatter);
  187. singleParameterTextField.setValue(parameterValue);
  188. String minValue = (parameterMinValue == Double.MIN_VALUE)?"Double.MIN_VALUE":String.valueOf(parameterMinValue);
  189. String maxValue = (parameterMaxValue == Double.MAX_VALUE)?"Double.MAX_VALUE":String.valueOf(parameterMaxValue);
  190. singleParameterTextField.setToolTipText("Only double \u2208 [" + minValue + "," + maxValue + "]");
  191. singleParameterTextField.addPropertyChangeListener(actionEvent -> setter.accept(Double.parseDouble(singleParameterTextField.getValue().toString())));
  192. singleParameterTextField.setMaximumSize(new Dimension(200, 30));
  193. singleParameterTextField.setPreferredSize(new Dimension(200, 30));
  194. singleParameterPanel.add(singleParameterTextField);
  195. borderPanel.add(singleParameterPanel);
  196. }
  197. //boolean
  198. protected void addBooleanParameter(String parameterName, boolean parameterValue, Consumer<Boolean> setter){
  199. JPanel singleParameterPanel = new JPanel();
  200. singleParameterPanel.setLayout(new BoxLayout(singleParameterPanel, BoxLayout.LINE_AXIS));
  201. singleParameterPanel.setAlignmentX(0.0f);
  202. singleParameterPanel.add(new JLabel(parameterName + ": "));
  203. singleParameterPanel.add(Box.createHorizontalGlue());
  204. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  205. useGroupNodeCheckBox.setSelected(parameterValue);
  206. useGroupNodeCheckBox.addActionListener(actionEvent -> setter.accept(useGroupNodeCheckBox.isSelected()));
  207. singleParameterPanel.add(useGroupNodeCheckBox);
  208. borderPanel.add(singleParameterPanel);
  209. }
  210. private void startTimer(){
  211. startTime = System.currentTimeMillis();
  212. }
  213. private void printElapsedTime(){
  214. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  215. console.println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  216. }
  217. private void plott() {
  218. if(db!=null) {
  219. console.println("Plott..");
  220. printer.print("");
  221. }else {
  222. console.println("No run inistialized.");
  223. }
  224. }
  225. private void cancel() {
  226. if(runThread.isAlive()) {
  227. console.println("Cancel run.");
  228. cancel = true;
  229. runProgressbar.stop();
  230. } else {
  231. console.println("Nothing to cancel.");
  232. }
  233. }
  234. private void fitness() {
  235. if(runThread.isAlive()) {
  236. console.println("Run have to be cancelled First.");
  237. return;
  238. }
  239. double currentFitness = evaluatePosition(extractPositionAndAccess());
  240. resetChain.removeLast();
  241. console.println("Actual Fitnessvalue: " + currentFitness);
  242. }
  243. private void selectGroupNode() {
  244. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  245. @SuppressWarnings("unchecked")
  246. 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, "");
  247. if(selected != null) {
  248. console.println("Selected: " + selected);
  249. dGroupNode = selected.object;
  250. }
  251. }
  252. protected double evaluatePosition(List<Boolean> positionToEvaluate) {
  253. runProgressbar.step();
  254. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  255. setState(positionToEvaluate);
  256. control.calculateStateOnlyForCurrentTimeStep();
  257. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  258. return evaluateState(actualstate);
  259. }
  260. protected abstract double evaluateState(DecoratedState actualstate);
  261. private void run() {
  262. cancel = false;
  263. control.guiDisable(true);
  264. executeAlgoWithParameter();
  265. updateVisual();
  266. control.guiDisable(false);
  267. }
  268. private void executeAlgoWithParameter(){
  269. runProgressbar.start();
  270. int actualIteration = control.getModel().getCurIteration();
  271. console.println("TimeStep:" + actualIteration);
  272. startTimer();
  273. Individual runBest = new Individual();
  274. runBest.fitness = Double.MAX_VALUE;
  275. db = new RunDataBase();
  276. for(int r = 0; r < rounds; r++)
  277. {
  278. Individual roundBest = executeAlgo();
  279. if(cancel)return;
  280. resetState();
  281. if(roundBest.fitness < runBest.fitness) runBest = roundBest;
  282. }
  283. printElapsedTime();
  284. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  285. setState(runBest.position);
  286. updateVisual();
  287. console.println("AlgoResult:" + runBest.fitness);
  288. runProgressbar.stop();
  289. }
  290. protected abstract Individual executeAlgo();
  291. private void reset() {
  292. if(runThread.isAlive()) {
  293. console.println("Run have to be cancelled First.");
  294. return;
  295. }
  296. if(!resetChain.isEmpty()) {
  297. console.println("Resetting..");
  298. setState(resetChain.getFirst());
  299. resetChain.clear();
  300. control.resetSimulation();
  301. control.setCurIteration(0);
  302. updateVisual();
  303. }else {
  304. console.println("No run inistialized.");
  305. }
  306. }
  307. /**
  308. * To let the User See the current state without touching the Canvas.
  309. */
  310. private void updateVisual() {
  311. control.calculateStateAndVisualForCurrentTimeStep();
  312. }
  313. /**
  314. * Sets the Model back to its original State before the LAST run.
  315. */
  316. private void resetState() {
  317. control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
  318. setState(resetChain.getLast());
  319. }
  320. /**
  321. * Sets the State out of the given position for calculation or to show the user.
  322. * @param position
  323. */
  324. private void setState(List<Boolean> position) {
  325. int i = 0;
  326. for(Boolean bool: position) {
  327. access.get(i++).setState(bool);
  328. }
  329. }
  330. /**
  331. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  332. * Also initialize the Access Hashmap to swap faster positions.
  333. * @param model
  334. * @return
  335. */
  336. protected List<Boolean> extractPositionAndAccess() {
  337. Model model = control.getModel();
  338. access= new ArrayList<AccessWrapper>();
  339. List<Boolean> initialState = new ArrayList<Boolean>();
  340. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  341. resetChain.add(initialState);
  342. for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){
  343. access.add(new AccessWrapper(flex.getFlex()));
  344. initialState.add(false);
  345. }
  346. console.println(access.stream().map(Object::toString).collect(Collectors.joining(", ")));
  347. return initialState;
  348. }
  349. /**
  350. * Method to extract the Informations recursively out of the Model.
  351. * @param nodes
  352. * @param positionToInit
  353. * @param timeStep
  354. */
  355. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  356. for(AbstractCpsObject aCps : nodes) {
  357. if (aCps instanceof HolonObject) {
  358. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  359. positionToInit.add(hE.isActive());
  360. access.add(new AccessWrapper(hE));
  361. }
  362. }
  363. else if (aCps instanceof HolonSwitch) {
  364. HolonSwitch sw = (HolonSwitch) aCps;
  365. positionToInit.add(sw.getState(timeStep));
  366. access.add(new AccessWrapper(sw));
  367. }
  368. else if(aCps instanceof CpsUpperNode) {
  369. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  370. }
  371. }
  372. }
  373. @Override
  374. public JPanel getPanel() {
  375. return content;
  376. }
  377. @Override
  378. public void setController(Control control) {
  379. this.control = control;
  380. }
  381. private class RunProgressBar{
  382. //progressbar
  383. private JProgressBar progressBar = new JProgressBar();
  384. private int count = 0;
  385. private boolean isActive = false;
  386. public void step() {
  387. if(isActive) progressBar.setValue(count++);
  388. progressBar.setMaximum(getProgressBarMaxCount());
  389. }
  390. public void start() {
  391. isActive = true;
  392. progressBar.setValue(0);
  393. }
  394. public void stop() {
  395. isActive = false;
  396. }
  397. public JProgressBar getJProgressBar(){
  398. return progressBar;
  399. }
  400. }
  401. protected abstract int getProgressBarMaxCount();
  402. public class RunDataBase{
  403. List<List<Double>> allRuns = new ArrayList<List<Double>>();
  404. public void insertNewRun(List<Double> newRun){
  405. allRuns.add(newRun);
  406. }
  407. }
  408. public class RunPrinter{
  409. //Fields
  410. private JFileChooser fileChooser = new JFileChooser();
  411. private boolean append = false;
  412. //Constructor
  413. public RunPrinter(String filename) {
  414. this(filename, false);
  415. }
  416. public RunPrinter(String filename, boolean append){
  417. this.append = append;
  418. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
  419. setFilename(filename);
  420. }
  421. //public methods
  422. public void enableAppend(boolean enable) {
  423. append = enable;
  424. }
  425. public void setFilename(String filename) {
  426. fileChooser.setSelectedFile(new File(filename));
  427. }
  428. public void print(String info) {
  429. File file = fileChooser.getSelectedFile();
  430. try {
  431. file.createNewFile();
  432. BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
  433. new FileOutputStream(file, append), "UTF-8"));
  434. printToStream(out, info);
  435. out.close();
  436. } catch (IOException e) {
  437. System.out.println(e.getMessage());
  438. }
  439. }
  440. //private methods
  441. private void printToStream(BufferedWriter out, String info) throws IOException {
  442. out.write(info);
  443. out.newLine();
  444. if(db != null)
  445. out.write(db.allRuns.stream().map(list -> list.stream().map(Object::toString).collect(Collectors.joining(","))).collect(Collectors.joining(System.lineSeparator())));
  446. }
  447. }
  448. /**
  449. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  450. */
  451. private class AccessWrapper {
  452. public static final int HOLONELEMENT = 0;
  453. public static final int SWITCH = 1;
  454. public static final int FLEXIBILITY = 2;
  455. private int type;
  456. private HolonSwitch hSwitch;
  457. private HolonElement hElement;
  458. private Flexibility flex;
  459. public AccessWrapper(HolonSwitch hSwitch){
  460. type = SWITCH;
  461. this.hSwitch = hSwitch;
  462. }
  463. public AccessWrapper(HolonElement hElement){
  464. type = HOLONELEMENT;
  465. this.hElement = hElement;
  466. }
  467. public AccessWrapper(Flexibility flex){
  468. type = FLEXIBILITY;
  469. this.flex = flex;
  470. }
  471. public void setState(boolean state) {
  472. switch(type) {
  473. case HOLONELEMENT:
  474. hElement.setActive(state);
  475. break;
  476. case SWITCH:
  477. hSwitch.setManualMode(true);
  478. hSwitch.setManualState(state);
  479. break;
  480. case FLEXIBILITY:
  481. if(state) {
  482. console.println("Flex True");
  483. if(flex == null) console.println("flex == null");
  484. if(control.getSimManager() == null) console.println("control.getSimManager() == null");
  485. if(control.getSimManager().getActualFlexManager() == null) console.println("control.getSimManager().getActualFlexManager() == null");
  486. control.getSimManager().getActualFlexManager().orderFlex(flex);
  487. }else {
  488. console.println("Flex false");
  489. }
  490. break;
  491. default:
  492. }
  493. }
  494. public String typeString() {
  495. switch(type) {
  496. case HOLONELEMENT:
  497. return "HOLONELEMENT";
  498. case SWITCH:
  499. return "SWITCH";
  500. case FLEXIBILITY:
  501. return "FLEXIBILITY";
  502. default:
  503. return "unknown";
  504. }
  505. }
  506. public String toString() {
  507. return "[" + typeString() + "]";
  508. }
  509. }
  510. /**
  511. * To create Random and maybe switch the random generation in the future.
  512. */
  513. protected static class Random{
  514. private static java.util.Random random = new java.util.Random();
  515. /**
  516. * True or false
  517. * @return the random boolean.
  518. */
  519. public static boolean nextBoolean(){
  520. return random.nextBoolean();
  521. }
  522. /**
  523. * Between 0.0(inclusive) and 1.0 (exclusive)
  524. * @return the random double.
  525. */
  526. public static double nextDouble() {
  527. return random.nextDouble();
  528. }
  529. /**
  530. * Random Int in Range [min;max[ with UniformDistirbution
  531. * @param min
  532. * @param max
  533. * @return
  534. */
  535. public static int nextIntegerInRange(int min, int max) {
  536. return min + random.nextInt(max - min);
  537. }
  538. }
  539. private class Handle<T>{
  540. public T object;
  541. Handle(T object){
  542. this.object = object;
  543. }
  544. public String toString() {
  545. return object.toString();
  546. }
  547. }
  548. public class Individual {
  549. public double fitness;
  550. public List<Boolean> position;
  551. public Individual(){};
  552. /**
  553. * Copy Constructor
  554. */
  555. public Individual(Individual c){
  556. position = c.position.stream().collect(Collectors.toList());
  557. fitness = c.fitness;
  558. }
  559. }
  560. }