Tuesday 3 September 2013

Generating Latex table of Matlab/Octave Matrix


I created some code in Octave/Matlab to generate latex table from matrix data. I created this because in my case I was tuning some data and algorithms for a paper I was writing and I loathed entering my data into the latex over and over in large tables.

The use just needs to supply a file descriptor, names for the table rows, column, the data matrix and if desired a wrapper to wrap the data entries from the matric in any specific formatting.


Example wrapper functions



function outstr = numWrapper(value)

outstr= strcat("\\num{" , num2str (value), "}");

endfunction
function outstr = ccolWrapper(value)
outstr= strcat("\\ccol{" , num2str (value), "}");
endfunction
 
 


This is the code used to generate the latex
 


%
% creates a latex style table from matrix data.
% wrapper is a function used to wrap the data in each cell
% can be used to apply more formatting in latex
%
% fid is the file pointer to the file to write to
% matrix is the data matrix that will be placed starting at row 1 column 1
% rowNames is a column vector of the string names to be inserted as the names for the rows
% size(rowNames,1) == size(columnNames,1)+1, i.e. the
% columnNames will be used to label each of the column in the data
% wrapper is a special function that will take your input data and wrap it with latex formatting
%
% Will look like
% latex table formatting
% columnNames[0] | columnNames[1] | columnNames[2] | columnNames[2] | ...
% rowNames[0] | matrix(0,0) | matrix(0,1) | matrix(0,2) | ...
% rowNames[1] | matrix(1,0) | matrix(1,1) | matrix(1,2) | ...
% .
% .
% .
%
%
%
%
% latex table formating
function fid = matrixToLatexTable(fid, matrix, rowNames, columnNames, wrapper )
fprintf(fid,'\\documentclass{article}\n');
fprintf(fid,'\\begin{document}\n');
fprintf(fid,' \\begin{tabular}{ |');
for col=1:size(matrix,2)+1
fprintf(fid,'c | ');
end
fprintf(fid,'}\n\\hline\n');
for col=1:size(columnNames,1)
if col==size(columnNames,1)
fprintf(fid,' %s', columnNames(col,:))
else
fprintf(fid,' %s & ', columnNames(col,:))
end
end
fprintf(fid,'\n \\\\ \\hline\n');
% now write the elements of the matrix
for r=1:size(matrix,1)
fprintf(fid,' %s & ', rowNames(r,:))
for c=1:size(matrix,2)
if c==size(matrix,2)
if true
fprintf(fid,'%s ',wrapper(matrix(r,c)));
else
fprintf(fid,'%f ', matrix(r,c));
end
else
if true
fprintf(fid,'%s & ',wrapper(matrix(r,c)));
else
fprintf(fid,'%f & ', matrix(r,c));
end
end
end
fprintf(fid,' \\\\ \\hline \n');
end
fprintf(fid,'\\end{tabular}\n');
fprintf(fid,'\\end{document}\n');
fclose(fid);
endfunction
 
 
Best of luck
- Glen 

Sunday 19 May 2013

psycopg2 instering an array of polygons

This post is an example of how to insert an array of polygons into the Postgres database using Python and psycopg2.

The most important and problematic part of inserting a polygon array is the string formatting for the polygon[].

The first thing I tried was to just make a string for the exact syntax the Postgresql expects. This was not easy in my case. Probibly mostly because I was reading all of my data from a file and python would wrap qoutes around many of the changes I made in the file.

Next I found that psycopg2 will automatically turn a Python list into the proper syntax for ARRAY[] insertion. This would work great but some of the type checking between Python and psycopg2 lead to an error that the column you are trying to insert into is of type polygon not type text[].

Last I stumbled upon what worked for me. I had to turn the array of polygons into a python list just I could encapsulate the string in double quotes and lastly in the whole thing in single quotes.

Example:

Data:
    This is a list of axis aligned box polygons that I am inserting separated by ';'
((-7,-7),(-7,-5.6),(-5.6,-5.6),(-5.6,-7),(-7,-7));((-7,-2.8),(-7,-1.4),(-5.6,-1.4),(-5.6,-2.8),(-7,-2.8));((-7,-0),(-7,1.4),(-5.6,1.4),(-5.6,-0),(-7,-0));((-7,2.8),(-7,4.2),(-5.6,4.2),(-5.6,2.8),(-7,2.8));((-7,5.6),(-7,7),(-5.6,7),(-5.6,5.6),(-7,5.6));((-5.6,-5.6),(-5.6,-4.2),(-4.2,-4.2),(-4.2,-5.6),(-5.6,-5.6));((-5.6,-4.2),(-5.6,-2.8),(-4.2,-2.8),(-4.2,-4.2),(-5.6,-4.2));((-4.2,-5.6),(-4.2,-4.2),(-2.8,-4.2),(-2.8,-5.6),(-4.2,-5.6));((-4.2,-4.2),(-4.2,-2.8),(-2.8,-2.8),(-2.8,-4.2),(-4.2,-4.2));((-4.2,-2.8),(-4.2,-1.4),(-2.8,-1.4),(-2.8,-2.8),(-4.2,-2.8));((-4.2,4.2),(-4.2,5.6),(-2.8,5.6),(-2.8,4.2),(-4.2,4.2));((-4.2,5.6),(-4.2,7),(-2.8,7),(-2.8,5.6),(-4.2,5.6));((-2.8,5.6),(-2.8,7),(-1.4,7),(-1.4,5.6),(-2.8,5.6));((-1.4,-7),(-1.4,-5.6),(-0,-5.6),(-0,-7),(-1.4,-7));((-0,-7),(-0,-5.6),(1.4,-5.6),(1.4,-7),(-0,-7));((1.4,4.2),(1.4,5.6),(2.8,5.6),(2.8,4.2),(1.4,4.2));((2.8,-7),(2.8,-5.6),(4.2,-5.6),(4.2,-7),(2.8,-7));((4.2,5.6),(4.2,7),(5.6,7),(5.6,5.6),(4.2,5.6));((5.6,-5.6),(5.6,-4.2),(7,-4.2),(7,-5.6),(5.6,-5.6));((5.6,2.8),(5.6,4.2),(7,4.2),(7,2.8),(5.6,2.8))

After reading this from a file into a single string I used the following code to format it to psycopg2's liking.


            obstacles=valuesDict['box_obstacles'].split(";")
            obstacles_string = "{"
            for obstacle in obstacles:
                obstacles_string = obstacles_string + "\"" + str(obstacle) + "\","
               
            obstacles_string = obstacles_string[:-1] + "}"
            self._box_obstacles=obstacles_string

