Monday, May 14, 2012

JavaScript Object Class

JavaScript Object Oriented Framework

JavaScript is fairly quirky (you can learn it at the code academy). It is object oriented, but its a sort of duck typed version.

Every object is really an associative array, so writing foo.bar is the same as foo["bar"]. They are synonymous.

Curiously enough, JavaScript's object oriented framework has a base class called Object. Lets discuss its properties.

Object Properties

What properties does a generic object have?

1. It keeps track of its own constructor, for example:

var foo = new Array();
console.log(foo.constructor === Array); // prints "true"

The instanceof operator checks the value of the constructor property.

2. We can also convert an object to a string by a toString() method.

This does the obvious thing: returns a string representation of the object.

(Actually, if you're a mathematician, you might want to make a toTeX() method...)

3. What about converting an object to a primitive type (well, a primitive type except a string)? We have the valueOf() method.

4. Since we're duck typing objects, we might want to check the properties an object has. We can do this with the hasOwnProperty() method.

It's a function that takes a string, for example "toString", then checks to see if our object has it or not. If our beloved object has it, then foo.hasOwnProperty("toString") returns true.

5. The object base class has a method testing a given property if it's enumerable or not. In other words: it tests if we can use it in a loop construction. This method is called propertyIsEnumerable(). For example:

var foo = { bar:0 };
foo.propertyIsEnumerable("x"); // returns true
foo.propertyIsEnumerable("spam"); // returns false, since foo.spam is undefined
foo.propertyIsEnumerable("valueOf"); //returns false for inherited properties

6. The last method I'll discuss is kind of tricky. The isPrototypeOf() method is similar to the instanceof operator discussed above (see this discussion [StackExchange.com] for more details).

Object.prototype.instanceOf = function( iface )
{
    return iface.prototype.isPrototypeOf( this );
};

Addendum: to find all the properties of the Object class on YOUR system, run the following in your browser's javascript console (however you find that...on Mozilla, it's in the "Tools" part of the browser):

function getAllProperties(object){
    return Object.getOwnPropertyNames(object);
}
console.log(getAllProperties(Object));

/* prints out
[ 'prototype',
  'getPrototypeOf',
  'getOwnPropertyDescriptor',
  'keys',
  'defineProperty',
  'defineProperties',
  'create',
  'getOwnPropertyNames',
  'isExtensible',
  'preventExtensions',
  'freeze',
  'isFrozen',
  'seal',
  'isSealed',
  'length',
  'name',
  'arguments',
  'caller' ] */

Monday, April 30, 2012

Metanotes on C# with Ubuntu Linux

This is a "note-to-self" type blogpost, but some other people might find it useful.

How to install the C# compiler on Ubuntu (Linux)? There are several possibilities.

The first: use Mono. This is an open-source version of Microsoft's .NET framework.

Compiling things on the command line is simple, merely use gmcs when calling the compiler.

There are some idiosyncrasies unique to Mono, however. For example, you'll need to install (for Ubuntu 12.04) the gtk-sharp2 package for GUI programming.

There are difficulties with this (I never got it to work!). Consider the following program:

/* begin hello.cs */
using Gtk;
using System;
 
class Hello {
 
        static void Main()
        {
                Application.Init ();
 
                Window window = new Window ("helloworld");
                window.Show();
 
                Application.Run ();
 
        }
}
/* end hello.cs */

There is an error:

$ gmcs hello.cs -pkg:gtk-sharp-2.0
alex@tomato:~/app/cv$ ./hello.exe
Missing method System.Type::op_Inequality(Type,Type) in assembly /usr/lib/mono/2
.0/mscorlib.dll, referenced in assembly /usr/lib/mono/gac/gtk-sharp/2.12.0.0__35
e10195dab3c99f/gtk-sharp.dll

Unhandled Exception: System.MissingMethodException: Method not found: 'System.Ty
pe.op_Inequality'.
  at Gtk.Window..ctor (System.String title) [0x00000] in :0 
  at Hello.Main () [0x00000] in :0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.MissingMethodException: Method not fou
