Monday, May 24, 2010

Evenly Partition an Integer

Update: I just noticed after re-watching Slava's Google Tech Talk that he discusses his vector version of this word (which I originally was calling "distribute") at 34:20. Very cool.

I came across a question on Stack Overflow about how to evenly divide an integer.

The discussion was not particularly interesting, but it reminded me of a similar problem that I had to solve, and decided to implement in Factor. This was early in my experience with Factor, and the conversations on IRC proved helpful for understanding how to structure my Factor code, which I want to share.

This type of problem is part of number theory. There is some discussion on Wolfram Mathworld describing the various ways that a positive integer can be partitioned into the sum of some number of other positive integers.

In my particular case, I needed an even division with the result to be produced in such a way that the rounding affect was distributed across the result set. For example:

( scratchpad ) 3 1 n-partition .
{ 3 }

( scratchpad ) 3 3 n-partition .
{ 1 1 1 }

( scratchpad ) 5 3 n-partition .
{ 2 1 2 }

( scratchpad ) 3 5 n-partition .
{ 1 0 1 0 1 }

In an applicative language like Python, you might write this algorithm like so:

def n_partition(x, n):
    delta = float(x) / n
    last, total = 0, 0.0
    l = []
    for _ in range(n):
        total += delta
        value = int(round(total))
        l.append(value - last)
        last = value
    return l

My first version in Factor solved the problem, but was terribly ugly and non-idiomatic:

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip [
        + [ [ dup ] dip + ] dip  
        [ dup round ] dip 2dup -
        [ drop ] dip 
    ] map nip nip nip ;

One sign that you are "doing it wrong" in Factor is frequent usage of stack manipulation using shuffle words. Another sign is creating large words that would be better when broken up into smaller pieces. My solution had both characteristics. Worse, I could barely read it.

The Factor developers are very responsive to questions from beginners, and are helpful in providing an experienced eye to guide newcomers in learning better ways to write their programs. You can reach them on the mailing list or on the #concatenative IRC channel. Often it is useful to paste code so that others can see and comment on it. I thought I'd ask for help, and see if I could learn how to improve.

I received some iterative feedback showing each step along the way towards improving the original code, by using higher-level words and concepts:

  1. First, extract the logic inside map into its own word:
: (n-partition) ( a b c d -- a b c d )
    + [ [ dup ] dip + ] dip  
    [ dup round ] dip 2dup -
    [ drop ] dip ; 

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip
    [ (n-partition) ] map nip nip nip ;
  1. Instead of the first +, use drop since there is always a zero there.
  2. Instead of [ dup ] dip, use dupd.
  3. Instead of [ drop ] dip, use nip.
: (n-partition) ( a b c d -- a b c d )
    drop [ dupd + ] dip [ dup round ] dip 2dup - nip ;

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip
    [ (n-partition) ] map nip nip nip ;
  1. Realize that [ foo ] dip [ bar ] dip is the same as [ foo bar ] dip.
: (n-partition) ( a b c d -- a b c d )
    drop [ dupd + dup round ] dip 2dup - nip ;

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip
    [ (n-partition) ] map nip nip nip ;
  1. Realize that 2dup - nip is dupd -.
  2. Realize that dupd is [ dup ] dip and apply the [ foo bar ] dip rule again.
: (n-partition) ( a b c d -- a b c d )
    drop [ dupd + dup round dup ] dip - ;

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip
    [ (n-partition) ] map nip nip nip ;
  1. Now, extract the drop out and put it inside the map.
: (n-partition) ( a b c -- a b c d )
    [ dupd + dup round dup ] dip - ;

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip 
    [ drop (n-partition) ] map nip nip nip ;
  1. Realize that [ drop foo ] map is [ foo ] replicate.
: (n-partition) ( a b c -- a b c d )
    [ dupd + dup round dup ] dip - ;

: n-partition ( x n -- seq ) 
    [ / ] keep 0 <array> [ 0 0 ] dip 
    [ (n-partition) ] replicate nip nip nip ;
  1. Now, replicate doesn't care what elements of the sequence are, only its length, so you may as well be using "n" instead of an array of "n" zeroes, so we can remove the 0 <array>.
  2. Finally, [ foo ] keep [ bar ] dip is the same as [ foo bar ] keep.

This produces our final "cleaned up" version:

: (n-partition) ( a b c -- a b c d )
    [ dupd + dup round dup ] dip - ;

