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. 

Monday, 6 April 2015

Final post?

Classes have ended and only the exam is left.
I'm not sure if I will maintain this blog after I finish this course. I really enjoyed this course and I must admit that I really enjoyed posting here.

I'm not convinced as to how much it has helped people do better in general in the course. In fact, I don't think it helped me do better in the course (ie. I think my mark would be the same none the less). Surely, it helped me explore ideas and learn more, but I think that is mostly because I  really enjoyed posting and I posted a lot since there was so many interesting ideas (and I actually have several more that I was thinking of posting...maybe I will continue to post...). It's difficult to say that many other people had similar outcomes just based on one person's experience. But, I do want to talk about how things went for me. One of the things that happened though is that writing a post was a substitute for studying. For me, this is better than nothing since I probably would not have studied weekly. However, due to my personal circumstances (it isn't my core course and I have "more important" commitments), I did have to limit my total weekly contribution for this course somewhat. I think this is where this weekly posting falls apart. Sometimes, I had to write some posts during lectures or labs and so forth. I spent some time that I could have used on say building test cases or completing the labs more thoroughly.

I'm wondering if self evaluation is really worth the time. I think that if people are short on time, it may be better to do lab exercises for example. The "research question" should not be whether writing a blog helps students do better. It should be whether writing a blog is more helpful than another activity such as having extra lab questions. I guess the interesting argument comes where you have to realize that doing the lab questions is helpful... which seems many people believe that they were based on some of the other people's posts.

Maybe the point of the weekly post isn't to make us learn more (which is I believe the instructor's reasoning at least on the surface). Maybe it is to obtain feedback from peers. So that you know how you are doing. One of the requirements of the posts is to read other people's post. Although some people write wonderful posts (I mentioned several great bloggers) that many claimed to have helped to reinforce their understanding of the course, is this better than say reading a textbook (some of them are written in textbook style...). Maybe reading other people's post just help you see where you are... but then there's a bit of echoing effect in such cases where I've read for example relief that they are not the only person not able to solve recursion easily. Of course some post the opposite and mention how some other blogger has things down but I've found it to be rare. I do think that it would be interesting to analyze self evaluation trends here. If people are echoing their inability to do something and feeling relieved then that's not a good direction for the weekly posts.

I think that where our weekly point stands strongest is to encourage us to read and write and to create a sense of community. In my experience the CS community is very good in that way. Stackoverflow posts are super helpful for example. Probably, maintaining a portfolio is a good way to demonstrate your knowledge so my guess is that a great blog really can demonstrate your ability. I would say that if this were the purpose, the post recommendations should be updated a little (so remove a bit of self reflection and provide more guides as to what the post should look like), but I think although it may not necessarily improve our "computer science skills/knowledge", it may help as a computer scientist in the future.

Anyhow, I think my comp sci journey might end here... I will try to keep it as a hobby but probably it will be more programming than comp sci for me. To those who are just beginning their journey, good luck!

Monday, 30 March 2015

Still about Tippy :)

Haha.. I'm done my assignment but I'm still not happy about the result of optimization. I guess I don't let go when I bite. As someone else was saying, cracking 4x4 tippy might be a fun task.

Although in class, Diane emphasized the big picture and the O(g(n)), I think at this point of the Tippy assignment, it might be worth considering the details.

One thing about minimax is that the overall speed of minimax depends on the speed of the game. For example, we will be calling apply_move very often and also be checking whether the game has ended. To that effect, it's useful to be able to perform all of these tasks faster. Suppose minimax goes through N iterations of suggest_move_helper. Then the overall speed boost the USER gets is N*improvement_time.
In practical terms, I don't care what N is as long as N*time_per_N < thresh-hold.

Anyhow, I have a new idea about how to make TippyGameState faster. So, if you read my following post, I mentioned that my game was stored as a nested list, which looking back was a horrible idea. It's one of the first structures that came to mind. Another structure was a dictionary whose elements are "p1", "p2", "p0" and the values are the locations of the possible moves, but I gave up on this approach since I thought that when I look for the value at some location x,y, that the nested list would be faster since I need to iterate through "all" the elements to see if something is in "p1", "p2" or "p0".
But now, I know hashing and that finding an element in "hashed space" only requires O(1).

This means now I know that the following is fast:
D = {"p1":set((x,y), (x2,y2)), "p2":set((x3,y3), (x4,y4)), "p0":set((x5,y5), (x6,y6))}
When you are looking for (x2, y2), you need to ask whether its in D['p1'], D['p2'], or D['p0'].
Overall, this only requires "3 lookups". (for is this value 'p1', you only need "1 lookup" and this is something that is probably often done).
Also, when you look for the possible moves, you just need to get D['p0'].
And thinking of implementing symmetry (about p1 and p2), you just need to swap D['p1'] and D['p2'].
In my implementation, it's sometimes useful to know from time to time what moves have been made by 'p1' or 'p2'... Now, this is also super fast.

Hashing is ingenious.

Friday, 27 March 2015

Still about A3 :0

I'm finding A3 pretty boring... but the overall topic very interesting. Especially, optimization algorithm analysis :)

Right now, I'm working on understanding the effectiveness of Pruning. This is something I'm not sure about. As mentioned previously, I decided to try using cProfile to obtain all the function calls.
I've just completed it and I'm finding that compared to my original minimax, it's significantly faster for Tippy, but not so much for SubtractSquareState, since I already do some pruning (return win if I just get a winning state; this is a no-brainer form of pruning... Not complete pruning tho).
I also "fixed" that just now to do a better testing. My fixed version basically goes through everything...