nd: 'System.Type.op_Inequality'.
  at Gtk.Window..ctor (System.String title) [0x00000] in :0 
  at Hello.Main () [0x00000] in :0

Quite tragic, yes yes. Aside from this, very basic C# program appears to work on Ubuntu.

Next time I'll examine how Mono handles C# programs involving LINQ [wikipedia.org].

Sunday, April 29, 2012

OpenCL (Part 1)

So suppose you had a fancy multicore processor and a fancy GPU...what can you do with them? How to take advantage of the parallelism?

It seems OpenCL and friends (e.g., CUDA) deal with this.

You've got kernels which intuitively is like a C function, but serves as the basic unit of executable code. It can be either data-parallel or task-parallel. In any event, kernels are parallel.

The Program Object then consists of kernels and other functions (analogous to a dynamic library).

More precisely, we have application queue kernel execution instances, which queues kernel objects in order. But it may execute kernel objects either in-order or out-of-order.

Since we are working with a graphics chip, we can process vectors, images, or volumes. These are 1-dimensional, 2-dimensional, and 3-dimensional domains, respectively.

Each independent element of execution in an N-dimensional domain is called a work-item; the N-dimensional domain defines the total number of work-items that execute in parallel.

Parallelization demands concern for synchronization, viz. synchronizing either data [i.e., memory] or execution.

Although OpenCL does not permit global synchronization, we can have "local" synchronization. What does this mean? Well, consider some image processing problem. We can make the image into a "quilt" of "patches" where each patch is, e.g., 128×128 pixels...this "patch" is called a workgroup, and we may synchronize within each workgroup.

Note we must be clear if we synchronize memory or execution.

We cannot synchronize between different workgroups.

We use "barriers" to synchronize execution; and "memory fences" to synchronize memory accesses.

Sadly, alas, this may require using multipass algorithms for global synchronization (e.g., between kernels). Alas, alas, multipass!

So How to Program in OpenCL?

Well, there are five things we work with: cl_device_id, cl_kernel, cl_program, cl_command_queue, and cl_context.

We already discussed kernels and programs, which are like functions (kernel) and a collection of functions (program).

So what's the other guys...bonus parts?

No! The Host is your computer, and it's connected to one or more Devices (e.g., CPU, GPU, DSP, etc.). A device is anything providing processing power.

The Device receives kernels from the host. A cl_device_id represents a device.

We have two things left: the command queue, and the context.

The device receives its kernels through a Command Queue.

OpenCL contexts enables devices to receive kernels and transfer data.

Further Reading

  1. A Gentle Introduction to OpenCL, Dr Dobbs Journal.
  2. OpenCL Presentation [pdf]
  3. OpenCL by Example [ucdavis.edu] discusses...OpenCL...by...example...
  4. Getting started with OpenCL and GPU computing

Thursday, December 22, 2011

Lectures on the Metacircular Evaluator

I have been struggling with the notion of a "metacircular evaluator" for a while. Then I stumbled upon the MIT lectures for it.

The lectures are quite beautiful, and should be watched!

MIT's 6.001 Lecture 7A YouTube clip

MIT's 6.001 Lecture 7B YouTube clip

Bear in mind, these "clips" are roughly an hour long...but they will solve all problems involving the metacircular beast!

Monday, December 19, 2011

Learning Lua

So I have learned about LuaTeX, which basically implements TeX in Lua and thus enables Lua scripting inside a TeX document. Thus I want to learn Lua!

Hello World!

I installed the basic lua50 package on ubuntu, so let me write my first program.

-- begin hello.lua

-- This is a comment

print("Goodbye, Cruel World!")

-- end hello.lua

One runs it on the *nix command line by $ lua hello.lua

However, we can use write(...) instead of print(...), the difference is that print() automatically adds a new line.

Getting User Input

We can ask for user's information:

-- begin name.lua 

io.write("What's your name? ")
name = io.read()
print("Why, '"..name.."' is a stupid name!")

-- end name.lua

We start using the io module's functions. We need to indicate this by calling io.read() and io.write()

