Friday, 13 November 2015

reverse engineering a serial port communication

In old science labs, there are a lot of machines that are forgotten and not used. Over the years of personnel change, significant amount of knowledge about these instruments is lost. At the same time, a lot of new technology is being developed. Unfortunately, most labs cannot buy new instruments every year (although now that I think about it, a business strategy may be to put people on subscription based model where they upgrade old instruments every year). Eventually, these become nearly until a new graduate student feels like fixing it and trying it out...

I'm exactly in that situation... I'm trying to fix an old single cell peltier machine. It works perfectly on its own, so hardware wise, it's good. It can communicate with the computer via a RS232 port, but the existing software to control does not have the capability I need. I decided to make my own control software.

Being a beginner, I did some searching to find that there is a python library for serial communications. I installed python and the library on the windows 98 computer. Interestingly, this windows computer is the only one with the RS232 9 pin com port out of the 6 computers inside the lab space. In any case, I think I have succeeded in opening communication between the two.  The reason I think the communication is established is because the instrument is unavailable to the other software (although this might be just because I am trying to open two communications on the same port). The problem is that I have no idea what codes to send or how to interpret msg that it spits out... But I thought that it might be possible to hijack the msg that the already existing software is exchanging with the instrument. So looked into serial port listeners and found one which I tried (and not many were for windows 98), but didn't work. I think I was using it incorrectly... Finally, I found out that for Portmon you need to have all the windows closed before running portmon.exe... Why? I don't know, but it worked. One more important note is that you need to start collecting on Portmon first before establishing the software's connection to the instrument.

Anyhow, I put some of the results at the end. But I realized that I need to do it in hex rather than ascii. I did that today, but I don't have it with me right now, but the results shown clearly demonstrated what kind of data flows and how simple this communication is. From what I understand, the computer only sends two different requests: 1. ask for temperature data; 2. tell it the temperature set point.

I think I can easily get it working. I just need practical info on how to send data in hex, etc. Based on the ascii data it's clear what info I need. Other things are... I'll just ignore them I guess. I guess I'll post again once I get it to work (and have a bit of time). I hope this helps whoever is trying to resurrect old instruments. I had trouble finding detailed information on how to do this, which is one of the reasons why I'm writing.