I'm testing for subtract square where I seed it with current sum of 29.
StrategyMinimax: 612235 function calls (572894 primitive calls) in 6.180 seconds
Wow... out of those, if we look at the recursive calls only:
  ncalls  tottime  percall  cumtime  percall filename:lineno(function)
  39342/1    0.973    0.000    6.180    6.180 strategy_minimax.py:66(_suggest_move_helper)
             1    0.000    0.000    6.180    6.180 strategy_minimax.py:46(suggest_move)
FYI, _suggest_move_helper was the helper function that gets called recursively.

Now, I want to compare this to pruning... which calls move_score... I should change that too... fixed.
StrategyMinimaxPrune: 865 function calls (814 primitive calls) in 0.010 seconds
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     52/1    0.002    0.000    0.010    0.010 strategy_minimax_prune.py:69(_suggest_move_helper)
          1    0.000    0.000    0.020    0.020 strategy_minimax_memoize.py:53(suggest_move)

No wonder it's so much faster... but now, I want to CHECK how many times it should be checking... To do that... I added a function called tree_form to game_state_tree. I only show the docstring below since I'm not sure if code sharing is allowed... So, the idea was to use this new thing to visualize the tree with current node 29 and to "prune" by hand... but then you see that 39342/1 function calls... what does that mean? That should be the number of nodes right? since it's called at EVERY node... so... This might be hard to SEE. Kind of funny side note is that code is often more accurate than my doctests -_-; haha. Anyhow, I decided to check pruning on just current number 10.


so... here...I am... maybe I should just do it for size 6... sighs...
Actually surprisingly simple and my calculation says 16... but my code says less??? Right... my hand checking ability sucks... Retry... got 9... awesome. =) Partial analysis shown below (fyi, I traverse the nodes in my minimaxPrune in the same order as shown in the tree):

For further checking, I will probably use a print statement showing cur_val to check that only the "expected" states are being checked. Doing that now... checked awesome. Repeat for 1 other case... Or not. I'm actually confident it should work. I'll just think about whether there are any special boundary cases I need to worry about.

Just as a side note, I want to add that just by returning when you see a WIN get's you what in a two state (-1, 1) game. I'll leave out the detailed analysis but it should be somewhat obvious.

Wednesday, 25 March 2015

Minimax-other potential "upgrades"

So my digression about minimax from my last post got moved here :)

Before I go in, I would like to mention that in class we do worst case analysis. I don't like that. I want to talk about the average needed time. For example, we can easily see that the worst time for pruning is the same as checking everything... but on average for Tippy... it saves so much time... (3x3 tippy first point runs fast enough that you're not waiting for computation). Kind of interesting aspect of average time analysis is to think about when the averages change. In a sense, the average time is just an expected value and it depends on the probability distribution of the input feeds.

First:
Combine pruning and memoizing... these two techniques are obviously somewhat mutually exclusive. I would try to prune first and then if I need the data, see if I can fetch from my memos... An interesting twist / implementation detail might be whether I should store the partial info I get from pruning. Let's say I exit early since I know 0 is a guaranteeable score, should I remember this to take advantage of the next potential pruning step??? I think this is a design decision and probably what's better is game dependent. I'm not sure what's best, but I'm thinking in along the following lines. 1) suppose the tree can be pruned often... that's good right? I'm saving a lot of computation... but this also means that I'm not collecting much memos and it's kind of useless. Suppose I do keep partial info... then I would need two different notes for each state I encounter... 1) The minimum gauranteed or actual score depending on 2) whether the value I have is the actual score. Upon some thought, I'm starting to wonder if there would be significant boost in performance. Here's why: Suppose you pruned... but you actually need this value then you need to go back and evaluate everything anyways, regardless of the minimum gauranteed score. This means even with the memo, you might need to compute that many more times, but of course on your second try... you might get some help when you prune since you know the minimum value you can achieve out of it... but then you need to be careful about what to do when the values are the same... Also, you need to check if it's in your set, which takes time. Here, I used python Set() which uses hashing, but if I used a list... the finding time would be nlogn... Overall, I CAN see it potentially beneficial... but I'm not sure if it would be so much.

Second:
Notice that the last child can be "pruned". The actual value at the last node doesn't matter This is probably beneficial where the number of children is small...

Third:
and most interesting in my opinion is symmetry considering memoize.
In all the two player games, the score is symmetric in that score for p1 in state1 is the same as the score for p2 in -state1... where -state1 is the condition where all the "stuff" are as though p2 and p1 are switched... To illustrate, in subtract squares game, suppose the score for state p1: 500000 is 1.0 then I know that the score for p2: 500000 is 1.0 (score for p2). In tippy, take the stones in the grid and exchange p1 and p2's play... you get the mirror image state. Now, you can cut the number of states to memorize in half.

For the implementation of this, I think that concept of hashing might be interesting thing to introduce to GameState. Make a method that returns an ID of this game... some sort of number which encapsulates all the stuff about the state. And make it such that if it's symmetric, this tag is the same... That would provide a really cool handle for the implementation of memoize. I would call it memoizeSymmetry. Another interesting thing about tippy is that there's also rotational symmetry that can be taken advantage of. The score does not depend on the rotational state of the grid. You can use this to further cut the checks. The best part is that the memoizeSymmetry would work in both cases but in subtract sq game get a 2x boost and in tippy get ~8x boost (the rotations may be identical in some grids). I think this is a really cool class to write.

