SimulationManager.java 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. package ui.controller;
  2. import classes.*;
  3. import classes.comparator.EnergyMinToMaxComparator;
  4. import classes.comparator.MinEnergyComparator;
  5. import classes.comparator.WeakestBattery;
  6. import ui.model.Model;
  7. import ui.view.FlexiblePane;
  8. import ui.view.MyCanvas;
  9. import java.util.ArrayList;
  10. import java.util.Collections;
  11. import java.util.HashMap;
  12. /**
  13. * Controller for Simulation.
  14. *
  15. * @author Gruppe14
  16. */
  17. public class SimulationManager {
  18. int global = 0;
  19. private Model model;
  20. private ArrayList<AbstractCpsObject> objectsToHandle;
  21. // private ArrayList<CpsEdge> allConnections;
  22. private ArrayList<SubNet> subNets;
  23. private ArrayList<CpsEdge> brokenEdges;
  24. private MyCanvas canvas;
  25. private int timeStep;
  26. private HashMap<Integer, Float> tagTable = new HashMap<>();
  27. private FlexiblePane flexPane;
  28. private HashMap<HolonElement, Float> flexDevicesTurnedOnThisTurn = new HashMap<>();
  29. /**
  30. * One Element of each HolonObject will be powered first, starting with the
  31. * smallest Demand. If ale HolonObjects have an active Element, the
  32. * simulation will try to fully supply as many HolonObjects as possible.
  33. */
  34. public static final short fairnessMininumDemandFirst = 0;
  35. /**
  36. * All HolonObjects will receive the same amount of energy.
  37. */
  38. public static final short fairnessAllEqual = 1;
  39. /**
  40. * Constructor.
  41. *
  42. * @param m
  43. * Model
  44. */
  45. SimulationManager(Model m) {
  46. canvas = null;
  47. model = m;
  48. subNets = new ArrayList<>();
  49. brokenEdges = new ArrayList<>();
  50. }
  51. /**
  52. * calculates the flow of the edges and the supply for objects.
  53. *
  54. * @param x
  55. * current Iteration
  56. */
  57. void calculateStateForTimeStep(int x) {
  58. reset();
  59. timeStep = x;
  60. searchForSubNets();
  61. for (SubNet singleSubNet : subNets) {
  62. if(singleSubNet.getObjects().size() == 0)
  63. {
  64. resetConnections(singleSubNet.getBatteries().get(0),
  65. new ArrayList<>(), new ArrayList<>());
  66. }else
  67. {
  68. resetConnections(singleSubNet.getObjects().get(0),
  69. new ArrayList<>(), new ArrayList<>());
  70. }
  71. }
  72. for (SubNet singleSubNet : subNets) {
  73. float production = calculateEnergyWithoutFlexDevices("prod",
  74. singleSubNet, timeStep);
  75. float consumption = calculateEnergyWithoutFlexDevices("cons",
  76. singleSubNet, timeStep);
  77. // surplus of energy is computed by sum, since consumption is a
  78. // negative value
  79. float energySurplus = production + consumption;
  80. //float minConsumption = calculateMinimumEnergy(singleSubNet, timeStep);
  81. // --------------- use flexible devices ---------------
  82. if (energySurplus != 0 && model.useFlexibleDevices()) {
  83. turnOnFlexibleDevices(singleSubNet, energySurplus, x);
  84. // if (!flexDevicesTurnedOnThisTurn.isEmpty()) {
  85. // System.out.println("The following devices were turned on in this turn: ");
  86. // System.out.println(flexDevicesTurnedOnThisTurn.toString());
  87. // }
  88. // recompute after having examined/turned on all flexible
  89. // devices
  90. production = calculateEnergyWithFlexDevices("prod",
  91. singleSubNet, timeStep);
  92. consumption = calculateEnergyWithFlexDevices("cons",
  93. singleSubNet, timeStep);
  94. energySurplus = production + consumption;
  95. }
  96. // --------------- set flow simulation ---------------
  97. setFlowSimulation(singleSubNet);
  98. // --------------- visualise graph ---------------
  99. /**
  100. * production of subnets, that might be partially turned on/off
  101. */
  102. float currentProduction = production;
  103. /**
  104. * HolonObjects that can be partially Supplied but might be fully
  105. * Supplied
  106. */
  107. /*
  108. ArrayList<HolonObject> partiallySuppliedList = new ArrayList<HolonObject>();
  109. /**
  110. * HolonObjects that can get the spare energy
  111. */
  112. //
  113. // ArrayList<HolonObject> notSuppliedList = new ArrayList<HolonObject>();
  114. /**
  115. * Number of HolonObjects that need to be supplied
  116. */
  117. // long numberOfConsumers = singleSubNet.getObjects().stream()
  118. // .filter(hl -> (hl.getState() != HolonObject.NO_ENERGY
  119. // && hl.getState() != HolonObject.PRODUCER && hl
  120. // .getConnectedTo().stream()
  121. // .filter(e -> (e.getFlow() > 0)).count() > 0))
  122. // .count();
  123. /**
  124. * energy each HolonObject receives in AlleEqualModus
  125. */
  126. if(energySurplus >= 0)
  127. {
  128. //Supply all consumer
  129. for(HolonObject hO : singleSubNet.getObjects())
  130. {
  131. float neededEnergy = hO.getCurrentEnergyAtTimeStep(x);
  132. if(neededEnergy < 0)
  133. {
  134. hO.setCurrentSupply(-neededEnergy);
  135. currentProduction -= -neededEnergy; //Subtract the Energy from the Production
  136. }
  137. }
  138. //Supply all Batterys with the left currentProduction
  139. singleSubNet.getBatteries().sort(new WeakestBattery(x));//Sort all batteries by the Value of ther StateOfCharge/Capasity
  140. for(HolonBattery hB : singleSubNet.getBatteries())
  141. {
  142. float energyToCollect = hB.getInAtTimeStep(x-1);
  143. if(currentProduction >= energyToCollect)
  144. {
  145. //change StateofCharge soc = soc + energyToCollect
  146. hB.setStateOfChargeAtTimeStep(hB.getStateOfChargeAtTimeStep(x-1) + energyToCollect, x);
  147. currentProduction -= energyToCollect;
  148. }else
  149. {
  150. //change StateofCharge soc = soc + currentProduction
  151. hB.setStateOfChargeAtTimeStep(hB.getStateOfChargeAtTimeStep(x-1) + currentProduction, x);
  152. currentProduction = 0;
  153. //no break must be calculatet for all break; //because no more energy
  154. }
  155. }
  156. //Over_Supply all consumer equal
  157. long nOConsumer = singleSubNet.getObjects().stream().filter(hl -> (hl.getCurrentEnergyAtTimeStep(x) < 0)).count();
  158. if(nOConsumer != 0)
  159. {
  160. //energy to seperated equal
  161. float EnergyOverSupplyPerHolonObject = currentProduction / nOConsumer;
  162. for(HolonObject hO : singleSubNet.getObjects())
  163. {
  164. float neededEnergy = hO.getCurrentEnergyAtTimeStep(x);
  165. if(neededEnergy < 0)
  166. {
  167. hO.setCurrentSupply(hO.getCurrentSupply() + EnergyOverSupplyPerHolonObject);
  168. }
  169. }
  170. currentProduction = 0;
  171. }
  172. }
  173. else
  174. {
  175. //Check all Battries what they can provide
  176. if(energySurplus + GetOutAllBatteries(singleSubNet.getBatteries(), x) >= 0)
  177. {
  178. singleSubNet.getBatteries().sort(new WeakestBattery(x));//.reverse();
  179. Collections.reverse(singleSubNet.getBatteries()); //most supplyed first
  180. //Get the NEEDED energy
  181. for(HolonBattery hB : singleSubNet.getBatteries())
  182. {
  183. float neededEnergyFromBattery = currentProduction + consumption; //Energy is negativ
  184. float maxEnergyAvailable = hB.getOutAtTimeStep(x-1); //energy is positiv
  185. if(maxEnergyAvailable >= -neededEnergyFromBattery)
  186. {
  187. //change StateofCharge soc = soc - -neededEnergyFromBattery
  188. hB.setStateOfChargeAtTimeStep(hB.getStateOfChargeAtTimeStep(x-1) - -neededEnergyFromBattery, x);
  189. currentProduction += -neededEnergyFromBattery;
  190. //no break must be calculatet for all beabreak; //When a energy can supply the last needed energy break;
  191. }
  192. else
  193. {
  194. //change StateofCharge soc = soc - maxEnergyAvailable
  195. hB.setStateOfChargeAtTimeStep(hB.getStateOfChargeAtTimeStep(x-1) - maxEnergyAvailable, x);
  196. currentProduction += maxEnergyAvailable;
  197. }
  198. }
  199. //Supply all consumer all ar in state Supplied no one is oversupplied because
  200. // just the energy that is needed is gained from the batteries
  201. for(HolonObject hO : singleSubNet.getObjects())
  202. {
  203. float neededEnergy = hO.getCurrentEnergyAtTimeStep(x);
  204. if(neededEnergy < 0)
  205. {
  206. hO.setCurrentSupply(-neededEnergy);
  207. currentProduction -= -neededEnergy; //Subtract the Energy from the Production
  208. }
  209. }
  210. }
  211. else //Objects have to be partially supplied
  212. {
  213. //Get all Energy out of battries as possible
  214. for(HolonBattery hB : singleSubNet.getBatteries())
  215. {
  216. float maxEnergyAvailable = hB.getOutAtTimeStep(x-1); //energy is positiv
  217. //change StateofCharge soc = soc - maxEnergyAvailable
  218. hB.setStateOfChargeAtTimeStep(hB.getStateOfChargeAtTimeStep(x-1) - maxEnergyAvailable, x);
  219. currentProduction += maxEnergyAvailable;
  220. }
  221. //Calc
  222. singleSubNet.getObjects().stream().forEach(hl -> hl.setCurrentSupply(0));
  223. if(model.getFairnessModel() == fairnessAllEqual)
  224. {
  225. long nOConsumer = singleSubNet.getObjects().stream().filter(hl -> (hl.getCurrentEnergyAtTimeStep(x) < 0)).count();
  226. float energyPerHolonObject = 0;
  227. if (nOConsumer != 0)
  228. energyPerHolonObject = currentProduction / nOConsumer;
  229. for(HolonObject hO : singleSubNet.getObjects())
  230. {
  231. if(hO.getCurrentEnergyAtTimeStep(x) < 0) //Just Consumer need Energy
  232. {
  233. hO.setCurrentSupply(energyPerHolonObject);
  234. currentProduction -= energyPerHolonObject; //Subtract the Energy from the Production
  235. }
  236. }
  237. }
  238. else //(model.getFairnessModel() == fairnessMininumDemandFirst)
  239. {
  240. singleSubNet.getObjects().sort(new MinEnergyComparator(x));
  241. //SupplyAllMinimumEnergy
  242. for(HolonObject hO : singleSubNet.getObjects())
  243. {
  244. if(hO.checkIfPartiallySupplied(x))continue;
  245. if(hO.getCurrentEnergyAtTimeStep(x) > 0)continue;
  246. float minEnergy = -hO.getMinEnergy(x); //Energy from getMinEnergy is negative -> convert to positive
  247. if(minEnergy <= currentProduction)
  248. {
  249. hO.setCurrentSupply(minEnergy);
  250. currentProduction -= minEnergy;
  251. }else
  252. {
  253. hO.setCurrentSupply(currentProduction);
  254. currentProduction = 0;
  255. break;
  256. }
  257. }
  258. singleSubNet.getObjects().sort(new EnergyMinToMaxComparator(x));
  259. //supplyFullytillEnd ... because its cant be fully supplied
  260. for(HolonObject hO : singleSubNet.getObjects())
  261. {
  262. float actualSupplyEnergy = hO.getCurrentSupply();
  263. float neededEnergy = -hO.getCurrentEnergyAtTimeStep(x) - actualSupplyEnergy;
  264. if(neededEnergy <= 0)continue; //Producer or No EnergyNeeded
  265. if(neededEnergy <= currentProduction)
  266. {
  267. hO.setCurrentSupply(neededEnergy+actualSupplyEnergy);
  268. currentProduction -= neededEnergy;
  269. }else
  270. {
  271. hO.setCurrentSupply(currentProduction+actualSupplyEnergy);
  272. currentProduction = 0;
  273. break;
  274. }
  275. }
  276. }
  277. }
  278. }
  279. //Visualize the Color
  280. for(HolonObject hO : singleSubNet.getObjects())
  281. {
  282. float neededEnergy = -hO.getCurrentEnergyAtTimeStep(x); // convert negative energy in positive for calculations
  283. if(neededEnergy < 0)
  284. {
  285. hO.setState(HolonObject.PRODUCER);
  286. }
  287. else if(neededEnergy > 0)
  288. {
  289. float currentSupply = hO.getCurrentSupply() ;
  290. if(currentSupply > neededEnergy)
  291. {
  292. hO.setState(HolonObject.OVER_SUPPLIED);
  293. }else if (currentSupply == neededEnergy)
  294. {
  295. hO.setState(HolonObject.SUPPLIED);
  296. }else if (currentSupply < neededEnergy)
  297. {
  298. float minEnergy = -hO.getMinEnergy(x);
  299. if(currentSupply >= minEnergy || hO.getSelfMadeEnergy(x) >= minEnergy )
  300. {
  301. hO.setState(HolonObject.PARTIALLY_SUPPLIED);
  302. }else
  303. {
  304. hO.setState(HolonObject.NOT_SUPPLIED);
  305. }
  306. }
  307. }
  308. else if(neededEnergy == 0)
  309. {
  310. hO.setState(HolonObject.NO_ENERGY);
  311. }
  312. }
  313. }
  314. canvas.repaint();
  315. flexPane.recalculate();
  316. }
  317. /**
  318. * add all battries.getOut() from a list of battries and return them
  319. * @param aL a List of HolonBattries likely from subnet.getBatteries()
  320. * @param x TimeStep
  321. * @return
  322. *
  323. */
  324. private float GetOutAllBatteries(ArrayList<HolonBattery> aL, int x)
  325. {
  326. float OutEnergy = 0;
  327. for(HolonBattery hB : aL)
  328. {
  329. //System.out.println("Iteration: "+ x +"OutBattery: "+ hB.getOutAtTimeStep(x-1));
  330. OutEnergy += hB.getOutAtTimeStep(x-1);
  331. }
  332. //System.out.println("Iteration: "+ x +"GetOutAllBatteries: "+ OutEnergy);
  333. return OutEnergy;
  334. }
  335. /**
  336. * search for all flexible devices in the network and turn them on, until
  337. * energy surplus = 0 or all devices have been examined.
  338. *
  339. * This code could be compressed (cases inside over- and underproduction are
  340. * the same), but we decided that it is better readable this way
  341. *
  342. * @param subNet
  343. * the subnet
  344. * @param energySurplus
  345. * the current surplus of energy
  346. */
  347. private void turnOnFlexibleDevices(SubNet subNet, float energySurplus,
  348. int timestep) {
  349. for (HolonObject holonOb : subNet.getObjects()) {
  350. for (HolonElement holonEl : holonOb.getElements()) {
  351. // if this element is flexible and active (can be considered for
  352. // calculations)
  353. if (holonEl.isFlexible() && holonEl.isActive()) {
  354. float energyAvailableSingle = holonEl
  355. .getEnergyAtTimeStep(timestep);
  356. float energyAvailableMultiple = energyAvailableSingle
  357. * holonEl.getAmount();
  358. // ------------- flexible consumer / OVERPRODUCTION
  359. // -------------
  360. if (energyAvailableMultiple < 0 && energySurplus > 0) {
  361. // if there is more wasted energy than energy that this
  362. // device can give, give all energy available
  363. if (Math.abs(energyAvailableMultiple) <= Math
  364. .abs(energySurplus)) {
  365. energySurplus += energyAvailableMultiple;
  366. // set the new energy consumption to the maximum
  367. holonEl.setEnergyPerElement(energyAvailableSingle);
  368. flexDevicesTurnedOnThisTurn.put(holonEl,
  369. energyAvailableMultiple);
  370. }
  371. // else: we just need to turn on part of the flexible
  372. // energy available
  373. else {
  374. float energyNeeded = -energySurplus;
  375. energySurplus += energyNeeded; // should give 0, but
  376. // was kept this was
  377. // for consistency
  378. // the energy needed divided through the amount of
  379. // elements
  380. holonEl.setEnergyPerElement(energyNeeded
  381. / holonEl.getAmount());
  382. flexDevicesTurnedOnThisTurn.put(holonEl,
  383. energyNeeded);
  384. }
  385. }
  386. // ------------- flexible producer / UNDERPRODUCTION
  387. // -------------
  388. else if (energyAvailableMultiple > 0 && energySurplus < 0) {
  389. // if there is more energy needed than this device can
  390. // give, give all the energy available
  391. if (Math.abs(energyAvailableMultiple) <= Math
  392. .abs(energySurplus)) {
  393. energySurplus += energyAvailableMultiple;
  394. // set the new energy consumption to the maximum
  395. holonEl.setEnergyPerElement(energyAvailableSingle);
  396. flexDevicesTurnedOnThisTurn.put(holonEl,
  397. energyAvailableMultiple);
  398. }
  399. // else: we just need to turn on part of the flexible
  400. // energy available
  401. else {
  402. float energyNeeded = -energySurplus;
  403. int i = 0;
  404. energySurplus += energyNeeded; // should give 0, but
  405. // was kept this was
  406. // for consistency
  407. // the energy needed divided through the amount of
  408. // elements
  409. holonEl.setEnergyPerElement(energyNeeded
  410. / holonEl.getAmount());
  411. flexDevicesTurnedOnThisTurn.put(holonEl,
  412. energyNeeded);
  413. }
  414. }
  415. }
  416. if (energySurplus == 0) {
  417. break;
  418. }
  419. }
  420. if (energySurplus == 0) {
  421. break;
  422. }
  423. }
  424. }
  425. /**
  426. * Set Flow Simulation.
  427. *
  428. * @param sN
  429. * Subnet
  430. */
  431. private void setFlowSimulation(SubNet sN) {
  432. ArrayList<AbstractCpsObject> producers = new ArrayList<>();
  433. AbstractCpsObject tmp = null;
  434. tagTable = new HashMap<>();
  435. // traverse all objects in this subnet
  436. for (HolonObject hl : sN.getObjects()) {
  437. float energy = hl.getCurrentEnergyAtTimeStep(timeStep);
  438. // if their production is higher than their consumption
  439. if (energy > 0) {
  440. tagTable.put(hl.getId(), energy);
  441. hl.addTag(hl.getId());
  442. for (CpsEdge edge : hl.getConnections()) {
  443. if (edge.isWorking()) {
  444. // set other end of edge as tmp-object
  445. // and add this end to the other end's tag-list
  446. AbstractCpsObject a = edge.getA();
  447. AbstractCpsObject b = edge.getB();
  448. if (a.getId() == hl.getId()) {
  449. b.addTag(hl.getId());
  450. tmp = b;
  451. }
  452. if (b.getId() == hl.getId()) {
  453. a.addTag(hl.getId());
  454. tmp = a;
  455. }
  456. edge.setFlow(edge.getFlow() + energy);
  457. edge.calculateState();
  458. edge.addTag(hl.getId());
  459. if (edge.isWorking() && !producers.contains(tmp)) {
  460. if (tmp instanceof HolonSwitch) {
  461. if (((HolonSwitch) tmp).getState(timeStep)) {
  462. producers.add(tmp);
  463. }
  464. } else if (!(tmp instanceof CpsUpperNode)) {
  465. producers.add(tmp);
  466. }
  467. }
  468. }
  469. }
  470. }
  471. }
  472. setFlowSimRec(producers, 0);
  473. }
  474. /**
  475. * Set Flow Simulation Rec.
  476. *
  477. * @param nodes
  478. * the nodes
  479. * @param iter
  480. * the Iteration
  481. */
  482. private void setFlowSimRec(ArrayList<AbstractCpsObject> nodes, int iter) {
  483. ArrayList<AbstractCpsObject> newNodes = new ArrayList<>();
  484. ArrayList<CpsEdge> changedEdges = new ArrayList<>();
  485. AbstractCpsObject tmp;
  486. if (nodes.size() != 0) {
  487. for (AbstractCpsObject cps : nodes) {
  488. // check whether the cps is in a legit state if it is a switch
  489. if (legitState(cps)) {
  490. for (CpsEdge edge : cps.getConnections()) {
  491. // is edge working
  492. // and does the edge's tag-list not (yet) contain all
  493. // tags of the cps
  494. if (edge.isWorking()
  495. && (!(edge.containsTags(edge.getTags(),
  496. cps.getTag())))) {
  497. if (edge.getA().getId() == cps.getId()) {
  498. tmp = edge.getB();
  499. } else {
  500. tmp = edge.getA();
  501. }
  502. for (Integer tag : cps.getTag()) {
  503. if (!(edge.getTags().contains(tag))
  504. && !(edge.getPseudoTags().contains(tag))) {
  505. edge.setFlow(edge.getFlow()
  506. + tagTable.get(tag));
  507. edge.addTag(tag);
  508. }
  509. }
  510. // uppernodes do not spread energy
  511. if (!(tmp instanceof CpsUpperNode)) {
  512. for (Integer tag : tmp.getTag()) {
  513. if (!(edge.getTags().contains(tag))
  514. && tagTable.get(tag) != null
  515. && !(edge.getPseudoTags()
  516. .contains(tag))) {
  517. edge.setFlow(edge.getFlow()
  518. + tagTable.get(tag));
  519. edge.addPseudoTag(tag);
  520. changedEdges.add(edge);
  521. }
  522. }
  523. }
  524. edge.calculateState();
  525. if (edge.isWorking()
  526. && !(tmp instanceof CpsUpperNode)) {
  527. tmp.addAllPseudoTags(cps.getTag());
  528. if (!newNodes.contains(tmp)) {
  529. newNodes.add(tmp);
  530. }
  531. }
  532. }
  533. }
  534. }
  535. }
  536. setPseudoTags(newNodes, changedEdges);
  537. setFlowSimRec(newNodes, iter + 1);
  538. }
  539. }
  540. /**
  541. * Set the Pseudo Tags.
  542. *
  543. * @param nodes
  544. * Array of AbstractCpsObjects
  545. */
  546. private void setPseudoTags(ArrayList<AbstractCpsObject> nodes,
  547. ArrayList<CpsEdge> edges) {
  548. for (AbstractCpsObject node : nodes) {
  549. node.recalculateTags();
  550. node.setPseudoTags(new ArrayList<>());
  551. }
  552. for (CpsEdge edge : edges) {
  553. edge.recalculateTags();
  554. edge.setPseudoTag(new ArrayList<>());
  555. }
  556. }
  557. /**
  558. * Reset the Connection.
  559. *
  560. * @param cps
  561. * CpsObject
  562. * @param visitedObj
  563. * the visited Objects
  564. * @param visitedEdges
  565. * the visited Edges
  566. */
  567. private void resetConnections(AbstractCpsObject cps,
  568. ArrayList<Integer> visitedObj, ArrayList<CpsEdge> visitedEdges) {
  569. visitedObj.add(cps.getId());
  570. cps.resetTags();
  571. for (CpsEdge e : cps.getConnections()) {
  572. if (!(visitedEdges.contains(e))) {
  573. e.setFlow(0);
  574. e.calculateState();
  575. e.setTags(new ArrayList<>());
  576. visitedEdges.add(e);
  577. if (!(visitedObj.contains(e.getA().getId()))) {
  578. resetConnections(e.getA(), visitedObj, visitedEdges);
  579. e.getA().resetTags();
  580. }
  581. if (!(visitedObj.contains(e.getB().getId()))) {
  582. resetConnections(e.getB(), visitedObj, visitedEdges);
  583. e.getB().resetTags();
  584. }
  585. }
  586. }
  587. }
  588. /**
  589. * calculates the energy of either all producers or consumers. Flexible
  590. * devices are filtered out
  591. *
  592. * @param type
  593. * Type
  594. * @param sN
  595. * Subnet
  596. * @param x
  597. * Integer
  598. * @return The Energy
  599. */
  600. private float calculateEnergyWithoutFlexDevices(String type, SubNet sN,
  601. int x) {
  602. float energy = 0;
  603. for (HolonObject hl : sN.getObjects()) {
  604. float currentEnergyWithoutFlexibles = hl
  605. .getCurrentEnergyAtTimeStepWithoutFlexiblesAndResetFlexibles(x);
  606. if (type.equals("prod")) {
  607. if (currentEnergyWithoutFlexibles > 0) {
  608. energy += currentEnergyWithoutFlexibles;
  609. hl.setState(HolonObject.PRODUCER);
  610. }
  611. }
  612. if (type.equals("cons")) {
  613. if (currentEnergyWithoutFlexibles < 0) {
  614. energy += currentEnergyWithoutFlexibles;
  615. hl.setState(HolonObject.NOT_SUPPLIED);
  616. }
  617. }
  618. if (currentEnergyWithoutFlexibles == 0) {
  619. hl.setState(HolonObject.NO_ENERGY);
  620. }
  621. }
  622. return energy;
  623. }
  624. /**
  625. * calculates the energy of either all producers or consumers. Flexible
  626. * devices are filtered out
  627. *
  628. * @param type
  629. * Type
  630. * @param sN
  631. * Subnet
  632. * @param x
  633. * Integer
  634. * @return The Energy
  635. */
  636. private float calculateEnergyWithFlexDevices(String type, SubNet sN, int x) {
  637. float energy = 0;
  638. for (HolonObject hl : sN.getObjects()) {
  639. float currentEnergy = hl.getCurrentEnergyAtTimeStep(x);
  640. if (type.equals("prod")) {
  641. if (currentEnergy > 0) {
  642. energy += currentEnergy;
  643. hl.setState(HolonObject.PRODUCER);
  644. }
  645. }
  646. if (type.equals("cons")) {
  647. if (currentEnergy < 0) {
  648. energy = energy + currentEnergy;
  649. hl.setState(HolonObject.NOT_SUPPLIED);
  650. }
  651. }
  652. if (currentEnergy == 0) {
  653. hl.setState(HolonObject.NO_ENERGY);
  654. }
  655. }
  656. return energy;
  657. }
  658. /**
  659. * Calculate the Minimum Energy of a Subnet.
  660. *
  661. * @param sN
  662. * Subnet
  663. * @param x
  664. * Integer
  665. * @return the Calculated minimum Energy of a Subnet
  666. */
  667. private float calculateMinimumEnergy(SubNet sN, int x) {
  668. float minimummConsumptionSubnet = 0;
  669. for (HolonObject hl : sN.getObjects()) {
  670. float minElement = 0;
  671. // Search for a activ element
  672. for (HolonElement he : hl.getElements()) {
  673. if (he.isActive()) {
  674. float overallEnergy = he.getOverallEnergyAtTimeStep(x);
  675. if (overallEnergy < 0) {
  676. // Is a consumer
  677. minElement = overallEnergy;
  678. }
  679. }
  680. }
  681. for (HolonElement he : hl.getElements()) {
  682. if (he.isActive()) {
  683. float overallEnergy = he.getOverallEnergyAtTimeStep(x);
  684. if (minElement < overallEnergy && overallEnergy < 0) {
  685. // is a smaller consumer
  686. minElement = overallEnergy;
  687. }
  688. }
  689. }
  690. minimummConsumptionSubnet += minElement;
  691. }
  692. System.out.println("MinimumEnergy = "+ minimummConsumptionSubnet);
  693. return minimummConsumptionSubnet;
  694. }
  695. /**
  696. * generates all subNets from all objectsToHandle.
  697. */
  698. private void searchForSubNets() {
  699. subNets = new ArrayList<>();
  700. brokenEdges.clear();
  701. boolean end = false;
  702. int i = 0;
  703. AbstractCpsObject cps;
  704. if (objectsToHandle.size() > 0) {
  705. while (!end) {
  706. cps = objectsToHandle.get(i);
  707. SubNet singleSubNet = new SubNet(new ArrayList<>(),
  708. new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
  709. singleSubNet = buildSubNet(cps, new ArrayList<>(), singleSubNet);
  710. if (singleSubNet.getObjects().size() + singleSubNet.getBatteries().size() != 0 ) {
  711. subNets.add(singleSubNet);
  712. }
  713. if (0 == objectsToHandle.size()) {
  714. end = true;
  715. }
  716. }
  717. }
  718. }
  719. /**
  720. * recursivly generates a subnet of all objects, that one specific object is
  721. * connected to.
  722. *
  723. * @param cps
  724. * AbstractCpsObject
  725. * @param visited
  726. * visited Array of Integer
  727. * @param sN
  728. * Subnets
  729. * @return Subnet
  730. */
  731. private SubNet buildSubNet(AbstractCpsObject cps,
  732. ArrayList<Integer> visited, SubNet sN) {
  733. visited.add(cps.getId());
  734. if (cps instanceof HolonObject) {
  735. sN.getObjects().add((HolonObject) cps);
  736. }
  737. if (cps instanceof HolonSwitch) {
  738. sN.getSwitches().add((HolonSwitch) cps);
  739. }
  740. if (cps instanceof HolonBattery) {
  741. sN.getBatteries().add((HolonBattery) cps);
  742. }
  743. removeFromToHandle(cps.getId());
  744. AbstractCpsObject a;
  745. AbstractCpsObject b;
  746. for (CpsEdge edge : cps.getConnections()) {
  747. if (edge.isWorking()) {
  748. a = edge.getA();
  749. b = edge.getB();
  750. if (!(cps instanceof HolonSwitch)) {
  751. if (!(sN.getEdges().contains(edge))) {
  752. sN.getEdges().add(edge);
  753. }
  754. }
  755. if (cps instanceof HolonSwitch
  756. && ((HolonSwitch) cps).getState(timeStep)) {
  757. if (!(sN.getEdges().contains(edge))) {
  758. sN.getEdges().add(edge);
  759. }
  760. }
  761. if (!visited.contains(a.getId()) && legitState(cps)
  762. && !(a instanceof CpsUpperNode)) {
  763. sN = buildSubNet(a, visited, sN);
  764. }
  765. if (!visited.contains(b.getId()) && legitState(cps)
  766. && !(b instanceof CpsUpperNode)) {
  767. sN = buildSubNet(b, visited, sN);
  768. }
  769. if (a instanceof CpsUpperNode && a.getId() != cps.getId()) {
  770. edge.setConnected(CpsEdge.CON_UPPER_NODE_NOT_INSIDE);
  771. checkForConnectedStates(b, (CpsUpperNode) a, edge);
  772. }
  773. if (b instanceof CpsUpperNode && b.getId() != cps.getId()) {
  774. edge.setConnected(CpsEdge.CON_UPPER_NODE_NOT_INSIDE);
  775. checkForConnectedStates(a, (CpsUpperNode) b, edge);
  776. }
  777. } else {
  778. brokenEdges.add(edge);
  779. }
  780. }
  781. return sN;
  782. }
  783. /**
  784. * is the Switch in a legitimate State.
  785. *
  786. * @param current
  787. * AbstractCpsObject
  788. * @return boolean
  789. */
  790. private boolean legitState(AbstractCpsObject current) {
  791. return !(current instanceof HolonSwitch)
  792. || ((HolonSwitch) current).getState(timeStep);
  793. }
  794. // /**
  795. // * ensures that objectsToHandle only contains HolonObjects.
  796. // */
  797. // public void cleanObjectsToHandle() {
  798. // for (int i = 0; i < objectsToHandle.size(); i++) {
  799. // if (!(objectsToHandle.get(i) instanceof HolonObject)) {
  800. // objectsToHandle.remove(i);
  801. // }
  802. // }
  803. // }
  804. /**
  805. * removes an Object that already has been handled.
  806. *
  807. * @param id
  808. * the Object ID
  809. */
  810. private void removeFromToHandle(int id) {
  811. for (int i = 0; i < objectsToHandle.size(); i++) {
  812. if (objectsToHandle.get(i).getId() == id) {
  813. objectsToHandle.remove(i);
  814. }
  815. }
  816. }
  817. /**
  818. * copies the data of an array of Objects.
  819. *
  820. * @param toCopy
  821. * the ArrayList of CpsObjects co Copy
  822. */
  823. private void copyObjects(ArrayList<AbstractCpsObject> toCopy) {
  824. for (AbstractCpsObject cps : toCopy) {
  825. if (cps instanceof CpsUpperNode) {
  826. copyObjects(((CpsUpperNode) cps).getNodes());
  827. } else {
  828. objectsToHandle.add(cps);
  829. }
  830. }
  831. }
  832. /**
  833. * Prints the Components auf all subnets.
  834. */
  835. private void printNetsToConsole() {
  836. for (int i = 0; i < subNets.size(); i++) {
  837. SubNet subNet = subNets.get(i);
  838. System.out.println("SUBNET NR:" + i);
  839. subNet.toString(timeStep);
  840. }
  841. }
  842. /**
  843. * Set the Canvas.
  844. *
  845. * @param can
  846. * the Canvas
  847. */
  848. public void setCanvas(MyCanvas can) {
  849. canvas = can;
  850. }
  851. /**
  852. * Reset all Data to the current state of the Model.
  853. */
  854. public void reset() {
  855. objectsToHandle = new ArrayList<>();
  856. copyObjects(model.getObjectsOnCanvas());
  857. flexDevicesTurnedOnThisTurn = new HashMap<>();
  858. }
  859. /**
  860. * Resets the State of all Edges
  861. */
  862. private void resetEdges() {
  863. for (CpsEdge e : brokenEdges) {
  864. e.setWorkingState(true);
  865. }
  866. }
  867. /**
  868. * Resets the State for the whole Simulation Model
  869. */
  870. void resetSimulation() {
  871. reset();
  872. resetEdges();
  873. }
  874. /**
  875. * Get all Subnets.
  876. *
  877. * @return all Subnets
  878. */
  879. public ArrayList<SubNet> getSubNets() {
  880. return subNets;
  881. }
  882. /**
  883. * Get broken Edges
  884. */
  885. // public ArrayList<CpsEdge> getBrokenEdges() {
  886. // return brokenEdges;
  887. // }
  888. /**
  889. * checks whether a given object is connected to an object inside the
  890. * upperNode. if yes, the state for the edge is changed in "connected" or
  891. * "not connected"
  892. */
  893. private void checkForConnectedStates(AbstractCpsObject cps,
  894. CpsUpperNode cUNode, CpsEdge theEdge) {
  895. AbstractCpsObject tmp;
  896. for (CpsEdge edge : cps.getConnections()) {
  897. if (edge.getA().getId() == cps.getId()) {
  898. tmp = edge.getB();
  899. } else {
  900. tmp = edge.getA();
  901. }
  902. if (cUNode.getNodes().contains(tmp)) {
  903. if (tmp instanceof CpsUpperNode) {
  904. checkForConnectedStates(cps, (CpsUpperNode) tmp, theEdge);
  905. } else {
  906. theEdge.setConnected(CpsEdge.CON_UPPER_NODE_AND_INSIDE);
  907. break;
  908. }
  909. }
  910. }
  911. }
  912. public FlexiblePane getFlexiblePane() {
  913. return flexPane;
  914. }
  915. void setFlexiblePane(FlexiblePane fp) {
  916. flexPane = fp;
  917. }
  918. }