Ed's Big Plans

Computing for Science and Awesome

  • Page 1 of 2
  • 1
  • 2
  • >

Archive for the ‘Pure Programming’ Category

Exposing MATLAB data with JFrame & JTextArea

without comments

Today, I’ll describe my first foray into MATLAB. My task is simple — there’s already a GUI developed as a toolbox. The user inputs a bunch of data, and it crunches it away and provides a graph and displays a dialogue box about the moments of the data. The issue here is that we’d like to know more about the data — particularly, we’d like to retrieve the ordered pairs corresponding to each of the plotted points in the graph.

In this exercise, I’ll show you how to use JFrame & JTextArea to display the coordinates of a graph in an already existing MATLAB GUI toolbox or plugin.

The reason why I’ve decided on this approach rather than outputting directly to the MATLAB console is because I eventually want to add additional functions to reshape and reformat the text, and also to save the text that appears in its own window using additional Java swing components. But that’s a story for another day.

The Quick How-To … ( 3 steps )

Choose the toolbox or plugin you’d like to modify and open up its “.m” file. This is where you’ll want to add your custom code. There are three parts to this exercise — first, we need to get a few classes from Java; then, we need to store the data we want to display; finally, we make the display appear.

In this example, I’ll import the bare minimal amount of Java classes — you can extend this functionality by adding more swing classes if you like. I’ve arbitrarily prefixed my Java variables above with the prefix “expose”.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane; // Scrollbars -- optional.
exposeReport = JFrame('Data Report');
exposeTa = JTextArea(24, 80);
exposeScroll = JScrollPane(exposeTa);
exposeScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
exposePane = exposeReport.getContentPane();
exposePane.add(exposeScroll);
exposeReport.pack();

I’m not exactly sure why MATLAB doesn’t include scrollbars automatically.

Of the above, there are only two variables which we’ll need to refer to again later — “exposeReport” and “exposePane”.

The next step is to use your JTextArea as an output terminal. Just append strings to it as the graph is being built — you’ll have to look at your specific plugin to figure out the logic behind the graph — in general, you’ll be looking for a for-loop and a function that alters the graph.

// Look for a 'for' loop with a line that adds data to the graph.
// Here, I've used the variable SomeX for a point's x-coordinate,
// and SomeY for a point's y-coordinate.
exposeTa.append(sprintf('%d\t%d\n', SomeX, SomeY));

The loop spins around and incrementally adds all of the points. Note that I’ve used “%d” as a conversion to numbers expressed in base-ten (including floating point values). This is different from the conversion character in C where “%d” indicates only integers.

We add the final code after the loop exits. This next code makes your data report window visible — just as you’d expect from Java.

exposeReport.setVisible(1);

I opted to put this line after the code that reveals the toolbox’s original summary window — this causes my report to appear on top.

That’s all there is to it! Enjoy 😀

MATLAB from a CS student perspective

MATLAB has always been a bit of an oddball language for me. It’s dynamically typed but also exposes Java’s classes if you ask nicely. It’s C-looking and provides functions that the C-programmer would be happy accepting such as strcat and sprintf, but again — putting on the dynamic spin by returning the constructed string rather than modifying the contents of a buffer. All in all, the design choices do a good job of making MATLAB do what it’s intended to do; it gives scientists and engineers a way to succinctly express math to a machine without having to take too many computer science courses.

Eddie Ma

July 11th, 2011 at 1:18 am

Python’s List Multiply — Use List Comprehension Instead

without comments

Brief: I ran into a snag parsing a CSV today — I have lines upon lines of 27 integers each. Each line represents a cube of values — each cube has dimensions 3×3×3. Here’s an example line and the corresponding cube it represents.

A line …

0, 0, 0, 0, 0, 0, 0, 50, 0, 2, 22, 0, 0, 4, 0, 5, 0, 17, 0, 26, 24, 0, 0, 0, 0, 0, 0,

The corresponding cube …

0 0 0
0 0 0
0 50 0
2 22 0
0 4 0
5 0 17
0 26 24
0 0 0
0 0 0

… Where the three major squares represents three levels of depth; each major square has three rows and three columns — the values in each depth are organized row-major.

So let’s say the lines in a file are read from stdin thanks to the magic of posix pipes.

We might be able to use a construct like this to store all of our lines in the variable cases as below …

import sys
cases = []
for line in sys.stdin:
    entry = [int(i) for i in line[:-1].split(",") if i != '']
    current_cases = [[[[0] * 3] * 3] * 3] # Doesn't work ...
    for ii, i in enumerate(entry):
        current_cases[ii/9%3][ii/3%3][ii%3] = i
        # ii is the index (of enumeration), i is the value (from the 'entry')
    cases.append(current_cases)