Do you have any extra ideas about other minimax implementations? Criticisms or runtime/resource analysis?

Lab 10, sorting

Today's post will not be about big O... which is what we learned in class. It will be more about sorting algorithms which is this week's lab.

I think the most interesting thing about this week's lab could be the intro to various sorting algorithms (more so than the big O). Diane talked about merge sort and maybe several other sorting algorithms were covered in the prerequisite course (csc108), but either I forgot or never learned so they are not very fresh in my mind. The labs have really interesting concepts, but it's too much boring work recently... so I end up getting the gist of doing them and just spending my time analyzing the implications. Anyhow, while "learning" about some of these, I came across a super cool visualization of various algorithms that instantly taught me about it in a sense.

overall in this lab, we should have seen that it's not just the number of loops you go through, but also what operations you do in it. I think this is somewhat trivial. When I code, I have been aware of this and even if it may save some lines, I often say A = function(), if I know I will need A more than once. An obvious implication of this that I hadn't considered before is the memory that I am using.

One cool thing was the profile_comparisons() method... It uses cProfile module to findout about all the function calls. Now... where might that come in handy??? I think anyone who read some of my previous posts would realize that this would solve (at least partly) the testing of pruning. Whether I will end up doing that instead of trying to make my own other "minimax improvements"... I'm not sure. At the moment, I have several ideas in mind that could potentially further improve the runtime. I will write about this in my next post, since I want to keep things somewhat organized...

I will update this post later ... (I ended up digressing and writing about minimax again -_-)

Monday, 23 March 2015

Tippy Implementation

I know it's very late but I would like to share my implementation of Tippy today. Fortunately, though it doesn't feel so untimely since we covered running time analysis and maybe I can add a few words about why my implementation is good. 

So this is how my algorithm checks for the presence of Tippy and some rationale.

First, figure out where the stone was placed last. I do this by remembering the last move that was made.
Now, we know that if there exists a tippy, it MUST involve this stone.
we just need to check whether there exists a tippy here.
I did this by using recursion. Based on the z shape you can see that essentially you are travelling in zigzag patterns. if you think about it as a person driving from the "center", it's like turning left right left right in sequence. There are two general directions and two possible assymetries (go left first or right first).

My partial code is shown below and I think it might make my explanation clearer so it's somewhat worth skimming through. I just want to add that I used a list in list to store the game_state. In retrospect, think tuple in tuple might have been better since things are immutable...

I also want to briefly add a time analysis for my tippy versus if you did it without remembering last move applied. For this coarse analysis, I will suppose say time is proportional to the number of grid spots that are checked for grid size n

Remember last_move:
Maximum number of checks = 1+9+3+4+3= 20
I'm not sure about this... but I think the following is the worst case... marked in yellow is the last position. Notice in my code that I don't exit even when I find 4. I just go till the end. I did this since time is not a huge issue in this assignment and since most of the time unless the players aren't being crazy... this will not happen.


Don't remember last_move:
I don't know for sure since I don't have any such algorithm at hand. I will say we do a "similar" seeding position analysis. Even with the entire grid on the line, we still know that only the last person to have gone could have made a tippy. This means that we can do a similar analysis on the last few players. Suppose we have size n grid. This means that we have n^2 grid positions and thus at maximum around n^2./2 positions in which the last player played. say we do a check around this point. This means we need to check around n^2/2*(const).
Another method is perhaps to do a subgrid analysis where we find a 3x3 matrix inside. Still this means there's a (n-3)(n-3) grids so (n-3)^2*const. still n^2
I don't know how I can show it, but without remembering anything, the analysis must be scaling n^2.
In some sense, the rationale here is similar to the problem of finding an element in a list. We know that we must see all the elements to know that something does not exist in the list.
But still you can see that if we think about each of these actually run, they do multiple checks on the same point. Probably, there is a way to do better, which reduces that constant time, but for sure it cannot be a constant time.


Friday, 20 March 2015

My Lab 9 Work

Lab 9 was really boring I think. It's one thing to come up with test cases and it's another to write them up. On the bright side, there were some interesting "testing" questions. For delete, what's the best way to test it works? Obviously, you can ask if the result is "what you should have gotten based on the known algorithm" but as I briefly touched upon last post, there may be more than one valid trees outputted after deleting. My approach was to 1) check that the value disappears if any, 2) check that the tree remains in "good shape" (ie. the BST conditions are maintained) by travelling in order.  You can easily see that in-order traversal results in "sorted nodes" iff the BST is maintained.
Also, I found a bug in bt_functions.py for the bst_contains method.
I think based on this lab, I think I know how to autotest my minimax. I can add a tester function that keeps track of all the states it visited (or print something about it) and then see if it matches my expectation.
In any case, this week there should have been a very wide range of possible solutions. Mine is shown below, but I would recommend that you don't waste your time reading through it:

Assignment 3: Memoization, Pruning, Myopia

Continuing from the previous assignment, the goal of Assignment 3 is to extend the game by adding computer strategies. Minimax strategy, which effectively looked at all the possible combination of moves leading to an end of game was really slow and impractical for Tippy. Here, three different "optimization" techniques are employed to speed up the minimax strategy. Myopia is really an optimization in my opinion because it does not neccessarily generate the same result as minimax.

Memoization: avoids redundancy by storing the value returned by recursive calls
Pruning: avoid "travelling" through states that you will never choose anyways
Myopia: Avoid "travelling" through all the states by limiting how far you look ahead

