Cogs and Levers A blog full of technical stuff

Using python from the safety of your virtualenv on Debian

I like having my specific development environments setup, tailored for the particular project that I’m working on. When I’m working on a python project, virtualenv is my go to tool for the job. It’s great.

We’re going to install this using easy_install so that these instructions should translate pretty well to any linux environment. I am doing this from my Debian workstation though.

First up, we need to install the python-setuptools package so that we get access to easy_install.

sudo apt-get install python-setuptools

Next we install virtualenv with easy_install

sudo easy_install virtualenv

As far as the installation is considered, you’re done! It’s that easy. From here you can start to use virtualenv for all of your python based projects. I’ll do a quick cheat-sheet write up shortly on how to use virtualenv at a glance.

Turn off that pc speaker in Debian!

Only a short post.

The ThinkWiki has a great little write-up on disabling the pc speaker device under Debian linux. I thought I’d just shortcut the details in this post.

# Remove the pc speaker module
$ sudo modprobe -r pcspkr snd_pcsp

Remove the pc speaker permanently

# the following lines need to be added to
# the /etc/modprobe.d/blacklist.conf
# make sure you find out which device you actually have

blacklist pcspkr
blacklist snd_pcsp

Anyway, these are just the details to disable the device. The ThinkWiki article has some other ideas also on how to make the bell tone tolerable. Not for me though. I can’t stand it.

RVM & Debian

It’s always nice to have a sandboxed environment for all of your little projects. I know with how frequently I’m jumping between technologies on the same machine, I always like to use a sandbox technology of choice for the particular platform. This is a quick walk through on getting RVM up and running on a debian machine.

# First up, you need to download an install RVM:
$ curl -L get.rvm.io | bash -s stable

# Load RVM into your environment:
$ source ~/.rvm/scripts/rvm

# Check for additional requirements that rubies (you're about to install) need:
$ rvm requirements

It’s strongly advised that you follow the suggestions above for the Ruby(ies) that you want to run:

# Install the Ruby that you want to use:
$ rvm install 1.9.3

# Get Rubonic (yes, it's a word ... I ... I ... I think)
$ which ruby                      
/home/michael/.rvm/rubies/ruby-1.9.3-p327/bin/ruby

The basics of RVM

Generic value interpolation

Introduction

The core of animation in software (not necessarily graphical) is movement. That movement is between known points to achieve and overall effect. Such well-known movements might be a human moving their legs alternatively so that they can walk or a sound constantly moving from low to high to make a siren or moving your mouse cursor automatically. All of these things share the same premise. An attribute of the object needs to have its position interpolated from a starting point to an ending point over a period of time.

Some of these interpolations repeat, some do not.

Today’s post is about interpolating values between two points, but it’s about doing it with any type and with any interpolation scheme. Let’s break these parts down.

Doing it with any type

The idea here is that anything (within reason) can be interpolated. In real C/C++ terms, I mean short, int, long, float, double, char, etc. A little more interestingly when dealing with spatial objects, we could define our own Cartesian co-ordinate object - give this object X and Y attributes and then interpolate this co-ordinate between two points.

Interpolation schemes + some math

It’s the small details that matter. Linear interpolation is the simplest form of interpolation leaning on the whole “the shortest distance between two points is a straight line”. Linear interpolation will take its sequence values for progressing the object through its interpolation life using:

y = c + mx

Which looks dangerously close to the standard formula you would use to draw a straight line. In this case c would be our starting point, m would be the distance (or length) between the start and end points and x defines how far along our interpolation progression we are taking the form in range of 0.0 up to 1.0.

Another interesting scheme is trigonometric in nature. Using a soft curve to get between two points can be a softer approach. Trigonometric interpolation will take its sequence values for progressing the object through its interpolation life using:

y = c + (sin(x * (PI / 2)) * m)

Again, we have alike named variables in that c is our start point, x is our progress through the interpolated progression and m is the distance. Notice how our progress, x is multiplied by (PI / 2) only talking us 1 quarter through the progress of the curve. This is simply because we’re at 0% progress at 0 degress and 100% at 90 degrees.

Show me some code

First off, we have a base “tweener” object that will manage all of the mundane tasks that this interpolater will need to undergo in order to realize these tweened-values. You’ll notice that it is in fact a templated C++ class.

/** Provides a base interface for value interpolation */
template<class T>
class tweener {
public:
    /** Construction */
    tweener(T start, T end, const bool repeat, const Uint32 ticks);

    /** Destruction */
    virtual ~tweener(void);

    /** Resets the state of this tweener */
    void reset(void);

    /** Gets the value of this tweener */
    T value(void);

    /** Determines if the tweener has finished */
    const bool finished(void) { return _finished; }

protected:
    /** User supplied value getter */
    virtual T value_internal(const float prog) = 0;

protected:
    bool        _repeat, _finished;

    T          _start, _end;
    Uint32     _ticks, _prog_ticks;

    timer       *_timer;
};

Ignore the timer class for now. It’s there just so we can make the interpolations happen with respect to time. We move ourselves along the interpolation progression just with some simple math with regards to time. To be a little more polite about things, we detect when we’re at the start and just send the start value and detect when we’re at the end and just send the end value - rather than calculating this over and over.