© 2013 Glen Berseth | www.fracturedplane.com

Postgresql: Calculate the number of polygon islands or overlapping groups

This post is about some work I did on how to calculate the number of number of groups of intersecting polygons in an array of polygons in Postgresql


First lets be a little more strict about what the definition of an island is. For the purposes of this algorithm an island consists of a set polygons where at least one polygon in the set overlaps another in the set.


I created a function to calculate the number of islands attached is the plpgsql code for the function.


CREATE OR REPLACE FUNCTION getNumIslands(polys polygon[]) RETURNS INT AS
$BODY$
DECLARE
islandList polygon[]; -- holds the set of obstacles that make up the current island.
islandCount INT; -- holds the count of the number of islands.
poly polygon; -- holds the polygon to start an island search
polys_copy polygon[]; -- A copy of the input list
inddex INT; -- keeps track of the current index in the polys_copy search

BEGIN
    
islandCount := 0;

islandList := polys;
polys_copy := polys;
inddex := 1;

WHILE array_length(polys_copy,1) > 0
LOOP
    -- RAISE NOTICE 'Poly_list length is: %', array_length(polys_copy, 1);
    -- grab the first poly
    poly := polys_copy[1];
    islandList := array_append(ARRAY[]::polygon[], poly);
    -- RAISE NOTICE 'Current island is %', islandList;
    -- remove the first poly because we dont care about it overlaping itself.
    polys_copy := polys_copy[2:array_length(polys_copy, 1)];
    
    -- Make a list of all the polys left that overlap with poly
    WHILE inddex <= array_length(polys_copy, 1)
    LOOP
        -- If the poly_copy overlaps the poly then add its index to the list
        -- of polys to be removed
        FOREACH poly IN ARRAY islandList
        LOOP
            IF polys_copy[inddex] && poly
            THEN
                islandList := array_append(islandList, polys_copy[inddex]);
                --
                IF array_length(polys_copy,1) = 1
                THEN
                    polys_copy := null;
                ELSE
                    polys_copy := polys_copy[1:inddex-1] || polys_copy[inddex+1:array_length(polys_copy, 1)];
                END IF;
                -- RAISE NOTICE 'Intersects with poly index: %', inddex;
                -- When a new intersecting poly is found it needs to be compared
                -- to every poly not just the polys left in the list
                inddex := 0;
                EXIT;
            END IF;
        END LOOP;
        -- RAISE NOTICE 'Current island is %', islandList;
        inddex := inddex + 1;
    END LOOP;
    
    islandCount := islandCount + 1;
    inddex := 1;
END LOOP;

RETURN islandCount;
                
END
                
$BODY$ LANGUAGE plpgsql;
© 2013 Glen Berseth | www.fracturedplane.com

Sunday 21 April 2013

Install Twiki on Ubuntu 12.04


