Friday, November 4, 2011

Shopping For Electricity at WattDepot

     With the previous introduction of energy comes the idea of utilizing the data centered around it. Why do such a thing you may ask? Well interestingly, energy data could be used to research different areas while gathering data on the amount of energy consumed or produce. With this information, there could be a way to use it such that in the future when a hypothetical smart grid is developed, energy could be dispersed based on the need of a certain area. Could this be possible? Most certainly, but maybe not today.
     Today on the other hand, I introduce to you WattDepot. This web service collects electricity data from meters and stores it in a data base. This data can then be retrieved and analyzed then possibly become the basis to developing applications for a future smart grid.
     Like previous applications introduced to you in my blog, before we decide to use an application, we must learn how to use it ourselves. See the pattern? Here we go… Code Katas. The following code katas were designed to help one become proficient in utilizing the WattDepot API.

Kata 1: SourceListing
     Implement a class called SourceListing, whose main() method accepts one argument (the URL of the WattDepot server) and which writes out the URL argument and a list of all sources defined on that server and their descriptions, sorted in alphabetical order by source name.  Use the System.out.format method to provide a nicely formatted list. 
  • Using the wattdepot-simpleapp distribution as a basis, I built this kata off of it. I took out some unnecessary code such as retrieving sensor data and just left it pruning out the sources and descriptions.
  • Time to completion: 10 Minutes.


Kata 2: SourceLatency
     Implement a class called SourceLatency, whose main() method accepts one argument (the URL of the WattDepot server) and which writes out the URL argument and a list of all sources defined on that server and the number of seconds since data was received for that source, sorted in ascending order by this latency value.  If no data has every been received for that source, indicate that.  Use the System.out.format method to provide a nicely formatted list.
  • This kata was a bit tricky. I could calculate the latencies and print them along with the list, but this kata states that the output must be sorted by the latency values. My first though was to create an array and then sort it, but it might take too much time and wouldn't be efficient. Ultimately, the best solution was to create a class that implements comparable. I called this call WattDepotUtility and created it such that I could benefit from using it for the next katas, hopefully. I also note there is a delay in getting the latencies before showing the list. A user might think the program might be stalled, but it's actually doing the calculations.
  • Time to completion: 2 hours (Estimate. Most of time was spent on researching how to create my WattDepotUtility class).


Kata 3: SourceHierarchy
     Implement a class called SourceHierarchy, whose main() method accepts one argument (the URL of the WattDepot server) and which writes out the URL argument and a hierarchical list of all sources defined on that server.  The hierarchy represents the source and subsource relationship between sources.
  • Building off from the previous katas, I discovered that there is a method in the API to retrieve sub sources of a source. The problem is that this method returned the path of the sub source instead of only the name. What I did to solve this problem was to split the string at the last index of the '/' character to get the name. I also created a method that would generate a tab character (2 spaces) when the hierarchy needs to be branched out.
  • Time to completion: 45 minutes.


Kata 4: EnergyYesterday
     Implement a class called EnergyYesterday, whose main() method accepts one argument (the URL of the WattDepot server) and which writes out the URL argument and a list of all sources defined on that server and the amount of energy in watt-hours consumed by that source during the previous day, sorted in ascending order by watt-hours of consumption.  If no energy has every been consumed by that source, indicate zero.
  • Most of my time spent building this kata was learning how to retrieve the energy data and getting yesterday date. I know I need to use the getEnergyConsumed method, but I always kept getting errors. What I discovered with some testing was that if the XMLGregorianCalendar being passed it had a time with seconds and milliseconds that were not zero, it would produce a resource not found error, so these time always had to be set to zero. First problem solved. For getting yesterdays date, I went through many methods such as Calendar and SimpleDateFormat. After browsing through the API, I could my answer in using the Tstamp class.
  • Time to completion: 3 hours.


