Matlab: 2 Methods of Generating a Rainbow

In my data visualization class, we had an assignment to create a “rainbow” (create and display 128 vertical stripes of color in one image, in RGB sequence). Something like this:

In Matlab, a colormap is an m-by-3 matrix of real numbers between 0.0 and 1.0. Each row is an RGB vector that defines one color. The [R,G,B] color attribute value for a dataset with attribute value ranging between 0 and 1.

My original solution is:

image(1:128);
colormap(jet(128))
print -dpng 'rainbow.png'

The command colormap(jet(128)) creates a rainbow colormap with 128 colors. Files in the color folder generate a number of colormaps, and each file (in this case, “jet”) accepts the colormap size as an argument.
While this solution is certainly concise and clear, it is not the solution the professor is looking for.
It turns out that the professor wants the map to be generated algorithmically (instead of using a built-in file from the color folder).

My second solution is:

image(1:128);
R(128,1) = 0;
G(128,1) = 0;
B(128,1) = 0;
dx = 0.8;
for f=0:(1/128):1
    g = (6-2*dx)*f+dx;
    index = int16(f*128 + 1);
    R(index,1) = max(0,(3-abs(g-4)-abs(g-5))/2);
    G(index,1) = max(0,(4-abs(g-2)-abs(g-4))/2); 
    B(index,1) = max(0,(3-abs(g-1)-abs(g-2))/2);
end
%concatenate arrays horizontally
map = horzcat(R, G, B);
%map colors onto image
colormap(map)
print -dpng 'rainbow.png' 

This creates a different rainbow and satisfies the professor’s algorithmic requirement.

CAMEL Poster

The poster I’m using to present my research creating CAMEL is finally finished (full-size version: CAMEL_poster).

Rin 2013-04-18 at 12.50.33 PM

In order to condense the entirety of my paper into a viewer-friendly poster, I decided to make diagrams to describe the program’s inner workings in layman’s terms.

If you like the format of this poster: all code used in this project is on github.

Introduction to CAMEL

  • machine learning program that uses Braille as a language platform. CAMEL is an acronym of ContextuAl MachinE Learning.
  • uses context of unknown symbols to deduce meaning and compress information.
  • provided the meaning of an initial set of symbols (a dictionary, or dict). CAMEL deduces meanings of unknowns and adds these meanings to the dict.
  • grows more accurate as the dict increases in size andoptions. Some symbols differ in meaning depending on their context. These translation options are stored in the dict in the form of Map[String, TranslationOptions].

What is Grade 2 Braille

  • As English words are composed of letters, Braille words are composed of Braille cells.
  • Contractions are special characters used to reduce the length of words.
  • Some contractions stand for a whole word. For example: ‘for’ = braille{{for}}; ‘and’ = braille{{and}}; ‘the’ = braille{{the}}.
  • Other contractions stand for a group of letters within a word. In the example below, the contraction ‘ing’ is used in the word ‘sing’ and as an ending in the word ‘playing.’ {ing} ; ‘s’ + {ing} = s{ing}; ‘play’ + {ing} = play{ing}
  • Grade 1 Braille is uncontracted Braille.
  • Grade 2 Braille consists of Grade 1 Braille symbols and additional contracted cells.

Binary Braille

  • The Braille alphabet is depicted by a cell that contains six raised/flat dots, numbered one through six beginning with the dot in the upper left-hand corner with the number descending the columns (see figure below).
  • To simplify the calculation, I let “0″ = flat, “1″ = raised.
  • The 3×2 matrix (Braille cell) is represented as a 1×6 bitstring (Binary Braille).
  • Thus, the letter “c”

String Processing Method

CAMEL deduces the complex grammar rules of Grade 2 Braille given partially translated text.

CAMEL learns new symbols by taking 2 input text files (Braille text and corresponding English text), and analyzing them until all unknowns are identified, their meanings are found, and said symbols and their meanings are added to the dictionary.

braille

Methods of Tagging and Text Extraction

CAMEL must Tag Unknowns & Compare to English(Extract Chunks) to infer symbol meaning. Four different tag types were used: end, front, mid, and full-word.

Below are examples of how these different types of tags were each used to extract meaning.

Using Contracted Braille as a Platform

An example of this process infers the symbols that represent en and in using the word penguin (contracted to p{en}gu{in} in Grade 2 Braille).