: n-partition ( x n -- seq )
    [ / 0 0 ] keep [ (n-partition) ] replicate nip nip nip ;

Afterwards, I discussed with Slava other alternatives. One idea was to use locals for the (n-partition) word, but it was not much of an improvement by itself (perhaps better if we introduced meaningful names instead of a b c d):

:: (n-partition) ( a b c -- a b c d )
    a a b + dup round dup c - ;

Another idea was to work on an array of values and then apply vector arithmetic on it:

: percentages ( n -- seq ) [ [1,b] ] keep v/n ;

: steps ( x n -- seq ) percentages n*v ;

: rounded ( seq -- seq' ) [ round ] map ;

: differences ( seq -- seq' ) dup 0 prefix v- ;

: n-partition ( x n -- seq ) steps rounded differences ;

To some extent, this is a question of aesthetics. I happen to like this last version (that uses vectors) the best, but I can see reasons why the original cleaned up version might be attractive too.

Monday, May 17, 2010

Creating Fake Data

A few days ago there was a post on Hacker News about a project called Faker.js. Basically, the project is a Javascript clone of libraries in Ruby and Perl for creating fake data for names, phone numbers, e-mails, street addresses, company information, etc.

I took a look at the code, and got inspired to create a Factor version.

First, some useful vocabularies:

USING: ascii combinators fry kernel make math random sequences ;

All three implementations seem to use simple random selection to generate the "fake" information. For example, each has a long list of valid first and last names. It looks sort of like:

CONSTANT: FIRST-NAME {
    "Aaliyah" "Aaron" "Abagail" "Abbey" "Abbie" "Abbigail"
    "Abby" "Abdiel" "Abdul" "Abdullah" "Abe" "Abel" "Abelardo"
    "Abigail" "Abigale" "Abigayle" "Abner" "Abraham" "Ada"
    "Adah" "Adalberto" "Adaline" "Adam" "Adan" "Addie" "Addison"
    "Adela" "Adelbert" "Adele" "Adelia" "Adeline" "Adell"
    ...

CONSTANT: LAST-NAME {
    "Abbott" "Abernathy" "Abshire" "Adams" "Altenwerth"
    "Anderson" "Ankunding" "Armstrong" "Auer" "Aufderhar"
    "Bahringer" "Bailey" "Balistreri" "Barrows" "Bartell"
    "Bartoletti" "Barton" "Bashirian" "Batz" "Bauch" "Baumbach"
    ...

Given a long list of possible names, generating a fake name is no more complicated than:

( scratchpad ) FIRST-NAME random LAST-NAME random " " glue .
"Greyson Barrows"

Similarly, creating phone numbers is no more complicated than a list of typical phone number patterns, combined with a word that performs substitution of random numbers:

CONSTANT: PHONE-NUMBER {
    "###-###-####"
    "(###)###-####"
    "1-###-###-####"
    "###.###.####"
    "###-###-####"
    "(###)###-####"
    "1-###-###-####"
    ...

: (numbers) ( str -- str' )
    [ dup CHAR: # = [ drop "0123456789" random ] when ] map ;

Generating a fake phone number (without performing any kind of validation on area codes or local numbers) is as easy as:

( scratchpad ) PHONE-NUMBER random (numbers) .
"352-327-9815"

For added flavor, the author chose to include "business bullshit" generation:

( scratchpad ) 5 [ fake-bs . ] times
"leverage 24/7 models"
"deploy ubiquitous vortals"
"maximize holistic channels"
"exploit real-time niches"
"unleash proactive mindshare"

And "product catch phrase" generation:

( scratchpad ) 5 [ fake-catch-phrase . ] times
"Reverse-engineered value-added toolset"
"Diverse systemic concept"
"Ergonomic holistic pricing structure"
"Persevering local interface"
"Intuitive human-resource time-frame"

Useful for scale testing websites, practical jokes, and probably less innocent purposes. You can see the full version on my GitHub account.

Friday, May 14, 2010

Time Spans for Humans

When dealing with time spans or durations, it is nice to be able to render elapsed time in a way that is easy for the human eye to read.

In some cases, this could mean translating the way you might say it or write it (two years, ten days, four hours, thirty minutes, and fifteen seconds) or a more concise form (2y 10d 4h 30m 15s). The concise form has become popular in some web applications, and solutions exist for both in most languages including python, perl, and java. I thought I would build a word in Factor to calculate it.

First, we need some other vocabularies:

USING: kernel make math math.parser sequences ;

The make vocabulary can be used to execute a quotation that builds a sequence of values at runtime. This can be a little confusing for those new to Factor. Basically, you provide it a quotation that periodically emits values (by calling the , word) that are collected into the sequence type you provide. For example:

( scratchpad ) [ 1 , 2 , 3 , ] { } make .
{ 1 2 3 }

Next, we need an algorithm. One way is to iteratively divmod the number of seconds into each category (e.g., years, weeks, days, hours, minutes, seconds) and count it if the number in the category is non-zero.

: elapsed-time ( seconds -- string )
    dup 0 < [ "negative seconds" throw ] when [
        {
            { 60 "s" }
            { 60 "m" }
            { 24 "h" }
            {  7 "d" }
            { 52 "w" }
            {  f "y" }
        } [
            [ first [ /mod ] [ dup ] if* ] [ second ] bi swap
            dup 0 > [ number>string prepend , ] [ 2drop ] if
        ] each drop
    ] { } make [ "0s" ] [ reverse " " join ] if-empty ;

And then to see it work:

( scratchpad ) 123456 elapsed-time .
"1d 10h 17m 36s"

Thursday, May 13, 2010

Relative Time for Humans

Many applications deal with events that have occurred at different points in time. Often, these times are relatively recent, such as a list of emails in an inbox or a list of status updates on a social network. When we talk about when an event occurred, it is sometimes useful to be precise (e.g., Thu May 13 19:12:02 2010), and other times it is better to be a bit softer (e.g., about a minute ago).

This function gets built from time-to-time in various languages: for example in Python and Javascript. I thought it might be fun to see how simple it could be in Factor.

A very useful type of conditional combinator is called cond. It applies to a sequence of quotations. The first elements in the sequence are pairs of quotations. The combinator proceeds to call the first quotation in each pair until a true value is yielded, at which point it calls the second quotation in that pair and stops iterating. A final quotation can be provided to handle the case where none of the pairs returned a true value.

In typical applicative languages, this would be provided by an "if/else if/else" chain. It is a general pattern and is used in Factor to implement case (a type of switch statement).

Using a few vocabularies:

USING: combinators formatting kernel math ;

We will write a word that takes the number of seconds that something happened in the past, and calculates how long ago it was in "human terms":

: relative-time ( seconds -- string ) dup 0 < [ "negative seconds" throw ] when { { [ dup 1 < ] [ drop "just now" ] } { [ dup 60 < ] [ drop "less than a minute ago" ] } { [ dup 120 < ] [ drop "about a minute ago" ] } { [ dup 2700 < ] [ 60 / "%d minutes ago" sprintf ] } { [ dup 5400 < ] [ drop "about an hour ago" ] } { [ dup 86400 < ] [ 3600 / "%d hours ago" sprintf ] } { [ dup 172800 < ] [ drop "1 day ago" ] } [ 86400 / "%d days ago" sprintf ] } cond ;

Fairly concise as it turns out. If it wasn't for the minor stack manipulation, you might say this was getting very close to the essence of the algorithm.

Thursday, April 29, 2010

What time is it? Part 3

In Part 1, we implemented a DAYTIME server using TCP. In Part 2, we implemented a TIME server using UDP.

Today, we will implement a simple NTP client using UDP.

The NTP (Network Time Protocol) specification has been evolving since 1985. Most of the focus has been on algorithms for synchronizing the clocks of computers to varying precisions. Currently the IETF is drafting version 4, but has only formally documented up to version 3 in RFC 1305. For use cases where less precision is required, version 4 of a variant called SNTP is documented in RFC 4330.

We will begin by referencing a set of vocabularies we depend upon:

USING: accessors arrays calendar combinators destructors
formatting kernel io io.sockets math pack random sequences ;

To parse and manipulate the NTP responses, we need to refer to the specification. These are often helpfully documented in ascii diagrams. The latest specification includes this description of a NTP packet:

1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|LI | VN  |Mode |    Stratum    |     Poll      |   Precision   |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                          Root  Delay                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                       Root  Dispersion                        |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                     Reference Identifier                      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
|                    Reference Timestamp (64)                   |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
|                    Originate Timestamp (64)                   |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
|                     Receive Timestamp (64)                    |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
|                     Transmit Timestamp (64)                   |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                 Key Identifier (optional) (32)                |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                                                               |
|                                                               |
|                 Message Digest (optional) (128)               |
|                                                               |
|                                                               |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

The specification contains detailed information about each of these fields and how they should be interpreted and used. For now, we will just create a tuple class to hold the values contained in a typical NTP packet:

TUPLE: ntp leap version mode stratum poll precision
root-delay root-dispersion ref-id ref-timestamp
orig-timestamp recv-timestamp tx-timestamp ;

Timestamps in the NTP protocol are stored in 64-bits. The first 32-bits are an integer number of seconds, and the last 32-bits are a fractional number of seconds. This gives the protocol a theoretical precision of 233 picoseconds. Most clocks in use by NTP servers are not that accurate, so some of the precision is wasted. Currently, this timestamp should be simply interpreted as a number of seconds since January 1, 1900 (this will change slightly when the 64-bit value overflows in the year 2036).

To parse each timestamp, we will want to convert it into a number of seconds and then use the calendar vocabulary to manipulate it into a timestamp object:

: (time) ( sequence -- timestamp )
    [ first ] [ second 32 2^ / ] bi + seconds
    1900 1 1 0 0 0 instant <timestamp> time+ ;

Now that we have that, parsing the NTP packet is fairly direct:

: (ntp) ( payload -- ntp )
    "CCCcIIIIIIIIIII" unpack-be {
        [ first -6 shift HEX: 3 bitand ]  ! leap
        [ first -3 shift HEX: 7 bitand ]  ! version
        [ first HEX: 7 bitand ]           ! mode
        [ second ]                        ! stratum
        [ third ]                         ! poll
        [ [ 3 ] dip nth ]                 ! precision
        [ [ 4 ] dip nth 16 2^ / ]         ! root-delay
        [ [ 5 ] dip nth 16 2^ / ]         ! root-dispersion
        [ [ 6 ] dip nth ]                 ! ref-id
        [ [ { 7 8 } ] dip nths (time) ]   ! ref-timestamp
        [ [ { 9 10 } ] dip nths (time) ]  ! orig-timestamp
        [ [ { 11 12 } ] dip nths (time) ] ! recv-timestamp
        [ [ { 13 14 } ] dip nths (time) ] ! tx-timestamp
    } cleave ntp boa ;

The simplest client request is a 48-byte packet encoded with no timestamp information, but only the mode of operation (e.g., 3 or "client"):

CONSTANT: REQUEST B{ HEX: 1b 0 0 0 0 0 0 0
                     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
                     0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
                     0 0 0 0 0 0 0 0 }

We will use the <datagram> word from the io.sockets vocabulary to send and receive UDP packets. Note that the resolve-host word is used to lookup the IP addresses for domain names, and picks one to use at random.

: <ntp> ( host -- ntp )
    123 <inet> resolve-host [ inet4? ] filter random
    f 0 <inet4> <datagram> [
        [ REQUEST ] 2dip [ send ] [ receive drop ] bi (ntp)
    ] with-disposal ;

We can make some convenience words for well-known hosts:

: default-ntp ( -- ntp )
    "pool.ntp.org" <ntp> ;

: local-ntp ( -- ntp )
    "localhost" <ntp> ;

Putting this all together, a NTP request/response can look like this:

( scratchpad ) default-ntp .
T{ ntp
    { leap 0 }
    { version 3 }
    { mode 4 }
    { stratum 3 }
    { poll 0 }
    { precision -8 }
    { root-delay 6453/65536 }
    { root-dispersion 4379/65536 }
    { ref-id 2903084642 }
    { ref-timestamp
        T{ timestamp
            { year 2010 }
            { month 4 }
            { day 30 }
            { minute 25 }
            { second 55+819995115/2147483648 }
        }
    }
    { orig-timestamp
        T{ timestamp { year 1900 } { month 1 } { day 1 } }
    }
    { recv-timestamp
        T{ timestamp
            { year 2010 }
            { month 4 }
            { day 30 }
            { minute 36 }
            { second 19+729484793/4294967296 }
        }
    }
    { tx-timestamp
        T{ timestamp
            { year 2010 }
            { month 4 }
            { day 30 }
            { minute 36 }
            { second 19+732746657/4294967296 }
        }
    }
}

This could be improved by parsing some of the fields as "human-readable" (like the leap indicator, mode, stratum, and reference id) and adding support for handling unresponsive servers or dropped packets. From here, one could learn the clock synchronization algorithms, or even use this as the basis to begin implementing a NTP server.

Monday, April 26, 2010

What time is it? Part 2

In Part 1, we implemented a server using the human-readable DAYTIME protocol.

One of the drawbacks of human-readable time is the challenge of parsing the text into an object that can be manipulated by computers. This is made harder when there is no clear specification for the format of the text (some conventions like RFC 822 exist, but the DAYTIME protocol leaves this detail unspecified).

Also in 1983, the TIME protocol (specified in RFC 868) was developed. It was intended to be used by machines (rather than humans) to retrieve the current time. As with the DAYTIME protocol, it supports both TCP and UDP. Below, we will implement a TIME server using UDP in Factor.

These are the vocabularies that we will be using:

USING: arrays destructors io.sockets kernel math pack system ;

The timestamp representation used as a payload is a 32-bit binary number of seconds since January 1, 1900. Most computers now use a 64-bit number of milliseconds since January 1, 1970 (referred to as the "epoch") to store the current time. Factor allows access to the current time as a number of microseconds since the epoch using the system-micros word.

We need to first create a word that will return the number of seconds since 1900. There were 2,208,988,800 seconds between January 1, 1900 and January 1, 1970. We will use that to adjust the current time:

CONSTANT: TIME1970 2208988800

: seconds-since-1900 ( -- n )
    system-micros 1000000 / >fixnum TIME1970 + ;

Jumping ahead slightly, we will create a word that receives a packet from a client (usually empty) and then sends the current time as a 32-bit binary number of seconds since 1900 back to the client. The io.sockets vocabulary provides some words for creating datagram servers (for UDP).

: serve-time ( datagram -- )
    [ receive nip ] keep
    [ seconds-since-1900 1array "i" pack ] 2dip
    send ;

According to the specification, the TIME server should run on port 37, but that typically requires administrative privileges, so we will run it on port 3700 for ease of testing. It is also best practices to bind to a specific network interface but, for now, we will listen for packets from any interface.

By running this code in the listener, we can test a datagram port that handles a single packet:

( scratchpad ) f 3700 <inet4> <datagram> [
                   serve-time
               ] with-disposal

And then using netcat, we can send an empty UDP packet to the server, which should respond with the current time in binary (which is why it is hard to read):

$ nc -u 127.0.0.1 3700 ?X?

Putting this all together, we can create a word that will loop forever, serving the current time in this manner:

: time-server ( -- )
    f 3700 <inet4> <datagram> [
        [ dup serve-time t ] loop drop
    ] with-disposal ;

The resolution of this protocol is low (since it is number of seconds), limiting the use-cases it is capable of supporting. Over the years, much better solutions have become standardized.

Wednesday, April 14, 2010

What time is it? Part 1

Time is a harder-than-it-looks concept in most computing systems.

Every machine has a clock, every clock has a time, and every time has a near infinite number of representations. The challenges include mastery of such topics as timezones, calendars, encodings, localizations, offsets, precision, drift, geographic latencies, atomic clocks, even GPS synchronization.

Back in the early 1980's, one of the tasks for building computer networks involved designing protocols by which applications could determine the current time. Over the years, these protocols have grown in features and complexity.

But back in 1983, in RFC 867, the IETF standardized a very simple human-readable time protocol called DAYTIME to solve the basic question: "what time is it?". The specification supports both TCP and UDP implementations, but we will implement just the TCP portion in Factor.

First, we need some vocabularies:

USING: accessors calendar formatting kernel io
io.encodings.ascii io.servers.connection ;

Using the formatting vocabulary that I wrote, printing the current time is easy with strftime:

( scratchpad ) now "%c" strftime .
"Wed Apr 14 18:13:51 2010"

The threaded-server type can then be used to accept connections from clients and output the current time before closing the connection:

: <daytime-server> ( port -- server )
    ascii <threaded-server>
        swap >>insecure
        "daytime.server" >>name
        [ now "%c" strftime print flush ] >>handler ;

According to the specification, the DAYTIME server should run on port 13, but that typically requires administrative privileges, so we will run it on port 1300 for this test.

( scratchpad ) 1300 <daytime-server> start-server

And to test it, using netcat:

$ nc localhost 1300 Wed Apr 14 17:17:53 2010 $ nc localhost 1300 Wed Apr 14 17:17:53 2010 $ nc localhost 1300 Wed Apr 14 17:17:54 2010 $ nc localhost 1300 Wed Apr 14 17:17:54 2010 $ nc localhost 1300 Wed Apr 14 17:17:55 2010

Characteristic of some of the early, and quite rapid, development on the internet, the specification is a little loose as to what format the time should be represented in. Other protocols developed later will be much more specific about the form and character of the time representations they contain.