Kata 5: HighestRecordedPowerYesterday
Shopping For Electricity at WattDepotImplement a class called HighestRecordedPowerYesterday, whose main() method accepts one argument (the URL of the WattDepot server) and which writes out the URL argument and a list of all sources defined on that server and the highest recorded power associated with that source during the previous day, sorted in ascending order by watts.  Also indicate the time when that power value was observed. If no power data is associated with that source, indicate that.  Use the System.out.format method to provide a nicely formatted list.
  • In this kata, it's very similar to the previous one. I just added in a method that would get all the power values from the previous date and get the highest value. My utility class only holds a string and data (double), but the output also wants the time. I could have added another field to my WattDepotUtility class, but instead, I concatenate the time with the name and the deconstruct it before printing the result. Same like the second kata, there is a delay in showing the list, but is much, much longer to the point most users would think it froze. So I added in print statements that would tell users when it is getting data from a certain source, in this test, there where 64 sources, so there were 64 messages printed to ensure the program is doing something in the background.
  • Time to completion: 35 minutes.


Kata 6: MondayAverageEnergy
     Implement a class called MondayAverageEnergy, whose main() method accepts one argument (the URL of the WattDepot server) and which writes out the URL argument and a list of all sources defined on that server and the average energy consumed by that source during the previous two Mondays, sorted in ascending order by watt-hours.  Use the System.out.format method to provide a nicely formatted list.
  • For the final kata, I think the trickiest part is determining when the previous two Mondays were. Playing with the Tstamp class and writing a switch statement product the correct result.
  • Time to completion: 30 minutes.


     Overall with my experience using WattDepot I think it's very simple, though what you do with the data however, can get really complex. I completed all the katas listed above and most where not easy to complete as described. WattDepot is straight forward on getting energy data with many methods that probably sound what they will do such as getEnergyConsumed (getting the data for the amount of energy consumed). The katas can teach you how to sort data in a way that is easy to compare data from one source to another. In the end, this could be applied to any type of data and is not limited to energy data. Data manipulation may take some work to produce the correct output, but what really maters is how one will use this information.

Links:

Monday, October 31, 2011

Down with Oil: Renewing Hawaii's Energy Future

     It must a dream to live in Hawaii for most people, but the cost of living and lack of space would deter people from doing so. One of the more costly expenses in Hawaii is the source of energy. Hawaii has the most expensive power rate in the United States due to our heavily dependence on imported oil. Governor Linda Lingle signed the Hawaii Clean Energy Initiative that would achieve 70% Clean Energy in Hawaii by 2030. In order to promote clean energy and bring down the cost of energy, Hawaii has to change its way on getting its energy beside using oil, such as using renewable energy, use local resources and lower the overall power consumption of the state. By doing these tasks, Hawaii could become the leader in clean energy development.
     Using renewable energy will make Hawaii less dependent on imported sources of energy. In fact, Hawaii has almost every source or renewable energy such as wind, waves, solar, ocean thermal and geo thermal energies. The problem with this is that the state is divided into several islands and not all islands provide all these natural resources. For example, The Island of Lana'i would be a viral place to produce wind energy due to strong wind currents over the island, but the island doesn't need all the power. Other islands such as O'ahu needs this power, but the problem is how does it retrieve the power from Lana’i since the ocean is separating them both. The mainland consists of one giant main power grid and regions can produce or even sell its energy to other regions. In Hawai'i, each island has its own power grid and can't share it with others. If Hawaii can solve this problem and find a way to share energy with the other islands, using renewable energy will lower the over cost of power.
     Oil accounts for 77% of energy in Hawaii. This a very large portion of the energy consumption of Hawaii. Due to oil being imported, the cost to bring the oil to Hawaii effects the overall price of not just energy, but practically everything such as gas, food, clothes and jobs. When the price for oil goes up, the prices of all goods goes up along with it. By breaking this dependency on imported resources like oil and coal, the cost of living in Hawaii can be significantly lower if the state uses local resources just like the mainland.
     Local consumption of energy is high and will continue to grow, unless Hawaii finds a way to use energy efficiently. Currently Hawaii uses about 1000 Megawatts of energy everyday and is projected to rise to 1200 Megawatts in the near future. This would probably mean if Hawaii does indeed produce renewable clean energy but also increases its power consumption, the cost of energy might be less the same. If Hawaii can keep the power consumption at the same level or even decrease the demand for power, that's when the state can expect to see a decrease of price in energy. To promote lower power consumption, the state will have to work together and use power efficient devices such as replacing old lightbulbs with new CFL's or LED lights. It might be a small change for one person, but if everyone in Hawaii contributes, efficient use of power will lower the over power demand for the state.
     Hawaii has the potential to provide the state with most of its energy needs without the dependency of oil as an energy source. Using renewable energy, local resources and lowering the power consumption of the state, Hawaii can achieve it's Hawaii Clean Energy Initiative that would achieve 70% Clean Energy in Hawaii by 2030 and could significantly lower the cost of energy and consumer goods of the state.

