FlexExample.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package exampleAlgorithms;
  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.text.NumberFormat;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. import java.util.List;
  11. import java.util.concurrent.TimeUnit;
  12. import java.util.stream.Collectors;
  13. import java.util.stream.Stream;
  14. import javax.swing.BorderFactory;
  15. import javax.swing.ImageIcon;
  16. import javax.swing.JButton;
  17. import javax.swing.JCheckBox;
  18. import javax.swing.JFormattedTextField;
  19. import javax.swing.JFrame;
  20. import javax.swing.JLabel;
  21. import javax.swing.JOptionPane;
  22. import javax.swing.JPanel;
  23. import javax.swing.JProgressBar;
  24. import javax.swing.JScrollPane;
  25. import javax.swing.JSplitPane;
  26. import javax.swing.JTextArea;
  27. import javax.swing.text.NumberFormatter;
  28. import api.Algorithm;
  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.controller.FlexManager.FlexState;
  36. import ui.controller.FlexManager.FlexWrapper;
  37. import ui.model.DecoratedGroupNode;
  38. import ui.model.DecoratedNetwork;
  39. import ui.model.DecoratedState;
  40. import ui.model.Model;
  41. public class FlexExample implements Algorithm {
  42. //Parameter for Algo with default Values:
  43. private boolean closeSwitches = true;
  44. //Settings For GroupNode using and cancel
  45. private boolean useGroupNode = false;
  46. private DecoratedGroupNode dGroupNode = null;
  47. private boolean cancel = false;
  48. //Parameter defined by Algo
  49. private HashMap<Integer, AccessWrapper> access;
  50. private List<Boolean> initialState;
  51. private List<HolonSwitch> switchList;
  52. private List<HolonObject> objectList;
  53. //Gui Part:
  54. private Control control;
  55. private JTextArea textArea;
  56. private JPanel content = new JPanel();
  57. //ProgressBar
  58. private JProgressBar progressBar = new JProgressBar();
  59. private int progressBarCount = 0;
  60. private long startTime;
  61. private Thread runThread;
  62. public static void main(String[] args)
  63. {
  64. JFrame newFrame = new JFrame("exampleWindow");
  65. DemoAlgo instance = new DemoAlgo();
  66. newFrame.setContentPane(instance.getAlgorithmPanel());
  67. newFrame.pack();
  68. newFrame.setVisible(true);
  69. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  70. }
  71. public FlexExample() {
  72. content.setLayout(new BorderLayout());
  73. textArea = new JTextArea();
  74. textArea.setEditable(false);
  75. JScrollPane scrollPane = new JScrollPane(textArea);
  76. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
  77. createOptionPanel() , scrollPane);
  78. splitPane.setResizeWeight(0.0);
  79. content.add(splitPane, BorderLayout.CENTER);
  80. content.setPreferredSize(new Dimension(800,800));
  81. }
  82. public 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. // JLabel showDiagnosticsLabel = new JLabel("Set all switches closed:");
  94. // showDiagnosticsLabel.setBounds(200, 60, 170, 20);
  95. // parameterPanel.add(showDiagnosticsLabel);
  96. JPanel borderPanel = new JPanel(null);
  97. borderPanel.setBounds(200, 85, 185, 50);
  98. borderPanel.setBorder(BorderFactory.createTitledBorder(""));
  99. parameterPanel.add(borderPanel);
  100. JLabel showGroupNodeLabel = new JLabel("Use Group Node:");
  101. showGroupNodeLabel.setBounds(10, 1, 170, 20);
  102. borderPanel.add(showGroupNodeLabel);
  103. JButton selectGroupNodeButton = new JButton("Select GroupNode");
  104. selectGroupNodeButton.setEnabled(false);
  105. selectGroupNodeButton.setBounds(10, 25, 165, 20);
  106. selectGroupNodeButton.addActionListener(actionEvent -> selectGroupNode());
  107. borderPanel.add(selectGroupNodeButton);
  108. JCheckBox useGroupNodeCheckBox = new JCheckBox();
  109. useGroupNodeCheckBox.setSelected(false);
  110. useGroupNodeCheckBox.setBounds(155, 1, 25, 20);
  111. useGroupNodeCheckBox.addActionListener(actionEvent -> {
  112. useGroupNode = useGroupNodeCheckBox.isSelected();
  113. selectGroupNodeButton.setEnabled(useGroupNode);
  114. });
  115. borderPanel.add(useGroupNodeCheckBox);
  116. NumberFormat format = NumberFormat.getIntegerInstance();
  117. format.setGroupingUsed(false);
  118. format.setParseIntegerOnly(true);
  119. NumberFormatter integerFormatter = new NumberFormatter(format);
  120. integerFormatter.setMinimum(0);
  121. integerFormatter.setCommitsOnValidEdit(true);
  122. JLabel portLabel = new JLabel("between:");
  123. portLabel.setBounds(10, 330, 70, 30);
  124. parameterPanel.add(portLabel);
  125. JLabel afterLabel = new JLabel("after:");
  126. afterLabel.setBounds(10, 360, 70, 30);
  127. parameterPanel.add(afterLabel);
  128. return parameterPanel;
  129. }
  130. public JPanel createButtonPanel() {
  131. JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
  132. JButton cancelButton = new JButton("Cancel Run");
  133. cancelButton.addActionListener(actionEvent -> cancel());
  134. buttonPanel.add(cancelButton);
  135. JButton clearButton = new JButton("Clear Console");
  136. clearButton.addActionListener(actionEvent -> clear());
  137. buttonPanel.add(clearButton);
  138. JButton resetButton = new JButton("Reset");
  139. resetButton.setToolTipText("Resets the State to before the Algorithm has runed.");
  140. resetButton.addActionListener(actionEvent -> reset());
  141. buttonPanel.add(resetButton);
  142. JButton runButton = new JButton("Run");
  143. runButton.addActionListener(actionEvent -> {
  144. Runnable task = () -> run();
  145. runThread = new Thread(task);
  146. runThread.start();
  147. });
  148. buttonPanel.add(runButton);
  149. return buttonPanel;
  150. }
  151. private void cancel() {
  152. if(runThread.isAlive()) {
  153. println("");
  154. println("Cancel run.");
  155. cancel = true;
  156. progressBar.setValue(0);
  157. } else {
  158. println("Nothing to cancel.");
  159. }
  160. }
  161. private void run() {
  162. cancel = false;
  163. disableGuiInput(true);
  164. startTimer();
  165. executeDemoAlgo();
  166. if(cancel) {
  167. reset();
  168. disableGuiInput(false);
  169. return;
  170. }
  171. printElapsedTime();
  172. disableGuiInput(false);
  173. }
  174. private void reset() {
  175. if(initialState != null) {
  176. println("Resetting..");
  177. resetState();
  178. updateVisual();
  179. }else {
  180. println("No run inistialized.");
  181. }
  182. }
  183. private void disableGuiInput(boolean bool) {
  184. control.guiDiable(bool);
  185. }
  186. @Override
  187. public JPanel getAlgorithmPanel() {
  188. return content;
  189. }
  190. @Override
  191. public void setController(Control control) {
  192. this.control = control;
  193. }
  194. private void clear() {
  195. textArea.setText("");
  196. }
  197. private void print(String message) {
  198. textArea.append(message);
  199. }
  200. private void println(String message) {
  201. textArea.append(message + "\n");
  202. }
  203. private void selectGroupNode() {
  204. Object[] possibilities = control.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().values().stream().map(aCps -> new Handle<DecoratedGroupNode>(aCps)).toArray();
  205. @SuppressWarnings("unchecked")
  206. 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, "");
  207. if(selected != null) {
  208. println("Selected: " + selected);
  209. dGroupNode = selected.object;
  210. }
  211. }
  212. private void progressBarStep(){
  213. progressBar.setValue(++progressBarCount);
  214. }
  215. private void calculateProgressBarParameter() {
  216. int max = 100;
  217. progressBarCount = 0;
  218. progressBar.setValue(0);
  219. progressBar.setMaximum(max);
  220. }
  221. private void startTimer(){
  222. startTime = System.currentTimeMillis();
  223. }
  224. private void printElapsedTime(){
  225. long elapsedMilliSeconds = System.currentTimeMillis() - startTime;
  226. println("Execution Time of Algo in Milliseconds:" + elapsedMilliSeconds);
  227. }
  228. //Algo Part:
  229. private void executeDemoAlgo() {
  230. extractPositionAndAccess();
  231. int actualIteration = control.getModel().getCurIteration();
  232. println("AlgoStart....");
  233. control.calculateStateAndVisualForCurrentTimeStep();
  234. DecoratedState actualstate = control.getSimManager().getActualDecorState();
  235. for(DecoratedNetwork net : actualstate.getNetworkList()) {
  236. float production = net.getSupplierList().stream().map(supplier -> supplier.getEnergyToSupplyNetwork()).reduce(0.0f, (a, b) -> a + b);
  237. float consumption = net.getConsumerList().stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.0f, (a, b) -> a + b);
  238. float difference = Math.abs(production - consumption);
  239. boolean toMuchEnergy = production - consumption > 0;
  240. boolean notEnoughEnergy = production - consumption > 0;
  241. if(notEnoughEnergy)
  242. println("production:" + production + " consumption:" + consumption + " difference:" + difference);
  243. List<FlexWrapper> allOfferedFlex = control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED);
  244. List<FlexWrapper> allFlexThatGetMeEnergy = allOfferedFlex.stream().filter(flexWrapper -> (flexWrapper.getFlex().bringtmir() > 0)).collect(Collectors.toList());
  245. float energyICanOrder = allFlexThatGetMeEnergy.stream().map(flexWrapper -> flexWrapper.getFlex().bringtmir()).reduce(0.0f,(a, b) -> a + b);
  246. println("canOrder: " + energyICanOrder);
  247. List<FlexWrapper> orderedOfferedFlexes = allFlexThatGetMeEnergy.stream().sorted((flex1, flex2) -> Float.compare(flex1.getFlex().bringtmir(), flex2.getFlex().bringtmir())).collect(Collectors.toList());
  248. for(FlexWrapper flex : orderedOfferedFlexes){
  249. System.out.println(flex.getFlex().name +" " +flex.getFlex().bringtmir());
  250. if(flex.getFlex().bringtmir() > difference) break;
  251. flex.order();
  252. difference -= Math.abs(flex.getFlex().bringtmir());
  253. }
  254. }
  255. println("AlgoEnde....");
  256. updateVisual();
  257. }
  258. /**
  259. * Method to get the current Position alias a ListOf Booleans for aktive settings on the Objects on the Canvas.
  260. * Also initialize the Access Hashmap to swap faster positions.
  261. * @param model
  262. * @return
  263. */
  264. private List<Boolean> extractPositionAndAccess() {
  265. Model model = control.getModel();
  266. switchList = new ArrayList<HolonSwitch>();
  267. objectList = new ArrayList<HolonObject>();
  268. initialState = new ArrayList<Boolean>();
  269. access= new HashMap<Integer, AccessWrapper>();
  270. rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
  271. return initialState;
  272. }
  273. /**
  274. * Method to extract the Informations recursively out of the Model.
  275. * @param nodes
  276. * @param positionToInit
  277. * @param timeStep
  278. */
  279. private void rollOutNodes(List<AbstractCpsObject> nodes, List<Boolean> positionToInit, int timeStep) {
  280. for(AbstractCpsObject aCps : nodes) {
  281. if (aCps instanceof HolonObject) {
  282. for (HolonElement hE : ((HolonObject) aCps).getElements()) {
  283. positionToInit.add(hE.isActive());
  284. access.put(positionToInit.size() - 1 , new AccessWrapper(hE));
  285. }
  286. objectList.add((HolonObject) aCps);
  287. }
  288. else if (aCps instanceof HolonSwitch) {
  289. HolonSwitch sw = (HolonSwitch) aCps;
  290. positionToInit.add(sw.getState(timeStep));
  291. switchList.add(sw);
  292. access.put(positionToInit.size() - 1 , new AccessWrapper(sw));
  293. }
  294. else if(aCps instanceof CpsUpperNode) {
  295. rollOutNodes(((CpsUpperNode)aCps).getNodes(), positionToInit ,timeStep );
  296. }
  297. }
  298. }
  299. /**
  300. * To let the User See the current state without touching the Canvas.
  301. */
  302. private void updateVisual() {
  303. control.calculateStateAndVisualForCurrentTimeStep();
  304. control.updateCanvas();
  305. control.getGui().triggerUpdateController(null);
  306. }
  307. /**
  308. * Sets the Model back to its original State before the LAST run.
  309. */
  310. private void resetState() {
  311. setState(initialState);
  312. }
  313. /**
  314. * Sets the State out of the given position for calculation or to show the user.
  315. * @param position
  316. */
  317. private void setState(List<Boolean> position) {
  318. for(int i = 0;i<position.size();i++) {
  319. access.get(i).setState(position.get(i));
  320. }
  321. }
  322. private void addObjectToList(List<AbstractCpsObject> listToSearch, List<HolonObject> listToAdd){
  323. for (AbstractCpsObject aCps : listToSearch) {
  324. if (aCps instanceof HolonObject) listToAdd.add((HolonObject) aCps);
  325. else if(aCps instanceof CpsUpperNode) {
  326. addObjectToList(((CpsUpperNode)aCps).getNodes(),listToAdd);
  327. }
  328. }
  329. }
  330. /**
  331. * A Wrapper Class for Access HolonElement and HolonSwitch in one Element and not have to split the List.
  332. */
  333. private class AccessWrapper {
  334. public static final int HOLONELEMENT = 0;
  335. public static final int SWITCH = 1;
  336. private int type;
  337. private HolonSwitch hSwitch;
  338. private HolonElement hElement;
  339. public AccessWrapper(HolonSwitch hSwitch){
  340. type = SWITCH;
  341. this.hSwitch = hSwitch;
  342. }
  343. public AccessWrapper(HolonElement hElement){
  344. type = HOLONELEMENT;
  345. this.hElement = hElement;
  346. }
  347. public void setState(boolean state) {
  348. if(type == HOLONELEMENT) {
  349. hElement.setActive(state);
  350. }else{//is switch
  351. hSwitch.setManualMode(true);
  352. hSwitch.setManualState(state);
  353. }
  354. }
  355. public boolean getState(int timeStep) {
  356. return (type == HOLONELEMENT)?hElement.isActive():hSwitch.getState(timeStep);
  357. }
  358. public int getType() {
  359. return type;
  360. }
  361. }
  362. private class Handle<T>{
  363. public T object;
  364. Handle(T object){
  365. this.object = object;
  366. }
  367. public String toString() {
  368. return object.toString();
  369. }
  370. }
  371. }