This is short guide on how to install Twiki ~5.13 on Ubuntu 12.04. This guide has a fix or two that was not present in any other guide I found.

  1. Install all of the relevant dependencies.

    sudo apt-get install apache2 libgdal-perl libcgi-session-perl libhtml-tree-perl liberror-perl libfreezethaw-perl libgd2-xpm rcs libapache2-mod-perl2-doc libapache2-mod-perl2 libapache2-mod-php5 latex2html
  2.  Download Twiki

    If installing in the default directory for Apache (/var/www) place the downloaded zip/tar.gz file in /var/www (http://twiki.org/cgi-bin/view/Codev/DownloadTWiki).
  3. Install Twiki

    cp /var/www/twiki/bin/LocalLib.cfg.txt /srv/www/ducklington.org/twiki/bin/LocalLib.cfg
    chown -R www-data:www-data /var/www/twiki
  4. Configure Twiki
    Go to this link and have the page generate the configuration needed for your apache and perl configuration.
    http://twiki.org/cgi-bin/view/TWiki/ApacheConfigGenerator

    save the generated configuration to /etc/apache2/conf.d/twiki.conf
  5. Restart Apache2
    sudo /etc/init.d/apache2 reload
  6. Allow configuration file to know where the path to the configuration should be put.

    Edit /var/www/twiki/bin/LocalLib.cfg:
    $twikiLibPath = "/var/www/twiki/lib";
  7. Run Twiki config.
    Configure your twiki: go to http://localhost/twiki/bin/configure,  setup admin password and paths.


  8. Edit /var/www/twiki/bin/LocalLib.cfg:
    $twikiLibPath = "/var/www/twiki/lib";

Wednesday 17 April 2013

Putting a steering algorithm into SteerSuite



This is a guide I created which I hope to turn into a Wiki some day on how to put your steering algorithm in SteerSuite.

  1. First things first
    1. Your agent needs to extend the SteerLib::AgentInterface class so that is can be used properly with the gspacialDatabase
    2. If your algorithm keeps collections of obstacle types or other agents the types should be changed to SteerLib::AgentInterface or other agents and SteerLib::BoxObstacle
    3. Next you will need to start converting geometries
      1. If you are lucky the algorithm that is being ported to SteerSuite will differentiate between Points and Vecotors otherwise you will need to go through every operation and check if it produces a Point or Vectory because SteerSuite differentiate between them.
    4. The *AIModule should not include the Agent type
      1. This is to avoid circular includes
      2. Not should the agent include the module type only the interfaces provided from SteerSuite
    5. Try not to change any of the math in the algorithm
      1. Best is to alter the initial conditions to fit the algorithm best and then convert the reusult computed by the algorithm back into SteerSuite coordinates.

Tuesday 19 March 2013

Postgresql Transfer Database to New Tablespace with Python

This is a quick script I wrote in python to generate the sql file needed to transfer one database to another tablespace.



 #!/usr/bin/python

# will generate the sql file needed to alter the tablespace for a database.

import psycopg2
import psycopg2.extras
import sys

#
# Configuration
# 
host = '';            # The host on which the database resides.
user = '';            # The username to access the database.
password = '';            # The password to access the database.
db = '';            # The database to move.
tablespace = '';    # The tablespace to move the database to.
output = ""

#
# Application
#
conn = psycopg2.connect(database=db, user=user, password=password)
conn.set_isolation_level(0)  
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

# Create SQL code to put new tables and indexes in the new tablespace.
output = output + "ALTER DATABASE " + db + " SET default_tablespace = " + tablespace + ";\n"

# Select all tables from the database.
tableQuery = "SELECT * FROM pg_tables where tableowner='" + user + "' ORDER BY tablename"

cur.execute(tableQuery)

db_tables = cur.fetchall()
# print db_tables 
for table in db_tables:
    schemaName = table['schemaname']
    tableName = table['tablename']

    # Create SQL code to move the table to the new tablespace.
    output = output + "ALTER TABLE "+ schemaName +"." + tableName + " SET TABLESPACE " + tablespace + ";\n";
    # print output

    # Select all indexes from the table.
    indexQuery = "SELECT * FROM pg_indexes WHERE schemaname = '" + schemaName + "' AND tablename = '" + tableName + "' ORDER BY indexname"
    print indexQuery
    cur.execute(indexQuery)
    print cur.statusmessage
    db_indexes = cur.fetchall()
    # print db_indexes
    for index in db_indexes:
        print dict(index)
        indexName = index['indexname']

        # Create SQL code to move the index to the new tablespace.
        output = output + "ALTER INDEX " + schemaName + "." + indexName + " SET TABLESPACE " + tablespace+ ";\n";
    


# Write the resulting SQL code to a file.
filename = 'migrate_' + host + '_' + db + '_to_' + tablespace + '.sql'
sqlfile = open('filename, 'w')
sqlfile.write(output)

 


Best of luck.


References:
  1. http://blog.lodeblomme.be/2008/03/15/move-a-postgresql-database-to-a-different-tablespace/
  2. http://www.postgresql.org/docs/9.1/static/sql-createtablespace.html

Saturday 9 March 2013

Rare but powerful Unix/Linux commands

This blog is a list of some of the more powerful but not as frequently used Linux or Unix commands.

Need to copy a large amount of files from one directory to another

find $directory1 -maxdepth 1 -type f -name '*' -exec mv {} $directory2/. \; 

This can also be used with the mv command.
 
 
What to rename a number of file in a directory and preserve their numbering
 
rename "s/scenario/testcase-/" scenario*.xml
 
Files were
 



scenario2797.xml scenario4597.xml scenario6397.xml scenario8197.xml scenario9998.xml
scenario2798.xml scenario4598.xml scenario6398.xml scenario8198.xml scenario9999.xml
 
Now they are 
testcase-2797.xml testcase-4597.xml testcase-6397.xml testcase-8197.xml testcase-9998.xml
testcase-2798.xml testcase-4598.xml testcase-6398.xml testcase-8198.xml testcase-9999.xml 
 
 
for file in `find . -name '*.sql' -print 2>/dev/null`
do
    echo $file
    echo "Dirname:"
    echo ${file##*/}
    filename=${file##*/}
    fileprefix=${filename%.*}
    dirname $file
    echo "fileprefix: $fileprefix"
    psql -d  -U  -f $filename > "results/$fileprefix.result"
done
 

Friday 8 March 2013

SmartBody, first steps


SmartBody is a character animation platform originally developed at the University of Southern California Institute for Creative Technologies. SmartBody provides locomotion, steering, object manipulation, lip syncing, gazing and nonverbal behavior in real time.
SmartBody is written in C++ and can be incorporated into most game and simulation engines. SmartBody is a Behavioral Markup Language (BML) realization engine that transforms BML behavior descriptions into realtime animations. SmartBody runs on Windows, Linux, OSx as well as the iPhone and Android devices.

I want to use this to control the character animations for a video game made in Unity3D.

 The package does say this it can work with
  • Unity
  • Ogre
  • Unreal
  • Panda3D
  • GameBryo
However it supports Unity and Ogre actively. 

Goal: To send BML messages to a control characters in SmartBody via TCP or UDP messages.

Tasks:
  1. Get and Compile SmartBody ( For Windows and Linux )
  2. Familiarize self with SmartBody examples
  3. Learn how to use TCP in Python.
  4. Produce code to control SmartBody character from python code combining what was learned from 2 and 3.


    
    import random

    import select
    import socket
    import sys

    service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect the socket to the port where the server is listening
    server_address = ('localhost', 3850)
    print >> sys.stderr, 'connecting to %s port %s' % server_address
    service.connect(server_address)


    print "|--------------------------------------------|"
    print "|       Starting Locomotion Type Demo        |"
    print "|--------------------------------------------|"

    smartBodyRelitivePath = "../../smartbody/data/"

    # Add asset paths
    scene.addAssetPath('script',smartBodyRelitivePath + 'sbm-common/scripts')
    scene.addAssetPath('mesh', smartBodyRelitivePath + 'mesh')
    scene.addAssetPath('mesh', smartBodyRelitivePath + 'retarget/mesh')
    scene.addAssetPath('motion', smartBodyRelitivePath + 'ChrBrad')
    scene.addAssetPath('motion', smartBodyRelitivePath + 'ChrRachel')
    scene.addAssetPath('motion', smartBodyRelitivePath + 'retarget\motion')
    scene.addAssetPath('motion', smartBodyRelitivePath + 'sbm-common/common-sk')
    scene.loadAssets()


    # Set scene parameters and camera
    print 'Configuring scene parameters and camera'
    scene.setScale(1.0)
    scene.setBoolAttribute('internalAudio', True)
    scene.run('default-viewer.py')
    camera = getCamera()
    camera.setEye(0, 2.87, 11.67)
    camera.setCenter(0, 2.14, 9.81)
    camera.setUpVector(SrVec(0, 1, 0))
    camera.setScale(1)
    camera.setFov(1.0472)
    camera.setFarPlane(100)
    camera.setNearPlane(0.1)
    camera.setAspectRatio(0.966897)
    scene.getPawn('camera').setPosition(SrVec(0, -5, 0))

    # Set joint map for Brad
    print 'Setting up joint map for Brad'
    scene.run('zebra2-map.py')
    zebra2Map = scene.getJointMapManager().getJointMap('zebra2')
    bradSkeleton = scene.getSkeleton('ChrBrad.sk')
    zebra2Map.applySkeleton(bradSkeleton)
    zebra2Map.applyMotionRecurse('ChrBrad')

    # Retarget setup
    scene.run('motion-retarget.py')
    # Animation setup
    scene.run('init-param-animation.py')

    # Set up 3 Brads
    print 'Adding characters into scene'
    posX = -200
    for i in range(1): # Only add one brad
        baseName = 'ChrBrad%s' % i
        brad = scene.createCharacter(baseName, '')
        bradSkeleton = scene.createSkeleton('ChrBrad.sk')
        brad.setSkeleton(bradSkeleton)
        # Set position
        bradPos = SrVec((posX + (i * 200))/100, 0, 0)
        brad.setPosition(bradPos)
        # Set up standard controllers
        brad.createStandardControllers()
        # Set deformable mesh
        brad.setDoubleAttribute('deformableMeshScale', .01)
        brad.setStringAttribute('deformableMesh', 'ChrBrad')
        # Play idle animation
        bml.execBML(baseName, '')
        # Retarget character
        retargetCharacter(baseName, 'ChrBrad.sk', False)

    # Turn on GPU deformable geometry for all
    for name in scene.getCharacterNames():
        scene.command("char %s viewer deformableGPU" % name)

    # Whether character has reached its target
    brad1Reached = True

    # Paths for characters
    brad1Path = [SrVec(-2, 8, 0), SrVec(-2, -8, 0)]

    bradCur = 0
    pathAmt = 2


    class LocomotionDemo(SBScript):
        def update(self, time):
            # Select is a creative way of checking to see if a service has data ready to read,
            # ready to write to or an exceptional condition.
            r, w, e = select.select([service], [], [], 0.0)
            if r: # There is something to read
                data = service.recv(256)
                character = 'ChrBrad0'
                # The last 0 in the target is zero just so the character stays on the plane
                bmlMessage = ''
               
                print "BML Message for " + character + ": " + bmlMessage
                bml.execBML(character, bmlMessage)
           

    # Run the update script
    scene.removeScript('locomotiondemo')
    locomotiondemo = LocomotionDemo()
    scene.addScript('locomotiondemo', locomotiondemo)

Eclipse Find/Replace

This is a quick example on how to use the power of find and replace in eclipse. Some might say that eclipse find and replace is not as powerful as something like vi or sed but it is still rather powerful.



I had a program where I wanted to transform all of all of parameters created using #define statement to command line arguments so that I could write an algorithm to test the effect of different values for these parameters. 

First copy and past all of the define statements to another location of your program ( I wanted to keep the define statements to be used as defaults if no new parameter value is passed.

After you have copied the text should look something like 


#define PED_BRAKING_RATE    0.95f

#define PED_COMFORT_ZONE    1.5f

#define PED_QUERY_RADIUS    10.0f
 
NOTE: Make sure you have Regular expressions check-box checked.

To replace these lines with atribute definitions you can use ability of find and replace to capture strings (). Putting a regular expressions between () will save that string into a variable $1 that can be used in your replace with:. IN this case use "#define ([A-Z|_]*)[ |.|0-9|f]*" (don't include the quotes ") to find one of the above lines. Now this line can be replaced with "float $1;". very cool stuff.

If you want to change all of the character to lowercase you will have to use ctrl+shift+y. Highlight want you want to change then use ctrl+shift+y.

The last thing I did was copy and paste a bunch of lines that assigned the #defined macro to the class varaible

ped_max_speed = PED_MAX_SPEED;

That I had to do slightly by hand because find and replace does not replace with lowercase as far as I know.

I want to change these lines into the piece of code that will be used to check if there was a command line parameter option passed to change this value. If there was update the value. This part was really easy.

I could use this in my find statement:


([a-z|_]*)[a-z| |_|A-Z|=]*;


and this to replace each line with the code I wanted:

else if ((*optionIter).first == "$1")\n\t\t{\n\t\t\t(*optionIter).second >> $1;\n\t\t}


To result in:


        else if ((*optionIter).first == "ped_max_speed")
        {
            (*optionIter).second >> ped_max_speed;

        }

I used this to replace about 50 assignments. Took me about 30 seconds. 

Now all of my #define statement parameters are also command line arguments that can be passed to easily test out different values.

Happy hunting!

References:
  1. Me.

Wednesday 6 March 2013

SmartBody Example:


SmartBody characters are usually controlled via python scripts. These scripts are responsible for loading all of the features need for the character animation and then seting up the character in the environment and last functions to control the actions of the character(s).

This is a common exmaple, there are more advanced features than what is discussed in this post.

The first part of the python script to control a SmartBody character should be calls to add any assests that are need for the character animations that will be used later in the script.


smartBodyRelitivePath = "../../smartbody/data/"

# Add asset paths
scene.addAssetPath('script',smartBodyRelitivePath + 'sbm-common/scripts')
scene.addAssetPath('mesh', smartBodyRelitivePath + 'mesh')
scene.addAssetPath('mesh', smartBodyRelitivePath + 'retarget/mesh')
scene.addAssetPath('motion', smartBodyRelitivePath + 'ChrBrad')
scene.addAssetPath('motion', smartBodyRelitivePath + 'ChrRachel')
scene.addAssetPath('motion', smartBodyRelitivePath + 'retarget\motion')
scene.addAssetPath('motion', smartBodyRelitivePath + 'sbm-common/common-sk')
scene.loadAssets()


The above code first defines the relative path to the directory that contain all of the assest for character animation. These include meshes, skeletal meshes, joint maps, etc. These are usually stored in the data folder in SmartBody. As can bee seen assets for the mesh for a character is added as well as common script for that character and motion data that will be used to create the motion of the character.

The next section of the program Will configure the scene. This is much more OpenGL like and is to define the setting for the camera.


# Set scene parameters and camera
print 'Configuring scene parameters and camera'
scene.setScale(1.0)
scene.setBoolAttribute('internalAudio', True)
scene.run('default-viewer.py')
camera = getCamera()
camera.setEye(0, 2.87, 11.67)
camera.setCenter(0, 2.14, 9.81)
camera.setUpVector(SrVec(0, 1, 0))
camera.setScale(1)
camera.setFov(1.0472)
camera.setFarPlane(100)
camera.setNearPlane(0.1)
camera.setAspectRatio(0.966897)
scene.getPawn('camera').setPosition(SrVec(0, -5, 0))


The next section is a little less obvious. It first runs a script, this script loads a joint map. After a joint map is loaded it can be applied to a character in SmartBody.


# Set joint map for Brad
print 'Setting up joint map for Brad'
scene.run('zebra2-map.py')
zebra2Map = scene.getJointMapManager().getJointMap('zebra2')
bradSkeleton = scene.getSkeleton('ChrBrad.sk')
zebra2Map.applySkeleton(bradSkeleton)
zebra2Map.applyMotionRecurse('ChrBrad')


Next two more scripts are run to setup the motion animation that the character can do and next activates the parametric animation that is used for the characters.


# Retarget setup
scene.run('motion-retarget.py')
# Animation setup
scene.run('init-param-animation.py')


Now everything that needs to be done to be able to use animations is complete The last step that needs to be done so that a character can be used in the scene is described below.


# Set up Brads

print 'Adding characters into scene'
posX = -200
for i in range(1): # Only add one brad
    baseName = 'ChrBrad%s' % i
    brad = scene.createCharacter(baseName, '')
    bradSkeleton = scene.createSkeleton('ChrBrad.sk')
    brad.setSkeleton(bradSkeleton)
    # Set position
    bradPos = SrVec((posX + (i * 200))/100, 0, 0)
    brad.setPosition(bradPos)
    # Set up standard controllers
    brad.createStandardControllers()
    # Set deformable mesh
    brad.setDoubleAttribute('deformableMeshScale', .01)
    brad.setStringAttribute('deformableMesh', 'ChrBrad')
    # Play idle animation
    bml.execBML(baseName, '')
    # Retarget character
    retargetCharacter(baseName, 'ChrBrad.sk', False)



# Turn on GPU deformable geometry for all
for name in scene.getCharacterNames():
    scene.command("char %s viewer deformableGPU" % name)


To add a character to the scene it needs to have a unique name ( will be seen later why ) and must be assigned a skeleton. THe rest of the code sets up the initial conditions for the character Brad: initial position, standard controllers, scale and turn on deformable geometry (by default a characters geometry is not displayed) and the initial posture for brad. A posture is the stance the character will take when no other animations are in effect.


The last part of the script is the part that you must write. After the characters have been initialized properly it is up to you to control the character as you want. For this example I wrote a simple controller that accepts information from a TCP connection so that I can control the character with another program.



class LocomotionDemo(SBScript):
    def update(self, time):
        # Select is a creative way of checking to see if a service has data ready to read,
        # ready to write to or an exceptional condition.
        r, w, e = select.select([service], [], [], 0.0)
        if r: # There is something to read
            data = service.recv(256)
            character = 'ChrBrad0'
            # The last 0 in the target is zero just so the character stays on the plane
            bmlMessage = ''
            
            print "BML Message for " + character + ": " + bmlMessage
            bml.execBML(character, bmlMessage)


To add a controlling script you need to write a class and have a method called update in that class. This update method will be called every frame and you can check the characters and scene for events of interest to further animate your characters. THe code include some notes on some features of Python.

Last the script that you have created need to be given control. This is done by explicitely removing the script name if it already exsist and then creating an object that can be used to reference your update function.

NOTE: this script name is for the class that is created not the name of script file that is be used.



# Run the update script
scene.removeScript('locomotiondemo')
locomotiondemo = LocomotionDemo()
scene.addScript('locomotiondemo', locomotiondemo)




References
  1. http://smartbody.ict.usc.edu/forum
  2. http://smartbody.ict.usc.edu

Sunday 3 March 2013

plpgsql: Creating Functions and saving intermetiate query results


Sometimes SQL queries are difficult or impossible to optimize if you are using pure standard SQL.

I started this because I just wanted to find a way to save the result of a sub-query to use later. In my example I wanted to save the average + the standard deviation of a large set of values for some research. I found that Posgresql supports standard SQL only so you can not save query results. Instead you can use plpgsql with is a procedural langauge that can be used with Postgresql (psql).

These are the two tables being considered for these examples.


CREATE TABLE IF NOT EXISTS test 

(

  test_id integer NOT NULL primary key,

  algorithm_data_id integer NOT NULL references 

  test_timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

  test_status integer NOT NULL,

  num_agents integer NOT NULL,

  num_obstacles integer NOT NULL

) ;



CREATE TABLE IF NOT EXISTS composite1

    benchmark_id integer NOT NULL references test(test_id) ON DELETE CASCADE,

    collisions integer NOT NULL,    

    time double precision NOT NULL,    

    success integer NOT NULL,    

    num_unique_collisions integer NOT NULL,       

    total_distance_travelled double precision NOT NULL,       

    agent_complete integer NOT NULL,    

    agent_success integer NOT NULL,    

    optimal_path_length double precision NOT NULL,    

);


Basic syntax for a function definition


CREATE OR REPLACE FUNCTION multiply(x real, y real) RETURNS real AS 
CREATE OR REPLACE The replace part is useful for development if testing a function and updating it but also useful if it so happens that there already exist a function with the same name you want to override it to ensure proper functionality.

After the AS comes the function definition. The most non obvious part that I found was the use of '$$'. Think of the $$ as {} from many programming languages that are used to symbolize a body of code, in this case the function body.


CREATE OR REPLACE FUNCTION multiply(x real, y real) RETURNS real AS
$$
BEGIN
    RETURN x * y;
END;
$$ LANGUAGE plpgsql;
 
This is a simple example of a simple definition that can be used to multiply two numbers.
 
Note the uses of ';' they are only at the end of return statements and queries. This will be seen more later.

A more advanced example:


CREATE OR REPLACE FUNCTION getAVG_WRTTotalTicksforScenario(scenarioID INT) RETURNS double precision AS

$BODY$

DECLARE

average double precision;

BEGIN

    

SELECT AVG(total_total_ticks_accumulated/total_number_of_times_executed) INTO STRICT average

    FROM ppr_ai_data pd2, test test, algorithm_data

    WHERE test.algorithm_data_id = algorithm_data.algorithm_data_id and

           -- test.scenario_group = scenario_group and

           algorithm_data.algorithm_data_id = pd2.ppr_ai_id and

            test.scenario_group = scenarioID;

    RETURN average;

END

$BODY$ LANGUAGE plpgsql; 


Any variables that are going to be used should be defined in the declare section.

The return types of functions can be of the basic types for can be of a time defined for a table. For example



CREATE OR REPLACE FUNCTION getAllSignificantTestsForScenario(scenarioID INT, algorithmName TEXT) RETURNS SETOF Test AS

$BODY$

DECLARE

average double precision; 

std_dev double precision;

r test%rowtype;





BEGIN



average := getAVG_WRTTotalTicksforScenario(scenarioID)

        

std_dev :=    getSTDDEV_WRTTotalTicksforScenario(scenarioID)

                

RAISE NOTICE 'Average is %', average;

RAISE NOTICE 'Standard deviation is %', std_dev;



RETURN QUERY     SELECT * from test where test_id IN (

SELECT t.test_id

    FROM test t, ppr_ai_data pd, algorithm al, algorithm_data Adata

    WHERE t.algorithm_data_id = Adata.algorithm_data_id and

            pd.ppr_ai_id = Adata.algorithm_data_id and

            Adata.algorithm_type = al.algorithm_id and

            al.name = algorithmName and

            t.scenario_group = scenarioID and

        pd.total_total_ticks_accumulated / pd.total_number_of_times_executed > (average + std_dev));

                

RETURN;



END


Return can be used a in few ways. In the above case it is used to return the result of an entire query. In the above example the return is typed to that of a row of the table test. A small trick was used to get around having to return a full test row. The use of Raise in this case is just used to inform the user of the values being used in the sub query. Usually RAISE is used to inform the user issues in the function and can be used to throw exception like many other programming languages [4].

References
  1. http://www.postgresql.org/docs/9.1/static/plpgsql-statements.html
  2. http://www.postgresql.org/docs/8.4/static/plpgsql-declarations.html
  3. http://www.postgresql.org/docs/9.1/static/plpgsql-control-structures.html#PLPGSQL-STATEMENTS-RETURNING
  4. http://www.postgresql.org/docs/9.1/static/plpgsql-errors-and-messages.html

Friday 22 February 2013

IndiGolog Basics

This is a guide on the steps I took set-up a IndiGolog Program.

I prefer to divide up the sections of an IndiGolog program into different files. The different sections of an IndiGolog program are:
  1. Exogenous Actions
    1. Contains the code to handle exogenous actions from then environment.
  2. Fluents
    1. Fluents handle the current state of the environment relative to the agent.
  3. Initial Conditions
    1. The initial conditions of the agent
  4. Primitive Actions
    1. The primitive actions of the agent. These are the lowest level actions that the agent can make
  5. Procedures 
    1. The procedures of the agents. Procedures are sequences of primitive actions that are created from knowledge of the Agent.

The exogenous actions code can be small but will grow depending design. For a basic set of exogenous actions this short list could be used.



/* exog_action(reached(Location)).
    Lets the Agent know when it has fully arived at a location it was navigating
to.
*/
exog_action(reached(_)).

/*
    catch all to make sure system does not crash
*/
exog_action(_).

Fluents are one of the most important parts of the Agents design. fluents are supposed to evolve according to actions that occur. Then these fluents can be used in procedures to make good choices or in any conditions.


% Used to keep track of the state of the Entity
% When the controlled Entity dies this will be set to false.
rel_fluent(alive).
causes_val(died, alive, false, true) :-
    nl, write('Entity died'), nl.


There are different kinds of fluents in IndiGolog rel_fluent and fun_fluent which I believe stand for relational fluent and functional fluent. I am not totally sure what the difference is...


% Will be used to keep track of the inventory of the Entity.
/*    hasItem(item, player)
    Use to keep track of the many game items and players with an
    association of players with items.
*/
rel_fluent(hasItem(_,_)).
causes_val(pickup(Item,Player), hasItem(Item, Player), true, true).
causes_val(drop(Item,Player), hasItem(Item, Player), false, hasItem(Item, Player)).
 
% -- causes_true(action,fluent,cond)
%          when cond holds, doing act causes relational fluent to hold
% doing this because predicate does not exist
% these need to be defined so that the causes_val will work properly because it is
% defined to use these two predicates in ../../Eval/evalbat.pl
% because of relational fluents
causes_true(action,fluent,false).

causes_false(action, fluent, false).


The initial conditions describe the state of the agents world when the program is started. This section can also be use to test the agent by adjusting initial conditions to inspect of the agent still preforms a reasonable set of actions. 

Some predicates can be defined to help solidify the definition of initial conditions



enemies([valerie, will, amy, player]).
friends([glensnemesis, heather, jim, bob, self]).
isEnemy(Player) :- domain(Player, enemies).
isFriend(Player) :- domain(Player, friends).
isPlayer(Player) :- isFriend(Player); isEnemy(Player). 




%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Initial conditions
%% Initial values of fluents
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

initially(alive, true).
initially(hasItem(Item, Player), false) :-
    isItem(Item),
    isPlayer(Player).


initially(name, none).



Primitive actions as said are the lowest actions that an Agent can take. The reason for the primitive actions are to define what is a acceptable action and to define when a particular action is indeed possible in a given situation.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Primitive actions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


prim_action(die).
 prim_action(look(_)).


prim_action(startgoto(_)).



These are preconditions for the primitive actions. These are very important in a search so the search knows that the actions it selects are valid in the situation thet are selected for.


/*
    Preconditions for primitive actions
*/

poss(check_for_enemy, true).

poss(look(_), true).



poss(startgoto(Location), location(Location)). 



Now procedures are more involved than any of the other pieces of code but they are heavily depandant on them. Some can be as simple as,


proc(defendCapturer,
    pi(teammate, 
        [?(hasItem(enemyflag, teammate)), 
            defend(teammate)
        ]
    )
).


This procedure is to defend the capturer (comes form an agent written to play capture the flag). Essentially it uses pi (pronounced "pick") to choose the teammate of the agent for which the condition hasItem(enemyflag, teammate) is true. Choose the teammate that has the enemyflag and defend that teammate. Pretty awesome for really only 4 lines of code. 

For the functionality of the IndiGolog agent this line needs to be added and is very importand


% THIS IS THE MAIN PROCEDURE FOR INDIGOLOG
proc(main,  mainControl(N)) :- controller(N), !.


When the "main" method is called it will try all of controllers defined for the agent. 

Some examples


/*

    This procedures includes parts of the last. This one will loop while

    the Entity is still alive. It will prioritize these action states

    1. If there is enemyContact engage and attack that enemy.

    2. If an enemy is seen follow that enemy.

    3. Otherwise wonder the map.

*/

proc(mainControl(2),

%    [goto(home), sleep]

     prioritized_interrupts(

    [

        interrupt(contactedEnemy=glen, attack( _, [target,glen], _)),

         interrupt(seenEnemy=glen, follow(_, [target,glen])),

         interrupt(true, pi(start, pi(location, [relocate(start,location)])))

     ]) % end of interupts

).


prioritize interrupts chooses the interrupt for which its condition is true first.


% Controller for the Wumpus:

%    1. If agent knows where the wumpus is, she is in line with it and

%       the wumpus may be alive, then aim to wumpus and shoot arrow

%    2. If agent knows that there is gold in the current square, pick it up

%    3. Otherwise: sense everything and take a randomWalk

proc(mainControl(3),

   prioritized_interrupts(

         [interrupt([dir], and(aliveWumpus=true,

                     in_line(locRobot,dir,locWumpus)), [shoot(dir)] ),

      interrupt(isGold(locRobot)=true, [pickGold]),

      interrupt(inDungeon=true, [smell,senseBreeze,senseGold,

                wndet(newRandomWalk, [goto(loc(1,1)),climb])])

         ])  % END OF INTERRUPTS

).





proc(mainControl(4),

    while(alive, searchForEnemy(glen))

).





proc(mainControl(9),

%    [goto(home), sleep]

     prioritized_interrupts( 

    [

        interrupt(and(role=capdef, neg(hasenemyflag=false)), defendCapturer),

        interrupt(and(role=capdef, some([enemy, friend], and(attacking(enemy, friend)=yes, neg(isEnemy(friend))))), 

            pi(enemy, attack( _, [target, enemy], _))),

        interrupt(and(role=capdef, neg(seeEnemy=false)),    pi(enemy, 

            if(bAttackedBy(enemy), 

                attack( _, [target,enemy], _), 

                avoidEnemy))),

        interrupt(role=capdef, startgoto(_, [destination, enemyflag2]))

    ]%,

        %if  % end of if

     )% end of while

).



References:
  1. http://www.cs.toronto.edu/~alexei/ig-oaa/indigolog.htm
  2. http://www.cse.yorku.ca/~lesperan/IndiGolog/
  3. http://sourceforge.net/projects/indigolog/



Thursday 21 February 2013

Install/setup Postgres 9.1 on Ubuntu 12.04

Start by installing Postgres:


sudo apt-get install postgresql


After installing the first thing that needs to be done is adjust the connections postgres will accept. open the file /etc/postgresql/9.1/main/posrgresql.conf and turn on the listen addres


listen_addresses = 'localhost'


Then turn password encryption on


password_encryption = on


Then restart postgresql for these changes to take effect.


/etc/init.d/postgresql restart


Now the server is ready to access. First thing to do is to create a database user to use for all of your work.


sudo -u postgres createuser

Enter name of role to add: username

Shall the new role be a superuser? (y/n) n

Shall the new role be allowed to create databases? (y/n) n

Shall the new role be allowed to create more new roles? (y/n) n


 Then create the database you are going to use:


sudo -u postgres createdb somedb

CREATE DATABASE
After the database has been created a setup a password for that user and grant all privaleges for that user on the database.


sudo -u postgres psql

postgres=# alter user username with encrypted password 'passwd';

ALTER ROLE

postgres=# grant all privileges on database somedb to username;

GRANT




Now it is time to install the postgres client.


sudo apt-get install postgresql-client


Last it might be necessary to change the connection protocol in /etc/postgresql/9.1/main/pg_hba.conf. I was getting an error related to not having the privileges to access the database.

On installation, your pg_hba.conf file will look like this:



# TYPE  DATABASE        USER            ADDRESS                 METHOD 



# "local" is for Unix domain socket connections only 

local   all             all                                     peer 

# IPv4 local connections: 

host    all             all             127.0.0.1/32            ident 

# IPv6 local connections: 

host    all             all             ::1/128                 ident 

# Allow replication connections from localhost, by a user with the 

# replication privilege. 

#local   replication     postgres                                peer 

#host    replication     postgres        127.0.0.1/32            ident 

#host    replication     postgres        ::1/128                 ident  


Change the METHOD to md5 as shown below:


# TYPE  DATABASE        USER            ADDRESS                 METHOD 



# "local" is for Unix domain socket connections only 

local   all             all                                     md5 

# IPv4 local connections: 

host    all             all             127.0.0.1/32            md5 

# IPv6 local connections: 

host    all             all             ::1/128                 md5  


In order for the change to take effect, reload the pg_hba.conf file.

sudo -u postgres psql


posgres=# select pg_reload_conf();  



 pg_reload_conf 

---------------- 

 t 

(1 row) 

 

postgres=# 
Now it should be possible to connect to your database with  psql -d somedb -U username It will ask you for your password. If you want to create a tablespace for your database: I just used the same hard-drive I installed it on, if you computer has more than one hard-drive you might want to distribute databases across table spaces. By default on Ubuntu postgres store the default tablespace in /var/lib/postgresql/9.1/main. You can double check this with the command

$ sudo -u postgres psql

psql (9.1.7)

Type "help" for help.



postgres=# show data_directory;

        data_directory       

------------------------------

 /var/lib/postgresql/9.1/main

(1 row)



postgres=#


This next section gives direction on how to a table_space for postgres to store all of the information for table in a particular directory.

You can just create a new directory in /var/lib/postgresql/9.1


sudo mkdir /var/lib/postgresql/9.1/somedir


This will result in

$ ls -la /var/lib/postgresql/9.1/

total 16

drwxr-xr-x  4 postgres postgres 4096 Feb 21 21:40 .

drwxr-xr-x  3 postgres postgres 4096 Feb  7 12:05 ..

drwx------ 13 postgres postgres 4096 Feb 21 20:43 main

drwxr-xr-x  2 root     root     4096 Feb 21 21:40 somedir


The permissions need to be changed for postgres to be able to access the tablespace store correctly


$ sudo chown postgres /var/lib/postgresql/9.1/somedir

$ sudo chgrp postgres /var/lib/postgresql/9.1/somedir

$ ls -la /var/lib/postgresql/9.1/

total 16

drwxr-xr-x  4 postgres postgres 4096 Feb 21 21:40 .

drwxr-xr-x  3 postgres postgres 4096 Feb  7 12:05 ..

drwx------ 13 postgres postgres 4096 Feb 21 20:43 main

drwxr-xr-x  2 postgres postgres 4096 Feb 21 21:40 somedir


Now your tablespace has a home the postgres has access to. At this point there should be no issue in creating a new tablespace.


$ sudo -u postgres psql

psql (9.1.7)

Type "help" for help.

                                         

postgres=# CREATE TABLESPACE table_store OWNER username  LOCATION '/var/lib/postgresql/9.1/somedir/';

CREATE TABLESPACE

postgres=# 


All Set.

References:
  • http://blog.lodeblomme.be/2008/03/15/move-a-postgresql-database-to-a-different-tablespace/
  • http://www.postgresql.org/docs/9.1/static/sql-commands.html
  • http://linuxpoison.blogspot.ca/2012/01/how-to-install-configure-postgresql.html
  • http://www.davidghedini.com/pg/entry/install_postgresql_9_on_centos

Wednesday 20 February 2013

Python and TCP/IP

TCP/IP in Python

Some notes on how TCP/IP works in Python (2.7).

Basic TCP client



import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)

try:
    
    # Send data
    message = 'This is the message.  It will be repeated.'
    print >>sys.stderr, 'sending "%s"' % message
    sock.sendall(message)

    # Look for the response
    amount_received = 0
    amount_expected = len(message)
    
    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print >>sys.stderr, 'received "%s"' % data

finally:
    print >>sys.stderr, 'closing socket'
    sock.close()


This client is simple and easy to use but I need something that would not block at all. To achieve this Python has a feature called select that can be used on stream like object that have a file descriptor. This selector can be used to check if the selector object has data ready for reading, writing or an exceptional condition (exceptional conditions not covered here).


import select
import socket
import sys

service = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('localhost', 10000)
print >> sys.stderr, 'connecting to %s port %s' % server_address
service.connect(server_address)



This beginning stays the same but now the method to receive has changed.


 r, w, e = select.select([service], [], [], 0.0)
    if r: # There is something to read
       data = service.recv(256)
       character = 'ChrBrad0'
       
       bmlMessage = data







Get and Compile Smart Body

This page is linked to another and will outline the steps to get and compile SmartBody.

Current svn command and link


svn co https://smartbody.svn.sourceforge.net/svnroot/smartbody/trunk smartbody 


To Compile for Windows follow the steps in the guide that basically just say to use visual studio to open the solution and build the project.

For Linux it was a little more complicated. I prefer to work on Linux (Ubuntu) for my work so I ventured on writing a script to setup all of the dependencies.

Here is a script I wrote to setup all the dependencies for SmartBody on Ubuntu 12.04.

Thursday 7 February 2013

Ubuntu 12.04 on ASUS n56v

This blog is a collection of solutions to issues or not preferred settings in Ubuntu when installing on ASUS n56v

Press f2 to get into bios

  1. After installing Ubuntu fix Grub to boot Windows 8 again.
    1. So installing Ubuntu 12.04 along with a EFI partition with GRUB will result in a boot error for Windows8 (from /dev/sda[some number]), some thing like: error: unknown command 'drivemap' error: invalid EFI file path. While there are many threads online discussed about this issue. Here is the most elegant solution I found: using the Boot-Repair tool. Here is how: 
       1. After Ubuntu is installed (make sure you can access the internet), open the terminal:

      sudo add-apt-repository ppa:yannubuntu/boot-repair
      sudo apt-get update
       2. Press Enter. 
       3. Then type:
       
       sudo apt-get install -y boot-repair
       boot-repair
       4. Press Enter, let this software figure everything out for you.
      It will automatically generate the GRUB files such that your Windoes8 can boot again.
       
      Best to choose the Recommended option to fix your boot issues in boot-repair

  2. Get the nvidia card working
    1. taken from, http://askubuntu.com/questions/163900/ubuntu-any-version-and-650m-cuda
    2. NOTE: if using Ubuntu 12.04.2 read these first 
      1. http://askubuntu.com/questions/256995/ubuntu-12-04-2-wont-boot-after-bumblebee-instalation 
      2. https://bugs.launchpad.net/ubuntu/+source/cedarview-drm-drivers/+bug/1132584
        1. Yes your integrated graphics will no longer work.
    3. Short story if Ubuntu 12.04:
      
      sudo add-apt-repository ppa:ubuntu-x-swat/x-updates
      sudo add-apt-repository ppa:bumblebee/stable
      sudo apt-get update
       
      sudo apt-get install bumblebee bumblebee-nvidia linux-headers-generic
       
      # If using Ubuntu 12.04.2 with the hardware enablement stack use this to install bumblebee instead
       
      sudo apt-get install bumblebee bumblebee-nvidia linux-headers-generic-lts-quantal 
       
      Log out and log back in to update your user groups
       
      optirun glxspheres
      
      
      Basically to make sure the graphics for the program you want to run is handled by the graphics card run it with optirun. 
    4. 
      
  3. Fixing Eithernet
    1. http://www.linuxfoundation.org/collaborate/workgroups/networking/alx
    2. Worked great
  4. Multi-Touch
    1. http://askubuntu.com/questions/127049/help-trying-to-get-two-finger-scrolling-to-work-on-asus-ul80vt/220299#220299 
  5. Fix computer freezing ever couple of hours
    For whatever reason the computer seem to freeze every so often. Looks to occur whenever I go to save something.

    Apparently it can be easily remedied by enabling the long term service hardware stack like so:

    sudo apt-get install linux-generic-lts-quantal xserver-xorg-lts-quantal
    After this you should have kernel version >= 3.5.0 which is the point of enabling the hardware support.
  6. Fix auto brightness
    You could try adding a line to /etc/rc.local that will set the desired brightness level. To edit the file, run
    gksudo gedit /etc/rc.local
    
    and add the following
    echo X > /sys/class/backlight/intel_backlight/brightness
    
    so that the end result looks like this
    #!/bin/sh -e
    #
    # rc.local
    #
    # This script is executed at the end of each multiuser runlevel.
    # Make sure that the script will "exit 0" on success or any other
    # value on error.
    #
    # In order to enable or disable this script just change the execution
    # bits.
    #
    # By default this script does nothing. 
     
    # Max vlaue seems to be 4882 
     echo X > /sys/class/backlight/intel_backlight/brightness
    
    exit 0
    
    Substitute the X by the desired brightness level.

  7. Sub woofer
    1. Source is http://doc.ubuntu-fr.org/asus_n76vm#son in french
    2. Basically add
      
      echo 0x16 0x99130112 > /sys/class/sound/hwC0D0/user_pin_configs
      echo 1 > /sys/class/sound/hwC0D0/reconfig
      
       
                      To /etc/rc.local                      Before exit 0
                      reboot
                      Might need to change some settings in alsamixer. 



Using PYSdm
http://ubuntuforums.org/showthread.php?t=872197
Use: user,exec,auto,uid=1000,gid=1000,utf8,dmask=027,fmask=007

References
  1. http://askubuntu.com/questions/166263/fn-keys-not-working-on-an-asus-n56v
NOTES:
  1. Kernel 3.5.x will not work with the cedarview GPU on Intel chips. Find the bug here. https://bugs.launchpad.net/ubuntu/+source/cedarview-drm-drivers/+bug/1132584