Links:
Hawaii Clean Energy Initiative: http://www.hawaiicleanenergyinitiative.org/

Friday, October 21, 2011

Study, Stress, Study, Stress, Study, Pass The Test!

     It's the middle of the semester. Guess what time it is? Yup. Midterms!!! I know you're thinking: "noooooooooooo" times 100 while rolling on the floor stressing out, but it doesn't have to be this way. In one class of mine (Software Engineering) our professor let us students create questions for our upcoming midterm. This is what all you students should be doing anyways. Studying does equal stress, but in the end, it helps you pass the test. Now grab those box of kleenex and wipe your tears. It's time to study!
     In this blog, I've been writing about the experiences I've been through and all the new things I've learned under the subject of Software Engineering. The following are five study guide questions I've created for the upcoming midterm. It might give you some time to look back at what was learned to see if you've been up to date. Not sure if I am, but who is anyways. Keep that spirit up and see you after you pass that midterm of yours!!!

1. When generating JavaDoc for your projects, what 2 files must be created and where do they need to be placed?
     overview.html in the top-level of your system implementation. 
     package.html in the package.

2. When designing a Robocode robot, there are 3 basic moves. Name one and write the method that enables that function.
     Movement: ahead(), back();
     Radar: scan()
     Shoot its gun: fire();

3. We are using the Apache Ant build system for assignments in this class. Name one feature of Ant.
     Java-Based
     Cross-platform
     Extensible
     XML configuration files
     Open Source
     Defacto standard for Java Projects
     File-Level, but not library-level dependency management.

4. When running an Ant build file, what argument must you put before the file name to execute the build file.
     -f = Use given build file.

5. Given the following program below, which of the following automated quality assurance tool (Checkstyle, PMD, FindBugs) will produce an error?
Checkstyle will produce an error. There is no package 

Thursday, October 20, 2011

Changes Made Simple. Now Commit!

       With Robocode somewhat aside, let's move away from coding and look at projects as a whole. When working on a project alone, it's simple to keep the project up to date. When sharing And distributing projects, we ran into the problem of getting the project to work on other user systems. That's where we were introduced to Build Systems such as Apache Ant to help distribute, compile, test and debug projects. So now, how can we take projects further? Well, first step was to work on projects alone, second was to share them with others, so I guess the third logical step is to work on projects together. Many of you may think that it's just like group work where everyone splits up and do their share then come back together to piece it up. Sounds simple right? In theory it does, but there are some issues we do have to address in this situation. Having the same project on different systems causes every copy of the project being slightly different from one another after the changes that are committed. The problem with this is that how do all the developers of the project merge all there files together without overwriting everyone's changes? This is where I introduce to you Configuration Management, *Applause*. What is it? Magic? A life saver? Something that will bore you if I explain in too deep? I guess all is true. Let's summarize and say that configuration management allows users to work on a project and they could update the project that is hosted online with what they locally on their systems. When users update (Commit) the project, only the. Hanged in the project are changed, for example, one line of code rewrittenI set as Users or a renamed file. Configuration Management makes multi user projects easier to handle. 
       After being introduced to Configuration Management myself, I decided to try it out  using my Robocode project. For this experiment I used Google Project Hosting as my hosting site for my project and Smart VN as the Configuration Managment. After some speed bumps trying to get my project to upload into the server, I finally got it to work. While playing around with the system, I made some updates to my projects such as formatting and better javadoc. These changes causes the revision number to change and I can use this to see what changes were made since the original upload. With Google Project Hosting, it was simple to create some wiki pages that I set as user and developer guides. The SVN client SmartSVN was also simple to use to upload and commit changes to the project. The only initial problem was setting it up, but most of what I needed to know was listed in the Google Project Hosting site. Overall with my experience, I thought it was a simple process. I can see why this is another handy tool for many developers.