At the end, to decrease computation time, what you need to do is decrease the number of states you consider. What these options show for the most part is something like "entropy-enthalpy tradeoff" in chemistry. To speed things up, you need to use more memory(memoization) or give up accuracy (myopia). To gain speed, you need to trade something else. Pruning is particularly interesting since it does not seem to compensate speed. My guess is that the "tradeoff" lies in what happens where there are no avoidable paths. Since pruning tries to avoid checking certain states, it needs to check whether things can be avoided. In some sense, this is a time investment. In certain (probably very many) situations, you may get the benefit, but you may not.

I currently have a more or less working version of all three. I am very surprised by the speed at which these work, particularly pruning. One big problem though is that I'm not entirely sure HOW to test these. Maybe I can see that they are faster and they give accurate results but that does not mean that the algorithm is implemented perfectly. Maybe it is still visiting certain nodes that it can avoid. One sloppy way of checking of course is to verify that the results agree, but does not ensure that the code is working properly.

At the end, I think option B is way easier. You don't need to write any docstrings or care about formatting too much and the functions are similar to what we have seen in labs. Also, to check your code for the minimax optimizations, you kind of need game_state_tree. I think the only way to truly check your minimax optimization algorithms is to collect which nodes have been visited and show that it matches your expectations. To obtain your expectations, you probably need a game state tree...

Time to get working... I will do my lab 9 and post my soln probably today. I don't like to get behind on weekly commitments...




Friday, 13 March 2015

Binary Tree Mutation and Structure (related to lab 8)

We had a test this week and on Monday lecture, we talked about mutating trees. The lab was also about tree mutation. In this post, I want to provide my analysis on trees (particularly relating to the lab)

Personally, I found the first bit of the course very straight forward. I see algorithms that can be applied to solve the problem. Okay done. Now, we are thinking about different algorithms and how they compare to one another. I think this makes one of the most interesting topics we ever touched on.

The lab was easy in some sense but I think it raised a lot of interesting questions. To fully (mathematically) answer the question, I needed to think really hard.

For lab 8, we had to tinker with insert. Here are my observations on insert:
1. the insertion only occurs at the "edge".
    This is significant because if there were nodes with only one child, there is an opportunity for insert to work there. First, let's examine for how many positions insertion is "valid" for the following example (blue is the tree and red is after inserting). I see 2.

From this example, it could be seen that there are at maximum possible positions in general: one "sandwitched between nodes" and one at the leaf. It is also easy to reason out considering the >, < relations that must hold. Just as side node, also notice that the "sandwitched between nodes" option may not exist when the value is the new max or min.
2. based on the current algorithm there is a "best" order of insertion and it is to insert the "middle values" first.
    By this I mean to say that if you have a list of 7 values, you would first insert the 3rd largest, then the (6-1)/2 = 2nd largest and 6th largest, and then finally the remaining values.
Try it with [1, 2, 3, 4, 5, 6, 7] and you will see that you get a tree with minimum height.
This can be reasoned based on 1. Since we know that insertion only happens at the edges, once we have a point in the "non-edge" you need certain numbers to populate that edge. With a sorted list, you will never actually get that "certain number".
3. One related observation is that the total number of valid ways to arrange a tree with node count n is the number of possible node arrangements.
   So, you can easily see that given the shape of the tree, it is always possible to fill in the values fitting that tree in exactly one way (since exactly x values must be < the node at every point, where x is the number of nodes in the left subtree; as an aside, you  and easily fill this tree with sorted values by travelling "inorder"). So what are the possible arrangement of nodes given size n?
I have yet to figure that out... but I have three leads:
   a) thinking inductively, what are the possible combinations for size n-1; what is the number of child        nodes where that 1 new node can be added for each? things to sort out with this approach are:
            i) degenerate trees are created and I'm not sure how to account for them
           ii) the number of child changes depending on the structure, how can I generalize?
   b) at every node, you have at maximum 4 choices: to add to left, to add to right, to add to none, to           add to both. Problems:
           i) adding to none is not an always accessible choice.
           i) again only the leafs get this kind of choice. all other nodes have no choice (already fixed)
        In a sense, method b is the same as option a I think.
    c) Somehow the order of the list will influence the tree arrangement. How?
         i) again there are issues of degeneracies. It is easy to calculate the total possible list order tho.

If you have any hints on the latter, I would be really interested to hear about it.

I will not be posting my work on lab 8, since it should be obvious that you just need to shuffle the list for insert and when deleting randomly choose to "fill" using left or right (at least based on the hint)


         

Saturday, 7 March 2015

Thinking about recursion

Way back, I asked a question about what kinds of problems are best for recursive functions. Since then, I have solved many problems such as lab exercises and in particular I have implemented minimax which is a strong strategy which finds the best move by evaluating all possible move combinations in a two player game. Through these exercises, I have reached a conclusion that recursive functions can always be drawn as a tree where each node represents a recursive "state".

Let's think about what happens when we do a recursive call. The name space changes. If you were in name space X, now you are in X in X. As described, function calls can be dealt with using stacks. So at the top of the stack is where you are currently. Each node is like that name space. In our exercises, we only dealt with a node having only one value, but that's not a requirement. In fact, I think we can think of the whole recursive process as a tree where each node contains information about all the local variables at that point.

With the context of the meaning of recursive functions defined above let's see how this might be true. If the problem at hand matches all properties of a tree, then it must follow that the problem can be expressed as a tree.

So what are the requirements/properties of a tree?

Tree – A kind of directed graph
1. (Composed of set of nodes with directed edges between nodes)
             2. (Edge connects parent node to a child node)
             3. (Nodes may (or may not) contain values)

             4. Where each node has exactly one parent except the root has none

