Randomizer.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 com.google.gson.annotations.Expose;
  29. import api.AddOn;
  30. import classes.AbstractCpsObject;
  31. import classes.Constrain;
  32. import classes.CpsUpperNode;
  33. import classes.Flexibility;
  34. import classes.HolonElement;
  35. import classes.HolonObject;
  36. import classes.HolonSwitch;
  37. import ui.controller.Control;
  38. import ui.model.Model;
  39. public class Randomizer implements AddOn {
  40. private Control control;
  41. private int minAmountOfElements = 3;
  42. private int maxAmountOfElements = 7;
  43. private JPanel content = new JPanel();
  44. //To Test the Layout Faster
  45. public static void main(String[] args)
  46. {
  47. JFrame newFrame = new JFrame("exampleWindow");
  48. Randomizer instance = new Randomizer();
  49. newFrame.setContentPane(instance.getPanel());
  50. newFrame.pack();
  51. newFrame.setVisible(true);
  52. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  53. }
  54. private File file;
  55. public double randomChance = 1.0;
  56. public Randomizer(){
  57. content.setLayout(new BorderLayout());
  58. content.add(createParameterPanel(), BorderLayout.CENTER);
  59. JButton buttonRun = new JButton("Run");
  60. buttonRun.addActionListener(actionEvent -> run());
  61. content.add(buttonRun, BorderLayout.PAGE_END);
  62. content.setPreferredSize(new Dimension(300,300));
  63. }
  64. private JPanel createParameterPanel() {
  65. JPanel parameterPanel = new JPanel(null);
  66. parameterPanel.setPreferredSize(new Dimension(300,300));
  67. JLabel minAmount = new JLabel("minAmountOfElements:");
  68. minAmount.setBounds(20, 60 , 200, 20);
  69. parameterPanel.add(minAmount);
  70. JLabel maxAmount = new JLabel("maxAmountOfElements:");
  71. maxAmount.setBounds(20, 85 , 200, 20);
  72. parameterPanel.add(maxAmount);
  73. //Integer formatter
  74. NumberFormat format = NumberFormat.getIntegerInstance();
  75. format.setGroupingUsed(false);
  76. format.setParseIntegerOnly(true);
  77. NumberFormatter integerFormatter = new NumberFormatter(format);
  78. integerFormatter.setMinimum(0);
  79. integerFormatter.setCommitsOnValidEdit(true);
  80. JFormattedTextField minAmountTextField = new JFormattedTextField(integerFormatter);
  81. minAmountTextField.setValue(this.minAmountOfElements);
  82. minAmountTextField.setToolTipText("Only positive Integer.");
  83. minAmountTextField.addPropertyChangeListener(actionEvent -> this.minAmountOfElements = Integer.parseInt(minAmountTextField.getValue().toString()));
  84. minAmountTextField.setBounds(220, 60, 50, 20);
  85. parameterPanel.add(minAmountTextField);
  86. JFormattedTextField maxAmountTextField = new JFormattedTextField(integerFormatter);
  87. maxAmountTextField.setValue(this.maxAmountOfElements);
  88. maxAmountTextField.setToolTipText("Only positive Integer.");
  89. maxAmountTextField.addPropertyChangeListener(actionEvent -> this.maxAmountOfElements = Integer.parseInt(maxAmountTextField.getValue().toString()));
  90. maxAmountTextField.setBounds(220, 85, 50, 20);
  91. parameterPanel.add(maxAmountTextField);
  92. JButton chooseFileButton = new JButton("Choose File");
  93. chooseFileButton.setBounds(20, 10, 200, 30);
  94. chooseFileButton.addActionListener(actionEvent -> file = openCatalogFile());
  95. parameterPanel.add(chooseFileButton);
  96. JSlider bitSlider = createFlipChanceSlider();
  97. bitSlider.setBounds(10, 110, 280, 80);
  98. parameterPanel.add(bitSlider);
  99. return parameterPanel;
  100. }
  101. private void run() {
  102. List<HolonElementSketch> holonElementCatalog = new ArrayList<HolonElementSketch>();
  103. if(file == null)file = openCatalogFile();
  104. if(file == null) return;
  105. readCatalogFromJson(file, holonElementCatalog);
  106. holonElementCatalog.forEach(con -> con.checkValues());
  107. List<HolonObject> consumerList = new ArrayList<HolonObject>();
  108. rollOutNodes(control.getModel().getObjectsOnCanvas(), consumerList, control.getModel().getCurIteration());
  109. consumerList.forEach(con -> {
  110. con.getElements().clear();
  111. int randomAmountOfElementsToAdd = Random.nextIntegerInRange(minAmountOfElements, maxAmountOfElements + 1);
  112. for(int i = 0; i < randomAmountOfElementsToAdd; i++) {
  113. HolonElement ele = holonElementCatalog.get(Random.nextIntegerInRange(0, holonElementCatalog.size())).createHolonElement(control.getModel(), Random.nextDouble() < randomChance , con.getName());
  114. con.getElements().add(ele);
  115. }
  116. });
  117. control.calculateStateAndVisualForCurrentTimeStep();
  118. control.updateCanvas();
  119. }
  120. private void rollOutNodes(List<AbstractCpsObject> nodes, List<HolonObject> consumerList, int timeStep) {
  121. for (AbstractCpsObject aCps : nodes) {
  122. if (aCps instanceof HolonObject) {
  123. HolonObject hO = (HolonObject) aCps;
  124. if(hO.getEnergyAtTimeStep(control.getModel().getCurIteration()) < 0)consumerList.add(hO);
  125. }
  126. else if(aCps instanceof CpsUpperNode) {
  127. rollOutNodes(((CpsUpperNode)aCps).getNodes(), consumerList ,timeStep );
  128. }
  129. }
  130. }
  131. @Override
  132. public JPanel getPanel() {
  133. return content;
  134. }
  135. @Override
  136. public void setController(Control control) {
  137. this.control = control;
  138. }
  139. private class HolonElementSketch {
  140. //HolonElement
  141. public String name;
  142. public int minAmount;
  143. public int maxAmount;
  144. public float energy;
  145. //Flexibility
  146. public double flexChance;
  147. @Expose
  148. public float minCost;
  149. public float maxCost;
  150. /** The Duration in TimeSteps how long the Flexibility is activated.*/
  151. private int minDuration;
  152. private int maxDuration;
  153. /** The Duration after a successful activation between the next possible activation.*/
  154. private int minCooldown;
  155. private int maxCooldown;
  156. public HolonElementSketch(String name, int minAmount, int maxAmount, float energy) {
  157. this.name = name;
  158. this.minAmount = minAmount;
  159. this.maxAmount = maxAmount;
  160. this.energy = energy;
  161. }
  162. public HolonElement createHolonElement(Model model, boolean active, String nameOfHolonObject) {
  163. HolonElement ele = new HolonElement(name, Random.nextIntegerInRange(minAmount, maxAmount + 1), energy , model);
  164. ele.setActive(active);
  165. if(Random.nextDouble() < flexChance)addFlex(ele, nameOfHolonObject);
  166. return ele;
  167. }
  168. public void checkValues() {
  169. minAmount = Math.abs(minAmount);
  170. maxAmount = Math.abs(maxAmount);
  171. if(maxAmount < minAmount) {
  172. //Swap
  173. int intermediate = minAmount;
  174. minAmount = maxAmount;
  175. maxAmount = intermediate;
  176. }
  177. minDuration = Math.abs(minDuration);
  178. maxDuration = Math.abs(maxDuration);
  179. if(maxDuration < minDuration) {
  180. //Swap
  181. int intermediate = minDuration;
  182. minDuration = maxDuration;
  183. maxDuration = intermediate;
  184. }
  185. minCooldown = Math.abs(minCooldown);
  186. maxCooldown = Math.abs(maxCooldown);
  187. if(maxCooldown < minCooldown) {
  188. //Swap
  189. int intermediate = minCooldown;
  190. minCooldown = maxCooldown;
  191. maxCooldown = intermediate;
  192. }
  193. minCost = Math.abs(minCost);
  194. maxCost = Math.abs(maxCost);
  195. if(maxCost < minCost) {
  196. //Swap
  197. float intermediate = minCost;
  198. minCost = maxCost;
  199. maxCost = intermediate;
  200. }
  201. flexChance = Math.max(0, Math.min(1, flexChance)); //Clamp
  202. }
  203. public void addFlex(HolonElement ele, String nameOfHolonObject) {
  204. Flexibility toCreateFlex = new Flexibility(ele);
  205. boolean flexType = ele.isActive();
  206. toCreateFlex.name = nameOfHolonObject + "_" + ele.getEleName() + (flexType?"_OnFlex":"_OffFlex");
  207. toCreateFlex.speed = 0;
  208. toCreateFlex.setDuration(Random.nextIntegerInRange(minDuration, maxDuration+1));
  209. toCreateFlex.cost = Random.nextFloatInRange(minCost, maxCost);
  210. toCreateFlex.setCooldown(Random.nextIntegerInRange(minCooldown, maxCooldown+1));
  211. toCreateFlex.offered=true;
  212. if(flexType) {
  213. toCreateFlex.constrainList.add(Constrain.createOnConstrain());
  214. }else {
  215. toCreateFlex.constrainList.add(Constrain.createOffConstrain());
  216. }
  217. ele.flexList.add(toCreateFlex);
  218. }
  219. }
  220. private JSlider createFlipChanceSlider() {
  221. JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 100);
  222. flipChance.setBorder(BorderFactory.createTitledBorder("ActiveProbability"));
  223. flipChance.setMajorTickSpacing(50);
  224. flipChance.setMinorTickSpacing(5);
  225. flipChance.setPaintTicks(true);
  226. Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
  227. labelTable.put( Integer.valueOf(0), new JLabel("0.0") );
  228. labelTable.put( Integer.valueOf(50), new JLabel("0.5") );
  229. labelTable.put( Integer.valueOf(100), new JLabel("1.0") );
  230. flipChance.addChangeListener(actionEvent ->randomChance =(double)flipChance.getValue()/100.0);
  231. flipChance.setLabelTable( labelTable );
  232. flipChance.setPaintLabels(true);
  233. return flipChance;
  234. }
  235. private static class Random{
  236. private static java.util.Random random = new java.util.Random();
  237. /**
  238. * True or false
  239. * @return the random boolean.
  240. */
  241. public static boolean nextBoolean(){
  242. return random.nextBoolean();
  243. }
  244. /**
  245. * Between 0.0(inclusive) and 1.0 (exclusive)
  246. * @return the random double.
  247. */
  248. public static double nextDouble() {
  249. return random.nextDouble();
  250. }
  251. public static float nextFloatInRange(float min, float max) {
  252. return min + random.nextFloat() * Math.abs(max - min);
  253. }
  254. public static double nextDoubleInRange(double min, double max) {
  255. return min + random.nextDouble() * Math.abs(max - min);
  256. }
  257. /**
  258. * Random Int in Range [min;max[ with UniformDistirbution
  259. * @param min
  260. * @param max
  261. * @return
  262. */
  263. public static int nextIntegerInRange(int min, int max) {
  264. return min + random.nextInt(max - min);
  265. }
  266. }
  267. private void readCatalogFromJson(File file, List<HolonElementSketch> catalog) {
  268. Gson gson = new Gson();
  269. JsonParser parser = new JsonParser();
  270. try {
  271. JsonElement jsonTreeRoot = parser.parse(new FileReader(file));
  272. if(jsonTreeRoot.isJsonArray()) {
  273. JsonArray jsonArray = jsonTreeRoot.getAsJsonArray();
  274. jsonArray.forEach(jsonObject -> {
  275. HolonElementSketch newObject= gson.fromJson( jsonObject, HolonElementSketch.class);
  276. catalog.add(newObject);
  277. });
  278. }
  279. } catch (JsonSyntaxException e) {
  280. e.printStackTrace();
  281. } catch (JsonIOException e) {
  282. e.printStackTrace();
  283. } catch (FileNotFoundException e) {
  284. e.printStackTrace();
  285. }
  286. }
  287. public File openCatalogFile() {
  288. JFileChooser fileChooser = new JFileChooser();
  289. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/src/"));
  290. fileChooser.setFileFilter(new FileNameExtensionFilter("JSON Files", "json"));
  291. fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  292. fileChooser.setAcceptAllFileFilterUsed(false);
  293. int result = fileChooser.showOpenDialog(content);
  294. if(result == JFileChooser.APPROVE_OPTION) {
  295. //Found a file
  296. return fileChooser.getSelectedFile();
  297. }
  298. return null;
  299. }
  300. }