Results and Conclusions

Safety of Community

  • commercial application in development that will prevent future mislabeling, such as this sign: labeled “Electrical Room” the Braille translates to “stairwell”

Proof of Concept

  • 1st successful automated program that learns compressed Braille
  • translation system is effective for arbitrary symbol systems
  • language platform easily changed

Acknowledgements

Rin 2013-04-18 at 10.51.48 AM


The most difficult part of the poster was creating a mature acknowledgements section; I was very tempted to thank…

  • insomnia for allowing me to code at 2 am
  • coffee for powering me through the day after coding at 2am
  • my friend for introducing me to the instant protein-rich “meal” that is trail mix
  • my research partner that refused to code in C++, which forced me to learn Python
  • Guido van Rossum for inventing said language
  • my parents for putting up with me when I immerse myself in research
  • my friends for putting up with me when I stop in the middle of a conversation to write down ideas and/or zone-out thinking

Although these were essential to my completion of this project, I think it’s best to not include these points in the poster.

CodingBat Java Solutions (Assorted)

I’m brushing up on my Java lately using a wonderful code practice site called CodingBat. Below are a few of the solutions I’ve found to their practice problems.

Given a string, return a string where for every char in the original, there are two chars.

public String doubleChar(String str) {
    String doub = “”;
    for(int i = 0; i<str.length(); i++) {
        doub = doub + str.charAt(i) + str.charAt(i);
    }
    return doub;
}

Return an array that contains exactly the same numbers as the given array, but rearranged so that every 3 is immediately followed by a 4. Do not move the 3′s, but every other number may move. The array contains the same number of 3′s and 4′s, every 3 has a number after it that is not a 3 or 4, and a 3 appears in the array before any 4. 

public int[] fix34(int[] nums) {
    int counter =0;
    for(int i =0; i<nums.length; i++) {
        if (nums[i] == 3) {
            for(int j =counter; j<nums.length; j++) {
                if (nums[j] == 4) {
                    int t = nums[i+1];
                    nums[i+1] = nums[j];
                    nums[j] = t;
                    counter = j;
                }
            }
        }
    }
    return nums;
}

Given n>=0, create an array with the pattern {1,    1, 2,    1, 2, 3,   … 1, 2, 3 .. n} (spaces added to show the grouping). Note that the length of the array will be 1 + 2 + 3 … + n, which is known to sum to exactly n*(n + 1)/2.

public int[] seriesUp(int n) {
    int[] array = new int[n];
    int[] array1 = new int[n*(n+1)/2];
    for (int i = 0; i<n;i++) {
        array[i] = i+1;
    }
    for (int j = 0; j <n; j++) {
        array1[j*(j+1)/2+j] = array[j];
        for (int x = 0; x < j+1; x++) {
            array1[j*(j+1)/2+j-x] = array[j-x];
        }
    }
    return array1;
}

CodingBat Java (Assorted Warmup-1) Solutions

For warmups, CodingBat provides solutions. Some of my solutions differ from the provided.

The parameter weekday is true if it is a weekday, and the parameter vacation is true if we are on vacation. We sleep in if it is not a weekday or we’re on vacation. Return true if we sleep in.

public boolean sleepIn(boolean weekday, boolean vacation) {
    return (!weekday || vacation);
}

We have two monkeys, a and b, and the parameters aSmile and bSmile indicate if each is smiling. We are in trouble if they are both smiling or if neither of them is smiling. Return true if we are in trouble. 

public boolean monkeyTrouble(boolean aSmile, boolean bSmile) {
    return ((aSmile && bSmile) || (!aSmile && !bSmile)); }

Given two int values, return their sum. Unless the two values are the same, then return double their sum.

public int sumDouble(int a, int b) {
    if(a == b) {
        return 2*(a+b);
    }
    return a+b;
}

Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.

public int diff21(int n) {
    if (n <= 21) {
        return 21-n;
    }
    else {
        return (n-21)*2;
    }
}

We have a loud talking parrot. The “hour” parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble.

public boolean parrotTrouble(boolean talking, int hour) {
    return (talking && (hour < 7 || hour > 20));
}

Given 2 ints, a and b, return true if one if them is 10 or if their sum is 10.

public boolean makes10(int a, int b) {
    return (a == 10 || b == 10 || a + b == 10);
}