So...
1. yes the recursive problem has nodes and directed edges. The directed edges are function calls. 
    A calling on B is not symmetric (it is directed).
2. yes the edge connects between two nodes only. There cannot be three way connections.
3. yes the nodes (name space) may or maynot have values
4. yes each function call can only have one "caller". The root is the "original" call.  

All of them are satisfied and I think it makes sense. I often think of recursive problems as a reference shift (I guess in actuality it is a name space change). You can call a child node from the parent node and once you move along that path (calling), now the previously child node is the new parent node. I think this kind of thinking might have shown slightly in my lab 6 explanation.

As to the above, I suppose it is not a formal proof and I am not yet convinced that this must be True. At the moment, it is a running hypothesis and possibly another way to think about recursion. It partly answers the question of when recursion may be appropriate: when you can create a tree that is finite... But then it still does not answer the question... just asks the question in a different angle (provides an answer in a different angle).

Wednesday, 4 March 2015

My Lab 7 Work

There's a strike... so no tutorials this week... But still did my lab. I was in a hurry, so I will probably revisit and make sure I updated front and back and so forth... This version passes the doctests.
But you should note that the doctest doesn't check all possibilities. It typically prints lnk. That means lnk.back is never checked or size is never checked. For some functions that matters. If you find any errors, feel free to comment. As always, my solution is posted below.

Monday, 2 March 2015

proof(?) for tree height approx log (n)

In Diane's morning lecture, we talked bout height of a "perfect" tree being approximately log (n). Here, I want to show a "proof" for it. It probably will not be a formal proof, but I will show something that hopefully can be written in that form.

let's think of a tree with arity k. Then at "level" n, there will be k^(n-1) nodes.

At level 1, there is 1 node, at level 2 there is k nodes, at level 3 there is k^2... everytime you go one more level there will be k times more.
#Nodes(n) = #Nodes(n-1) * k, #Nodes(1) = 1
explicitly, #Nodes(n) = k^(n-1)

Then the total number of nodes leading to n is sum (k^(i)) for i = 0...n-1

S = (1-k^n)/(1-k)

This can be shown by subtracting S from rS and rearranging. I believe this kind of technique is called telescoping.
Conceptually, you have x + y + z - (y + z + A) = x + y - y + z - z - A

Anyhow, rearranging
S = (1-k^n)/(1-k),
we get log(S) = log(1-k^n) - log(1-k).
if r is const and as n-> inf,
log(S) = n*log(k), rearranging, the height n is ...
n = log(S)/log(k) = log base k of S
remembering that S was the total number of nodes,  we are where we want to be. :)

This post I diverted a little... Next post for sure, I will discuss my realization about what kinds of problems might be suitable for recursion. It's kind of obvious when you think about it, and I think I understood kind of intuitively but couldn't really exactly describe it...

Thursday, 26 February 2015

Abstract Data Types (ADT) Part 2: An Example - Queue

As promised, my second post about ADT will be an indepth analysis of and ADT covered in class. In my previous post, I talked about ADT as a specification manual of some sort for some general object. At the end, ADT allowed us to be modular. There are several very useful abstract datatypes we covered in class. In addition to some of the built-in types such as integers, lists, etc, we covered several other ways to store data: trees, queue, and stack.
For no good reason, I want to focus on queues. Queues are first in first out structures. It may have enqueue, dequeue, and is_empty. Think about queues in a store. You're waiting to get your icecream on a hot summer day. If you come first, you can get your icecream first. It doesn't matter to the icecream seller who exactly is in position 2. All that matters is that the queue isn't empty, and the next person who gets icecream. When that person gets the icecream, they are removed from the queue

So translating the icecream stand using the concept of queues we get something like the following: is_empty? Yes
is_empty? Yes
someone came, enqueue Jayce
someone came, enqueue Katarina
is_empty? No
dequeue... Jayce
serving Jayce icecream
someone came, enqueue Corki
still serving Jayce icecream
Jayce got icecream is_empty? No
dequeue ... Katarina
serving Katarina icecream
still serving Katarina icecream
Katarina got icecream
is_empty? No
dequeue ... Corki
serving Corki icecream
still serving Corki icecream
Corki got icecream
is_empty? Yes
is_empty? Yes
... and so forth.

This doesn't apply just in the context of an icecream stand. Of course any line in a store can be used, but it's more than just that.

A less physical example is when requests are processed in the computer. For example, the computer seems to run a lot of programs simultaneously. In actuality, these are processed by a queue. Say you need to do X, Y, Z "simultaneously". You can create the illusion of simultaneous action by doing X, Y, Z, X, Y, Z, ... so forth but changing between them really quickly. It's kind of similar to flashing bird and cage to create bird in cage. Rapidly switching between tasks can make it seem like they are occuring simultaneously. In the context of a queue, we can think of X, Y, Z as being part of the queue. dequeue X and do X at the end enqueue X and then dequeue Y... and so forth.

The same basic data structure can be applied to many different "specific" cases since it's an Abstract Data Type.



My lab 6 Work

