Sunday, November 24, 2013

Kovalam and Crocodile bank

https://www.youtube.com/playlist?list=PLI1zEI7akO9yURviZvcnvOB0FiboGXg1L

Popular column in Hindu by his wife is an awesome read.

http://en.wikipedia.org/wiki/Madras_Crocodile_Bank_Trust

Saturday, June 22, 2013

Chain-i-II


And then Chennai talked to me through gestures. Faint movement of the droopy coconut leaves while the almost still waters waved at me. The beauty was breathtaking. and the fact that the beauty was right in the city, within a kilometer of my aunt's place, I have to take back my ridicule of miniscule issues.
And added to that, a radio channel dedicated to English songs makes up for the lack of Bollywood channels.

Wednesday, June 19, 2013

Chain-I


is the new home. The real deal are the trains. The lovely thing is how they don't have to bother about traffic, how they weave through picturesque locations maintaining their promise of leaving you at that urban end you expect, with a rhythmic background sound and the dull feeling of doing nothing, all the while zeroing in on the destination. Chennai has a good connectivity system using trains and they are way more comfortable than the average transport systems, even personal. While the weather promises improvement almost everyday, but manages to not deliver, the electricity board manages to increase the pain by doing away with current at the prime points of every night when sleep wants to slip into the soul. Add to this, the threat of mosquitoes from the open window and we have a perfect combination for insomnia. A/C goes off with power fluctuation, no ventilation calls for opening the windows and open windows are a free buffet invitation for the killer insects. All that said, this city looks beautiful in the night. I can see tree covered hills and water bodies reflecting the moon and the faintly lit clouds crawling their way across the sky with a range of stars arranged as we read in the books and as we expected to see them someday. As I change gears yet again, the promise seems wider and the tunnels seem deeper, hopefully this train will cross the tunnel soon and break on through to the other side.

Monday, May 13, 2013

First steps towards maze designing

I decided to go with a graph data structure(adjacency list) to build a rectangular maze. The maze would be designed in a fashion that the vertices would be the nodes of the path and the edges between the vertices would be positions where walls can be inserted.

I maintain a list of vertices with each vertex data structure having an array list of edges. An edge data structure would consist of two vertices.

Once I fill in my data structure, I start building the maze. Oh, I also need a stack for backtracking if required and also an array to check if a vertex is visited. From the start vertex, I pick a random neighbour which is unvisited and move to it after labelling the initial vertex as visited. I keep moving until I hit a position where are there are 1) no unvisited neighbours available or 2) I reach the destination. If 1, then I use my stack and back track.

The challenge now remains with drawing the randomly built maze.

Monday, May 06, 2013

The long seasons

I waited. I waited till I was provided. And then, I waited. I would observe a struggle to come out of a cocoon, a peck on bugs to enjoy a happy meal.  I had my own patch of earth and I was proud of it. 

I would be lying if I said I never wanted to know more about life. I wanted to know how I could grow, how I could improve, I wondered what sort of knowledge my ancestors held and if the knowledge was transferred. I often basked in the sun, making my food and thinking about life. I wondered if I had a specific function in life. I wondered if there were emotions that I could unravel. At times, I would feel thirsty.

I could feel movement with light. Sometimes, movement without it too. A good day would go by when I would just keep thinking. Sometimes, I would be bitten into, leaving me injured. I would wonder if there are others like me. Others who could grow, others who could compete. And then, I would wonder if I could live up to them if there was competition.

Slowly, the light faded. It stopped coming as it used to. I hoped that things would be the same again, but reality stood steadily defiant against my hope. Slowly, I started getting thinner and thinner. I was waging a losing war. I tried hard, I tried to somehow make light, but I could not. I remember the day I thought would be the last. The day after which I do not remember for a while. And then, when I woke, there was light. I slowly felt the familiar heat, I loved.

I knew I could grow now. I tried to make the best of a positive verve. It was great till it lasted. I was delighted and made no attempt to hide my delight as I dressed in my best colours. Colours which would often be stolen away.
And then, the light and the heat started burning me. There was never enough water to quench my thirst as I was sapped. This time I knew it was the end. I waited, as slowly, all my vitals stopped. I waited and thought if there were more.

-----------------------------------------------------------------------------------------------------------------------------
The plants are dying.



Monday, April 29, 2013

The forest fire in the Americas has been kindled

And was an experience unmatched. It started out early in the morning at nine and ended late in the evening around seven forty five when I finally started the long drive back with much exhilaration as I could feel that the spark had been lit and it was just a matter of time before the call would come back, a hint of disappointment as the level kindled was not > 1, but it appears that the level can be spiked before the next monsoons. Ah, the smell of moist earth would feel great when making stuff for the electronic book buffs.

Wednesday, April 24, 2013

Stop the '-gate' nomenclature

Coalgate, porn gate and now chitgate. What is it with so many gates?

After some search and our friend wiki I found that the gate reference started with president Nixon of USA because of a building called Watergate and of course Nixon's involvement. Dear Indian media, I did not understand the reference atleast not till now, and I am an average Indian. Put me in a sorted array of intellectuals and I would be somewhere near the average. Imagine how many people would be to my left. Also imagine that these many people might not be able to connect with gates other than of course, our Bill.