15 0.00000810 scan.exe IOCTL_SERIAL_SET_LINE_CONTROL Serial1 SUCCESS StopBits: 1 Parity: NONE WordLength: 8
16 0.00000615 scan.exe IOCTL_SERIAL_SET_CHAR Serial1 SUCCESS EOF:0 ERR:0 BRK:0 EVT:0 XON:11 XOFF:13
17 0.00000922 scan.exe IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:0 Replace:0 XonLimit:1024 XoffLimit:1024
18 0.00000251 scan.exe IOCTL_SERIAL_SET_QUEUE_SIZE Serial1 SUCCESS InSize: 4096 OutSize: 2048
19 0.00005839 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 6: .a.{..
20 0.00001648 scan.exe IOCTL_SERIAL_WAIT_ON_MASK Serial1 SUCCESS
21 0.00006509 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 2: .a
22 0.00006314 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 14: .a.x   25.00..
23 0.00002905 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 2: .a
24 0.00001872 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
25 0.00001983 scan.exe IOCTL_SERIAL_WAIT_ON_MASK Serial1 SUCCESS
26 0.00000698 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
27 0.00001369 scan.exe IRP_MJ_READ Serial1 SUCCESS Length 26: ..x.!{    0....x.!x    0..
28 1.94195128 scan.exe IOCTL_SERIAL_WAIT_ON_MASK Serial1 SUCCESS
29 0.00005448 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 6: .a.$.V
30 0.00003213 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 2: .a
31 0.00001676 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
32 0.00001844 scan.exe IOCTL_SERIAL_WAIT_ON_MASK Serial1 SUCCESS
33 0.00000754 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
34 0.00001425 scan.exe IRP_MJ_READ Serial1 SUCCESS Length 16: ..h.$    40.5@..
35 1.78213125 scan.exe IOCTL
...
9563 0.00005308 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 6: .a.$.V
9564 0.00004190 scan.exe IRP_MJ_WRITE Serial1 SUCCESS Length 2: .a
9565 0.00001537 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
9566 0.00001788 scan.exe IOCTL_SERIAL_WAIT_ON_MASK Serial1 SUCCESS
9567 0.00001816 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
9568 0.00001481 scan.exe IRP_MJ_READ Serial1 SUCCESS Length 16: ..h.$    35.9@..
9569 0.76596243 scan.exe IOCTL_SERIAL_WAIT_ON_MASK Serial1 CANCELLED
9570 0.00001956 scan.exe IOCTL_SERIAL_GET_COMMSTATUS Serial1 SUCCESS
9571 0.00001229 scan.exe IOCTL_SERIAL_PURGE Serial1 SUCCESS Purge: TXABORT RXABORT TXCLEAR RXCLEAR
9572 0.00000754 scan.exe IRP_MJ_CLEANUP Serial1 SUCCESS
9573 0.02937049 scan.exe IRP_MJ_CLOSE Serial1 SUCCESS

Saturday, 25 April 2015

container vs recursion

I'm finding that in some of the past exam questions, they specifically request NOT to use container objects. In their hint... it says use recursion...
So the following is a rev(q) that reverses the items in queue q using std queue functions and NOT usnig other container objects. FYI, I made enqueue and dequeue return the queue object after modifying. This just allows stuff like q.enqueue().enqueue().dequeue()... stuff like that. Anyhow, using this example I want to talk about what I think about this kind of method.
I'm not sure what the point of this question is because surely I don't use container objects but in the process of using recursion I create new name spaces and in essence I create variables that store things. The name spaces are like container objects. the next question is more interesting. can rev(s) be defined for stack s with similar restrictions? I'm not sure. If you can use loops and variables you can definitely hack this to work. It is possible to do something like exec("a" + str(i) + "=...") to make an "array of variables". I remember when I first learned programming and got to for loops I was thinking it would be awesome if I can autogenerate series of variables which conceptually was somewhat like arrays. Anyways... using recursion like above it's not possible. This is interesting because it kind of hints at how queues and stacks are complementary. With queues, you need a stack structure to reverse and with stacks you need a queue structure. It queues work with recursion because the namespace/namespace recursive calling forms a stack.

tree traversal

in a past exam, we are asked to figure out a unique tree given preorder and inorder traversal. I have briefly touched upon tree permutations before, but I think this is a slightly different question that asks you to understand recursion in tree traversal.

Based on this particular question, I was thinking that given preorder and inorder traversal you can always recreate the unique tree. I don't have a formal proof but the following can probably dressed up into such.

just a reminder:
pre-order = self, pre-order(left subtree), pre-order(right subtree)
in-order = in-order(left subtree), self, in-order(right subtree)

or simply:
pre: self, left,  right
in  : left,  self, right

I can see that the term right should be the last items... so what ever is the matching is the right most  "deepest tree".
Next, I go 1 left from in-order that's the "self" which is the parent of the right most item. I find that in the pre-order. I find where this value is from the pre-order. This is the new "self" (parent of the right most item) on the pre so everything between this and right is to the left of this. Now, all the suff here are the left subtree of the tree from the perspective of the parent of the right most node (which may be none btw if there are no matching elements). I repeat this process.

Here, I "traverse" the nodes from right, parent, parent's left subtree. Kind of interesting.
Obviously you can do the same with post and in order. Logic should be the same.

I should add that probably the nodes must be identifiable to reconstruct the tree. ie. repeating values may make it impossible. The obvious example is if all the nodes have the same value. All visits will give the same result.

As for why pre and post order doesn't cut it is kind of intuitive
pre-  : self, left,   right
post- : left, right, self
There are only two "distinct" blocks. self and (left,right);  (but also think in terms of trees). You cannot resolve everything. You see self being on the outter most of both pre and post so you can get rid of those but once you only have left and right... they are identical. Easy counter example would be a two node situation with parent P and child C. P with left child C has the same traversal as P with right child C.

Friday, 24 April 2015

new interesting question

This question talks about what I previously talked about... That the Tree class we constructed does not necessarily lead to a tree. cycles are permitted in the implementation and the objective is to find out whether this is in fact a tree.

First, we need to realize that the node may still be part of a something Not a tree (ex. two things are pointing at it). But there is no way to know this from the node.

If you think about the tree rules - they can only be reached in one way. so you can never see the same node twice if you "traverse all the nodes once".

I think this is interesting because you can't use sets for nodes (mutable. hashing is not possible for mutable instances). Of course the easy way is to just use lists. But is there something that is immutable and representative of what I'm thinking of that I can substitute here? memory location. id values. Having two different nodes (ie. "A is B" is not true) is okay even if they have the same value (the value need not be unique). It's the object itself that must be different and I believe id captures this idea.

Anyhow, my soln:

Past Exams

I'm starting to study for my final exam now. I got an interview on Monday :) so excited and I'm having a hard time focusing on studying so to keep myself motivated, I decided to post my solutions. I don't think anyone is reading my blog (o_O) but if you dear reader find any mistakes, do mention.

So the question is to determine whether or not a binary tree is "complete". Quick google search suggested complete binary tree is one where all nodes if applicable have 2 children. So minimum height binary tree. In class, we briefly touched on being balanced. Interestingly, the problem requests that I recursion NOT be used (which I thought was really weird).

It was a fairly fun problem. I used some sort of queueing system. I don't think the efficiency is good and the definitely a lot of room for improvement... but I do restrict my time spent on each problem (like on tests) to around 20 min (excluding typing problem time and debugging after to "verify" my solution since we don't get answer sheet)....

The function is called is_complete(root) and takes a BTNode. I think at the end, the restriction made me think of tree traversal differently. Definitely an interesting problem. I think I will get a recursive version up too (in a while). nvm I'll just explain the recursive version (too lazy to actually code it).

For the recursive version, you can code height(root) which returns the maximum number of paths ("non-reversing") in the tree leading from root to leaf. You also recursively find height2, which is where the first None occurs (so return min on "pseudo leaf" where pseudo leaf is where at least one of the two childs is None). Compare the two... and return False if the difference is greater than 1 (2 or more). I'm sure there is a better way though since you are traversing some parts of the tree multiple times. But I think the basic idea is there.

There are other stuff on the following... which is just some soln to other problems.


big O question

I want to post an interesting run time problem.

One problem goes as such: Given a length n list of lists of k ints, what is the most straight-forward way to check whether a given list of length k is equivalent to at least one of the lists (where same here implies that the order is also the same)?

For example:
input = [1,2,3], [[2,3,1], [2, 3,1]]
would give output = False
input = [1,1,2], [[2,2,1], [1,1,2]]
would give output = True

This is a very straight forward question. I can just compare the list 1 with list i where i ranges from 2 to n.
For each of the list comparisons, there are n elements to compare and thus you get n comparisons...

at the end, this is n*k comparisons.
So approx. I would say n*k time scale.

I want to modify the question to make it more interesting. What if you didn't care about the order? Suggest an efficient algorithm to do the comparison and discuss its time scale.

For me, the first idea that came to mind was to order the two lists using an efficient method. That would take it klogk time to sort and now I just need to make k comparisons so for each of the n elements (and the input list)... making it (n+1)*k^2*logk

But we know that sorting often slows things down. For example, is it faster to sort first and then find x or just find x?
To just find x, you need to say is x in list A? k comparisons, is x2 in A, k-1 and so forth. I get k(k-1)(k-2)... n times. k! comparisons n times.
so I get n*k!
Which is less than sorting first.

Can I do better? At first I wasn't sure. But I thought... I am looking for thing many items. It struck me then that I might be able to do better. What if I only sort the given list and look for elements in the long list in the sorted given list? Now:
O(n,k) = O_sorting_given_list + n*O_finding_k_elements_in_sorted_list
O(n,k) = k*log(k) + n*log(k)
now... O(n,k) = (k+n)*k*log(k)
which is better.

Is there a better way? I can't see it but I guess it doesn't mean it doesn't exist. This would make a very interesting test question. One problem I think with this course was that we didn't get interesting/sufficiently challenging problem sets (particularly in the latter half of the course) and the solutions are not very readily available. Working solution doesn't mean it's a great one and I would love to see alternate solutions.

Sunday, 12 April 2015

Finding Subsets

I often use programming to solve problems and automate tasks. Recently, I wanted to solve some simple optimization problem. I decided to generate all possible subsets in a list.
When I was thinking about this problem, I saw recursion.
Say you have a list of length n.
You can ask what the list of subsets of list n-1 is and then add element x
take that list of sets and add the removed element to generate an added set.

For example, take a list of 3 elements (A, B, C)
remove A.
Find the subset of 2 elements (B, C)
you get ((B, C), (B), and (C))
now generate the added set (B, C, A), (B, A), (C, A)
You should return (B, C, A), (B, A), (C, A), (B, C), (B), and (C))