My solution for the assignment is attached at the bottom. For this post, I wanted to provide a detailed illustration of how I tackle recursive problems with list_longest_path as example. Due to time issues (on my part), I will "draw" my logic rather than providing a good written explanation.
I ended up writing a bit more than I originally planned, but anyhow, hope it helps.
I particularly like the implementation where None is taken as a base case. Its conceptually simpler I think. It's kind of like saying min([...] +[0]), which says what are the minimum value in list X; if this value is negative, return 0. Anyhow, these tree exercise and assignment 2 I think has provided me some insight into what it means to be "recursible"... I hope to address this in next week's post (unfortunately this week I must finish writing about ADT... and I'm a little busy now).

Wednesday, 25 February 2015

Abstract Data Types (ADT) Part 1: The Concept

Last post, I talked in depth about OOP. More specifically, I talked about the modularity and inheritance which makes OOP powerful. For modularity, you need to have specifications for each of the parts.

For example, let's talk about building a computer (hardware wise). There are many components, but let's talk about the most important few: motherboard, CPU, GPU, and RAM. Computer is modular, due to the specific way in which they connect to each other. Each of their roles are defined and thus the motherboard knows how to interact with the RAM. There exists some interface. Due to this defined interface, many different RAM can connect to the same motherboard, even though the exact architecture and exactly how it is done may be different from RAM to RAM. For example, you know that it must have a particular pin dimension to connect to the motherboard. When given input X and the query Y, two different specific RAM must know that query and also provide the same answer for the other parts interfacing it to understand the output.

What does the general RAM not know? A lot of things of course are not defined, but one such is RAM speed. There are specific details that the motherboard does not care about. Once the detail matters to the motherboard, the detail must be specified at the interface level to maintain modularity. With RAM for example, this interface is given a name such as DDR2 or DDR3. This has information about which RAM can be used for certain CPU.

Let's shift gears a little and think about how this relates to ADT. The general RAM is like an ADT, while the ADT's subclasses (which should be instantiated) is like a specific RAM that can be bought like Desktop Momory Model F3-10600CL9S-4GBNT. All the tasks and the way it performs those tasks (and in this case also the way it interfaces with the hardware ie. the pin connections) is specified in that general RAM so that specific RAM can follow them. In this case, the motherboard or whatever is interacting with the RAM is the client. Notice how the client does not need to know how the memory works. Only the operations and the results of those matter.

I mentioned above that ADT's are like specifications for the interface. This is related also to inheritance in that the subclasses inheriting from ADTs in a sense are promising to follow these guidelines. It's like companies advertising their RAM as DDR3. I think of inheritance from ADT as being a claim to follow these specifications. X which inherited from Y is an instance of Y. Thinking about our RAM, the GBNT is an instance of RAM.

Modularity in general is very powerful. In the context of computers, the most obvious benefit as a consumer is easy upgrading and fixing. Your GPU isn't good enough to support the new game in high resolution... just change that. You don't need to buy a brand new computer. It's the same with programming. In class, we are making a two player game where one of them is a computer. By using a strategy class, we were able to "upgrade" from a random move chooser to a minimax strategy where the best move can be chosen.

For fixing, suppose your GPU got some electrical shock and doesn't work anymore. Same idea. You can just get a new GPU rather than spending more money on getting everything. Similarly for software development, you only need to debug and fix what's not working. You don't need to spend time and effort fixing everything.

In addition, parallel development is possible now. In the context of computers again, the CPU making companies do not need to know about how memory will be stored etc. As long as the two development teams agree to do things in a certain way (establish an interface), they can develop things separately. In the context of programming, it means many people can work on the project together.

I feel like I've rehashed a lot of the material from my previous post but with a better conceptual illustration. For a summary of some of the OOP terms and ideas, see my previous post.

For the next post, I want to provide an example of very famous ADT we covered in class.

Thursday, 12 February 2015

list.copy() how much does it copy?

So for my previous post, I mentioned that the list gets copied, so having multiple parents is not possible. But, what does list.copy() actually copy?
I initially thought that it copies everything and I originally thought that copy was a call existent in the object class equivalent to eval(repr(obj)). But according to the following... I was wrong:

In fact, when you try to call copy on user implemented object (I tried it on tree) that does not define copy themselves, you get an error.

Anyhow, this means I was wrong about my previous conclusion and to actually duplicate the Tree objects, you actually need to use "deep copy". I think the easiest way to implement this would be to use eval(repr(Obj)).

My lab 5 work

So my work on trees lab is given below. I tried to remove redundancy that could potentially arise when t.children is empty and I did not follow the instructions on the handout closely... I kind of have my own way of doing things, which was mostly based on intuition at first, but after today's lab, I think I kind of know what I am doing. Maybe for a future post, I will elaborate on my way of tackling recursive problems.
Additional exercises and one extra function from lecture is also included.

Wednesday, 11 February 2015

My thoughts on Trees

Trees are a type of graph where each node can only have one parent... at maximum. Since the node must be part of the tree, it must be connected to the tree... basically by being a child of another node. A consequence of this is that (for a finite tree) there must be exactly one node without a parent. It's called a node.

There are a few very interesting things about a tree.

First is that a tree is made up of many other trees, which are called subtrees. I previously posted a question about what problems lend themselves to being solved by recursion. The fact that trees are made of smaller trees makes it obvious that that problems involving trees are good for solving by recursion.

Another interesting thing kind of related to the above is that the root only needs direct access to its children. At the end though, it can figure everything about the tree. In a sense, the tree has emergent properties.

But more interesting I think is the fact that the child nodes are not "aware" of their parent. I'm not sure if this is just an implementation factor, but the child has no knowledge of the parent in the following implementation (partial) provided in course lectures copied here for easy viewing:

It is actually impossible for them to point to the same tree as shown below (since a copy is made). However, when such a graph (not really a tree anymore) is built, many of the recursive functions intended to act on it will work. Of course for some things like counting leaves, it will behave a bit strangely and behave like tree in Figure 2. And I think it could be easily accounted for by checking if they are the same object etc.
Figure 1
But the above (figure 1) is definitely different from the representation below (Figure 2). 
Figure 2
I wonder if figure 1 like structure has a name (more specific than a graph)? it's like a tree but it can have multiple parents or is it not special enough for a name...


EDIT: I was a little wrong about figure 1 being impossible in this implementation. see my follow up post

OOP Part2: OOP Notes

I hope to make this post a bit more note-like rather than exploratory and to provide a summary of the course in a fairly concise way. I don't normally read the text so most of the terms were googled... As the course progresses and new concepts mastered, hopefully this post will grow... Some key words are underlined.

A data type consists of both attributes and methods.
Object oriented language allows for a way to create custom data types and also a way to create instances of that custom data type.
Class is the definition of objects.

Encapsulation is a idea that attributes and associated methods are combined into some data type allowing the client to interact with the public interface without worrying about the details of is implementation. In class we learned about property function in Python which allows the Class to control how the client accesses or changes its attributes.

Inheritance is the act of deriving from another so that the inheriting class (child class) is obtaining methods and attributes from its parent class. Note that the child class is a type of the parent class. Rather than thinking about them as inheritance, I think subsets is a better way to describe it, eventhough child classes can be extended.

Polymorphism is the ability of related data types to respond to the same calls in data type specific ways. In class, we learned about using NotImplementedError on the parent class to implement this kind of behaviour. (but NotImplementedError is not the only way to achieve polymorphism. sometimes, parent class may be implemented, but overriden or extended)

Extending is the act of making a child class more specific. This can be done by adding attributes or methods not defined in the parent or by overriding parent behaviour (methods). For example, suppose parent does x. the child can do xy.

Overriding is the act of literally overriding parent behaviour. For example, suppose parent does x when x is called. The child can ignore that and just do y.


I found this post to be a good overview of some of the concepts covered in class. This person recaps how to approach the design of a class in a manner consistent with our lecture. A lot of other OOP posts were a good summary, but nanalelfe's post is interesting in that if you only know OOP, there's nothing to compare to and thus it cannot be truely understood. I would argue though that although Python is a OO language, Python we learn in csc108 is not.

Anyhow, if you feel like I've missed any important terms or made a mistake, feel free to leave a comment!

Monday, 9 February 2015

OOP Part 1: What is OOP?

Today's food for thought is Object Oriented Programming (OOP). Actually, this will be an organized summary of some OOP concepts for reference (and slog requirement...) rather than any interesting ideas.

Before OOP came along, I thought about a program as a series of commands. Each command does something. I want to handle some repeating task... make a loop. I want to do something in certain cases... use an if statement. But at the end, these are all part of a command. Next, we link several commands into a new master command. We call this a function... Here, we realize that only certain data can be passed on and that these data may be linked together... why not create an object that binds all the data (attributes) together and the functions that operate on it (methods). Now, we have OOP. I made a previous post about usefulness of OOP describing mostly in the context of going from a function to objects.

So... in essence, objects are just containers. It is there for human beings to process what is going on more easily. I want to emphasize that objects are just there for human beings and our inability to track many things simultaneously. As an example, take 5 dogs. I spread around their names and colors and age etc all over the place. that's 15 variables. I can't remember which dog was what. Now let's link all those attributes into one thing- an object- a Dog! I can remember 5 things :) Now, the program remembers for me which dog has what attribute. It also remembers how they bark (see previous post), etc.

Only after understanding that OOP is a form of organization method to boost our productivity that we can talk about how to design them. I have provided my method for OOP design in a previous post with assignment 1 as an example.

In the next post to follow, I will discuss the components and more about how to think about OOP in a more theoretical way.

EDIT: Here and in most of my other posts on OOP, I only talk about the positive effects, but greying student has pointed out some pitfalls of OOP. What do you get when you subdivide your code too much? I think this idea is somewhat in line with the "human aspect" I talk about here, but anyhow, I thought it was interesting to point out.

Saturday, 7 February 2015

My Work for Lab 4

I'm going to try to post my solutions to the lab exercises every week. I would welcome others to compare my solution to theirs and comment if you think my solution can be improved in any way (or any other constructive criticisms are welcome :) )

My Queue.py:
My queue_list:
That's all the work I have with me here now... starting lab 5, I will try to fetch all my previous work and post everything and also post my soln to lab 5. Also, when I have time, I'll try to add some explanations... Adding tasks to queue... queue overloaded :)