Link:
Robocode-cel-wayfarer Project: http://code.google.com/p/robocode-cel-wayfarer/

Monday, October 10, 2011

Your Robot's Way Far! Errr...

     Hey, it's robot's again! Have you been perfecting your's since my last post? I guess you did since you're here. Well, I too have been working on making my robot better. By utilizing some of the things I learned from the katas, I experimented ways to make a robot that could compete with some of the included sample robots of robocode. In my opinion, it's not the best robot, but it's decent and I call it WayFarer! (No, not sunglasses, but thought it sounded to cool to name it after it.)

     For my robot, I took some note from the code katas from the other blog. The design is basically my robot moving back and fourth along an axis. When the robot moves, it scans for enemies, turn its gun towards the enemy and fires every other turn. When the robot hits another robot, it moves away and when the robot gets hit by a bullet, it turns 90 degrees and traverses that axis. So how does this robot perform? Let's see!

     Moving on to testing. I put my robot against 8 of the sample robots:(Corners, Crazy, Fire, RamFire, SittingDuck, SpinBot, Tracker and Walls.) For this test, I ran 100 battles each and recorded the scores. Here are the outcomes:

Enemy Challenged
Rank Against Enemy
Total Score
Survival
Survival Bonus
Bullet Damage
Bullet Bonus
Ram Damage
(x2)
Ram Bonus
1sts
2nds
Corners 1st 15493 (87%) 4850 970 8033 1579 31 0 97 3
Crazy 1st 9380 (69%) 2800 560 5196 700 124 0 60 40
Fire 1st 13177 (92%) 4900 980 9417 1852 29 0 98 2
RamFire 1st 15027 (53%) 3100 620 9492 1201 450 163 62 38
SittingDuck 1st 18034 (100%) 5000 1000 9966 2000 68 0 100 0
SpinBot 1st 9988 (61%) 2900 580 5668 791 49 0 59 41
Tracker 1st 17209 (71%) 4050 810 10366 1742 208 34 81 19
Walls 2nd 3060 (22%) 100 20 2815 41 86 0 2 98

     As you can see, WayFarer is a decent robot, but definitely not the best. It can only defeat one sample robot 100% of the time, but majority, it comes in first place. It;s not perfect, but good. WayFarer is a good robot because it moves constantly and changes direction to dodge incoming bullets. This might be a good strategy, but one robot isn't affected by it, meaning the walls robot as you see on the table. WayFarer doesn't go well against walls because it travels along the "walls" of the battlefield while tracking and shoot. Walls also moves in constant motion, so many bullets shot by WayFarer miss the target. What could be implemented to make WayFarer better is to predict the future location of the enemy to ensure that bullets will hit the target all the time.

     Building more on testing is some JUnit tests I created to tests some robot behaviors. My 4 tests include testing if WayFarer hits a wall, changing direction after being hit, turning its radar to scan enemies and seeing if bullets shot hit the enemy. When WayFarer hits the wall, it confirms that the robot traverses an axis. When WayFarer get's hit by a bullet, it should change directions of the traverse. When WayFarer turns its radar, it ensures that it is scanning and when a shot bullet hits an enemy, it ensures that the gun is pointed at the enemy.

     Overall, designing the perfect robot is not easy. There are some robots that are easier to defeat while others require more thinking. During this development using the Ant build system, inning testing and checking for errors are simple to do and faster than running them manually. Creating projects are now easier to transport for other users to use since the build system automatically installs and downloads required files. I can now see why build systems are viral to many projects and I intend to use it for future projects.