Let’s break apart the line that assigns entry first — it’s equal to the below …

entry = line[:-1]
# get rid of the trailing newline character

entry = entry.split(",")
# break apart the line by comma character

entry = [int(i) for i in entry if i != '']
# convert each element into an integer
# except for the trailing empty string

Now let’s break apart the line that assigns current_cases — here’s the logic behind getting each element of the 27-element cube …

[ i x x i x x i x x i x x i x x i x x i x x i x x i x x ] - column index
[ i i i x x x x x x i i i x x x x x x i i i x x x x x x ] - row index
[ i i i i i i i i i x x x x x x x x x x x x x x x x x x ] - depth index

The columns are indexed by [index (mod 3)] — every third item falls in the same column. The rows are indexed by [index /3 (mod 3)] — every run of three items out of nine are part of the same row. The levels of depth are indexed by [index /9 (mod 3)] — every run of nine items out of the 27 elements is part of the same depth.

So here’s the line that doesn’t work

current_cases = [[[[0] * 3] * 3] * 3]

In current_cases as defined above, there are only three integers — not 27 that are allocated in memory. The above saves cubes where the depth index and the row index don’t matter, only the inner-most column index has any meaning. The strange thing is, this wasn’t immediately intuitive to me — I expected the list multiply operation to create nested lists — instead, each of the two enclosing levels of lists just creates additional references to the same list.

This is the line we must use instead to make the nested lists correctly save the cubes …