Thursday, 5 February 2015

Recursion Part 2: Spin off Idea?

In Recursion Part 1, I talked about one analogous recursive formulation in mathematics and the logic for using "simplified" tracing.
Here, I want to talk about my attempts to create a recursive function for the additional exercises. I took just the docstrings and thought about how to write it. The docstrings are given below:
From the docstring, I could guess that for the recursive structure: if recursive_case then base_case, the base_case should be False... but it was difficult to understand where the element comparison should be...

At the end, the solution that I reached was:
Here, all the provided test cases work... but it is obvious that it would fail for case nested_contains(2,2).
I personally think that this should be the correct response of the function considering an object as a list of depth 0, but I'm just trying to match the specification here... so... after consulting the TA's advice, I used a helper function that would call this structure:
This kind of got me to think of structures where function A calls B calls C calls A calls B and so forth. I haven't thought much about this problem yet, but it can obviously be used when you need some cyclic behavior until a certain point. A trivial example is given below:
A very useless thing but the number of function calls to A might be the solution to something like kola climbs 2 cm and then slips 1 cm every day; how many days does it take for the kola to travel to the top of a 100 cm tree.
Another possibility is to call something depending on what was called previously, but this is structured in such a way that the caller can be called in the "chain" of calls.

Recursion is really interesting, but thinking about it in this way makes it seem like just another function... with one caveat that it might "loop" infinitely.