Throw out the -gate word. Find something more appropriate. Search for a good word, a suffix that can go along with all corrupt scams by choosing one of unheard proportion and attaching a related word. Or something smarter, people to the right of the array of intellectuals need to work on this, so that people on left can understand.

oh, by the way, I find it appropriate to mention the word colgate here and I hope they can use these -gate suffixes to their advantage in some cool ad.

Tuesday, April 23, 2013

Hi! This is java. Just passing by

Passing by What?

Is it by value or it by reference?

Let's see how we can go about understanding this. Java uses references to point to objects. So, when I call a method which has an argument of an Object A, what we are sending is a copy of the reference we created into the method. Oh! that means we are sending the argument by value. Really? whether it is the reference outside the method or inside, both point to the same object so, both are actually references to the same object and any change in the attributes of the target object would reflect back.

Simply put, if java was passing an object by value, then we would not be seeing changes. But hey! java does not even pass objects, it passes references. These references are obviously passed by value. Why, you ask? Well , let's make a reference to an object and call a method with this reference as an argument and inside the method we point to another object. There would be no changes in the original reference, although the one inside the method would now point to a new object.

So, java has references to objects which are passed by value, but the references themselves both point to the same object.

So, to conclude why people think java is pass by value is because we pass references a copy of which is passed to the method, so Aha! it is pass by value. But then, I ask arent both references referring to the same object in which case we are sending a link to the object by reference.

My take : it is all perspective. with respect to a reference, it is pass by value, with respect to the actual object, it is pass by reference.

Java passes references by value.

Also, while we are at this, it is worthwhile to notice that primitive objects are always passed by value.

Bonus Example: send an array as an argument and edit stuff, you will see a change in original array.  


Thursday, April 18, 2013

KMP algorithm

Getting my feet wet with some string pattern searching algorithms, I think the KMP makes headlines everywhere so I started off by downloading their publication from here

Reading the paper makes it crystal clear, although the volume(28 pages) might appear daunting, the first 5 pages finish up the explanation required for understanding how to go about KMP-ing.



Sunday, March 31, 2013

How to know more about a phone from it's name

My Pagan beliefs about phone nomenclature:
Whenever I see an HTC phone, I believe I am looking at an HTC one. And more often than not, my belief turns out to be true. After enough ones, I thought I should visit their site and see what all names have they given to their phones. And What do I see, hordes of phones all called one. I mean, how can you have more than one one? And then there is desire. There are enough desires with HTC that I can safely believe in phone polygamy.



Onto Micromax: Choosing a micromax phone is like deciding how many naya paisas we want to shell out. I mean A116 > A 87 and so on. I believe they have a simple strategy if you want to buy a phone. Arrange all their phone models and sort them. (remember, it takes n*logn only). Then do a binary search using our maximum budget versus price of the selected median.

Next comes YOLO: or was it XOLO. I guess the two strings are too close for comfort. But if they still chose the name, I guess they might as well appeal to the YOLOs buy saying XOLO because... YOLO. XOLO goes with a prefix [A, B, Q, X]. My understanding: A for android, B for android, Q for quad core android and X for intel android. How do we choose a YOLO phone? Again put them all in a sorted fashion. Enter max price feasible and perform binary search independent of the prefixes. Why, you ask? YOLO.

But of course, our favourite Samsung needs to be in this delectable list too. Samsung: If you own a samsung phone and it dont have a galaxy substring in it, it dont have swag, dog. What suffixes do we have for our galaxy? Wait, why is it galaxy? Coz these phones work only in the milky way duhh. Sound fine. So galaxy ace, beam, chat, S followed by increasing numbers and prices + added advantage of chronological ordering(got lost, oops),  y, not(e) and wait for it: a minimal set of non-galaxy variety too: they are called wave. I guess you need to wave your hand and call out people when it doesnt pick up enough signal.

What about the android majors google? I guess most logical: start with the word nexus, add up 4, 7 or 10 according to approximate screen size.

I love Nokia's naming schemes: the windows ones are called lumia because they light up your life with their art and for people who lose their phones, niraasha ki zaroorat nahi as there always is aaasha, a phone you can buy with a student's stipend.

Apple doesnt sell phones older than 2 releases I guess: so you have iphone (insert latest number) and iphone (decrease last inserted number by one) . Simple and hassle free as that is what an iphone buyer is interested in, I believe.



Sony: it has GOT to be an Experia. and all blame on that mango juice ad that even when Katrina throws water on the phone, all I can imagine is why is a phone being shown in a mango juice drink advertisement?


Saturday, March 23, 2013

ROS tf issues

I set up a launch file following a simple map building tutorial through simulation and hooked it with a good map so that I can have interesting trials with navigation. Once I set up everything and moved the robot around, I had two main questions? Where is the map published?

I could find services using rosservice list and found a /dynamic_map which I subscribed to.

One more pre-requisite before the navigation test was the attempt to see if the transforms were available.
rosrun tf view_frames
 
would generate a pdf file in the folder giving all transforms. Any problem with naming or transforms would be clearly visible as a node not having any connections. In my case, the map was connected to odom but there was no connection between odom and base_link, preventing me from moving the robot.

Rather odom_combined was connected to base_link and renaming the out to odom_combined solved the problem.


Tuesday, March 12, 2013