Tuesday, September 27, 2011

Awesomely Nifty Thing

   There are many tools in the programming world that help make things easier to do. Let me introduce you to this awesomely nifty thing by taking it's acronym: ANT. What is ANT? Well for starters it doesn't mean awesomely nifty thing like the title states it to be nor it is those tiny black creatures you find on your picnic. What is it then? ANT actually stands for Another Neat Tool… Yeah, my title might seem similar to its actual name, but hey, Ant is both awesomely nifty and neat.
     Developed by the Apache Software Foundation, Ant is a tool for automating software build processes. I'm not going into much detail what a build system does, but basically it is scripting that can compile, package, test, create documentation and deploy code.
     Ant is like a programming language that uses XML which I don't have much experience with, so to test out the functionalities of Ant… Yes, you guessed it, Code Katas. The total of eight Ant Code Katas creates the HelloAnt Program. Overall, these katas did show me the basics of Ant. The first three katas introduced printing to the console, the immutable properties of ant and dependencies which are conditions. The rest of the katas mixed in a bit of java with the scripting. With the help of the Ant API, it was fairly simple to compile, create javadoc and package the entire directory. These scripts are just simple shortcuts that otherwise someone would type manually in the console and they save time.

Monday, September 19, 2011

Kode Cut a Row Bow Code

     Who is Kode? Why did he cut a "row bow code"? What is this about? Say it slow: Kode-cut-a-row-bow-code. Now say it fast: Kodecutarobocode. Keep saying this phrase with practice and repetition then you'll get Code Kata: Robocode.
     For those who may know what this is about, did you see the analogy there? Well, basically what we did in this introduction exercise was to practice and repeat doing a task. In programming, a Code Kata is referred to an exercise which helps a programmer build their skills through practice and repetition. This is the first part of the topic. So this leaves Robocode as the second part.
     In short words, Robocode is "Robot Code". Robots programmed in Java compete with others through movement, radar and attack. There are many ways to design a robot, but how do you design the "best" robot? Well, first you need to… STOP! Before building the "best" robot, we need to start off small and deal with the basics first: code kata.

     The following list are simple robot exercises created to test out the basic robot functionalities:
  • Position01: The minimal robot. Does absolutely nothing at all.
  • Position02: Move forward a total of 100 pixels per turn. When you hit a wall, reverse direction.
  • Position03: Each turn, move forward a total of N pixels per turn, then turn right. N is initialized to 15, and increases by 15 per turn.
  • Position04: Move to the center of the playing field, spin around in a circle, and stop.
  • Position05: Move to the upper right corner. Then move to the lower left corner. Then move to the upper left corner. Then move to the lower right corner.
  • Position06: Move to the center, then move in a circle with a radius of approximately 100 pixels, ending up where you started.
  • Follow01: Pick one enemy and follow them.
  • Follow02: Pick one enemy and follow them, but stop if your robot gets within 50 pixels of them.
  • Follow03: Each turn, Find the closest enemy, and move in the opposite direction by 100 pixels, then stop.
  • Boom01: Sit still. Rotate gun. When it is pointing at an enemy, fire.
  • Boom02: Sit still. Pick one enemy. Only fire your gun when it is pointing at the chosen enemy.
  • Boom03: Sit still. Rotate gun. When it is pointing at an enemy, use bullet power proportional to the distance of the enemy from you. The farther away the enemy, the less power your bullet should use (since far targets increase the odds that the bullet will miss).
  • Boom04: Sit still. Pick one enemy and attempt to track it with your gun. In other words, try to have your gun always pointing at that enemy. Don't fire (you don't want to kill it).

     Now let's create them robots! Ready, set, GO!


     Okay, thanks for waiting while I was creating these robots. Some were easy to implement, while others took a lot more thinking to get it to run properly. Let me go over the robots I created in the three groups:

     Position
          This first group of robots practices with moving the robot. Position 01, 02 and 03 were straightforward using turns and moving the robot ahead. Then I got to writing out position 04. This robot could be implemented in… I would say 2 ways. The first is the simple method of moving the robot to the same X or Y coordinate as the center point then traversing the remaining axis to the center. I created this robot first but wanted to be adventurous and try the second method which involves a little trigonometry. a2 + b2 = c2? Right. This method calculates the distance to the center, rotates the robot to face the center, then moves it to the center. I drew it all on paper before attempting this method and it went well. The robots correctly moved to the center in every test. Here are some of the drawings I did for this algorithm:


