Randomizer.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. package exampleAlgorithms;
  2. import java.awt.BorderLayout;
  3. import java.awt.Dimension;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.text.NumberFormat;
  8. import java.util.ArrayList;
  9. import java.util.Hashtable;
  10. import java.util.List;
  11. import javax.swing.BorderFactory;
  12. import javax.swing.BoxLayout;
  13. import javax.swing.JButton;
  14. import javax.swing.JFileChooser;
  15. import javax.swing.JFormattedTextField;
  16. import javax.swing.JFrame;
  17. import javax.swing.JLabel;
  18. import javax.swing.JPanel;
  19. import javax.swing.JSlider;
  20. import javax.swing.filechooser.FileNameExtensionFilter;
  21. import javax.swing.text.NumberFormatter;
  22. import com.google.gson.Gson;
  23. import com.google.gson.JsonArray;
  24. import com.google.gson.JsonElement;
  25. import com.google.gson.JsonIOException;
  26. import com.google.gson.JsonParser;
  27. import com.google.gson.JsonSyntaxException;
  28. import api.AddOn;
  29. import classes.AbstractCpsObject;
  30. import classes.CpsUpperNode;
  31. import classes.HolonElement;
  32. import classes.HolonObject;
  33. import classes.HolonSwitch;
  34. import ui.controller.Control;
  35. import ui.model.Model;
  36. public class Randomizer implements AddOn {
  37. private Control control;
  38. private int minAmountOfElements = 3;
  39. private int maxAmountOfElements = 7;
  40. private JPanel content = new JPanel();
  41. //To Test the Layout Faster
  42. public static void main(String[] args)
  43. {
  44. JFrame newFrame = new JFrame("exampleWindow");
  45. Randomizer instance = new Randomizer();
  46. newFrame.setContentPane(instance.getPanel());
  47. newFrame.pack();
  48. newFrame.setVisible(true);
  49. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  50. }
  51. private File file;
  52. private double randomChance = 1.0;
  53. public Randomizer(){
  54. content.setLayout(new BorderLayout());
  55. content.add(createParameterPanel(), BorderLayout.CENTER);
  56. JButton buttonRun = new JButton("Run");
  57. buttonRun.addActionListener(actionEvent -> run());
  58. content.add(buttonRun, BorderLayout.PAGE_END);
  59. content.setPreferredSize(new Dimension(300,300));
  60. }
  61. private JPanel createParameterPanel() {
  62. JPanel parameterPanel = new JPanel(null);
  63. parameterPanel.setPreferredSize(new Dimension(300,300));
  64. JLabel minAmount = new JLabel("minAmountOfElements:");
  65. minAmount.setBounds(20, 60 , 200, 20);
  66. parameterPanel.add(minAmount);
  67. JLabel maxAmount = new JLabel("maxAmountOfElements:");
  68. maxAmount.setBounds(20, 85 , 200, 20);
  69. parameterPanel.add(maxAmount);
  70. //Integer formatter
  71. NumberFormat format = NumberFormat.getIntegerInstance();
  72. format.setGroupingUsed(false);
  73. format.setParseIntegerOnly(true);
  74. NumberFormatter integerFormatter = new NumberFormatter(format);
  75. integerFormatter.setMinimum(0);
  76. integerFormatter.setCommitsOnValidEdit(true);
  77. JFormattedTextField minAmountTextField = new JFormattedTextField(integerFormatter);
  78. minAmountTextField.setValue(this.minAmountOfElements);
  79. minAmountTextField.setToolTipText("Only positive Integer.");
  80. minAmountTextField.addPropertyChangeListener(actionEvent -> this.minAmountOfElements = Integer.parseInt(minAmountTextField.getValue().toString()));
  81. minAmountTextField.setBounds(220, 60, 50, 20);
  82. parameterPanel.add(minAmountTextField);
  83. JFormattedTextField maxAmountTextField = new JFormattedTextField(integerFormatter);
  84. maxAmountTextField.setValue(this.maxAmountOfElements);
  85. maxAmountTextField.setToolTipText("Only positive Integer.");
  86. maxAmountTextField.addPropertyChangeListener(actionEvent -> this.maxAmountOfElements = Integer.parseInt(maxAmountTextField.getValue().toString()));
  87. maxAmountTextField.setBounds(220, 85, 50, 20);
  88. parameterPanel.add(maxAmountTextField);
  89. JButton chooseFileButton = new JButton("Choose File");
  90. chooseFileButton.setBounds(20, 10, 200, 30);
  91. chooseFileButton.addActionListener(actionEvent -> file = openCatalogFile());
  92. parameterPanel.add(chooseFileButton);
  93. JSlider bitSlider = createFlipChanceSlider();
  94. bitSlider.setBounds(10, 110, 280, 80);
  95. parameterPanel.add(bitSlider);
  96. return parameterPanel;
  97. }
  98. private void run() {
  99. List<HolonObjectSketch> holonObjectCatalog = new ArrayList<HolonObjectSketch>();
  100. if(file == null)file = openCatalogFile();
  101. if(file == null) return;
  102. readCatalogFromJson(file, holonObjectCatalog);
  103. holonObjectCatalog.forEach(con -> con.checkMinMax());
  104. List<HolonObject> consumerList = new ArrayList<HolonObject>();
  105. rollOutNodes(control.getModel().getObjectsOnCanvas(), consumerList, control.getModel().getCurIteration());
  106. consumerList.forEach(con -> {
  107. con.getElements().clear();
  108. int randomAmountOfElementsToAdd = Random.nextIntegerInRange(minAmountOfElements, maxAmountOfElements + 1);
  109. for(int i = 0; i < randomAmountOfElementsToAdd; i++) {
  110. HolonElement ele = holonObjectCatalog.get(Random.nextIntegerInRange(0, holonObjectCatalog.size())).createHolonElement(control.getModel());
  111. ele.setActive(Random.nextDouble() < randomChance);
  112. con.getElements().add(ele);
  113. }
  114. });
  115. control.calculateStateAndVisualForCurrentTimeStep();
  116. control.updateCanvas();
  117. }
  118. private void rollOutNodes(List<AbstractCpsObject> nodes, List<HolonObject> consumerList, int timeStep) {
  119. for (AbstractCpsObject aCps : nodes) {
  120. if (aCps instanceof HolonObject) {
  121. HolonObject hO = (HolonObject) aCps;
  122. if(hO.getEnergyAtTimeStep(control.getModel().getCurIteration()) < 0)consumerList.add(hO);
  123. }
  124. else if(aCps instanceof CpsUpperNode) {
  125. rollOutNodes(((CpsUpperNode)aCps).getNodes(), consumerList ,timeStep );
  126. }
  127. }
  128. }
  129. @Override
  130. public JPanel getPanel() {
  131. return content;
  132. }
  133. @Override
  134. public void setController(Control control) {
  135. this.control = control;
  136. }
  137. private class HolonObjectSketch {
  138. public String name;
  139. public int minAmount;
  140. public int maxAmount;
  141. public float energy;
  142. public HolonObjectSketch(String name, int minAmount, int maxAmount, float energy) {
  143. this.name = name;
  144. this.minAmount = minAmount;
  145. this.maxAmount = maxAmount;
  146. this.energy = energy;
  147. }
  148. public HolonElement createHolonElement(Model model) {
  149. return new HolonElement(name, Random.nextIntegerInRange(minAmount, maxAmount + 1), energy , model);
  150. }
  151. public void checkMinMax() {
  152. minAmount = Math.abs(minAmount);
  153. maxAmount = Math.abs(maxAmount);
  154. if(maxAmount < minAmount) {
  155. //Swap
  156. int intermediate = minAmount;
  157. minAmount = maxAmount;
  158. maxAmount = intermediate;
  159. }
  160. }
  161. }
  162. private JSlider createFlipChanceSlider() {
  163. JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 100);
  164. flipChance.setBorder(BorderFactory.createTitledBorder("ActiveProbability"));
  165. flipChance.setMajorTickSpacing(50);
  166. flipChance.setMinorTickSpacing(5);
  167. flipChance.setPaintTicks(true);
  168. Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
  169. labelTable.put( Integer.valueOf(0), new JLabel("0.0") );
  170. labelTable.put( Integer.valueOf(50), new JLabel("0.5") );
  171. labelTable.put( Integer.valueOf(100), new JLabel("1.0") );
  172. flipChance.addChangeListener(actionEvent ->randomChance =(double)flipChance.getValue()/100.0);
  173. flipChance.setLabelTable( labelTable );
  174. flipChance.setPaintLabels(true);
  175. return flipChance;
  176. }
  177. private static class Random{
  178. private static java.util.Random random = new java.util.Random();
  179. /**
  180. * True or false
  181. * @return the random boolean.
  182. */
  183. public static boolean nextBoolean(){
  184. return random.nextBoolean();
  185. }
  186. /**
  187. * Between 0.0(inclusive) and 1.0 (exclusive)
  188. * @return the random double.
  189. */
  190. public static double nextDouble() {
  191. return random.nextDouble();
  192. }
  193. /**
  194. * Random Int in Range [min;max[ with UniformDistirbution
  195. * @param min
  196. * @param max
  197. * @return
  198. */
  199. public static int nextIntegerInRange(int min, int max) {
  200. return min + random.nextInt(max - min);
  201. }
  202. }
  203. private void readCatalogFromJson(File file, List<HolonObjectSketch> catalog) {
  204. Gson gson = new Gson();
  205. JsonParser parser = new JsonParser();
  206. try {
  207. JsonElement jsonTreeRoot = parser.parse(new FileReader(file));
  208. if(jsonTreeRoot.isJsonArray()) {
  209. JsonArray jsonArray = jsonTreeRoot.getAsJsonArray();
  210. jsonArray.forEach(jsonObject -> {
  211. HolonObjectSketch newObject= gson.fromJson( jsonObject, HolonObjectSketch.class);
  212. catalog.add(newObject);
  213. });
  214. }
  215. } catch (JsonSyntaxException e) {
  216. e.printStackTrace();
  217. } catch (JsonIOException e) {
  218. e.printStackTrace();
  219. } catch (FileNotFoundException e) {
  220. e.printStackTrace();
  221. }
  222. }
  223. public File openCatalogFile() {
  224. JFileChooser fileChooser = new JFileChooser();
  225. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/src/"));
  226. fileChooser.setFileFilter(new FileNameExtensionFilter("JSON Files", "json"));
  227. fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  228. fileChooser.setAcceptAllFileFilterUsed(false);
  229. int result = fileChooser.showOpenDialog(content);
  230. if(result == JFileChooser.APPROVE_OPTION) {
  231. //Found a file
  232. return fileChooser.getSelectedFile();
  233. }
  234. return null;
  235. }
  236. }