My Experiments with sneezes

A weird disease hit me late December when I started working from home. Almost everyday after I went to sleep, I would get up with an extremely itchy throat and a series of unending sneezes after which I would be a victim of post-sneezatic stress and would await the return of my body to normalcy for about another hour after which I could finally rest in peace(for the day). This disturbing syndrome led to recurring visits to first an allopathy doctor who gave anti-allergy tablets, followed by sugar pills homoeopathy doctor. Stopping the anti-allergy pills would revive my sneezy syndrome and the homoeo medicines proved good only for my sweet tooth.

A two-month experiment with different foods only led to the conclusions that I could reduce my day time sneezes by reduction of citrus intake but it had no effect on my nocturnal syndrome. Lots of sleepless nights and infinite sneezes later, I finally stumbled onto something during my late night  sleepy stupor after the sneezes when I was randomly browsing when I had typed all permutations and combinations of the words 'allergy', 'sneeze', 'after sleep' for the past sixty days, I finally found an answer.

The liver. One of the few organs I never knew much about. The liver is one of the prime organs of the body and contributes to filtering about everything. My liver was acting against me and releasing histamines. It said the liver tries to cleanse itself around 1-3 AM and it was just a comment on some post(link, search for comment by Madhavi). I just hoped that this find would be true and that I could conclude my experiment. So, I went on a strict fast of only fruits( including citrus ones) to see if I would get my nocturnal sneezy stuff.

Lo and behold!! I stand cured. My experiments are as a curious and a concerned patient and have been rewarded but I advise that this be taken only as advise and should not be understood as equivalent to a certified medial practitioner's opinion.

And that is the story of how I have been doing well since the last three days, by limiting my diets to foods that can go easy so that I give time to my liver to detoxify.

Saturday, March 09, 2013

Finding the loop starter of a linked list with a loop


A very popular problem is finding whether a linked list has a loop. The solution basically uses two pointers, one at normal pace and one at 2x pace. Let us assume two people are running a race. The race starts from a starting point, say my home. Then, both runners reach a park and do some laps around the park. Slow guy - S and Fast Guy - F. Fast guy goes at twice the speed of slow guy, reaches the park and keeps doing laps when finally both slow and fast guy meet at some point. Let us try to model this mathematically. When the slow guy enters the park, assume he would have covered C nodes. The faster guy, F, would have done 2*C. Let us now add another variable k, which is the distance of F from the loop start. And another variable, the loop size, let us call it n. Now, let us imagine when both runners meet. By the time S covers half a loop(n/2), F covers n and has a headstart of k, so he would have covered n + k. By the time S covers a distance of n - k, F covers a distance of 2*( n - k). Given the headstart of F, he would be at 2*(n - k) +k = 2*n - k. Since n is a circular loop, this translates to position n - k. So, both S and F meet at n - k. Now, Let us send F back to the start and ask him to do this slowly while we keep S walking at normal pace. When F would have covered C (yeah! our first variable from the start to the mouth of the loop), S would have walked C too. Now, going back to some interesting stuff about C. When S covered C, F covered 2*C. that means from the mouth of the loop, it have moved C nodes. That means C = b*n + k. so, when F covers C he will be at the mouth of the loop, but when S covers C from our earlier meeting position, that is n - k, he would have covered: n - k + b*n +k = (b+1)*n, i.e. he too would be at the mouth of the loop. This took me some real time to understand, so I am adding pictures to help.

Here is the main resource that led me towards the solution and has put up wonderful illustrations to understand: http://umairsaeed.com/2011/06/23/finding-the-start-of-a-loop-in-a-circular-linked-list/

Wednesday, March 06, 2013

Navigation in ROS

I would like to check the ability of the turtlebot to navigate from one point to another on a built map using SLAM. I believe these are the sub modules that need to be taken care of:

1. build a map using gmapping or some laser map.

2. Whenever the map is used on the robot, make sure to localize using amcl.

3. Get coordinate of target point on map with respect to map coordinates.  (My last post on ROS should do the job, although I am yet to verify it )

4. Give the coordinates in the form of simple navigation goals following the simple tutorial at ros.

Primitive but necessary work, and in fact, one of the building blocks that will be re-used almost for everything to be built, I guess.

Lie Detection

So, I was reviewing an episode from Lie to me and then went to Paul Eckman's site and looked up the resources on lie detection. I wanted to know if there were any softwares which would attempt to detect lies from facial microexpressions on the basis of extensive training using machine learning. The catch is first convincing yourself that you can get a 100% accuracy and then convincing the world with a proof that we can crack the liars. Seems quite the dream, but I would love to work towards it. From the perspective of a first time plan, I believe we can divide the job pretty easily.


Get datasets of all facial expressions.

train system on all expressions.

Run system on suspect while asking questions and see results of different micro-expressions made by the accused.

The challenge: Are the features of micro-expressions which are the basis for emotion detection reliably trackable?

Here are some relevant products I could find :
http://www.noldus.com/human-behavior-research/products/facereader
http://www.affectiva.com/affdex/#pane_overview
http://nviso.ch/technology.html


And here seems to be a relevant paper.

I will go through related materials and get some more content into this post in the weekend.

Tuesday, March 05, 2013

ROS