/** Gets the value of this tweener */
template<class T>
T tweener<T>::value(void) {

    // make sure the timer has started
    if (!_timer->started()) {
        _timer->start();
        return _start;
    }

    // if we've already finished,
    // no more processing
    if (_finished) {
        return _end;
    }

    // accumulate split timing
    _prog_ticks += _timer->split();

    // need to handle boundaries if we're repeating
    if (_repeat) {
        // have we overflowed?
        if (_prog_ticks > _ticks) {
            _prog_ticks %= _ticks;
        }
    } else {
        // have we finished?
        if (_prog_ticks > _ticks) {
            _finished = true;
        }
    }

    // return the calculated value
    return this->value_internal((float)_prog_ticks/(float)_ticks);
}

The custom implementations for getting actual values (from types of interpolation) are as simple as this:

/** Linear interpolation calculation */
template<class T>
T ltweener<T>::value_internal(const float prog) {
    return _start + (prog * _length);
}

/** Trigonometric interpolation calculation */
template<class T>
T ttweener<T>::value_internal(const float prog) {
    return _start + (sinf(prog * M_PI_2) * _length);
}

So you can see that these custom implementations marry very closely to the formula we specified above. I think that this design documents the implementer’s intention very clearly by not having to worry about the progression code. The choice of using C++ templates also allows future implementations to target specific types. Whilst the implementations given in this article will work well for scalar values, they won’t translate very well to complex class types that don’t correctly implement operator overloading with mathematical correctness in mind. That being said, if the scope of implementation is beyond what the generic base provides, it’s only a matter of specifying the specific type when implementing your own value_internal method.

Enjoy.

A few tweeners more

Just playing around with the code set that I have here, I’ve been able to make logarithmic and parabolic tweeners relatively easy. It would be great to be able to control the co-effecients in the parabolic formula, but for the time being it’s a quadratic class:

y = x2 + c

/** Construction */
template<class T>
log_tweener<T>::log_tweener(T start, T end,
                   const bool repeat, const Uint32 ticks) :
tweener<T>(start, end, repeat, ticks) {
    // calculate the linear delta
    _length = (end - start);
}

/** User supplied value getter */
template<class T>
T log_tweener<T>::value_internal(const float prog) {
    return _start + (log10f(1.0f + (prog * 9.0f)) * _length);
}

/** Construction */
template<class T>
parab_tweener<T>::parab_tweener(T start, T end,
                   const bool repeat, const Uint32 ticks) :
tweener<T>(start, end, repeat, ticks) {
    // calculate the linear delta
    _length = (end - start);
}

/** User supplied value getter */
template<class T>
T parab_tweener<T>::value_internal(const float prog) {
    return _start + ((prog * prog) * _length);
}

Simple logging in C

Logging is probably one of the most important services you can offer your application. Your programs have information that needs to be expressed to the user, in fact in parts it’s important for your program to be almost paranoid that it hasn’t said anything.

All things should be controllable though. Putting your application into production with a paranoid level of logging doesn’t make for very happy sys-admins, so this is left as an exercise to the reader. Here, I want to present you a configurable but most importantly, a usable logging framework that you can drop into your C projects without much effort at all. Let’s go through the header!

#ifndef __libced_log_h_

#define __libced_log_h_

#include <unistd.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

/** Logs a line of text */
void _ced_log(FILE *file, const char *fmt, ...);

#define ced_logf(f, ...) _ced_log(f   , __VA_ARGS__)
#define ced_log(...)     _ced_log(NULL, __VA_ARGS__)

#endif /* __libced_log_h_ */

This is very simple stuff. Only one function _ced_log is defined that’s used by this header. The user is encouraged to access the logging functionality by proxy of the macros defined (ced_log and ced_logf). ced_log takes in the same parameter structure as a printf call allowing the very natural format strings to be used for your logging. ced_logf takes the structure of fprintf where you can direct your log information to a specific file handle. Again, with some small modifications you can direct all of your logs into a file by default. I just like to throw all mine out to the console. I hate surprises (in development)!! The implementation for this library piece is also very simple with only one function needing to be filled out:

#include "../include/log.h"

/** */
void _ced_log(FILE *file, const char *fmt, ...) {
  va_list ap;
  time_t t;
  char datestr[51];

  /* determine if we just go to std error */
  file = (file == NULL) ? stderr : file;

  /* datetime & pid formatting */
  t = time(NULL);
  tzset();
  strftime(datestr, sizeof(datestr) - 1, "%a %b %d %T %Z %Y", localtime(&t));
  fprintf(file, "%s [%d]: ", datestr, getpid());

  /* draw out the vararg format */
  va_start(ap, fmt);
  vfprintf(file, fmt, ap);
  va_end(ap);

  /* bump to the next line */
  fprintf(file, "\n");
}

Here is where you can really make this module your own. The default format that I have going in here has the current process ID and date/time stamp. I find these very useful during the fault-finding process once a unit of software is running. The most important thing to draw from this is you can change the default makeup of a log line by changing this code. I use this code just about everywhere. I use it so much that I have included it in my library that it available from github here.