Given an int n, return true if it is within 10 of 100 or 200. Note: Math.abs(num) computes the absolute value of a number.

public boolean nearHundred(int n) {
    return (Math.abs(100 - n) <= 10 || Math.abs(200 - n) <= 10);
}

Given 2 int values, return true if one is negative and one is positive. Except if the parameter “negative” is true, then return true only if both are negative.

public boolean posNeg(int a, int b, boolean negative) {
    if (!negative) {
        return ((a < 0 && b > 0) || (a > 0 && b <0));
    }
    return (a<0 && b<0);
}

Given a string, return a new string where “not ” has been added to the front. However, if the string already begins with “not”, return the string unchanged. Note: use .equals() to compare 2 strings.

public String notString(String str) {
    if (str.length() >= 3 && str.substring(0,3).equals(“not”)) {
        return str;
    }
    return “not “+str;
}

Given a non-empty string and an int n, return a new string where the char at index n has been removed. The value of n will be a valid index of a char in the original string (i.e. n will be in the range 0..str.length()-1 inclusive).

public String missingChar(String str, int n) {
    return (str.substring(0,n)+str.substring(n+1,str.length()));
}

Given a string, return a new string where the first and last chars have been exchanged.

public String frontBack(String str) {
    if (str.length()>=2) {
        return (str.substring(str.length()-1,str.length())+str.substring(1,str.length()-1)+str.substring(0,1));
    }
    return str;
}

or

public String frontBack(String str) {
    if (str.length()>=2) {
        return (str.charAt(str.length()-1)+str.substring(1,str.length()-1)+str.charAt(0));
    }
    return str;
}

Given 2 int values, return true if they are both in the range 30..40 inclusive, or they are both in the range 40..50 inclusive.

public boolean in3050(int a, int b) {
    return ((30 <= a && a <= 40) && (30 <= b && b <= 40)) || ((40 <= a && a <= 50) && (40 <= b && b <= 50));
}

Given a non-empty string and an int N, return the string made starting with char 0, and then every Nth char of the string. So if N is 3, use char 0, 3, 6, … and so on. N is 1 or more.

public String everyNth(String str, int n) {
    String x = “”;
    for(int i =0; i<str.length(); i=i+n) {
        x = x+str.charAt(i);
    }
    return x;
}

Given a string, return a new string where the last 3 chars are now in upper case. If the string has less than 3 chars, uppercase whatever is there. Note that str.toUpperCase() returns the uppercase version of a string.

public String endUp(String str) {
    if (str.length()<=3) {
        return str.toUpperCase();
    }
    return (str.substring(0, str.length()-3) + (str.substring(str.length()-3, str.length())).toUpperCase());
}

Turning in Reverse

Do you have trouble remembering how to properly steer when driving in reverse?

I remember in two different ways:

(1)
If you want the rear of the car to turn to the right, turn the wheel to the right.
If you want the rear of the car to turn left, turn the wheel to the left.

(2)
Imagine (when you shift into reverse) that you’re sitting in the rear with the car in drive.

Then, turn as you would turn if you were sitting in the back and in drive.

Chess Tips for Beginners

Disclaimer: I’m a mediocre chess player, I do not consider myself a chess expert. These simple tips are for beginners looking to surprise intermediate players during games.

This post assumes you know basic chess rules and some chess terminology. If you are unfamiliar with Algebraic chess notation, I suggest you read this.

Setting up the board.
Queen on her colour.

h8 should be a white square.

Knights are next to rooks, don’t put them next to the king and queen!

Advance your pieces in the opening so you can protect your king without blocking your attacking pieces.

Search for traps, don’t be too eager.

Use a rook/queen to protect an advancing pawn.

Castle queen-side. You will throw your opponent off, if only for a brief period of time. This a lesser known alternative to the typical king-side Castling.

Queen-side O-O-O


King-side O-O

Pawn structure, pawn structure, pawn structure.
A forward V is far more powerful than a backward V. Don’t underestimate a well-protected wall of pawns!

NEIN!
Ja! Gut!

For Fischer’s sake, don’t stack your pawns unless you have a sneaky plan.

d2 and d3 are stacked

Fianchetto
It is my understanding that to fianchetto means to develop your bishop to an extreme rank.