Currently, perhaps the most popular software for robotics, ROS(Robotics Operating System) has been one of the long pending to-do items. Finally, the time and the task
came together in the form of PR2. 


A brief visit to the Tata Elxsi campus in Bangalore gave me a very clear understanding of the task at hand and the related challenges. The first module was to help the robot move from one point to another. To get map coordinates on to the robot, I wrote a small code with some opencv to intercept clicks and with help from Karthik Desingh's code for conversions. I believe we are good to go. A map server is first switched on to provide a static map which has been developed by gmapping earlier. Then our program is run which uses the service provided by the map server to get map data onto a Mat data type of opencv. Then, I resize the mat as the image was larger than my screen resolution and then finally load it up onto the screen. A click on the screen causes a callback which calls a converter method which finally prints out what we want. Here are some screenshots:
Might require close observation , but the second screenshot is where I click and a grey point is visible where I clicked.

On the shell, I print the info I need about the robot's pose in the context of the built map:


Here is the link to my small ROS repo: git@github.com:gururajkosuru/ros.git



And some resources from the ROS home page which I feel are good to start off with :
http://www.ros.org/wiki/Events
https://www.youtube.com/user/WillowGaragevideo
http://www.ros.org/wiki/Courses
http://www.ros.org/wiki/Papers

Wednesday, February 27, 2013

PR2


After a long wait, I was finally introduced to a PR2 today. The day ended on a high but my conversation with the PR2 was still left wanting. The amazing hardware capabilities along with the modular software make it one of the most-easy-to-tame beasts. Perhaps as the week progresses, there would be a chance to look into working end-to-end on a simple solution with the PR2. What is amazing about the PR2 is the array of sensors it boasts which make it very powerful. The grippers with their tactile sensors, which can ensure a soft touch along with a tilting laser scanner for a 3D scan along with a base laser scanner and of course the multiple stereo eyes make it an amazing piece of technology with immense scope for applications in all realms. But the question that arises from the first interaction is why does the PR2 collide with cups on the way when it does see them? Hopefully, the end of this problem would be visible before the week ends.

Tuesday, February 26, 2013

The Google Glass Project


One of the latest innovations being tested by google, the google glass is like any other pair of spectacles except for a display on the right eye and a voice based input which takes commands. It would be very interesting to see how reliably the glass takes instructions given difference accents and of course given background noise. A potential application that I see specially for people who keep forgetting the names of acquaintances would be a face recognition, a place recognition among things. I have already seen videos showing routes from GPS, routes nearby restaurants, shooting photos and videos on command. I also wonder about the possibility of gesture recognition in the glass. All in all, I see it as another sci-fi dream bend towards reality but the scope of the product, still not completely clear. I understand the google glass to be a mobile phone accessory with a GPS and a touch pad on the side. Primarily voice based commands. The verge guy had an outing with the glass at google HQ and has a post on his experience which is the closest I could get to knowing more. Here is the link. He claims it is a question of when rather than if and that is perhaps the most powerful way to close the debate.

Sunday, February 24, 2013

Motion capture with xtion pro





Oooh!! Plug the Xtion capture into the USB and cool effects seem automatic, Here is the first thing that I did after figuring out that there are so many cool things that people have developed already. Ran them to see the results. So, it is blender, PCL, OSceleton and the kinectblendertemplate for this show.


Xtion Pro hand tracking

Saturday, February 23, 2013

Balancing a binary search tree

This is a problem and a solution that I thought of while reading about binary search trees which have the property that each node has at most two children and all the nodes in the left sub-tree of a node are always less than or equal to the considered node and the ones in the right subtree are always greater than the considered node.

The problem basically arises when the tree is unbalanced. The search times in worst cases go by the order of the height of the tree and a badly balanced tree can cause bad search times. The question primarily asks, given a BST, how can we give a balanced version of that BST?


How did I approach the question?

I first felt that we needed a in-order traversal of the tree. An in-order traversal gives the nodes in increasing order. Obviously, it would be great if the median can be the new root. For each subtree, using the in-order traversal, we can recalculate a balanced version recursively.

The primary recurrence uses as input the nodes of the tree put into an array in in-order. For a subtree from index i to j, the root would be the mid of i and j and it's left subtree would come from the same recurrence from i to mid and the right subtree from mid + q to j.

Here is the method:

node balance(int min, int max,node[] arr) {
if(min == max)
return arr[min];
int mid = (min + max )/2;
node curr = arr[mid];
curr.left = balance(min, mid-1, arr);
curr.right = balance(mid + 1, max, arr);
return curr;
}

Here is the git link.

My opinion on Coursera Offerings I have taken

My interest was held intensely by courses on algorithms. Both courses are being(have been) conducted in two parts, one version(Stanford) by Tim Roughgarden, who in my opinion primarily showcases the theoretical background necessary required for dealing with new problems by filling our quiver with a set of tools. The other version(Princeton) by Robert Sedgewick and Kevin Wayne deals with the more realistic problems of understanding practical applications and how to use pre-defined API and how to estimate the complexity of a written code in more realistic terms than our big-O notation. All in all, I have had a very good experience with the Tim's courses and now I am onto Sedgewick whenever time permits.

There is also a guitar and a songwriting course starting up and now that I think of it the bathroom singer needs to improve!!

Not much updates with my iRobot Create and Xtion pro, but the next acquisition(adapter) will bring about some interesting enhancements.

Saturday, February 16, 2013

Another DP problem

AvoidRoads

Another fun albeit a more straightforward problem. This one could be solved quite in a straightforward fashion by assuming the recurrence that for the given vertex, a path can only be drawn from two vertices one to the left and one below it. And the sum of both paths to this vertex is the total number of paths to this vertex.
A pictorial representation of my breakdown:
In the above diagram, the red point is the final destination.
 The pink points are the subproblems for the the red one, the paths from where we can reach the red one. For the Pink vertex to the left(x-1,y), I have shown two green points as the subproblems, and for the other pink one(x,y-1), I have shown a brownish color for the subproblems. Because of an overlap, one of the green and brown vertices have been drawn smaller than the others. 

Here is my method as code:


public long numWays( int maxX, int maxY, String[] bad) {
this.maxX = maxX;
this.maxY = maxY;
processBads(bad);
pathArr = new long[maxX +1 ][maxY + 1];
for(int i = 0; i <= maxX; i++)
for(int j = 0; j <= maxY; j++)
pathArr[i][j] = -1;
return pathsRec(maxX, maxY);
}


public long pathsRec(int x, int y) {
if(x <0 || y < 0)
return 0;
if( pathArr[x][y] != -1)
return pathArr[x][y];
if(x > maxX || x < 0 || y > maxY || y < 0)
return 0;
if(x == 0 && y == 0)
return 0;
if(x == 0 && y == 1 && valid(0,0,0,1))
return 1;
if(x == 1 && y == 0 && valid(0,0,1,0))
return 1;
long path1 = 0, path2 = 0;
if( valid(x, y, x-1, y) )
path1 = pathsRec(x -1, y);
if( valid(x, y, x, y-1) )
path2 = pathsRec(x, y-1);
pathArr[x][y] = path1 + path2;
return  (path1 + path2);

}


public boolean valid(int x, int y, int x1, int y1) {
if(x > maxX || x < 0 || y > maxY || y < 0)
return false;
for(int i =0; i< blocked.length; i++) {
boolean cond1 = x == blocked[i][0] && y == blocked[i][1] && x1 == blocked[i][2] && y1 == blocked[i][3];
boolean cond2 = x1 == blocked[i][0] && y1 == blocked[i][1] && x == blocked[i][2] && y == blocked[i][3];
if(cond1 || cond2 ) {
return false;
}
}
return true;
}


public void processBads(String[] bad) {
blocked  = new int[bad.length][4];
for(int i = 0; i < bad.length; i++) {
String[] temp = bad[i].split(" ");
blocked[i][0] = Integer.parseInt(temp[0]);
blocked[i][1] = Integer.parseInt(temp[1]);
blocked[i][2] = Integer.parseInt(temp[2]);
blocked[i][3] = Integer.parseInt(temp[3]);
}

}

Another Dynamic Programming

ZigZag Problem

This problem gives an input array of int asks to find the length of a longest subsequence in which the difference of successive numbers has opposite signs.

The problem took an extraordinary effort to register and find the recurrences and although I must have seen something like this before, breaking into the recurrence took too long. The recurrence I chose finally was :

 for an element at index i in the array, a longest subsequence can be either by having a greater number than element[i] or an element lesser than element[i]. So, there can be two kinds of sub-sequences for each element, one kind for which the element before the current is smaller and the other subsequence in which the element is larger. (Subsequence 1: element[i], the last element is greater than the one before it, Subsequence 2: element[i], the last element is less than the one before it)

The recurrence would turn out to be:   the maximum subsequence of kind 1 for element i would be the maximum subsequence of kind 2 for all elements before the index i and similarly max subsequence of kind 2 would be max subsequence of kind 1 for all elements before the index i. The length of a longest subsequence would hence be the maximum of the length of both kinds of the subsequences.

Here is the method I wrote recursively without bothering for speed.

 
 public int longestZigZagRec(int[] n, int index, boolean pos) {
  if(index==0)
   return 1;
  int posMax = 1,negMax = 1;
  if(pos) {
   for(int i=0;i<index;i++) 
    if(n[i] < n[index])
     posMax = max(longestZigZagRec( n, i, !pos) + 1, posMax);
  }
  else {
   for(int i=0;i<index;i++)
    if(n[i] > n[index])
     negMax = max(longestZigZagRec( n, i, !pos) + 1, negMax);
  }
  
  int temp = pos==true?posMax:negMax;
  //System.out.println(" from index "+ index+ " longest zigzap length is " + temp +" for "+ pos);
  return pos==true?posMax:negMax;

 }

I call the code like so:
  ZigZag z = new ZigZag();
int [] in = {20,10,1,7,4,9,2,5};
System.out.println(z.max(z.longestZigZagRec(in, in.length-1, true),z.longestZigZagRec(in, in.length-1, false)));

Wednesday, February 13, 2013

Hello Depth

That one is from OpenCV, got depth maps from PCL and Nite too. Just ran the sample openn_capture.

PCL , the Point Cloud Library

A clean install using apt-get did not satisfy my needs as I needed the experimental one. So did an install from source and then ran apt-get install and it suggested that some of my libs were redundant and suggested to remove them. 
Did an autoremove with apt-get and now my PCL dependencies have gone. Here is what sufficed:

sudo apt-get install libboost-dev-all libvtk5-dev
and then the same exercise of  sudo ./install.sh in each of OpenNI,Sensor and Nite folders and we are back on good terms with the Xtion pro.

PCL experimental from source asked me to do:
sudo apt-get install libeigen3-dev libflann-dev and vtk was already installed above. So waiting for some kungfu with kinfu
 UPDATE:
Sigh!! Kinfu needs CUDA support!! Cant' run it on my laptop.  Need to setup on desktop and run remotely on laptop.

Help on OpenCV from source: 
http://renzhi.ca/2010/06/09/how-to-install-opencv-on-ubuntu-from-source/
http://varuagdiary.blogspot.in/2011/09/installing-opencv-23-on-ubuntu-1104.html

Monday, February 11, 2013

IRobot Create

Truck loads of limited edition gratitude to Satish and Madhan for delivering what should be the beginning of a great experience. All it lacks for a little unboxing + first run show is a 200-110V converter. Here is a sneak peak of the goods:



Also, this marks the 200th post on this blog. A fitting one indeed!!

Time to go Xtion Pro

Satish and Asus have brought together an Asus Xtion Pro live to me finally. First hours of experiments include hooking it up with OpenNI gods to get depth maps. PCL comes next and it has quite a depth of applications. I will have to go through some tutorials to get some hands on experience with 3D at home. Yay!

A smiley ball for a size estimate and my 'current' reads behind the sensor.

Thursday, February 07, 2013

Demolished one more in the bucket list


Plumbing
Waited a week for a plumber to turn up and fix a leaking tap. He replaced what he called a 'gadda' and one more week later, we were back to leak stage one. A few more days and advanced leak stage has set in. So, Plumberaj jumped in with a pipe wrench. Unscrewed the old tap, screwed in the new one and then did
skills++

Tuesday, February 05, 2013

C Programming

Declaration and Definition: subtle differences.

I was reading up on a little difference between words that appear to be the same at first glance. The point to note would perhaps be of interest only to the developer. A declaration is said to have been done when a variable has been told to have a certain data type. A definition is when a variable is given a certain memory to put a value in.

These words came up in my reading of geeksforgeeks.org which had a nice article about the extern keyword. Little surprise that extern is available by default for functions. Also, little surprise that extern is not available by default for variables. Extern primarily means a declaration and no allocation of memory. So, if extern were default then variables would never be given space.

However C declaration of vars with extern with values are not treated as errors.
eg- extern int i=0; 

The single source shortest path problem and some background

The Single Source Shortest Path (sssp) problem asks about finding the shortest path to all vertices from a given source vertex in a graph. So, how is it different from our Dijkstra's algorithm? Well, this graph is allowed to have negative edges. Why can Dijkstra's fail in the presence of negative edges? I guess we need to first start with Dijkstra's to understand it's shortcomings. So, a little about what Dijkstra does first.

Hey! No need, it does exactly the same thing sssp. So, now why do we need this? I guess we will need to code this down to talk more about it.

Here goes Dijkstra's .Oh!Wait, We will need a priority queue for Dijkstra's. So, Let's start with a priority queue- A min-Heap.

A min-Heap is a binary tree with the property that the parent is always less than the children.

Before we reach a heap, let us try to do this with our understanding of primitive data structures only. Let us first try to do a Dijkstra with no heap.

Little touch up to the concepts of how we make a data structure for a graph first: There are two popular mechanisms: Adjacency matrix and Adjacency list. As the name suggests, adjacency matrix is a matrix. It is a two-dimensional and has the dimensions of the number of the vertices of the graph on each side. Each number in the matrix(say A[i][j]) will denote the weight of an edge between the vertices i and j if such a vertex exists.

The other representation, called an adjacency list, stores the edges as a list and each vertex has an entry to denote the edge numbers which are connected to it.

Which of the two do we choose? As usual, the answer is "choose wisely". A matrix representation takes nxn memory where n is the number of vertices. A matrix representation also taken time O(n) to find all edges incident from/to a vertex. A look up for a cost of an edge between vertices however is an O(1).  An adjacency list on the other hand takes up size proportional to number of edges. Also, an adjacency list can fetch all edges from/to a vertex without having to traverse O(n).

I will discuss about a list representation, it has edges and vertices. Here is a sample implementation of an edge
 
    class edge{
        public edge(int vertex1, int vertex2, int weight2) {
            this.vertices[0] = vertex1;
            this.vertices[1] = vertex2;
            this.weight = weight2;
        }
        int weight;
        int[] vertices = new int[2];
    }


Here is my vertex class, which I have called a node(now I think this is a mistake, vertex should be a subclass of type node):
  import java.util.ArrayList;

class node{

 int number;
 ArrayList<Integer> edges = new ArrayList<Integer>();

  node(int num){
this.number = num;
  }
}


Back to a little about Dijkstra's. I assume that we need to find the SSSP from vertex 0 without loss of generality. I maintain a distance parameter from each vertex which we initialize with a huge number. However, since the distance to vertex 0 from 0 is 0, so cost to vertex zero is set to 0. I use a numbered flag to indicate how many vertices I have processed. There is one main for loop in which the numbered flag is incremented each time. In the loop,  we find the vertex closest to the source which is not processed, relax it(that is considering this new distance, we change the corresponding distances if they are less than the earlier ones).

