Advertisement
Guest User

Untitled

a guest
Jun 26th, 2019
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.46 KB | None | 0 0
  1. a. Sustainability score - to build a score for every home
  2. b. Badges - Provide badges or incentives for people when they achieve goals
  3. c. Incentives - Provide incentives when people achieve certain goals
  4.  
  5. 1. Scalable design
  6. 2. Data extensibility - ability to quickly extend attributes to consider additional scenarios.
  7. 3. For all devices - build the application to scale into using any devices or integrate with third party systems
  8.  
  9. package heca;
  10.  
  11. import java.sql.Time;
  12.  
  13. public class Appliance{
  14. String applianceCategory; //e.g Electricity
  15. ApplianceType applianceType; //e.g StrictAppliance like Refrigerator
  16. String applianceName; //e.g WashingMachine
  17. int usageTime;
  18. Time scheduledTime;
  19.  
  20. public Appliance(String applianceCategory, ApplianceType applianceType, String applianceName, int usageTime,Time scheduledTime) {
  21. this.applianceCategory = applianceCategory;
  22. this.applianceType = applianceType;
  23. this.applianceName = applianceName;
  24. this.usageTime = usageTime;
  25. this.scheduledTime = scheduledTime;
  26. }
  27.  
  28.  
  29. }
  30.  
  31. package heca;
  32.  
  33. public class Attribute{
  34. String attibuteName; //e.g WindPower
  35. double perUnitWeight;
  36. int consumed;
  37. int limit;
  38.  
  39. public static class Builder {
  40. //required
  41. private String attibuteName;
  42. //optional
  43. private double perUnitWeight;
  44. private int consumed;
  45. private int limit;
  46.  
  47. public Builder(String size) {
  48. this.attibuteName = size;
  49. }
  50.  
  51. public Builder perUnitWeight(double value) {
  52. perUnitWeight = value;
  53. return this;
  54. }
  55.  
  56. public Builder consumed(int value) {
  57. consumed = value;
  58. return this;
  59. }
  60.  
  61. public Builder limit(int value) {
  62. limit = value;
  63. return this;
  64. }
  65.  
  66. public Attribute build() {
  67. return new Attribute(this);
  68. }
  69. }
  70.  
  71. private Attribute(Builder builder) {
  72. attibuteName = builder.attibuteName;
  73. perUnitWeight = builder.perUnitWeight;
  74. consumed = builder.consumed;
  75. limit = builder.limit;
  76. }
  77.  
  78. public Attribute(String a){
  79. this(a, 0.0, 0, (int)1e6);
  80.  
  81. }
  82. public Attribute(String a, double w, int m, int l){
  83. attibuteName = a;
  84. perUnitWeight = w;
  85. consumed = m;
  86. limit = l;
  87.  
  88. }
  89. public String toString(){
  90. StringBuilder sb = new StringBuilder();
  91. sb.append("ntattibute : "+this.attibuteName+"tConsumed :"+ this.consumed + "tLimit : "+ this.limit);
  92. return sb.toString();
  93. }
  94.  
  95. @Override
  96. public int hashCode() {
  97. final int prime = 31;
  98. int result = 1;
  99. result = prime * result + ((attibuteName == null) ? 0 : attibuteName.hashCode());
  100. return result;
  101. }
  102.  
  103. @Override
  104. public boolean equals(Object obj) {
  105. if (this == obj)
  106. return true;
  107. if (obj == null)
  108. return false;
  109. if (getClass() != obj.getClass())
  110. return false;
  111. Attribute other = (Attribute) obj;
  112. if (attibuteName == null) {
  113. if (other.attibuteName != null)
  114. return false;
  115. } else if (!attibuteName.equals(other.attibuteName))
  116. return false;
  117. return true;
  118. }
  119. }
  120.  
  121. package heca;
  122.  
  123. import java.sql.Time;
  124. import java.util.List;
  125. import java.util.Map;
  126.  
  127. public interface Controller {
  128. public String createUser(String userName);
  129. public boolean addAppliance(String userId,String applianceCategory);
  130. public boolean addAppliance(String userId, String applianceCategory,List<Attribute> attribs);
  131. public void addAttribute(String userId,String applianceCategory,String attributeName);
  132. public void updateConsumption(String userId,String applianceCategory,String attributeName,int updatedValue);
  133. public List<Attribute> getMAXExpenses(String userId);
  134. public List<Attribute> getMINExpenses(String userId);
  135. public Map<String,List<Attribute>> getAllConsumptionDetails(String userId);
  136. public List<Attribute> getSpecificConsumptionDetails(String userId,String applianceCategory);
  137. public Score getScore();
  138. public Badge getBadge();
  139. public List<Attribute> getSuggestedOptimizedGoal(String userId,String applianceCategory,int target);
  140. public boolean modifyGoal(String userId,String applianceCategory,String attributeName,int targetValue);
  141. public boolean scheduleFlexibleAppliance(String userId,String applianceCategory, Appliance applianceName,Time schedule);
  142.  
  143. }
  144.  
  145. package heca;
  146.  
  147. import java.util.Comparator;
  148.  
  149. public class CostComparator implements Comparator<Attribute>{
  150.  
  151. // fractional knapsack comparator having only Weight(weight per unit) but all items are unbounded..same Value...Hence value ignored
  152. @Override
  153. public int compare(Attribute o1, Attribute o2) {
  154. return ((o1.limit -o1.consumed)*(int)o1.perUnitWeight ) - ((o2.limit -o2.consumed)*(int)o2.perUnitWeight ) > 0 ? 1:0 ;
  155. }
  156.  
  157. }
  158.  
  159. package heca;
  160.  
  161. import java.util.ArrayList;
  162. import java.util.List;
  163. import java.util.PriorityQueue;
  164. import java.util.Queue;
  165. import java.util.concurrent.ConcurrentHashMap;
  166.  
  167. public class EnergyTracker{
  168.  
  169. ConcurrentHashMap<String,List<Attribute>> appliances = new ConcurrentHashMap<>(); //AdjacencyMatrix
  170. Queue<Attribute> maxExpenseHeap = new PriorityQueue<>(20, new CostComparator());
  171. Queue<Attribute> minExpenseHeap = new PriorityQueue<>(20, new CostComparator().reversed());
  172.  
  173. public List<Attribute> getApplianceDetails(String aplianceName){
  174. if(appliances.containsKey(aplianceName))return appliances.get(aplianceName);
  175. else return new ArrayList<>();
  176. }
  177. public void setApplianceDetails(String aplianceName,List<Attribute> attribs){
  178. List<Attribute> renewedAttribs = appliances.get(aplianceName);
  179. if(renewedAttribs==null || renewedAttribs.isEmpty())
  180. renewedAttribs = attribs;
  181. else if(appliances.containsKey(aplianceName)){
  182. renewedAttribs.addAll(attribs);
  183. }
  184. appliances.put(aplianceName,renewedAttribs);
  185. renewedAttribs.forEach((attrib )-> this.maxExpenseHeap.offer(attrib));
  186. renewedAttribs.forEach((attrib )-> this.minExpenseHeap.offer(attrib));
  187.  
  188. }
  189.  
  190. public ConcurrentHashMap<String,List<Attribute>> getALLApplianceDetails() {
  191. return appliances;
  192. }
  193.  
  194. public List<Attribute> get_TopK_MINConsumptionAppliance(int K){
  195. ArrayList<Attribute> top5minConsumption = new ArrayList<>(K);
  196. Attribute temp =null;
  197. for( int i =0; i<K && K< minExpenseHeap.size() && i < minExpenseHeap.size(); ){
  198. temp = minExpenseHeap.poll();
  199. top5minConsumption.add(temp);
  200. minExpenseHeap.offer(temp);
  201. i++;
  202. }
  203. return top5minConsumption;
  204. }
  205.  
  206. public List<Attribute> get_TopK_MAXConsumptionAppliance(int K){
  207. ArrayList<Attribute> top5minConsumption = new ArrayList<>(K);
  208. Attribute temp =null;
  209. for( int i =0; i<K && K< maxExpenseHeap.size() && i < maxExpenseHeap.size(); ){
  210. temp = maxExpenseHeap.poll();
  211. top5minConsumption.add(temp);
  212. maxExpenseHeap.offer(temp);
  213. }
  214. return top5minConsumption;
  215. }
  216. }
  217.  
  218. package heca;
  219.  
  220. public class HomeUser{
  221.  
  222. String userId;
  223.  
  224. EnergyTracker targetExpenseTracker = new EnergyTracker();
  225. EnergyTracker actualExpenseTracker = new EnergyTracker();
  226.  
  227. int targetExpenseGoal, monthlyBudget, tillNowExpense;
  228.  
  229. public HomeUser(String uID){
  230. userId = uID;
  231. }
  232.  
  233. /* <TODO> calculate based on :
  234. getSavings()
  235. getGoalAchieved()
  236. */
  237. public Badge showBadgesAndIncentives(){
  238. return Badge.SILVER;
  239. }
  240. /* <TODO> judge based on
  241. total consumption cost of all Appliances -> Attribute -> consumed*perUnitWeight
  242. */
  243. public Score getScore(){
  244. return Score.CONSUMES_MEDIUM;
  245. }
  246.  
  247.  
  248. private int getGoalAchieved(){
  249. return targetExpenseGoal;
  250. }
  251. private int getSavings(){
  252. return monthlyBudget - tillNowExpense;
  253. }
  254.  
  255.  
  256.  
  257. //setters
  258.  
  259. public void setTargetExpenseGoal(int targetExpenseGoal) {
  260. this.targetExpenseGoal = targetExpenseGoal;
  261. }
  262.  
  263. public void setMonthlyBudget(int monthlyBudget) {
  264. this.monthlyBudget = monthlyBudget;
  265. }
  266.  
  267. public void setTillNowExpense(int tillNowExpense) {
  268. this.tillNowExpense = tillNowExpense;
  269. }
  270.  
  271. }
  272.  
  273. package heca;
  274.  
  275. import java.util.HashMap;
  276.  
  277. public class UserDB{
  278. HashMap<String,HomeUser> usserMap = new HashMap<>();
  279.  
  280. public void addUser(String userId,HomeUser u){
  281. usserMap.put(userId, u);
  282. }
  283.  
  284. public HomeUser getUser(String userId){
  285. return usserMap.get(userId);
  286. }
  287. }
  288.  
  289. package heca;
  290.  
  291.  
  292. import java.sql.Time;
  293. import java.util.ArrayList;
  294. import java.util.Collections;
  295. import java.util.List;
  296. import java.util.Map;
  297.  
  298.  
  299.  
  300. public class DesignHECA implements Controller {
  301.  
  302. private UserDB userDB = new UserDB();
  303.  
  304. @Override
  305. public String createUser(String userName) {
  306. String userId = userName+ new java.util.Random();
  307. HomeUser u = new HomeUser(userId);
  308. userDB.addUser(userId,u);
  309. return userId ;
  310. }
  311.  
  312. public HomeUser getUser(String userId) {
  313. return userDB.getUser(userId);
  314. }
  315.  
  316.  
  317. /*----------------------- addAppliance ----------------------------------------*/
  318. @Override
  319. public boolean addAppliance(String userId, String applianceCategory) {
  320. if(applianceCategory == null || applianceCategory.isEmpty()) return false;
  321. else getUser(userId).actualExpenseTracker.setApplianceDetails(applianceCategory,new ArrayList<>()); //telescoping
  322. return true;
  323.  
  324. }
  325. @Override
  326. public boolean addAppliance(String userId, String applianceCategory,final List<Attribute> attribs){ // not to be leaked to Client
  327.  
  328. HomeUser user = getUser(userId);
  329.  
  330. if(applianceCategory == null || applianceCategory.isEmpty()) return false;
  331. else
  332. if(!user.actualExpenseTracker.appliances.containsKey(applianceCategory)){
  333. user.actualExpenseTracker.setApplianceDetails(applianceCategory,attribs); //defensive copy
  334. }else{
  335. List<Attribute> prev = user.actualExpenseTracker.appliances.getOrDefault(applianceCategory, new ArrayList<>());
  336. prev.addAll(attribs); //handling override left for brevity
  337. user.actualExpenseTracker.setApplianceDetails(applianceCategory,prev);
  338. }
  339. return true;
  340. }
  341.  
  342.  
  343. /*----------------------- addAttribute ----------------------------------------*/
  344. @Override
  345. public void addAttribute(String userId, String applianceCategory, String attributeName) {
  346. List<Attribute> attribs = new ArrayList<>();
  347. Attribute attribute = new Attribute(attributeName);
  348. attribs.add(attribute);
  349.  
  350. addAppliance(userId, applianceCategory,attribs);
  351.  
  352. }
  353.  
  354. /*----------------------- updateConsumption ----------------------------------------*/
  355. @Override
  356. public void updateConsumption(String userId, String applianceCategory, String attributeName, int tillNowConsumed) {
  357. //left intentionally for brevity
  358. }
  359.  
  360. /*----------------------- getMAXExpenses ----------------------------------------*/
  361. @Override
  362. public List<Attribute> getMAXExpenses(String userId) {
  363. HomeUser user = getUser(userId);
  364. return user.actualExpenseTracker.get_TopK_MAXConsumptionAppliance(10);
  365. }
  366.  
  367. /*----------------------- getMINExpenses ----------------------------------------*/
  368. @Override
  369. public List<Attribute> getMINExpenses(String userId) {
  370. HomeUser user = getUser(userId);
  371. return user.actualExpenseTracker.get_TopK_MINConsumptionAppliance(10);
  372. }
  373. /*----------------------- getAllConsumptionDetails ----------------------------------------*/
  374. @Override
  375. public Map<String, List<Attribute>> getAllConsumptionDetails(String userId) {
  376. HomeUser user = getUser(userId);
  377. return user.actualExpenseTracker.getALLApplianceDetails();
  378. }
  379.  
  380.  
  381. /*----------------------- getSpecificConsumptionDetails ----------------------------------------*/
  382. @Override
  383. public List<Attribute> getSpecificConsumptionDetails(String userId, String applianceCategory) {
  384. HomeUser user = getUser(userId);
  385. //checks omitted for brevity
  386. return user.actualExpenseTracker.getApplianceDetails(applianceCategory);
  387.  
  388. }
  389.  
  390. /*----------------------- modifyGoal - lets user to newly calibrate his target expenses ---*/
  391. @Override
  392. public boolean modifyGoal(String userId, String applianceCategory, String attributeName, int newlimit) {
  393. HomeUser user = getUser(userId);
  394. List<Attribute> attribs = user.targetExpenseTracker.getApplianceDetails(applianceCategory);
  395. Attribute temp =null;
  396. for(int i=0; i<attribs.size();i++){
  397. if(attributeName.equals(attribs.get(i).attibuteName)){
  398. temp =attribs.remove(i);
  399. temp.limit = newlimit;
  400. attribs.add(temp);
  401. user.targetExpenseTracker.setApplianceDetails(applianceCategory,attribs);
  402. return true;
  403. }
  404. }
  405. return false;
  406. }
  407.  
  408. /*---------------------- getSuggestedOptimizedGoals ------------------------------
  409. * This method Suggests optimized path(Top 5 MIN Expense) for Goal if calibration set by User predicted to meet target
  410. * */
  411. @Override
  412. public List<Attribute> getSuggestedOptimizedGoal(String userId,String applianceCategory,int target) {
  413. HomeUser user = getUser(userId);
  414. List<Attribute> attribs = user.actualExpenseTracker.getApplianceDetails(applianceCategory);
  415. /* e.g
  416. "PowerSupply",340,880
  417. "WindPower",120,1
  418. "SolarEnergy",10,2
  419.  
  420. int[] w ={880,1,2};
  421. int[] c ={340,120,10};
  422.  
  423. if( this.canProduce(c,w,user.monthlyBudget -user.tillNowExpense) > 0){ //optimiseed combination
  424. return this.getMINExpenses(userId);
  425. }
  426. else
  427. return new ArrayList<>();
  428. */
  429. return this.getMINExpenses(userId);
  430. }
  431. public int canProduce(int[] c,int[] w, int W){
  432. return min_cost(c.length,W,c,w);
  433. }
  434.  
  435. // Dynamic programming to compute Minimum Cost Path for fixed Weight
  436. public int min_cost(int N, int W,int[] c, int[] w){
  437. // min_cost(i, W) = min(min_cost(i+1, W), min_cost(i, W - w[i]) + c[i])
  438.  
  439. int[][] dp = new int[N][W];
  440. int i=0;
  441.  
  442. //base cases
  443. if(dp[i][0] == 0 ) return 1; // We already reached our goal
  444. if(W < 0 || i > N) dp[i][W] = Integer.MIN_VALUE; // if (W < 0 or i > N) then we can't get to W
  445.  
  446. dp[i][ W] = Math.min(min_cost(i+1, W,c,w), min_cost(i, W - w[i],c,w) + c[i]);
  447.  
  448. if(dp[N][ W] <= W)
  449. return dp[N][ W];
  450. else
  451. return 0;//impossible --need to re calibrate
  452. }
  453.  
  454.  
  455. @Override
  456. public boolean scheduleFlexibleAppliance(String userId,String applianceCategory, Appliance applianceName,Time schedule) {
  457. // TODO omitted for brevity
  458. return false;
  459. }
  460.  
  461. @Override
  462. public Score getScore() {
  463. // TODO omitted for brevity
  464. return null;
  465. }
  466.  
  467. @Override
  468. public Badge getBadge() {
  469. // TODO omitted for brevity
  470. return null;
  471. }
  472.  
  473. /*------------Driver Program -----------------------------------------------------------*/
  474. public static void main(String args[] ) throws Exception {
  475.  
  476. DesignHECA d = new DesignHECA();
  477. String userId = d.createUser("Chandra");
  478.  
  479. /** Create Attribute */
  480. List<Attribute> attributeList1 = new ArrayList<>();
  481. attributeList1.add( new Attribute.Builder("CarOil").perUnitWeight(80.0).consumed(20).limit(60).build());
  482. attributeList1.add( new Attribute.Builder("CookingOil").perUnitWeight(60.0).consumed(4).limit(12).build());
  483. attributeList1.add( new Attribute.Builder("CandleOil").perUnitWeight(12.0).consumed(2).limit(10).build());
  484. List<Attribute> attributeList2 = new ArrayList<>();
  485. attributeList2.add( new Attribute.Builder("CrudeOil").perUnitWeight(12.0).consumed(10).limit(80).build());
  486.  
  487. List<Attribute> attributeList3 = new ArrayList<>();
  488. attributeList3.add( new Attribute("PowerSupply",340.0,880,60));
  489. attributeList3.add( new Attribute("WindPower",120.0,1,2));
  490. List<Attribute> attributeList4 = new ArrayList<>();
  491. attributeList4.add( new Attribute("SolarEnergy",0.0,0,2));
  492.  
  493. /** Create ApplapplianceCategorydd Attributes */
  494. d.addAppliance(userId,"Fuel",attributeList1);
  495. d.addAppliance(userId,"Fuel",attributeList2);
  496. d.addAppliance(userId,"Electricity",attributeList3);
  497. d.addAppliance(userId,"Electricity",attributeList4);
  498.  
  499. /** Optimize Electric Consumption */
  500.  
  501. /*------------show Electric consumption ----------------------------------------------------------------*/
  502. d.getAllConsumptionDetails(userId).forEach((k,v)-> System.out.println(k+" : "+v));
  503.  
  504. /*------------show Suggested Paths ----------------------------------------------------------------------*/
  505. System.out.println(d.getSpecificConsumptionDetails(userId,"Electricity"));
  506. System.out.println(d.getSuggestedOptimizedGoal(userId,"Electricity",9000)); //DP based on Graph
  507.  
  508. /*------------user can opt to re-calibrating his target ---------------------------------------------------*/
  509. d.modifyGoal(userId,"Electricity","PowerSupply", 600);
  510.  
  511. /*------------user can opt to schedule Washing Machine ---------------------------------------------------*/
  512. //d.scheduleFlexibleAppliance(userId,"Electricity", "WashingMachine", new Time(11,30,20));
  513.  
  514.  
  515. }
  516.  
  517.  
  518.  
  519. /* *********************************************
  520. <TODO> : Implement following Business Methods
  521. =============================================
  522. --remmoveAppliance()
  523. --getTargetGoal()
  524. --getProjectSavings()
  525. --getBadgesAndIncentives()
  526. --calculateDeviation()
  527. --getSuggestedOptimizedGoals("Electric") DP based on Graph
  528. */
  529. /*----Constructor-------------*/
  530. public DesignHECA(){ init(); }
  531.  
  532.  
  533. /*----Utility & Loaders-------*/
  534. public void init() { } //can be populated from File system
  535.  
  536.  
  537. }
  538.  
  539. enum ApplianceType{
  540. STRICT, FLEXIBLE;
  541. }
  542. enum Goal{
  543. EXCELLENT,GOAL_ACHIEVED,EXCEEDED;
  544. }
  545. enum Badge{
  546.  
  547.  
  548. // Badge with Incentive
  549. COPPER(100),SILVER(300),GOLD(800);
  550.  
  551. private int intValue;
  552. private String abbreviation;
  553.  
  554. private Badge(final int intValue) {
  555. this.intValue = intValue;
  556. }
  557. private Badge(String value) {
  558. this.abbreviation = value;
  559. }
  560. //lookup a Java enum from its ordinals
  561. private static Badge[] values = Badge.values();
  562. public static Badge getByID(int i) {
  563. return (values[i - 1] != null)? values[i - 1] : Badge.values()[i];
  564. }
  565.  
  566. }
  567.  
  568.  
  569. enum Score{
  570. CONSUMES_LOW, CONSUMES_MEDIUM, CONSUMES_HIGH, CONSUMES_PEAK;
  571. }
  572.  
  573. a. Please guide me for improving my Object Oriented Class Design
  574. b. Please guide me with examples, reference & ideas
  575. - to create TestNG/JUnit test cases
  576. - where will it be good to use Generics to make polymorphic Algo...
  577. - where will it be good to use MutliThread / Concurrency scenarios.
  578. - what all design patterns (eg. strategy) may be applied to which scenarios
  579. - to complete incomplete-implementations on some features like:
  580. Track energy, time interval, Savings, Suggest goals, WashingMachine rescheduling...etc
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement