Random people on the Internet want to know: Why is economics asocial
science?
---------------------------------------------------------------------------------
/ Pop-up advertisement. Breaking news. Help the Release Team [0] by reviewing \
pending unblock requests. Oh, and by fixing RC bugs too.
[0]: http://nthykier.wordpress.com/2012/12/09/wheezy-release-progress-december/
\---------------------------------------------------------------------------------/
Dear Project Members, here is another (delayed) monthly report
of DPL activities, this time for November 2012.
Highlights
master:/srv/leader/news/bits-from-the-DPL.txt.201211
Before we begin, everyone should read up on hashtables and what open
addressing / closed hashing is. The context is lines 111 190 of Python s
Objects/dictobject.c as of today (so we get the line numbers straight).
(I ve reworded this wlog entry a bit; I originally wrote it too late at
night for it to read coherent.) Basically, I ve got an application where
I d like to use a hashtable for a number of things not as generic as
Python, and with focus on small footprint. I d like to offer associative
arrays in a scripting language, where the keys are always arbitrary byte
strings excluding NUL. Also, I d like to use the hashtable as backend for
indexed arrays, where the keys are uint32_t and the usual use
case is sequential. Finally, I m using it for several internal tables,
such as a list of keywords, one of builtins, one of special variables,
etc. which is a reason for me to not use a self-balancing binary tree
as data structure (reading further below might suggest that, but getting
a sorted list of hashtable keys is not the focus, though not unimportant).
Why is the shift on perturb done after its first use? In my experiments (using 32-bit width everywhere), for the pathological case of an 8-element (i = 3) table with three entries 0, 0x40000000 and 0x800000000, the second round yields 1 for all three, so it cannot have to do with the upper bits. My lookup looks like:
mask = 2 - 1; j = perturb = hash(key); goto find_first_slot; find_next_slot: j = (j << 2) + j + perturb + 1; perturb >>= PERTURB_SHIFT; /* FALLTHROUGH */ find_first_slot: entry = table[j & mask]; if (!match(entry)) goto find_next_empty_slot;
This means that my first check is always the bare hash (so only do it if needed is no reason) and, since I m using gotos, I could just move the perturb >>= PERTURB_SHIFT; line before the line recalculating the next j to use. This seems to make more sense, even in the face of Python. (I actually looked at the Python file s comments again today because I thought to use a different resolution, but they have a good rationale for using the multiplication by 5.) Why can t we just use i as the PERTURB_SHIFT? Sure, this changes a shift-right by a constant, which can possibly be encoded as immediate value in assembly (unless you re on a pre-80186, which can only do SHR AX,1 and SHR AX,CL but not SHR AX,4, but that s outside of mksh s scope) into a right-shift by a variable, but i is already known, and I think the behaviour is better (it wouldn t eat any bits; assume the same 8-entry hashtable and pathologic keys 0, 8 and 16). Again: who do I think I am to go against the wisdom of the Python people, who seem to have shed more thought on this than everyone else I saw, asked, read about (including Spammipedia). That s why I m asking here. On that reference: I don t support spammers or people nagging for donations or premium accounts, like Xing and Groundspeak/Geocaching.COM, at all. In fact, I urge others to do the same, so it really hurts them; it may be their business model, but not if they spam me. Besides, OpenCaching.DE exists. Another thing is: to avoid CVE-2011-4815, I m randomising the hash used, with one seed value per hashtable, changed before a resize operation. I originally thought to seed it with nonzero, but then I have to rehash on hashtable resize, so I ll be XORing the final hash value instead (thanks ciruZ for the idea). I m thinking of omitting that for indexed arrays, as an attacker almost certainly cannot determine the keys there. (To directly use the indexed array keys, which are already uint32_t, as hashes makes using i from even more important.) The hash I m using is a modified Jenkins one-at-a-time called NZAAT: it s my new generic standard n n-cryptographic hash, and the changes are thus: while adding a byte, another increment of the hash is done (so NUL counts), and the finaliser got prefixed with the shift-left-add+shift-right-xor sequence of the adder (but not adding any value or the +1), to get best avalanche for all bytes. I actually compiled several versions of Hash.cs on a Windows VM at work to analyse the original one-at-a-time and all of my modifications; these turned out to be the simplest ones (I originally had added 0x100 instead of 1, but the effect was the same, and +1 is usually cheaper on most CPUs). Also, to avoid people being able to get to the seed, a user will always get only a sorted list of hashtable keys (numeric for indexed arrays, ASCIIbetically otherwise; see also my thoughts on JSON from the previous wlog entry). What algorithm do I use? For strings, comparisons are much more expensive, so I d like to keep them low. Memory use is also a factor; allocating one large(r) block is better than many small ones due to the pool allocator overhead and due to portability to ancient Unic s (which is another reason for me to use a hashtable which is a small struct plus an array of pointers, and then pass the list of keys as array of string pointers, instead of a tree). For both reasons, I m thinking a relatively simple MergeSort: I need to allocate the result array anyway, so I can just get two and free the one that isn t the end result, and it s AFAICT the cheapest on comparisons other than Tree Sort (which nobody really seems to use, and which would effect to using a balanced binary tree again). Since keys are unique, stability and duplicate handling is never an issue. I d like to use only one algorithm and one data structure, not a combination, as compactness is a design goal. Please drop your thoughts on Freenode, e.g. by /msg MemoServ send mirabilos your text here or per eMail to the domains debian, freewrt or mirbsd, which are organisations, with the localpart tg. Or just contact me as usual, if you re already acquainted. Or lookup 0xE99007E0. Thanks in advance! (Especially, Python Developers thoughts are welcome.)
Some brief software updates:
Although I've made extensive notes on common static site generators, and they will be discussed at length in the near future, I do want to highlight one problem common to 90% of them: Symbolic links. For example webgen fails my simple test:~/hg/websites$ webgen create test.example.com ~/hg/websites$ cd test.example.com/src/ ~/hg/websites/test.example.com/src$ mkdir jquery-1.2.3 ~/hg/websites/test.example.com/src$ touch jquery-1.2.3/jquery.js ~/hg/websites/test.example.com/src$ ln -s jquery-1.2.3 jquery ~/hg/websites/test.example.com$ webgen Starting webgen... ... Finished ~/hg/websites/test.example.com$ ls out/ grep jq jquery-1.2.3Here we see creating a symlink to a directory has not produced a matching symlink in the output. Something I use frequently. for example. Some tools mangled symlinked directories, or files, some ignore them completely. Neither is acceptible.
Apologies in advance for writing a long blog post about the dull and
specialised subject of
double-entry accounting
from the Unix tools perspective, that ends up talking about Monads to boot.
I can't believe I'm about to write such a thing, but I'm finding it an oddly
interesting subject.
double-entry accounting
I've known of, though probably not really understood double entry
accounting for a while, thanks to GnuCash. I think
GnuCash did something rather special in making such a subject approachable
to the layman, and I've been happy to recommend GnuCash to friends. I was
stoked to find a chapter in my sister Anna's
new book
that happily and plausibly suggests readers use GnuCash.
But for my personal use, GnuCash is clunky. I mean, I'm a programmer,
but I can't bring any of my abilities to bear on it, without a deep dive
into the code. The file format is opaque (and a real pain to keep checked
into git with all the log files); the user interface is often confusing,
but there's no benefit to its learning curve, it never seems to get better
than manually entering data into its ledger, or perhaps importing data from
a bank. I've never found the reports very useful.
I've got perhaps a year of data in GnuCash, but it's fragmented and
incomplete and not something I've been able to motivate myself to keep up
with. So I have less financial data than I'd like. I'm hoping ledger will
change that.
ledger
I've known about ledger for a while, at least since
This Linux Weekly News article.
It's a quintessential Unix tool, that simply processes text files.
The genius of it is the simplicity of the file format, that gets the essence
and full power of double entry bookeeping down to something that approaches a
meme. Once you get the file format stuck in your head, you're done for.
2004/05/27 Book Store
Expenses:Books $20.00
Liabilities:Visa
starting to use hledger
Now as a Haskell guy, I was immediately drawn to
the Haskell clone, hledger. It's nice that there
are two (mostly) compatable implementations of ledger too. So from here on,
I'll be talking about hledger.
I sat down and built a hledger setup for myself the other day.
I started by converting the GnuCash books I have been keeping up-to-date,
for a small side business (a rental property). It quickly turned into
something like programming, in the best way, as I used features like:
print, to a interactive interface.hledger stats says I have 3700 transactions on file,
which is not bad for what was just a few hours work yesterday.
One problem is hledger's gotten a little slow with this many transactions. It
takes 5 seconds to get a balance. The ledger program, written in C, is
reportedly much faster. hledger recently had a O(n^2) slowdown fixed,
which makes me think it's probably only starting to be optimised. With
Haskell code, you can get lucky and get near C (language, not speed of
light) performace without doing much, or less lucky and get not much better
than python performance until you dive into optimising. So there's hope.
harnessing haskell
If there's one place hledger misses out on being a state of the art modern
Unix program, it's in the rules files that are used to drive CSV
imports. I found these really hard to use; the manual notes that "rules
file parse errors are not the greatest"; and it's just really inflexible.
I think the state of the art would be to use a Domain Specific Language here.
For both my Amazon and PayPal imports I had CVS data something like:
date, description, amount, fees, gross
I want to take the feeds into account, and make a split transaction, like this:
date description
assets:accounts:PayPal $9.90
expenses:transaction fees:PayPal $0.10
income:misc:PayPal -$10.00
This does not seem possible with the rules file. I also wanted to combine
multiple CVS lines, to do with currency conversions, into a single
transaction, and couldn't.
The problem is that the rules file is an ad-hoc format, not a fully
programmable one. If instead, hledger's rules files were compiled into
standalone haskell programs that performed the import, arbitrarily
complicated conversions like the above could be done.
So, I'm thinking about something like this for a DSL.. I doubt I'll get
much further than this, since I have a hacked together multi-pass importer
that meets my basic needs. Still, this would be nice, and being able to
think about adding thing kind of thing to a program cleanly is one of the
reasons I reach for the Haskell version when possible these days.
First, here's part of one of my two paypal import rules files
(the other one extracts the transaction fees):
amount-field 7
date-field 0
description-field %(3) - %(4) - %(11)
base-account assets:accounts:PayPal
Bank Account
assets:accounts:checking
.*
expenses:misc:PayPal
That fills out the basic fields, and makes things with "Bank Account"
in their description be categorised as bank transfers.
Here's how it'd look as Haskell, carefully written to avoid the $
operator that's more than a little confusing in this context. :)
main :: IO () main = convert paypalConveter paypalConverter :: [CSVLine] -> [Maybe Transaction] paypalConverter = map convert where convert = do setAmount =<< field 7 setDate =<< field 0 setDescription =<< combine " - " [field 3, field 4, field 11] defaultAccounts "assets:accounts:PayPal" ==> "expenses:misc:PayPal" inDescription "Bank Account" ? "assets:accounts:PayPal" ==> "assets:accounts:checking"That seems like something non-haskell people could get their heads around, especially if they didn't need to write the boilerplate function definitions and types at the top. But I may be biased. :) Internally, this seems to be using a combination Reader and Writer monad that can get at fields from a CSV line and build up a Transaction. But I really just made up a simple DSL as I went along and thew in enough syntax to make it seem practical to implement. :) Of course, a Haskell programmer can skip the monads entirely, or use others they prefer. And could do arbitrarily complicated stuff during imports, including building split transactions, and combining together multiple related CVS lines into a single transaction.
I was a bit busy (mostly in pleasant ways) during the last two weeks, so
this reports covers a longer period of my RC bug activities:
The following proposal extends the JSON specification, with the idea
of using JSON as an information interchange format, rather than just a
way of writing certain ECMAscript values. They do not add anything but
only restrict valid JSON content and encoders with some rationale.
First of, I d like to remind everyone, including JSON s author, that
JSON is case-sensitive, except in the four hexdigits
after a backslash-u sequence in a String.
Second, I d like to remind everyone that JSON is not binary-safe. No
way around that, it implements Unicode (actually, 16-bit UCS-2, and it
doesn t guarantee that UTF-16 surrogates are correctly paired) text. I
also consider only UTF- 8, 16,32 B,L E valid encodings for JSON. (No
PDP endian, either. Sorry, guys.)
For my first proposal, I d like to point out CVE-2011-4815 which was
about overflowing hashtables. The obvious fix is to randomise the hash
per hashtable; to ensure this doesn t leak, we sort ASCIIbetically the
keys of an Object in the encoder. (Using Unicode is good here we can
just sort the keys as UTF-8 strings by their uint8_t value or
as Unicode (UCS-2 or even UCS-4 or UTF-16) strings by the codepoints.)
JSON was never preserving the order of elements in an Object anyway so
we make it standardised (we still accept any order, and, when parsing,
in collision cases, the later value wins). This also helps diffs.
For my second proposal, I d like to forbid \u0000, \uFFFE, \uFFFF in
strings. The first because many implementations use C strings, and for
an information interchange format this is better; it also has security
implications to allow NUL in a string. The other two, but not unpaired
UTF-16 surrogates (as ECMAscript uses UCS-2 and got UTF-16 only later)
because they re not valid Unicode; JSON was not binary-safe already so
why bother. Among other benefits, this also helps implementations.
For my third proposal, I d like to agree that implementations should
impose a nesting depth limit that may be user-defined, and in the face
of which, cyclic checking may be ignored by an encoder. I emit nesting
depth overflows as literalnull; might also throw an error. Since I was
asked, the common standard value is to restrict nesting depth is 32,
unless the user specified one. (I also saw 8, but 32 WFM pretty well.)
Most seem to use it even if it may seem low at first. Only specialised
applications probably need more, and they can always pass a value.
For my forth proposal, backslash-escape U+007F U+009F always. It may
upset humans, editors, databases, etc. (This paragraph is newly added,
after some IRC discussion.)
All these do not permit anything that wasn t accepted to be accepted
afterwards. I ve got a fifth proposal which changes acceptance rules
but only for a subset of parsers: formally JSON is defined in ECMA-262
as industry standard that, in contrast to RFC 4627, always allowed any
Value as top-level element of a JSON text. I d like to make it so, and
ignore the RFC s requirement for it to be an Object or Array. Even so,
the first two characters (after the BOM, if any) of a JSON text always
are in the non-NUL 7-bit ASCII range, allowing for encoding detection.
(This is done by the NUL octet pattern in the first four octets.)
JSON has only taken off because it s a tightly defined simple format
that can be used everywhere and isn t too awful for humans (escaping
not needed for U+0020 U+D7FF and U+E000 U+FFFD after all, although I d
also take the C1 control characters out, see my forth proposal above).
I ve started to use a trailing comma in indexed and associative arrays
in code I write at work, when the array values are one a line, to help
version control systems to do their diffs, but refrain from asking for
a JSON extension to permit that in order to not endanger compatibility
any (no comment needed, it s just not worth it), but I d like my above
proposals to be followed by implementators (and I m one of them).
Some more discussion with Jonathan pointed out that JSON5 allows for
trailing commata in Object and Array; IMHO the only feature of it that
is not bad or outright harmful. I ll probably keep from accepting them
because, on their own, they re not that useful, and I usually
would run JSON texts, even configs, through a parser/encoder roundtrip
to pretty-print them which would lose them anyway.
As for binary-safeness: probably best to just use base64 and let the
outer layers worry about compression. The data is usually unrelated to
the JSON-encoded structure, and even if it s related to other data the
base64 representation is usually similar (unless misaligned).
Update 02.12.2012 Wrong I was about the first two
characters: " " is a valid JSON text. Still possible to peek at four
octets and determine the encoding by ordering the tests; updated my notes.
After seeing some book descriptions recently on planet debian,
let me add some short recommendation, too.
Almost everyone has heard about Gulliver's Travels already,
so usually only very cursory. For example: did you know the book
describes 4 journeys and not only the travel to Lilliput?
Given how influential the book has been, that is even more suprising.
Words like "endian" or "yahoo" originate from it.
My favorite is the third travel, though, especially the acadamy of Lagado,
from which I want to share two gems:
"
His lordship added, 'That he would not, by any further particulars, prevent the pleasure I
should certainly take in viewing the grand academy, whither he was resolved I should go.' He
only desired me to observe a ruined building, upon the side of a mountain about three miles
distant, of which he gave me this account: 'That he had a very convenient mill within half a
mile of his house, turned by a current from a large river, and sufficient for his own family, as
well as a great number of his tenants; that about seven years ago, a club of those projectors
came to him with proposals to destroy this mill, and build another on the side of that mountain,
on the long ridge whereof a long canal must be cut, for a repository of water, to be conveyed up
by pipes and engines to supply the mill, because the wind and air upon a height agitated the
water, and thereby made it fitter for motion, and because the water, descending down a
declivity, would turn the mill with half the current of a river whose course is more upon a
level.' He said, 'that being then not very well with the court, and pressed by many of his
friends, he complied with the proposal; and after employing a hundred men for two years, the
work miscarried, the projectors went off, laying the blame entirely upon him, railing at him
ever since, and putting others upon the same experiment, with equal assurance of success, as
well as equal disappointment.'
"
"I went into another room, where the walls and ceiling were all hung
round with cobwebs, except a narrow passage for the artist to go in and out.
At my entrance, he called aloud to me, 'not to disturb his webs.' He
lamented 'the fatal mistake the world had been so long in, of using
silkworms, while we had such plenty of domestic insects who infinitely excelled
the former, because they understood how to weave, as well as spin.'
And he proposed further, 'that by employing spiders, the charge of dyeing
silks should be wholly saved;' whereof I was fully convinced, when he
showed me a vast number of flies most beautifully coloured, wherewith he fed
his spiders, assuring us 'that the webs would take a tincture from them; and as
he had them of all hues, he hoped to fit everybody s fancy, as soon as he
could find proper food for the flies, of certain gums, oils, and other
glutinous matter, to give a strength and consistence to the threads.'"
I host a number of websites which are mostly static in nature, these are often hand-crafted, but three of them us a slightly hacked up creation of my own.
Given a master "template" the file foo.skx gets massaged into foo.html.
Sadly I added features randomly, and now I have three template-driven sites which are handled slightly differently. This put me in the position of having to choose between two options:
At the moment I'm using the same 32-bit dom0 kernel as we run on the
32-bit port of Xen, obviously we eventually want to support both 32-
and 64-bit guests. In fact we went to a fair bit of trouble with the
32-bit port to try and ensure that the hypercall ABI would be the same
for both and avoid the need for a compatibility layer (Stefano's
talk from
XenSummit in the summer has some details on that).
Combined with Debian bug #599161 finally being tracked down and fixed
upstream all in all this is shaping up to be a pretty good week!
| Series: | Dune #1 |
| Publisher: | Ace |
| Copyright: | 1965 |
| Printing: | September 1990 |
| ISBN: | 0-441-17271-7 |
| Format: | Mass market |
| Pages: | 537 |
We introduced Rcpp 0.10.0 with a number of very nice new features a
few days ago, and the activity on the rcpp-devel mailing list has been pretty
responsive which is awesome.
But because few things beat a nice example, this post tries to build some more excitement. We will illustrate how Rcpp attributes
makes it really easy to add C++ code to R session, and that that code is as easy to grasp as R code.
Our motivating example is everybody's favourite introduction to Monte Carlo simulation: estimating . A common method uses the fact
the unit circle has a surface area equal to . We draw two uniform random numbers x and y, each between zero
and one. We then check for the distance of the corresponding point (x,y) relative to the origin. If less than one (or equal),
it is in the circle (or on it); if more than one it is outside. As the first quadrant is a quarter of a square of area one, the area of
the whole circle is -- so our first quadrant approximates over four. The following figure, kindly borrowed from Wikipedia
with full attribution and credit, illustrates this:
Now, a vectorized version (drawing N such pairs at once) of this approach is provided by the following R function.
And in C++ we can write almost exactly the same function thanks the Rcpp sugar vectorisation available via Rcpp:piR <- function(N) x <- runif(N) y <- runif(N) d <- sqrt(x^2 + y^2) return(4 * sum(d < 1.0) / N)
Sure, there are small differences: C++ is statically typed, R is not. We need one include file for declaration, and we need one instantiation of the#include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] double piSugar(const int N) RNGScope scope; // ensure RNG gets set/reset NumericVector x = runif(N); NumericVector y = runif(N); NumericVector d = sqrt(x*x + y*y); return 4.0 * sum(d < 1.0) / N;
RNGScope object to ensure random number draws remain coordinated between the calling R process and the C++ function
calling into its (compiled C-code based) random number generators. That way we even get the exact same draws for the same seed.
But the basic approach is identical: draw a vector x and vector y, compute the distance to the origin and then
obtain the proportion within the unit circle -- which we scale by four. Same idea, same vectorised implementation in C++.
But the real key here is the one short line with the [[Rcpp::export]] attribute. This is all it takes (along with
sourceCpp() from Rcpp 0.10.0) to get the C++ code into R.
The full example (which assumes the C++ file is saved as piSugar.cpp in the same directory) is now:
and it does a few things: set up the R function, source the C++ function (and presto: we have a callable C++ function just like that), compute two simulations given the same seed and ensure they are in fact identical -- and proceed to compare the timing in a benchmarking exercise. That last aspect is not even that important -- we end up being almost-but-not-quite twice as fast on my machine for different values of#!/usr/bin/r library(Rcpp) library(rbenchmark) piR <- function(N) x <- runif(N) y <- runif(N) d <- sqrt(x^2 + y^2) return(4 * sum(d < 1.0) / N) sourceCpp("piSugar.cpp") N <- 1e6 set.seed(42) resR <- piR(N) set.seed(42) resCpp <- piSugar(N) ## important: check results are identical with RNG seeded stopifnot(identical(resR, resCpp)) res <- benchmark(piR(N), piSugar(N), order="relative") print(res[,1:4])
N.
The real takeaway here is the ease with which we can get a C++ function into R --- and the new process completely takes care of passing
parameters in, results out, and does the compilation, linking and loading.
More details about Rcpp attributes are in the new vignette. Now enjoy the .
Update:One somewhat bad typo fixed.
Update:Corrected one background tag.
| Series: | Women Were Warriors #3 |
| Publisher: | Shield Maiden |
| Copyright: | 2008 |
| ISBN: | 0-9815636-3-5 |
| Format: | Kindle |
| Pages: | 301 |
This is an ebook, so metadata may be inaccurate or missing. See notes on ebooks for more information. A Hero's Tale is the third book in the When Women Were Warriors trilogy, which is best thought of as a single long novel. Reading it independently will miss most of the significance of the plot, since one wouldn't know many of the important characters. A Hero's Tale follows the pattern of the second book: even less quiet contemplation, and even more in the way of events and plot. Tamras completes her training, in a somewhat unexpected way (and in a rather interesting reworking of gender roles), but then both Maara's past and the problems of A Journey of the Heart catch up with them. There is, accordingly, quite a bit more action, or at least war councils and political maneuvering, than the previous books, and somewhat less time for thoughtful wisdom. That also means that A Hero's Tale shifts a bit more towards the traditional fantasy coming-of-age story, where the heroine is able to shift armies and win conflicts with an understated and self-deprecating skill that comes inevitably but indirectly out of all of her previous experiences. I think Wilson is still fairly original in how she presents those tropes, with an interesting focus on empathy and compassion that is all too rare in this sort of story, but this book does feel a lot more like a story that one has read before. If you're particularly allergic to that story shape, you may find this entry somewhat disappointing. One of the things I loved about it, though, was Wilson's avoidance of traditional villains. There is one, so it's not a complete avoidance, but nearly everyone in this story has their own viewpoint and perspective and is on the side of right in their own way. Wilson uses Tamras's empathy and willingness to listen and understand to let the reader see various different perspectives without moving away from the first-person perspective. It's very nicely done. I thought the handling of the emotional arc of the story was more mixed. Tamras is seriously tested in some moments that aimed for heartbreaking, but I thought they fell short of the emotional punch they were supposed to carry since the story shape had already made it obvious that everything would turn out okay in the end. The story is so gentle that Wilson hadn't established any willingness to end something badly, which robs a lot of the punch from emotional turmoil. I also had quite a bit of trouble with the principle of love above all else, particularly for someone in Tamras's position. Maybe that's because I'm still too entrenched in the attitude towards politics that this series argues against, but I had a hard time not seeing her as personally indulgent. Both of those factors blunted the emotional climax for me, leaving it moving but not as heartbreaking as I think Wilson was aiming for. (This is the point where a friend will tell me that I think too much about books while I'm reading them.) That said, Wilson continues to write one of the best mentoring relationships that I've seen in fiction. The dynamic between Tamras and Maara is just beautiful, and remains so through the end of the book. So many traditional issues with rivalry, growth, replacement of the mentor, and relative social position that are ignored or dealt with ham-handedly in other stories are handled adeptly and quietly. Maara is by far my favorite character of this series, largely because of how she handles that relationship. I could identify with her more easily than with Tamras at various points in the story, and I thought the understated ending was quietly beautiful. If you enjoyed the rest of the series, definitely read A Hero's Tale for the conclusion. If you've been hungry for more typical action, you'll get some of it here. I wish a few deep emotions other than love had been in play, but, despite that, When Women Were Warriors is still quietly and delightfully different than most things I've read, and worth the price. Rating: 8 out of 10
We released Rcpp 0.10.0 earlier today. This post will just provide a
simple example for one of the smaller new features -- the new namespace for functions from Rmath.h -- and illustrate one of the
key features (Rcpp attributes) in passing.
R, as a statistical language and environment, has very well written and tested statistical distribution functions providing
probability density, cumulative distribution, quantiles and random number draws for dozens of common and not so common distribution functions.
This code is used inside R, and available for use from standalone C or C++ programs via the standalone R math library which Debian /
Ubuntu have as a package r-mathlib (and which can be built from R sources).
User sometimes write code against this interface, and then want to combine the code with other code, possibly even with Rcpp. We allowed
for this, but it required a bit of an ugly interface. R provides a C interface; these have no namespaces. Identifiers can clash, and to be
safe one can enable a generic prefix Rf_. So functions which could clash such as length or error
become Rf_length and Rf_error and are less likely to conflict with symbols from other libraries. Unfortunately, the side-effect
is that calling, say, the probability distribution function for the Normal distribution becomes Rf_pnorm5() (with the 5
denoting the five parameters: quantile, mean, std.deviation, lowerTail, logValue). Not pretty, and not obvious.
So one of the things we added was another layer of indirection by adding a namespace R with a bunch of inline'd wrapper
functions (as well as several handful of unit tests to make sure we avoided typos and argument transposition and what not).
The short example below shows this for a simple function taking a vector, and returning its pnorm computed three different ways:
This example also uses the new Rcpp attributes described briefly in the announcement blog post and of course in more detail in the corresponding vignette. Let us just state here that we simply provide a complete C++ function, using standard Rcpp types -- along with one 'attribute' declaration of an export via Rcpp. That's it -- even easier than using inline. Now in R we simply do#include <Rcpp.h> // [[Rcpp::export]] Rcpp::DataFrame mypnorm(Rcpp::NumericVector x) int n = x.size(); Rcpp::NumericVector y1(n), y2(n), y3(n); for (int i=0; i<n; i++) // the way we used to do this y1[i] = ::Rf_pnorm5(x[i], 0.0, 1.0, 1, 0); // the way we can do it now y2[i] = R::pnorm(x[i], 0.0, 1.0, 1, 0); // or using Rcpp sugar in one go y3 = Rcpp::pnorm(x); return Rcpp::DataFrame::create(Rcpp::Named("Rold") = y1, Rcpp::Named("Rnew") = y2, Rcpp::Named("sugar") = y3);
to obtain a callable R function with the C++ code just shown behind it. No Makefile, no command-line tool invocation -- nothing but a single call toR> sourceCpp("mypnorm.cpp")
sourceCpp() which takes care of things --- and brings us a compiled C++ function to R just given the source file with
its attribute declaration.
We can now use the new function to compute the probaility distribution both the old way, the new way with the 'cleaner'
R::pnorm(), and of course the Rcpp sugar way in a single call. We build a data frame in C++, and assert that all
three variants are the same:
This example hopefully helped to illustrate how Rcpp 0.10.0 brings both something really powerful (Rcpp attributes -- more on this another time, hopefully) and convenient in the new namespace for statistical functions.R> x <- seq(0, 1, length=1e3) R> res <- mypnorm(x) R> head(res) Rold Rnew sugar 1 0.500000 0.500000 0.500000 2 0.500399 0.500399 0.500399 3 0.500799 0.500799 0.500799 4 0.501198 0.501198 0.501198 5 0.501597 0.501597 0.501597 6 0.501997 0.501997 0.501997 R> all.equal(res[,1], res[,2], res[,3]) [1] TRUE R>
Next.