current_cases = [[[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(3)]
# or ...
current_cases = [[[0] * 3] for i in xrange(3)] for i in xrange(3)]
# or ...
current_cases = [[[0, 0, 0] for i in xrange(3)] for i in xrange(3)]

Here, the comprehension iteratively creates the correct 27 memory locations needed for each cube. Each nested comprehension is responsible for creating a unique list at the correct depth.

Putting it together, the correct listing for this task is …

import sys
cases = []
for line in sys.stdin:
entry = [int(i) for i in line[:-1].split(",") if i != '']
    current_cases = [[[0 for i in xrange(3)] for i in xrange(3)] for i in xrange(3)]
    for ii, i in enumerate(entry):
        current_cases[ii/9%3][ii/3%3][ii%3] = i
    cases.append(current_cases)

I’ve written this solution down this time because I seem to rediscover it every time I encounter it. Hopefully, this will save you some work too 😀

Eddie Ma

March 5th, 2011 at 11:15 pm

The Right Tool (Why I chose Java to do RSA)

without comments

Brief: I learned something valuable last week when working on this RSA encryption/decryption assignment for my Computer Security class. It’s important to be versatile when doing computer science — we must ensure we always use the most efficient tool. If we aren’t versatile, we risk taking tremendous amounts of time trying to reimplement something that already exists elsewhere.

So, what tool is the right tool to quickly throw together RSA encryption?

It turns out that Java does an excellent job. Its BigInteger class has all the ingredients you’ll ever need.

// This function generates a new probable prime ...
BigInteger p = BigInteger.probablePrime(bits, random);

// This function performs modulus inverse ...
BigInteger d = e.modInverse(phi_n);

// These functions can be used to check your work ...
BigInteger one = d.multiply(e).mod(phi_n);
BigInteger one = p.gcd(q);

// This function is at the heart of RSA ...
BigInteger C = M.modPow(d, n);

Before I looked at the Java documentation, I had plans to do this with Python and some of my classmates had plans with MATLAB. It’s not that these are inherently bad technologies — they’re just not the right tool.

As much as I have gripes with Java, I’ve got to say that this made me and a lot of my class very happy 😀

Eddie Ma

February 24th, 2011 at 6:26 pm

Posted in Pure Programming

Tagged with , ,

The Null Coalescing Operator (C#, Ruby, JS, Python)

without comments

Null coalescence allows you to specify what a statement should evaluate to instead of evaluating to null. It is useful because it allows you to specify that an expression should be substituted with some semantic default instead of defaulting on some semantic null (such as null, None or nil). Here is the syntax and behaviour in four languages I use often — C#, Ruby, JavaScript and Python.

C#

Null coalescencing in C# is very straight forward since it will only ever accept first class objects of the same type (or null) as its operator’s arguments. This restriction is one that exists at compile time; it will refuse to compile if it is asked to compare primitives, or objects of differing types (unless they’re properly cast).

Syntax:

<expression> ?? <expression>

(The usual rules apply regarding nesting expressions, the use of semi-colons in complete statements etc..)

A few examples:

DummyNode a = null;
DummyNode b = new DummyNode();
DummyNode c = new DummyNode();

return a ?? b; // returns b
return b ?? a; // still returns b
DummyNode z = a ?? b; // z gets b
return a ?? new DummyNode(); // returns a new dummy node
return null ?? a ?? null; // this code has no choice but to return null
return a ?? b ?? c; // returns b -- the first item in the chain that wasn't null

No, you’d never really have a bunch of return statements in a row like that — they’re only there to demonstrate what you should expect.

Ruby, Python and Javascript

These languages are less straight forward (i.e. possess picky nuances) since they are happy to evaluate any objects of any class with their coalescing operators (including emulated primitives). These languages however disagree about what the notion of null should be when it comes to numbers, strings, booleans and empty collections; adding to the importance of testing your code!

Syntax for Ruby, Javascript:

<expression> || <expression>

Syntax for Ruby, Python:

<expression> or <expression>

(Ruby is operator greedy :P.)

The use of null coalescence in these languages are the same as they are in C# in that you may nest coalescing expressions as function arguments, use them in return statements, you may chain them together, put in an object constructor as a right-operand expression etc.; the difference is in what Ruby, Python or Javascript will coalesce given a left-expression operand. The below table summarizes what left-expression operand will cause the statement to coalesce into the right-expression operand (i.e. what the language considers to be ‘null’-ish in this use).

Expression as a left-operand Does this coalesce in Ruby? Does this coalesce in Python? Does this coalesce in JavaScript?
nil / None / null Yes Yes Yes
[] No Yes No
{} No Yes n/a*
0 No Yes Yes
0.0 No Yes Yes
“” No Yes Yes
No Yes Yes
false / False / false
Yes Yes Yes

*Note that in JavaScript, you’d probably want to use an Object instance as an associative array (hash) so that the field names are the keys and the field values are the associated values — doing so means that you can never have a null associative array.

Contrast the above table to what C# will coalesce: strictly “null” objects only.

The null coalescing operator makes me happy. Hopefully it’ll make you happy too.

Eddie Ma

July 7th, 2010 at 11:00 am

Borrowing Ruby ideas: Returning an object instance

with 3 comments

Brief: Ruby conventions were designed to be particularly satisfying and intuitive for the developer. One convention that Ruby adds to the object oriented world is for mutators (setters) to return the object instance — that is, calling an object’s mutators will not only alter the object, but will also return the object (not the mutated property). This is especially useful if you want to chain a bunch of mutators together for code legibility or developer convenience.

This would be a welcome shorthand for developers of C-derived object oriented languages such as Java and C#. The following chain…

a.setMass(17);
a.setName("cube");
a.setFace(null);

…would become…

a.setMass(17).setName("cube").setFace(null);

…a much more compact and what I feel is a more intuitive chain.

Eddie Ma

June 27th, 2010 at 3:00 am

Brief Hints: C# Nullable Types and Arrays, Special Double Values

with 2 comments

Brief Hints: I wanted to show you three things in C# that I’ve been using a lot lately.

Nullable Types are a convenient language construction in C# that allows one to assign a primitive type with null…

double? someval = null;
// declares a nullable double called 'someval'.

The question mark suffixing the keyword double makes the variable someval nullable. This was originally designed so that one can retrieve values from LINQ to SQL without checking for nulls (SQL inherently makes this distinction). This could be thought of as yet another construct to make autoboxing primitives more intuitive and more entrenched in the language.

I use nullable types when I need a special ‘unassigned’ value for “find the greatest” or “find the least” kinds of loops.

When we apply Nullable Types to Arrays, we get an array of nullable primitives (arrays are already nullable, being first class objects).

double?[] somevals = new double?[10];
// declares an array called 'somevals' of ten nullable doubles.

An array of primitives is initialized with all values 0.0; whereas an array of primitve?s is initialized with nulls.

Special Double Values are also something that I’ve started using a lot. There are many algorithms I’ve been coming across that use “magic numbers” corresponding to arbitrarily high and arbitrarily low numbers. Instead of using evil magical quantities, I’ve been using Double.PositiveInfinity and Double.NegativeInfinity. C# makes it easy to assign three more special quantities: Double.NaN, Double.MinValue and Double.MaxValue.

Edit: I forgot to mention why I kept italicizing the word primitive. C# doesn’t really have primitives that are exposed to the developer– everything actually IS an object, and the illusion of boxing or not isn’t really relevant. This just makes nullable types all the more logical.

Eddie Ma

March 16th, 2010 at 12:01 pm

  • Page 1 of 2
  • 1
  • 2
  • >