These drawings may look confusing, but I totally understand it and it works. Trust me, it does.

          Now to position 05. This method builds off of position 04 to move to the corners instead of the center. Finally, position 06 is basically position 04 plus a circle. To create the circle, I figured that since the robot will need to travel the circumference and there are 360 degrees in a circle, the robot will need to travel (circumference / 360) and turn 1 degree at every turn. The outcome was that the robot did move in a circle with the given radius, but it was very slow because the robot moved forward and it turned after moving instead of doing these two methods simultaneously.

     Follow
          These robots introduced the radar functions of the robot. All three were very similar in design which involves using the radar and moving when an enemy is detected. For the first two follow 01 and 02, we needed to only had to follow one enemy, and to do that you just scan the robot and get its name. If the name of the enemy scanned is the same as the previous enemy, then move, otherwise continue scanning.

     Boom
          The final set of robots brings in the gun of the robot. The first two robots Boom 01 and 02 were the same and differed by one thing. Boom 02 only fired at the same enemy. With these two robots, you simply rotate the guns and when the radar detects an enemy, you fire the robot's gun. Boom 03 builds off Boom 01. Instead of firing the guns at the same power, we get the distance of the enemy and fire the guns at a power according to the distance the enemy is away. Finally Boom 04. This is the only robot in this group that doesn't actually boom (Fire its gun). The algorithm here is to track the same enemy as in Boom 02, but rotate the robot's gun to always point at the enemy.

     Overall by completing these code katas, I learned more about the robocode class. I guess if you practice robocode by doing these code katas you will learn more about the rodocode API, don't you agree? So how about getting to designing the "best" robot? Let's not get into too much detail, but for me, a "good" robot has a great combination of movement, radar and attack. A "good" robot should know when to move and when to stay in position. It should also have a good defense system that detects all obstacles and treats and decide how to overcome them. Lastly, the robot should also have good offense. It should know when to attack and decide if it will hit an enemy instead of missing all the time. That's what I think the "best" robot is, however, there is an advanceRobot class in the robocode API. This allows for more advanced control over the robot, but for this topic, let's just stick to the basics and create something advance with the tools we have.
     Generally these code katas make you think in different ways to solve a problem. Sometimes you can approach a problem in a simple matter whereas others can be more complex, just like how I approached the position 04 robot. There are many ways to do one thing and there is no wrong way to do it if it works correctly. It like every day life. Practice makes perfect… Well nothing is perfect, so let's rephrase, practice makes better! So what do you think of robocode now? Cool or cool??? Try it out, take on these code katas, practice, and you could possibly design the best and destroy the rest! Good luck to you!

Links:
Robocode Home: http://robocode.sourceforge.net/
Robocode API: http://robocode.sourceforge.net/docs/robocode/
RoboWiki: http://robowiki.net/wiki/Main_Page