There are two steps (and two options) for a simple opening queen-side fianchetto (you can also fianchetto on king-side, or fianchetto in midgame)

Step 1) b3 (or b4) to clear the diagonal for Bc1
Step 2 – Option 1) Ba3
Step 2 – Option 2) Bb2

Fork your opponent. Forking is when a single piece attacks two (or more) pieces simultaneously. This is typically done with the knight, but can be done with any piece.

For example, in this endgame:

Nf3+ threatens Qd2 and Kg1

Both white and black are forking.

However, white’s pawn fork (b5 threatens Ra6 and Rc6) isn’t a stable fork, for taking either rook would entail a trade (2. bxa6 Rxa6 or 2. bxc6 Rxc6).

Additionally, the white king is under check, and the white side is at a material disadvantage. From here, assuming it’s white’s move:
1. Kg2 Nxd2
2. bxa6 Rxa6
3. Kh3 Nb1
4. Kg4 Ra3
and then they dance. I predict 0-1.

Playing black? Confused during openings? Use the Sicilian Defence.

1. e4 c5
or
1. e4 d6

All black’s moves proceeding this are generally considered Sicilian Defense variations. In the latter case (1. … d6), a common white response is 2. Nf3 … 2. d4

2. Nf3 d6
3. d4 cxd4

This is a common black opening, so experienced players are likely to have prepared white responses.

Play often. As with other skills, playing often is key to increasing your skill level. Your ability to pick up patterns and accurately evaluate the board increases as you play more.

Braille Cube

Often, when cubing, I’m asked: Can you solve it with your eyes closed?

I can’t solve a normal cube with my eyes closed.

Combining my interests, I can now truthfully answer with an affirmative.

braillecube

This is an original-colored cube, meaning that the faces are colored red, green, blue, yellow, orange and white.

Each face (except white) has the first letter of its color on its face.

green “g”
red “r”
yellow “y”
orange “o”
blue “b”
white “w”

The braille cell that means “w” () is the reverse of the braille cell that means “r” (), so I left all white faces blank to avoid confusion.

Are These 3 Points Collinear?

On the topic of groovy math, here’s some smooth algebra.

Given 3 points, are these points collinear?

Collinear means the points will all be on the same line. If this is the case, then all the points would satisfy an equation y=mx+b. If they are all on the same line, then they will all have the same slope (m) and same y-intercept (b).

For example: Given points (1,-1), (3,3) and (0,3)

y=mx+b
-1=1m+b

m=change in y/change in x
m= (-1-3)/(1-3)= -4/-2=2

-1=1(2)+b
-1=2+b
b=-1-2=-3

y=2x-3

Plug points in to see if they fit the equation.
-1=2(1)-3 yup
3=2(3)-3 yup
3=2(0)-3 nope!

Since (0,3) does not satisfy the equation, then the three given points are not collinear.

Algebraic Chess Notation

We use algebraic chess notation to represent chess positions without posting a full chessboard. This allows players to converse about chess positions clearly without a board in front of us.
Imagine the chess board as a 2D plot. Below is the table I made to explain this notation in my paper How Stockfish Works: An Evaluation of the Databases Behind the Top Open-Source Chess Engine. I will post more about this paper when I’ve finished editing it.

Symbol Meaning
a-h file from white’s left to right
1-8 rank from white to black
R, N, B/S, Q, K Rook, Knight, Bishop, Queen, King
x capture; the piece that was at this location is removed
+ a note that the king is threatened
# or ++ checkmate; a note that this is the reason for the end of the game
= promoted to; a pawn arriving at the opposite side of the board is promoted to another piece, often a queen.
0-0 castle on the kings side; move to positions (B – Kg8 Rf8 ; W – Kf1 Rg1) (if neither has moved before this point in the game)
0-0-0 castle on the queens side; (B – Kd8 Rc8 ; W – Kc1 Rd1) (if neither has moved before this point in the game)
e.p. en passant capture (non-SAN), a note that a pawn was taken by another pawn passing it. When a pawns first move is a two space move (from 7 to 5 for black or 2 to 4 for white) it can be captured by moving behind it to the 6th rank (white taking black) or 3rd rank (black taking white).
?, ??, !, !! editorial comments, weak, very weak, strong, very strong
Coordinates in Algebraic Chess Notation
I encourage you to explore additional background information provided by the online book Building Skills in Python.