Showing posts with label Lisp. Show all posts
Showing posts with label Lisp. Show all posts

Saturday, 6 July 2013

Bits of Minecraft

Minecraft has sunk a lot of my time over the few years it's been around. Here are some of the things I've done in it (in order of construction):

A rainbow made of wool is visible to the left, and a large woolen cake lurks in the fog to the right.
Rainbow! ... and cake

A triple helix with hanging vines made of dirt rises into the sky in front of a seemingly floating land.
Triple helix near an overworld plate

From my overworld you can see my home base tower on the left, satellite dish in the centre and the word "Craft" made of wool on the right.
Home, satellite dish and "Craft"
The rainbow, triple helix and satellite dish were all planned using Lisp. Here's some Lisp code you can use to plan rainbows:

(loop with freq = (list)
       and reach = (1+ 20)
       and width = 8
      for j from reach downto 0
    do (loop for i from (- reach) to reach
             for r = (round (sqrt (+ (square i) (square j))))
             for c = (cond ((= i j 0) #\+)
                           ((< r (- reach width)) #\-)
                           ((<= r (1- reach)) (- r (- reach width)))
                           (t #\Space))

        when (not (eql #\Space c))
        do (aif (cdr (assoc c freq))
            (incf (car it))
            (push (list c 1) freq))
        when (or (minusp i) (not (eql #\Space c))) do (princ c))

    do (terpri)
    finally (return freq))

It produces output like this (this one's a small version to fit in the width of the blog):

                 777777777
              777666666666777
            7766655555555566677
          77665554444444445556677
         7665544433333333344455667
        766544433322222223334445667
       76554433222111111122233445567
      7655433221110000000111223345567
     7655433211000-------0001123345567
    766543321100-----------001123345667
    7654332100---------------0012334567
   7654432100-----------------0012344567
   765432110-------------------011234567
  765443210---------------------012344567
  765432100---------------------001234567
  76543210-----------------------01234567
 765433210-----------------------012334567
 76543210-------------------------01234567
 76543210-------------------------01234567
 76543210-------------------------01234567
 76543210------------+------------01234567
((#\+ 1) (#\- 256) (0 45) (1 45) (2 43) (3 57) (4 57) (5 57) (6 59) (7 57))


The last bit is a count of each block type so you know how much to gather of each type. Three dimensional objects like the dish and triple helix use more code which I can post if people are interested.

P.S. Don't spend too much time playing computer games.

Friday, 8 February 2013

The 147 Problem from Programming Praxis

Programming Praxis is a great site. The 147 problem was recently posted there, and I tackled it with a bit too much time... Following is the code, with discussion.

(defun sum1/ (s)
    "Read the name as Sum the Inverses"
    (apply #'+ (mapcar #'/ s)))


(defun limits (n)
    "I took the limits discussion on the site a bit further..."
    (loop for i from n downto 1
          for prod = (apply #'* prods); Produces 1 to start with
          for prods = (cons (1+ prod) prods)
          for min = (min (car prods) n)
          for max = (max (* i prod) n)
        collect (list min max)))


When calling limits with n = 5, we get ((2 5) (3 8) (5 18) (5 84) (5 1806)) which shows the maximum ranges of each number we'll search for. The actual search for solutions to 1/a+1/b+1/c+1/d+1/e = 1 then looks like this:

(defun search1 (n &optional givens limits)
    "Actually finds all of the valid solutions to the 147
problem with n numbers. Call it without the optional arguments
to start it off."
    (let ((limits (if (null givens) (limits n) limits)))

        ;; Limits is whittled down during the recursion,
        ;; so detect starting off by looking at givens.
        (if (= n (length givens))
            (if (= 1 (sum1/ givens))
                (list (reverse givens)))
            (loop for next from (max (caar limits)

                                     (if givens (car givens) 0))
                           to (cadar limits)
                  for s = (cons next givens)
                until (or (every (lambda (i) (> i n)) s)
                          (and (not (cdr limits)) (< (sum1/ s) 1)))
                appending (search1 n s (cdr limits))))))




This code times how long it takes to solve the first few solutions before the times get too big:

(time (loop for n from 0 to 5 collect (nreverse (search1 n))))


Which gave 4.1 seconds on my computer.

Note that the code works for n = 0 and 1 (producing the empty list, and a single solution: 1, respectively). As some other people have mentioned, Common Lisp is well thought out. I think this also supports that thought, as I didn't design the algorithm specifically to handle cases n = 0 and 1.

And lastly, the following code finds the smallest distinct solutions, as described at Programming Praxis:

(sort
  (remove nil
    (mapcar (lambda (s)
              (if (apply #'/= s); Distinctness
                (cons s (apply #'+ s)))); Sum the denominators
            (search1 5)))
  #'< :key #'cdr); Sort by the sum of denominators


Which gives (3 4 5 6 20), confirming our solution.

Happy coding!

Saturday, 2 February 2013

Solving the Discretised Traffic Model Equations

This post follows on from when we discretised our traffic model equations. We now solve them in this post.

The solving process is quite simple since we avoided most references to the future values of variables. If we did, we'd have to use matrices to solve the discretised model equations. As it is, we can simply calculate each value separately.

The code is modeled around each cell, so here's the discretised cell equation: $$\rho(x_i,t_f) = \rho(x_i,t_c) - \frac{t_f-t_c}{x_{i+}-x_{i-}}\left(\rho(x_{i+},t_c) v(x_{i+},t_c) - \rho(x_{i-},t_c) v(x_{i-},t_c)\right).$$ where
\(\rho\) = vehicular density (veh/m);
\(t\) = time (s);
\(t_c\) = the current time (s);
\(t_f\) = the future time (s);
\(x\) = distance (m) along road;
\(i\) = the index of the current cell, ranging from 1 to \(n\);
\(x_i\) = the location of the 'centroid' of the current cell (m);
\(x_{i-}\) = the left (upstream) boundary of the current cell
\(x_{i+}\) =
\(v_f\) = free flow speed (m/s);
\(\rho_j\) = jam density (veh/m), the average vehicles per metre in stationary traffic; and
\(v\) = vehicle speed (m/s), and is given by: \(v = v_f(1-\rho/\rho_j)\).

The left boundary is given by: $$\rho(0,t) = \rho_j/4.$$

Oh, and in case it isn't clear, the flow of traffic is in the direction of increasing \(x\) , which is to the right. That means that upstream is to the left, and downstream is to the right.

The above equations have been implemented in Common Lisp, with MathP (but I'll wait till the end to show the final code). It outputs the values scaled up by 1000 for convenience. To call it, we evaluate something like this:

(step-simulation :road-length 1000 :n 20 :dt 1.0 :time-run 200)

Great! So, let's look at the results. Here is a visualisation of the results for the above simulation:

Initial traffic simulation results. Time increases from top to bottom, distance increases from left to right. Light traffic is green, medium traffic is yellow, and heavier traffic is red.


Not so good... there are fluctuations in the solution, causing negative vehicle densities. Thankfully, that can be fixed with an Upwind scheme. In our case, we just move the centroid more upstream within the cell. This removes the fluctuations, but probably increases error elsewhere in the simulation. The results with the Upwind scheme are:
"Upwind" traffic simulation results. Time increases from top to bottom, distance increases from left to right. Light traffic is green, medium traffic is yellow, and heavier traffic is red.

Looking good. The traffic on the left fills the road over time, and there are no fluctuations.

The final code to implement this is:

(defparameter *free-flow-speed* (/ 60 3.6); = 60 km/h
    "Speed (m/s) of freely flowing, low density traffic.")
(defparameter *jam-density* (/ 7.0); = 1 veh every 7 m

    "Jam density (veh/m), the average vehicles per metre in stationary traffic.")
(defparameter *road-length* 1000.0; = 1 km

    "Length (m) of road being simulated.")
(defparameter *cell-count* 10

    "Number of cells road is split into for simulation.")

(defun step-simulation (&key
        (vf *free-flow-speed*)
        (pj *jam-density*)
        (road-length *road-length*)
        (n *cell-count*)
        (dt 1.0); Time step in seconds.
        (time-run 10.0); Time to run simulation for.
        (t0 0.0); Starting time for simulation.
        (upwind 0.5); Upwinding parameter [0 = only upstream, 1 = only downstream]
        p0; Initial road density for each cell.
        pin); Input density function (veh/m). Should take one argument - the time.
    #M{
    dx = roadLength/(n-1)
; Spacing between cell centres.
    pin = if pin pin fn(_) pj/4.0

    ;; Set the boundary density in the initial state.
    unless(p0 p0 := makeArray(n :initialElement 0.0) p0[0] := #!pin(t0))
    v(p) = vf*(1-p/pj); Velocity as function of density.
    x(i) = (i-1)*dx; Cell centroid locations.
    xp(i) = if i<n (i-0.5)*dx roadLength; Plus, or right (downstream) boundary locations.
    xm(i) = if i>1 (i-1.5)*dx 0; Minus, or left (upstream) boundary locations.
    stepsim(pold atime dt) =
        makeVector(n fn(i) {
            pm = if i>1 (1-upwind)*pold[i-2]+upwind*pold[i-1] pold[0]
            pp = if i<n (1-upwind)*pold[i-1]+upwind*pold[i] pold[n-1]
            in = max(0 dt*pm*v(pm))
            out= max(0 dt*pp*v(pp))
            if i==1 #!pin(atime) pold[i-1] + (in - out)/(xp(i)-xm(i))})
    #L
(loop for atime from t0 to (+ t0 time-run) by dt
            for ps = p0 then (stepsim ps atime dt)
        do (loop for p across ps
            do (format t " ~4,1,3F" p)
            finally (terpri)))})

Saturday, 12 January 2013

Ignoring Arguments in Anonymous Functions

Anonymous functions are a useful (hmm, that's an understatement) feature of Common Lisp. I use them a lot. While using them, sometimes I want to ignore some arguments that are required by the consumer of the anonymous function. For example, here is an example of collecting the keys in a hash-table into a list:
(let (result)
    (maphash (lambda (key value)
                (declare (ignore value))
                (push key result))

             hash-table)

    result)
In this situation, the anonymous function is quite simple, and the ignore advice is swamping it. I wrote a small macro (named fn) to make ignoring arguments in anonymous functions easier. It's included and used extensively in the MathP code. To ignore an argument, use an underscore for it in the argument list. For example, the above code becomes:
(let (result)
    (maphash (fn (key _) (push key result))

             hash-table)
    result)
Because the code is that much shorter, I find it that much easier to read. Here is the macro that does the magic:
(defmacro fn (args &body body)
    (let (arg-list ignores)
        (loop for arg in args
            if (string= (symbol-name arg) "_")
            do (let ((sym (gensym)))
                   
(push sym arg-list) (push sym ignores))
            else do (push arg arg-list))
        `(lambda ,(nreverse arg-list) (declare (ignore ,@ignores)) ,@body)))

I hope the above code is useful to you; Use it however you want. I accept no responsibility for problems arising from it's use, but if you do find it useful, I'd be tickled pink to hear from you.

Do you know of a similar macro? Please leave a comment.

Saturday, 5 January 2013

Syntax for Lambda-Lift/Positional-Lambda

I've checked out the clever Lambda-Lift library by Hexstream, and I like it. It's a library that provides a succinct way to write positional lambdas. Having recently used implemented a reader macro, I decided to try one out for it. Almost immediately afterwards, I read the Reddit announcement, which mentioned that not using a reader macro was a good idea.

It seems that wanting to use reader macros for small things is a common weakness in Common Lisp programmers. Uses of dispatching macro character pairs to shorten code can actually make the code harder to read. This is more likely for people who don't know what the associated dispatch function does (or even sometimes where it came from). The tendency towards reader macros may arise from the desire for a more concise way to write Lisp code. This may be more of an issue if you are used to writing very terse code, such as Perl of Mathematica.

The issue with reader macros for general consumption is that they provide another layer to understand. While definitely not insurmountable, effort is still required to investigate and understand what the reader macro does or produces. In effect, reader macros use syntax to compress Lisp code.

The most Lispy way to compress code is probably to use higher order functions and macros. I think the benefit of using macros is that building macros upon macros is easier because of the uniform syntax. When macros are the right choice, you can benefit from their rich support in Common Lisp.

Anyway, here's my attempt. Use or leave it.

(defun read-positional-lambda-form (stream char n)
    (declare (ignore char))
    (let* ((next (peek-char nil stream))
           (n (or n (and (digit-char-p next)
                         (- (char-code (read-char stream))

                            #.(char-code #\0)))))
           (next (peek-char nil stream))
           (rest (and (char-equal next #\r) next))
           (next (progn (when rest (read-char stream))

                        (peek-char nil stream)))
           (body (if (member next '(#\Space #\Tab #\Newline nil #\)))
                    '() `(,(read stream nil nil t)))))
        `(lambda-lift:lift ,@(when n `(,(intern (format nil "~D" n) '#:keyword)))
               ,@(when rest `(&rest ,(read-from-string (string rest))))
               ,@body)))

(set-dispatch-macro-character #\# #\L #'read-positional-lambda-form)


The above code is released into the Public Domain the same as the Lambda-Lift library. Here are some examples of it:

'#L3           ;== (lift :3)
'#L3(print :2) ;== (lift :3 (print :2))
'#L2r          ;== (lift :2 &rest r)
'#L3r(print r) ;== (lift :3 &rest r (print r))
'#L3:2         ;== (lift :3 :2)
'#L2rr         ;== (lift :2 &rest r r)
(funcall #L5  
         'one 'two 'three 'four 'five) ;== FIVE
(funcall #L5:3          'one 'two 'three 'four 'five) ;== THREE
(funcall #L5(string :1) 'one 'two 'three 'four 'five) ;== "ONE"
(funcall #L5(reverse (string :4)) 'one 'two 'three 'four 'five) ;== "RUOF"
(funcall #L2rr 'one 'two 'three 'four 'five) ;== (THREE FOUR FIVE)

Saturday, 15 December 2012

Smooth Minimum and Maximum

The functions we examine in this post are closely related to p-norms. Lets say we have two equations that describe aspects of a relationship. For example, we might describe the selling price of an item in terms of a discounted price, \(d\), for small purchases, and a lower bound price, \(u\), for bulk purchases. In that case, we might have two equations to describe price: $$d(x)=202-2x,$$ and $$u(x)=150,$$ where \(x\) is the number of units purchased in a single transaction. In this case, it might be fine to simply decide the selling price, \(p\) as $$p(x) = \max(d(x), u(x)),$$ but what if we want a formula for the selling price that has continuous derivatives? (i.e. is smooth) Well, the formula I found in an attempt to do this is: $$m(x, s) = (d(x)^s + u(x)^s)^{1/s},$$ where \(s\) is the 'strength' of the maximisation.

The above formula is basically a p-norm (and is the Euclidean norm when \(s\) = 2). Here's a chart of it in action on \(d\) and \(u\) with \(s\) set to 2, 4, 6 and 8:
Example of a smooth maximum function for combining formulas.
The chart shows that a higher strength, \(s\) leads to a 'tighter' maximum. In the limit as \(s\) goes to infinity, we actually obtain the plain \(\max\) function. But what happens at higher unit quantities? Specifically, what happens when one of our inputs is negative? Well, that's shown here:
Example of the effect of a negative input on the smooth maximum.

That's not so good. The even strengths stay above both inputs, but diverge further and further above the intended maximum. The odd strengths (only one shown) start to trend towards the negative input, because towards the right, it is the largest in absolute value.

Before we attempt to deal with this issue, let's look at another interesting behaviour. Let's consider negative strengths. This chart shows strengths of -2, -3, -4 and -5:
A negative strength produces a smooth minimum function!

That's a convenient way to take the continuous minimum! And what happens when we feed in negative inputs? Well, it gets a little crazy:
A smooth minimum of a negative input does not look pretty.

So then, how might we deal with negative inputs? One way would be to transform inputs from the full number line onto just the positive half. To do that we turn to exponentiation. So here's the updated continuous maximum/minimum function, generalised to any number of functions: $$m(x, s) = \ln_b\left(\left[ \sum_{i=1}^q (b^{f_i(x)})^s \right]^{1/s}\right),$$ where \(b\) is the base of exponentiation. So, let's test it. I initially tried \(w = e\), but ran into overflow issues, and instead have used the value 1.01. Here is the maximum and minimum of positive and negative inputs, with \(s\) being 2, 5, -2 and -5:
A smooth minimum and maximum function that works with negative inputs.

One final thing. To use this in Lisp on individual values, evaluate this (with MathP):

(defun smooth-min-max (b s &rest vals)
    "Smooth minimum (s < -1) or maximum"
    #M log(reduce{#'+ vals :key fn(v) (b^v)^s}^(1/s) b))


And to construct a function that minimises or maximises other functions, try something like this:

(defun smooth-min-max-lambda (b s &rest funcs)
    "Returns a function that calculates a smooth min/max of the

given base and strength. If b > 1, positive s does maximisation,
negative s minimisation. If 0 < b < 1, it is reversed."
    (assert (or (< 0 b 1) (> b 1)))
    (assert (not (zerop s)))
    #M fn(&rest args) log(reduce(#'+ funcs :key fn(f) (b^apply(f args))^s)^(1/s) b))


Enjoy!

Saturday, 17 November 2012

MathP is not CL Standards Compliant

Bad news! MathP, my very own mathematics notation library for Common Lisp, breaks the ANSI CL standard. The problem is that unread-char cannot be called consecutively without calling something that will read a character (like read-char). From the CL Hyperspec page for unread-char:
It is an error to invoke unread-char twice consecutively on the same stream without an intervening call to read-char (or some other input operation which implicitly reads characters) on that stream. 

I used it to basically peek multiple characters ahead, like peek-char, but for multiple characters. This may be why MathP doesn't work in CLISP. That allows me to have arbitrary operators. For example, I could have the following as distinct operators:
  • * for multiplication
  • ** (perhaps for exponentiation)
  • .* (perhaps for element-wise multiplication, like in MATLAB)
  • *. (dot product?)
  • *.* (perhaps for element-wise exponentiation)
  • etc.

I thought I was being clever, but such a use contravenes the standard pretty clearly. So I'm interested in alternatives. Does anyone know if it's possible to do multiple unread-chars with other stream implementations? Also, can you read lisp from them with standard reading functions?

Saturday, 3 November 2012

MathP and Macros

MathP and macros can be used together a fair bit. I've added a 'math-macro' capability to do custom parsing within MathP input, but you can write macros within MathP (as of version 1.11). I've added direct support for backquote (which has been tested in Corman Common Lisp). Here are some examples of how it all works:

Math-Macro

Macros that use structure in a way that conflicts with the mathematical notation of MathP (that's most macros) can define custom parsing rules. Here's the defun math-macro:
(define-math-macro 'defun (fn (maths)
        (multiple-value-bind (args todo) (parse-argument-list (cdr maths));; Skip name
            (push (car maths) *global-callables*);; Register the function (for recursion and later)
            (multiple-value-bind (body todo) (parse-assignment todo)
                (values `((defun ,(car maths) ,args ,@body)) todo)))))

The above shows that the defun math-macro parses the maths (after the defun symbol) as a name, an argument list and an assignment expression. So input maths of '(defun f (x y) x + y z) would be parsed to a list of one form: (defun f (x y) (+ x y)). The remaining maths (the second return value) would be '(z).

The above also shows how parsing is done in MathP. Note that maths is an argument to parsing functions (including the defun parsing function), and that parsing functions return two values. The first is a list of Lisp forms and the second is the maths remaining to be parsed.

But that's really only useful to give existing macros syntax. Let's dive deeper.

Backquote

As of MathP v1.1, it is now possible to use backquote (including nested backquotes etc.) in MathP. Backquote is used extensively in macro definitions, but can also be used outside of macros. We'll look at backquote first, to lay the foundation for MathP macros. Backquotes in Common Lisp are described in Section 2.4.6 of the Hyperspec. I've attempted to preserve it's behaviour but there are differences. First, a backquoted MathP expression gets wrapped in a progn if it needs it. One potential point of confusion is that in MathP, quote will quote list content without parsing it, but backquote parses content. Here are some examples of the similarities and differences:

#M'a[4]; expands to '(aref a 4)
and
#M`a[4]; expands to `(aref a 4)
#M'(1 2 3+4); expands to '(1 2 3 + 4)
but
#M`(1 2 3+4); expands to `(progn 1 2 (+ 3 4))

Backquote inside MathP

Firstly, a math-macro has been defined for defmacro. It has the same syntax as the defun math-macro. Here's a definition of aif like from On Lisp:
#Mdefmacro aif(test then &optional else) `(it=,test if it ,then ,else)

To include a documentation string, just put it and the body into brackets:
#M{defmacro aif(test then &optional else)
   {"Anaphoric if defined in MathP"
    `(it=,test if it ,then ,else)}}


It's also possible to nest backquotes, but writing a macro with nested backquotes is left as an exercise for the reader.

MathP inside Backquote (Backquote across Lisp and MathP)

I've found that the handling of backquote in Corman Common Lisp doesn't make it possible to consistently backquote a form in Lisp, and unquote something inside it from MathP. If you have a better result in another implementation, please leave a comment. For example (and please excuse the contrived-ness):


(defmacro make-more-func (number) `(lambda (n) #M n+,number))

Saturday, 27 October 2012

Creating Bitmaps from Lisp

Having learned about programming computers later in my education (during university), the internals of computers and binary file formats have been very mysterious to me. Text files (and files with a text format) were usually understandable (or conceivably understandable), but binary files were impenetrable to me. At the time, I had no understanding of bytes, let alone concepts such as little/big-endianness. So, to get a feel for how binary file formats work, I wrote a bitmap writer function.

As reference, I used the Wikipedia page about the BMP file format. The code is released under a BSD license and is available for download here. It can make 24-bit colour bitmaps. It also contains some functions to manipulate colours. Bitmaps are created by calling a write-bmp function.

It was an interesting experience to work with binary streams, and I learned a lot. The code's not that nice, and probably not that efficient either, but it does what I want, which is output pictures.

One of the arguments to write-bmp is used to determine the colour of each pixel, and can be either a list of lists, or a function of two arguments. Here's a call that produces a twelve colour diagonal rainbow:
(write-bmp (path "bitmaps/diagonal-rainbow3.bmp") 80 80
  #'(lambda (row col) (rainbow12 (/ (+ row col) 2))))

The function rainbow12 selects a colour based on the floor of it's input mod 12. The above call produces*:
Dyeagonal rainbow!
Here's a fun example using MathP:
(write-bmp (path "bitmaps/picture-perfect.bmp") 80 80
    #M(fn(r c)
       {applR = 2.5
        inRad(x y rad) = (c-x)^2 + (r-y)^2 < rad^2
        if inRad(15 65 6) yellow; inner sun
        if inRad(15 65 8) orange; outer sun
        if inRad(48 55 applR) || inRad(65 45 applR) || inRad(52 40 applR) red
        if (r-50)^2+(c-55)^2<15^2 darkgreen
        if r<20+3*cos(c/10) green; grass
        if 50<c<60 && r<50 brown blue})
)

It produces*:
But since computers are good at calculations, let's try something a little more intense (and random, and ... psychedelic):
(write-bmp (path "bitmaps/trigonometric2.bmp")
    360 300
    #'(lambda (row col)
        (rainbow12
            #M{(row^1.1 + 0.6*col + 35*cos(col/15)*sin(row/16)
                + 2 * sqrt((row-250)^2 + (col-200)^2)
                + 20 * cos((col-0.3*row)/70) * (2-sin(row/80))
                + 20 * (1-cos(0.7+col/25)) * cos(0.6-row/50))/15}
)))

Viola*:
I hope your eyes aren't bleeding too much after that one. ;-)

I've also implemented some anti-aliasing, here's are some anti-aliased pictures:
The last one above is an attempt at creating a 'world' map with things like seas (blue), beaches (yellow), vegetation (green) and mountains (brown and white). The jump from vegetation to beach is sharp, but the anti-aliasing smooths it nicely.

* I've converted all of the pictures displayed here to PNG format using Paint.Net. It feels like cheating, but I was able to get things done. One of these days I'll look into ZPNG and Salza2. The compression used in the PNG format seems very mysterious to me.

Saturday, 13 October 2012

Cody's Algorithm for ERF

Here's a more substantial example of the use of MathP. Erf(x) is the error function - a function related to the cumulative normal distribution. One way to compute the error function is with Cody's algorithm. I've implemented it in Common Lisp to double precision with MathP.

The implementation here starts by defining two constants (i.e. constants in the following equations), then three helper functions. The helper functions are the three rational functions denoted Rlm in Cody's paper. Here's the code in one big MathP expression:

#M{e = exp(1d0) irpi = 1/sqrt(pi); irp = inverse root pi
rlmErf(x) = (3.209377589138469472562d3;; The 4th degree polynomial from Table II.
      + x * (3.774852376853020208137d2
      + x * (1.138641541510501556495d2
      + x * (3.161123743870565596947d0
      + x *  1.857777061846031526730d\-1))))
      /     (2.844236833439170622273d3
      + x * (1.282616526077372275645d3
      + x * (2.440246379344441733056d2
      + x * (2.360129095234412093499d1 + x))))
rlmErc(x) = (1.23033935479799725272d3;; The 8th degree polynomial from Table III.
      + x * (2.05107837782607146532d3
      + x * (1.71204761263407058314d3
      + x * (8.81952221241769090411d2
      + x * (2.98635138197400131132d2
      + x * (6.61191906371416294775d1
      + x * (8.88314979438837594118d0
      + x * (5.64188496988670089180d\-1
      + x *  2.15311535474403846343d\-8))))))))
      /     (1.23033935480374942043d3
      + x * (3.43936767414372163696d3
      + x * (4.36261909014324715820d3
      + x * (3.29079923573345962678d3
      + x * (1.62138957456669018874d3
      + x * (5.37181101862009857509d2
      + x * (1.17693950891312499305d2
      + x * (1.57449261107098347253d1 + x))))))))
rlmEr2(x) = (-6.58749161529837803157d\-4;; The 5th degree polynomial from Table IV.
      + x * (-1.60837851487422766278d\-2
      + x * (-1.25781726111229246204d\-1
      + x * (-3.60344899949804439429d\-1
      + x * (-3.05326634961232344035d\-1
      + x *  -1.63153871373020978498d\-2)))))
      /     (2.33520497626869185443d\-3
      + x * (6.05183413124413191178d\-2
      + x * (5.27905102951428412248d\-1
      + x * (1.87295284992346047209d0
      + x * (2.56852019228982242072d0 + x)))))
defun erfc(x) {"Placeholder" x}
defun erf (x) {"Error function computed with Cody's algorithm"
    x = float(x pi); Make sure it's a double
    if x < 0.0 (-erf(-x))
    if x < 0.5 x * rlmErf(x^2)
               1d0 - erfc(x)}
defun erfc(x) {"Complementary error function computed with Cody's algorithm"
    x = float(x pi); Make sure it's a double
    if x < 0.5 1d0+erf(-x); Based on identities.
    if x < 4.0 e^-x^2 * rlmErc(x);; These two avoid subtraction from one.
               (oox2=1d0/x^2  e^-x^2/x * {irpi + oox2*rlmEr2(oox2)})}}


To check that it works, we have here a small selection of values for erf and erfc, sampled from the Wikipedia page, compared to those calculated using the above code:

erf(0.1) ≈ 0.1124629 ≈ 0.112463d0
erfc(15)/2 ≈ 3.6065e-100 ≈ 3.606497d-100
erf(0.95) ≈ 0.8208908 ≈ 0.820891d0
erfc(0.7) ≈ 0.3221988 ≈ 0.322199d0

Going a bit further, here are some values based on the arbitrarily precise values computed by Wolfram Alpha:

erf(1/100)
0.0112834155558496160

0.0112834155558496169...
erf(1/3)
0.3626481117660628000

0.3626481117660629334...
erf(1/2)
0.5204998778130465000

0.52049987781304653768...
erf(1)
0.8427007929497148000

0.8427007929497148693...
erf(4)
0.9999999845827421000

0.9999999845827420997...

So it appears (from this small sample at least) that this implementation is accurate to about 1e-16 (see the value for erf(1/3)), but usually 1e-17, which appears to be the resolution of doubles for Corman Common Lisp.

Saturday, 6 October 2012

MathP is in git

Good news! The source code (and other tidbits) for my Common Lisp library MathP is available from my public git repository at bitbucket here. Please, go and fork as desired.

I've given MathP a logo at the same time:
Other logos I came up with and considered were:

Like a specific one? Let me know?

And since I want to show you more MathP, here's an implementation of exponential smoothing on the list of data points 0, 1, 2, 3 and 1:

#M{theta=0.2 d=nil
   s(x) = d := if !d x theta*x+(1-theta)*d
   mapcar(#'s '(0 1 2 3 1))}


It should produce the list:
(0 0.2 0.56 1.048 1.0384)

Saturday, 29 September 2012

Simple Error Handling in Lisp

Yup, simple error handling in Lisp. Lisp has a really powerful condition/error handling system (also known as it's condition system). We won't delve into that here. This post was actually inspired by MS Excel (I use MS Excel a lot at work). There's an iferror function that may be used in spreadsheet formulae. It is entered into a cell like so:
=IFERROR(1/0, "failed")
In the above formula, because there is an divide by zero error in the first argument, iferror returns the second argument instead. It's simplicity means it's easy to use and understand.

To replicate this behaviour in Common Lisp is fairly easy. I've included it in MathP. Here's the definition as a macro:
(defmacro iferror (try fallback)
    `(handler-case ,try (error () ,fallback)))
Using it is just as easy as in Excel:
(iferror (/ 1 0) 'failed)
I hope the above code is useful to you; Use it however you want. I accept no responsibility for problems arising from it's use. If you do find it useful, I'd be tickled pink to hear from you.

Do you know of a similar macro? Please leave a comment.

Saturday, 22 September 2012

If you use Windows, please use AutoHotkey

AutoHotkey is a powertool for Windows. It is one of my indispensable tools. I can hardly praise it highly enough. I use it for many things. I have used it to make using Windows less painful, and coding Lisp easier. Here are a few samples of AutoHotkey I use it to:

Make Caps Lock type hyphen (-) instead (I use hyphen a lot - you can make it do what you want):
SetCapsLockState, AlwaysOff
CapsLock::-

Swap brackets to my liking. Once I started programming Lisp, I quickly realised that round brackets should be easier to type. I've swapped ( and ) with [ and ]. I've also made the closing brackets get typed in when you type one of the opening brackets: (, [, or {. This one was the whole reason I started looking for something like AutoHotkey. Nothing else I've found can do this on Windows.
; The dollar signs stop the hotkeys from going into an infinite loop.
$[::Send (){left}
$]::Send )
$(::Send []{left}
$)::Send ]
$+[::Send +[+]{left}


Shorten some git workflow shortcuts (for example, typing gst then Enter is equivalent to typing git status then Enter):
SetTitleMatchMode 2
#IfWinActive, MINGW32:/
::gco::git checkout
::gcom::git checkout master
::gds::git diff --stat
::gdi::git diff
::gpu::git push -u
::gmm::git merge master
::gst::git status
::gct::git commit
::gcta::git commit -a


These and some other bits of AutoHotkey are packaged into a single script here.

I hope the above and linked script is useful to you; Use it however you want. I accept no responsibility for problems arising from it's use, but if you do find it useful, I'd be tickled pink to hear from you.

Saturday, 15 September 2012

MathP Examples

MathP is my Maths DSL for Common Lisp. Here are some examples of it in use. If you want to run these examples, don't forget to either use MathP (use-package '#:mathp), or qualify uses of fn as mathp:fn. Here we go:

In simple calculations. The REPL becomes a very powerful calculator:
#M dt=6 v=9 nl=2 v/dt*3600d0/nl
I appreciate brackets, but I also find it a lot quicker to write these kind of expressions at the REPL.

Here's the choose function:
#M(defun choose (n k)
   {assert(integerp(n) && integerp(k) && n >= k >= 0)
    result = 1
    #L(loop for i from 1 to k do #M result *= (n-k+i) / i)
    result})

Note the use of logical and (&&) as well as chained comparisons in the assert expression. I've also used the mutating assignment operator *=. MathP also contains +=, -=, /=, ^=, &= and |= (the last two perform logical and/or, not bitwise and/or).

To calculate normal distributions with closures:
#M e = exp(1d0)  scale = 1/sqrt(2*pi) #L
(defun normal-distribution (mean stdev)
    #M fn(x) scale/stdev * e^-(0.5d0*(x-mean)^2/stdev^2))
In the above, we use #L to read in a lisp form from within the MathP form. The top level of the MathP form with the #L would normally stop reading at the end of the line, but the lisp reader invoked by #L conveniently consumes it for us.

And to test the above normal distribution calculator:
(loop with dist = (normal-distribution 0 1)
      for x from -3 to 3.1 by 0.2
    do (format t "~&~4,1F ~A~%" x
               (make-string (round #M 40 * #!dist(x))
                            :initial-element #\=)))

The #! above is a syntax for funcall, where the actual function call looks like a normal function call in MathP.

And one last one, the binomial probability mass function:
#M defun binomial (p n k) choose(n k) * p^k * (1-p)^(n-k)

Sunday, 9 September 2012

MathP: Math notation in Common Lisp

MathP is my attempt at adding mathematical notation to Common Lisp.

Lisp has a beautiful, eminently grokkable syntax (if that even makes sense). It's great for general programming, macros and getting stuff done. Another of it's strengths is creating domain specific languages (DSLs). If you've tried to write more than basic mathematics in Lisp, you'll no doubt have wanted to write things like x+y*z or a*x^2 + b*x + c. I think many people who have just learned Lisp coming from other Algol style languages miss that expressiveness. They, like me, probably wanted a mathematics DSL. Well, now you've got one. MathP lets you write the above expressions within Common Lisp. MathP is a mathematics DSL.

MathP syntax attempts to retain a lot of the existing syntax of Common Lisp, while providing infix operators for mathematical notation. As a bonus, MathP syntax for function calls is vaguely similar to M-expressions, and there is a rudimentary macro system. More detail, including several examples, can be found in the documentation.

MathP is released under a BSD licence. It's been tested in Corman Common Lisp (on Windows).

[Edit: updated to version 1.1 - Support for backquote et. al.]
MathP Source Code
MathP Documentation (PDF) (original ODT)

To use it, download the source then load it with a call to load, something like this:
(load ".../path/to/MathP.lisp").

Here are some examples to try out (more can be found in the documentation and in the tests at the end of the code):
  • #M area := length * width
  • Positive root for a quadratic: #M x := (-b + sqrt(b^2 - 4*a*c)) / (2*a)
  • Local function and shared syntax: #M f(x)=x^2+1 mapcar(#'f '(1 2 3 4))
  • Factorial: #M defun fact(n) if n<=1 1 n*fact(n-1)
  • Naive Choose: #M defun choose(n k) fact(n)/fact(k)/fact(n-k)
  • Recursive Choose: #M defun choose(n k) {k=min(k n-k) prod(i res)=if i>0 prod(i-1 res*(n-k+i)/i) res  prod(k 1)}