Unique Aspects of Lua

Lua is unique in that everything is-a table. That's how you implement classes, data structures, and so on. (Think how LISP has everything is-a list.)

Even operator overloading is handled through tables...well, "metatables".

There are many examples of advanced table usage on Lua's wiki. So next time, we'll start considering examples involving tables.

Thursday, December 15, 2011

CWEB, Part 2: Hello World returns!

Continuing from our previous post on CWEB, we will take the time honored example:
lets consider a more complicated "Hello World!" Program.

\def\title{Hello World, Reloaded}

@*A Simple Example.
This is a trivial example of a \.{CWEB} program.
It is, of course, the classic "hello, world"
program we all know and love:

@c
@<Header files needed by the program@>@;
@#
main(void)
{
   @<Print the message |"hello, world"|@>@;
}

@ Naturally, we use |printf| to do the dirty work:

@<Print the message |"Hello, World!"|@>=
printf("Hello, World!\n");

@ The prototype for |printf| is in the standard
header, \.{<stdio.h>}.

@<Header files needed by the program@>=
#include <stdio.h>

@*Index.

This is perhaps the simplest example demonstrating how to use chunk identifiers (those @<...@> things) in CWEB.

Note that \.{CWEB} typesets CWEB using typewriter font.

Also note that we don't have to define a chunk before we use it. That's what we did in this example, all the chunks were defined after they were used.

What are those @; symbols used for? Well, they're for formatting, and they don't do anything other than prettyprint the TeX output.

Monday, December 12, 2011

CWEB

It turns out there is some interesting stuff to do with CWEB.

First off, you program in chunks/modules called "sections". Each section contains either code or documentation. Each section begins with @.

The skeleton of a CWEB program might look like:

% this is a comment
\def\title{My awesome program!!!!} % this sets the title
\datethis % this sets the date
@*Introduction. % create the introduction section
This program will solve all my problems.

[Code not shown]

@*Index.

The line of code @*Introduction. will create a section with a title, it would look like "1. Introduction. ". It's TeX equivalent would be \medbreak\noindent{\bf 1.\quad Introduction.\quad}, and yes those \quad spacings are correct.

The first line of code puts a time stamp between the first section and the title.

The last line produces an index of all the variables.

The Code

How do we actually write code in CWEB?

We can use @c to start writing code, just as @ is used to write documentation.

And just as we had @*[title]., we have something analogous for code @<[title]>

However, the first time we use @<section name>, we are defining it. When we use it later on, we are calling it. Note the difference!

Comments

A simple comment is formatted by @q ... and it is not printed to the TeX file.

Write to Different Files

If one writes @(foo>, then the contents of the section (onwards?) is written to the file foo.

Macro Definitions

Instead of that ungodly #define ..., we write @d ... to do the same thing.

Some example code (from string.w):

@s string int
@s Xstring int @q -- a hint for the typesetter -- @>
@(xstring.h@>=
#ifndef XSTRING_H
#define XSTRING_H // prevent multiple inclusions
@#
class Xstring {
 @<private |Xstring| members@>@;
public:@/
 @<public |Xstring| members@>@;
};
@#
#endif

What does the @# line do? Well, it forces a line break, and that's all.

Similarly, the @/ line forces CWEAVE to put a line break in the C code.

But what do those @>= lines mean? We are initializing and declaring an identifier for a section. For us, that is xstring.h, and since we have prefaced it with @( it means we are working with the code in a separate file.

Observe that @<public |Xstring| members@>@; simply loads the code defined in section public |Xstring| members since the section ended without an equal sign, i.e. @> instead of >=.

More notes to come, but one might also be interested in Knuth's straighten.w program for computing irreps of the symmetric group.

Addendum

Here is the obligatory "Hello World!" type program:

@*Introduction.
This is a simple ``Hello World!'' program using literate
programming. I hope it works! (It does work!)

@c
#include <stdio.h>

int main(int argc, char** argv)
{
 printf("Hello world! I am literate programming?\n");
 return 1;
}

@*Index.