Here is the code:
public void getDijkstra(){
int processed = 0;

while(processed<vertices.length){
flag = 1;
Arrays.sort(vertices);
int currVertexNum = vertices[processed].vertexNum;
flag = 0;
Arrays.sort(vertices);
for(int e:nodeList[currVertexNum].edges){
int otherEnd = edgeList[e].vertices[0] == currVertexNum? edgeList[e].vertices[1]: edgeList[e].vertices[0];
if(vertices[currVertexNum].dist!=Integer.MAX_VALUE &&vertices[currVertexNum].dist+edgeList[e].weight<vertices[otherEnd].dist)
vertices[otherEnd].dist = vertices[currVertexNum].dist+edgeList[e].weight;
}
processed++;

}


}
Dijkstra's relies on the fact that if we have a set of neighbours from one vertex, the cheapest distance to that neighbour cannot get any cheaper. But, what if we have negative edge costs? Then, for a vertex v, if we have neigbhours w and x, and x is cheaper, then cost from source to x will be cost from source to v and cost from v to x. However, if we have negative edges, we might find a path from v->w->(some more negative edges)->x which might be cheaper than the earlier one. Hence, Dijkstra babu gives up on negative edges.

//more analysis on negative edges to be filled here.

 So, the need for another algorithm for graphs with negative edge costs!!Follow up on bellman needs to be updated and some heapifying stuff too

The bellman ford algorithm , as other DP problems, relies on breaking down the SSSP problem into subproblems. The main recurrence relies on counting the number of edges from the source to a vertex being considered. The maximum shortest path between two vertices would go through all the vertices. Thus, the length of that path would be atmost (vertex count - 1) . The shortest distance from a source to a destination when using k edges can thus either be the shortest distance we get when we consider k-1 edges or it can be the shortest distance from a destination which has an incoming edge to the destination. Using this recurrence, we solve the bellman ford. Little subtle point to note : when using Dijkstra's we look at outgoing edges, when using bellman's we want incoming, so it would be better to change the data structure according to the algorithm.


private int manford(int destination, int maxEdges) {

System.out.println("destination "+destination+" Maxedges "+maxEdges);
if(cost[destination][maxEdges] != Integer.MAX_VALUE || maxEdges==0)
return cost[destination][maxEdges] ;
node dest = nodeList[destination];

int tempMin = manford(destination,maxEdges-1);

for(int e: dest.edges){
int restPlace = edgeList[e].vertices[0] == destination? edgeList[e].vertices[1]: edgeList[e].vertices[0];
int coster = manford(restPlace,maxEdges-1);
if(coster<Integer.MAX_VALUE)
tempMin = tempMin < coster+edgeList[e].weight?tempMin:coster+edgeList[e].weight;
}

cost[destination][maxEdges] = tempMin;
return tempMin;
}


Here is a link to my git repo for the full codes.

Sunday, February 03, 2013

Optimal Binary Search Tree Construction

Let us assume we somehow have the solution to the question in the last post. How can this solution have come from smaller subproblems?

Our understanding of an optimal BST is a tree with minimum average search cost. How do we find a BST with a minimum cost?

My naive understanding would say let us make all the binary trees we can and then find which of them has the minimum average search cost. The interesting thing to observe here are the overlapping subproblems. If we have found the minimum average cost(C_[1,k]) for a certain binary tree which has it's keys from key1,key2...keyk of the original binary tree and now we attempt to build a binary tree rooted at key(k+1) the average search time for the left subtree would be (C_[1,k]) and the average cost for the right subtree would be C_([k+1,rest of tree]). This is what helps form the main recurrence:


Hokay then! So for every subtree in our huge tree we would have to search for an optimal left subtree and an optimal right subtree by using all possible roots.

Let us try to write a recursive method for the same:
int minAvgCost(int start, int end){
if(start>end)
    return 0;
if(start==end)
    return freq[start];
int min = Integer.MAX_VALUE;
int sumOfSubP = sum(start,end);
for(int i=start;i<=end;i++){
     int temp = sumOfSubP+minAvgCost(start,i-1) +minAvgCost(i+1,end);
     min = min>temp?temp:min;
     }
return min;
}
Some Memoization later: int minAvgCost(int start, int end){


if(start>end)
return 0;
if(recArray[start][end]!=-1)
     return recArray[start][end];
if(start==end)
     return freq[start];
 

 int min = Integer.MAX_VALUE;
int sumOfSubP = sum(start,end);


for(int i=start;i<=end;i++){

     int temp = sumOfSubP+minAvgCost(start,i-1) +minAvgCost(i+1,end);
     min = min>temp?temp:min;
     }


recArray[start][end] = min;
return min;
}

Saturday, February 02, 2013

The Optimal Binary Search Tree Construction Problem