Tuesday, 3 February 2015

Recursion Part 1: Understanding the Logic Behind Recursion and Tracing

Today's question is when recursion can be used. Is this technique applicable for all problems, or is there only a subset of problems in which this idea can be used? Of course we only use it in iterables in all our examples in class... but can we be more general? Also, when is it a good idea to use it out of all the cases where it can be used?

But for now, I want to talk about the logic behind recursion
Ennanarts, jesse, and many other sloggers have shown recursion in a pictorial way. As you go in one step, you find that same thing. This kind of understanding is best exemplified by fractals as described by our course-link.

So, I want to show a slightly different approach: recursive form of mathematical expressions.
A sequence can be written in explicit form:
x(n) = 2^n
or
it could be written in recursive form:
x(n) = 2*x(n-1), x(0) = 1

In recursive form, the next value in the sequence is formulated as a function of the previous value. This means that if we can find that previous value x(n-1), we can find this value x(n). So... you do this again and again starting from n... until you reach a certain point... the base case (or in this case n = 0). But what if I gave you x(2) = 4. What is x(3)? Is it neccessary to unravel and go to x(0)? This leads to a fundamental logic involved in the tracing of recursive functions. After you prove/show the behaviour of a "lower level" in this case n - 1, you can use that result. it's not neccessary to go to x(0).

That's just some rationale about the "simplified" tracing scheme of recursive functions and also about another angle at which recursive functions can be thought about.

Next post, I would like to share some recursive functions from last week's lab and another function structure (or a spin off) that I was thinking about.

PS. type recursion on Google... it's really fun

Friday, 30 January 2015

On what basis to split classes

What should a generic turn based game consist of? How should classes be designed?

Whenever I program, I always try to think of some physical process. For example, when I was first tackling the sorting problem, I thought of insertion sort. When I sort my cards, that's how I sort. I trace back to how my brain does it and then I make the code do exactly that. Of course there may be limitations to this, but I find that this is a good starting point.

Similar methodology was used when I tackled this problem. When I imagine a game, what entities are involved? First and most obvious are the players. And then there is the some neutral entity that manages the game... I would call it the game master. The game master talks to the players and notifies them of the game state, announces other people's moves, etc. In poker this would be like the dealer. The game master is directly aware of the game state, since it keeps track and modifies it. The game master can learn about the game using the game state. I think of the game state as the chips/panel used to keep track of all the information and a rule book of how to manage the game. The game master refers to the book for what instructions are needed to be given to manage the game and also interacts with the record, modifying it and referring to it as needed. other_info is shown as an example to express that the game board can be extended (current number might be in the other_info). Note that some minor details are omitted and levels are only conceptual.

One "problem" I found with the assignment is that it is open but also closed. For example, in the game state I did not want to generate all possible moves. The rule_book only needs to be able to say whether the move can be made. There is no need to generate all moves. I wanted the computer to be able to find possible moves and so wanted to implement AI that is specific to the game. Part of the player's role is to find the moves given the game. Due to the structure of the requirements, it was more convenient for game state to be able to generate the moves. I  guess this is just a minor issue.

In a future post, maybe I will talk about more detailed implementation details. If you have any questions about how I did things, feel free to comment. I'm also interested in learning about how other people thought to do this.

Thursday, 22 January 2015

Why Use OOP?

Classes and Usefulness.

In class, we talked a lot about classes. I feel that the big question is why use OOP. Especially with the introduction of Stacks, Queues, and Assignment 1 in particular, many people just don't understand what their point is. For assignment 1... it's point is for us to learn, but in general, what are some advantages of using OOP?

I want to first outline briefly the conventional class design description and then discuss some of the advantages of classes.

Classes are containers. They contain information about something. Rather than having everything spread around everywhere, related variables and functions can be tied together. For example, we can have a dog object which might have a name, dog_type, weight, fur_status, and so forth as descriptors and bark, sleep, eat, poop, see, etc as is methods. The variables within the class describe the useful aspects of the object while the methods change the dog or do something depending on the dog.
We know that functions are useful because repetitive tasks are made easier and making changes later becomes easier. To elaborate on the latter, suppose that for sorting, faster algorithm was found. To make changes for all the things, all the positions where sorting was attempted needs to be found and then all of them must be changed. Also, parallel development is easier since the functions can be written simultaneously.

All the advantages of functions apply. You can make changes within the class methods or internal variables without affecting the external code that uses this class. Of course it also prevents one from needing to reinvent the wheel over and over again and allows parallel development.

An additional benefit of classes is evident in the above definition. It serves as a container, which groups concepts and breaks them down to facilitate implementation. Also interesting is the possibility of subclass usage.
The latter is similar to functions in that different functions can be passed. Let us analyze the following code:


Here, the function c is changed based on user input.

A similar task can be accomplished by using classes. Suppose you have a dog and a cat. You don’t know which one you might have… but you know they can both say hi… but the result of that should be different… The dog should output “woof” and the cat “meow.” This is where subclasses are useful. In a way, the act of being an instance of a particular subclass is in this case the instruction for the method say_hi.

Hope this was useful