The base case is when there is one element (empty is not a subset in this definition).

So I implemented this and found it to be slow. It's not supprising though. In a set of n elements, there are a set of 2^n  - 1
Based on this, there are at least 2^n base cases to evaluate. 2^n grows very fast and the problem really grows quickly. 

For optimization, I think the best way is to think about whether a variant of pruning could work. Based on the problem at hand, if smaller set meets the cut, the larger set may but if smaller set does not meet the cut, larger set will not work. I don't have to construct larger sets if the smaller set does not satisfy the condition. Depending on the exact conditions (which are the variables), there may be only a small number of possibilities.I'll see if this speed up, but I will probably need some additional optimizations. 

I'm thinking of trying to take the "best" choice at every step with a hint of randomness by also trying a few random elements. I think it's a variation of the finding a global minimum type algorithm. From my understanding, one of the ways to find minimum is by following the gradient, which only finds (possibly) a local minimum. In these algorithms, where you start is very important since you might be trapped in a local minimum and cannot find the global minimum due to this trapping. One of the methods used in such problems is to start the problem in many different "starting values". So for example, if you had the following function, if you start at the right hand side, you're going to find a local minimum, while if you start at the left hand side, you will find the global minima. If you start 50 different values between -5 to +5 increments, probably you will find the global minima. In this method though, you will obviously need to compute 50 times... which will take 50x more time.

One of the issues with approximations is that you compromise accuracy... But it stays practical and feasible. That's what's needed in science. In nature, I'm more of a pure scientist (meaning that I just enjoy the science because it's interesting rather than the practical benefits that come from it). But after working on "real" projects, I've realized that the world doesn't want pure science. They want results that are profitable or in some way useful. At first I was a little disappointed because to me science is like art - it's about making brilliant logic or experimental design to probe the world. At the end though, I think I've gotten kind of used to this need for practicality.