Again excerpts and knowledge gained from Tim's lecture on Dynamic Programming, this time I will attempt to elaborate on the problem of optimal binary search tree. A binary search tree is a tree with the property that all keys less than the key of a current selected now would always be available in the left subtree of the node with the additional property that each node can have a maximum of two children. So, what might an optimal binary search tree be? It can be thought of as a BST(binary search tree) with minimal search time. Search time can be thought of as the number of nodes to be traversed to reach the key which is being searched. The question then arises as to how can we know what nodes are going to be searched? This can be understood as gathering statistics or having data about the searches to be made. In some conditions, this constraint can be valid. For example: suppose I have a binary tree which has keys: good(key=1), bad(key=2) and ugly(key=3). (For some unthinkable reason, each word is associated with a key) People search for the word bad generally, say 80% and good and ugly follow with a meek 10% of the time. Let us see how a binary tree can be arranged with these three elements
Tree 1: (10%) people searching for good find it in first hit, (80%) people searching for bad find it in 2 steps and the rest find their ugly in 3 steps. So, an average search time which can be defined as probability of the node * number of nodes to be traversed to reach it. For tree 1: 0.1*1+0.8*2+0.1*3 = 2.0

Tree 2: Good guys still get their word in first hit, but now the uglies go to two. so, 0.1*1+0.8*3+0.1*2=2.7

 Tree 3: 0.8*1+0.1*2+0.1*2=1.2

 Tree 4: 0.1*1+0.8*2+0.1*3=2.0

 Tree 5: 0.1*1+0.1*2+0.8*3=2.7

Yay!! we got an optimal BST. Average search time for tree 3 appears to be minimal. Simple observation might lead to a wrong inference that a greedy algorithm in which highest probability node can be put at the root and simply following greedily might lead us to a solution.

Let's try to prove it otherwise. What if the good guy searches fell to 40, baddies down to 30 and the uglies up to reach the rest, i.e. 30. A simple greedy approach might tempt us to root the tree with good which will give us tree1 or tree2 which have the number: 1.9 (0.4*1+0.3*2+0.3*3) . But hey! Tree 3 has got just (0.3*1+0.4*2+0.3*2) = 1.7

 Greedy Boy don't get to help us here.!! So that is the problem we are dealing with. I will extend this post with an elaborate one as the solution to this problem despite the ample assistance provided by Tim and big bro google took ages to wrap my head around. So, I will attempt a clearer path towards a solution rather than a brain dump.


Please find the detailed solution here

Thursday, January 31, 2013

Sequence Alignment problem: Recursive solution without memoization


Thanks to Tim RougGarden's Alogrithms course -II, I worked on the sequence alignment problem. To the uninitiated, the sequence alignment program is to quantify the difference between two given sequences. Also, I have used help from here to post code for the first time(Yay!*2) on my blog
public class sqq {

String X,Y;
int blankfine=10,matchfine = 100;
int fine(char a, char b){
if(a==b)
return 0;
if(a=='-'||b=='-')
return blankfine;
return matchfine;
}

int seqAlign(int i, int j){

if(i==0&&j==0)
return fine(X.charAt(0),Y.charAt(0));
if(i<0&&j>=0)
return j*blankfine;
if(j<0&&i>=0)
return i*blankfine;
int t1 = seqAlign(i-1,j-1)+fine(X.charAt(i),Y.charAt(j));
int t2 = seqAlign(i-1,j)+fine(X.charAt(i),'-');
int t3 = seqAlign(i,j-1)+fine(Y.charAt(j),'-');
int temp = min(t1 , t2 , t3);
System.out.println("i= "+i+" j= "+j+" Ans: " + temp);
System.out.println(t1+" "+t2+" "+t3);
System.out.println("char i: "+X.charAt(i)+" char j: "+Y.charAt(j));

return temp;
}

int min(int a,int b, int c){
if(a<b&& a<c)
return a;
if(b<a&& b<c)
return b;
if(c<b&& c<a)
return c;
if(a<b)
return a;
else
return b;
}
public static void main(String farts[]){
sqq sq = new sqq();
sq.X = "ce";
sq.Y = "cd";
System.out.println(sq.seqAlign(sq.X.length()-1,sq.Y.length()-1));
}
}

Tuesday, January 29, 2013

MOOCs and me

MOOC is an acronym for Massive Open Online Course and these have spread open knowledge in the last one year in an amazing way. Every person has his own view on courses and would like to take his own time, references and relate to the subject in a way most convenient for him. MOOCs make a platform where this is feasible.

  To me MOOCs have been the biggest gamechanger since 2011. I like learning new things, but I am not the fastest of learners. I take my time, I read and I re-read. And MOOCs let me take my time, giving me a chance to change, a change to improve and a change to achieve.

For the uninitiated, I believe the first set of popular online MOOCs were ai-class.com, db-class.com and ml-class.com. After doing two of the three(Could not do DB), I realized how much they actually helped me widen my thinking. I wanted to do more courses, learn more. But seeing the lectures was hardly the main part. It was all about the assignments and the quizzes. They are the main ingredient specially for students who understand mainly by doing.

This was followed by a plethora of online courses which are now so many that it is barely possible to keep a count. I will however mention the two primary sites that keep me on my toes:
coursera.org
udacity.com

Also, please visit http://www.class-central.com/ which provides an updated list to all the courses from (perhaps) all the sites.

Thanks you all Professors, courses, and other people involved in making online education a success and kudos for keeping it free and helping me in life.
Got this graphic from OnlineCollegeCourses
The Minds Behind The MOOCs