Randomizer.java 12 KB

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