Thursday, September 18, 2008

Too powerful to evolve

Paragraph 1.4.8 of the C++ standard (draft copy) states that

A conforming implementation may have extensions (including additional library functions), provided they do not alter the behavior of any well-formed program.

It turns out that, strictly speaking, this unexpectedly bans many possible extensions an implementation of the C++ standard library might provide; C++ is such a powerful beast that a well-formed program might be made to depend on the non-existence of certain entities.

Function and function templates. The following program

‎#include <algorithm>
‎
‎using namespace std;
‎
‎int any_of(int count,int n1,...){/*...*/}
‎
‎int main()
‎{
‎ int n=any_of(2,1023,233);
‎}
‎

is valid C++03, but will fail with the upcoming C++0x revision of the standard, as this includes a function template any_of within <algorithm>:

‎template <class InputIterator, class Predicate>
‎bool any_of(InputIterator first, InputIterator last, Predicate pred);

that takes precedence over the user defined any_of due to the using namespace std directive.

Classes and class templates. Similarly, this C++03 valid program

‎#include <functional>
‎
‎using namespace std;
‎
‎template<typename T>
‎struct hash
‎{
‎ size_t operator()(const T& t){/*...*/}
‎};
‎
‎int main()
‎{
‎ hash<int> h;
‎ size_t s=h(983265);
‎}
‎

will fail with C++0x due to the presence of an homonym hash in <functional>.

Member functions. The previous situations can be avoided if non-standard extensions are declared in separate headers or belong to a namespace other than std. These measures cannot be taken, however, when we are adding members to a standard class. The following is a totally artificial yet valid C++03 program:

‎#include <vector>
‎
‎template<class Vector>
‎int foo(char x){/*...*/}
‎
‎template <typename T,void (T::*)()> struct mfp{};
‎
‎template<class Vector>
‎void* foo(int x,mfp<Vector,&Vector::shrink_to_fit>* =0){/*...*/}
‎
‎int main()
‎{
‎ int x=foo<std::vector<int> >(0);
‎}

The so-called SFINAE rule prevents the second overload of foo to be selected because vector has no member function called shrink_to_fit; but it does in C++0x, rendering the program invalid (the second foo return type is not convertible to int).

Of course this is not a serious objection to the C++ standard text: 1.4.8 could always be rephrased to restrict it to reasonable well-formed programs, for some definition of "reasonable". But it can be instructive to reflect on how C++ has become so powerful (some would say complex) that such devious tricks can emerge (and, in some cases, be benefited from).

Sunday, September 14, 2008

A causality calculus

Let us design a first-order calculus including causality as non-truth-functional connective for which causality semantics is defined at the same level as the rest of the (truth-functional) connectives, according to the philosophical position stated in a previous entry. We assume we are given an infinite set of variables V and a set R of predicate symbols with associated arities.

Propositional constants: F (falsehood).

Connectives: → (only if), > (causal implication).

Quantifiers: V (for all).

Axioms and rules of inference: the usual ones for standard first-order calculus plus the following axiom schemas dealing with causality:

(C1) p > q, q > r → p > r

(C2) (p > p) → F

(C3) p > q → (p and q)

(C4) p > r → (p or q) > r

(C5) p > (q and r) → p > q

These axioms deserve some comment: C1 states the usual transitivity of causation, while C2 says that no event causes itself; C3 allows us to speak about causation only among events actually taking place, which makes this a "realist" semantics. C4 and C5 translate some usual properties of material implication to causal implication.

Semantics: a valuation v specifies several mappings:

  • From V to some set U.
  • From each n-ary predicate in R to some n-ary relation in U.
  • From each formula to the set {F,T}.

and obeys the following rules:

  • v(F) = F.
  • v(φ → ψ) = T iff v(φ) = F or v(ψ) = T.
  • v(R(t1,...,tn)) = T iff (v(t1),...,v(tn)) is in v(R).
  • v(Vx φ) = T iff v'(φ) = T for every valuation v' identical to v except possibly at x.
  • The relation on formulas of the calculus defined by v(φ > ψ) = T is consistent with axiom schemas C1,..., C5. In particular, this implies that the relation thus defined is a strict partial order.

As usual, a statement is valid if it is true for any valuation. It is easy to see that there are valuations with the properties described above: just take any valuation for standard first-order predicate calculus and augment it with v(φ > ψ) = F for all φ, ψ (we may call this a Humean valuation).

Wednesday, September 10, 2008

Introducing stable_vector

We present stable_vector, a fully STL-compliant stable container that provides most of the features of std::vector except element contiguity. The underlying data structure has been discussed in a prior entry.

In the following we are using the terminology of the C++98 standard.

General properties. stable_vector satisfies all the requirements of a container, a reversible container and a sequence and provides all the optional operations present in std::vector. Like std::vector, iterators are random access. stable_vector does not provide element contiguity; in exchange for this absence, the container is stable, i.e. references and iterators to an element of a stable_vector remain valid as long as the element is not erased, and an iterator that has been assigned the return value of end() always remain valid until the destruction of the associated stable_vector.

Operation complexity. The big-O complexities of stable_vector operations match exactly those of std::vector. In general, insertion/deletion is constant time at the end of the sequence and linear elsewhere. Unlike std::vector, stable_vector does not internally perform any value_type destruction, copy or assignment operations other than those exactly corresponding to the insertion of new elements or deletion of stored elements, which can sometimes compensate in terms of performance for the extra burden of doing more pointer manipulation and an additional allocation per element.

Exception safety. (according to Abrahams' terminology) As stable_vector does not internally copy elements around, some operations provide stronger exception safety guarantees than in std::vector:

operationexception safety for
std::vector<T>
exception safety for
stable_vector<T>
insertstrong unless copy or assignment of T throw (basic)
strong
eraseno-throw unless copy or assignment of T throw (basic)
no-throw

Memory overhead. The C++ standard does not specifiy requirements on memory consumption, but virtually any implementation of std::vector has the same behavior wih respect to memory usage: the memory allocated by a vector v with n elements of type T is

mv = c·e,

where c is v.capacity() and e is sizeof(T). c can be as low as n if the user has explicitly reserved the exact capacity required; otherwise, the average value c for a growing vector oscillates between 1.25·n and 1.5·n for typical resizing policies. For stable_vector, the memory usage is

msv = (c + 1)p + (n + 1)(e + p),

where p is the size of a pointer. We have c + 1 and n + 1 rather than c and n because a dummy node is needed at the end of the sequence. If we call f the capacity to size ratio c/n and assume that n is large enough, we have that

msv/mv ≈ (fp + e + p)/fe.

So, stable_vector uses less memory than std::vector only when e > p and the capacity to size ratio exceeds a given threshold:

msv < mv ↔ f > (e + p)/(e − p). (provided e > p)

This threshold approaches typical values of f below 1.5 when e > 5p; in a 32-bit architecture, when e > 20 bytes.

Summary. stable_vector is a drop-in replacement for std::vector providing stability of references and iterators, in exchange for missing element contiguity and also some performance and memory overhead. When the element objects are expensive to move around, the performance overhead can turn into a net performance gain for stable_vector if many middle insertions or deletions are performed or if resizing is very frequent. Similarly, if the elements are large there are situations when the memory used by stable_vector can actually be less than required by std::vector.

Saturday, September 6, 2008

Causality as a primitive concept

The supposedly metaphysical nature of causality, according to such radical empiricists as Hume, stems from the fact that there cannot be a direct perception of a causal connection between events: perception of causes and effects is indistinguishable from perception of unrelated events that happen to be contiguous in space and time. This non-commitmental position is, however, untenable, as causality is absolutely central to any theory admitting the existence of an objective world: it is only by postulating a cause-effect relation between external events and our internal perceptions of them that we can escape solipsism.

It is my take then that causality, at least within the context of the human perception of events, can be seen as a primitive concept at the same level as event occurrence; saying "A causes B" is as basic a statement as "It is the case that C", because causality can only be explained in terms of event occurrence, and any account of an event occurrence depends on the implied causality connecting events and their perception. Formal renditions of causality, however, propose modal-like semantics denying this concept its primitiveness, which adds to the methaphysical aura sourrounding the subject: while the truth or falsity of a statement in a logical calculus is directly represented by the models of the calculus (cf. first-order predicate calculus semantics), causality semantics rely on more complex structures (vg. possible worlds) that build on "basic" models.

What would a formalization look like in which the truth of a statement and the causal connection between two statements are modeled at the same basic level? We will explore this approach in a later entry.

Tuesday, September 2, 2008

A combinatory theorem

Definition. Let S be a finite set of cardinality N, σ = (σ1,...,σN) a permutation of the elements of S and X a subset of S. We say the σ prefix-covers (or simply covers) X if X is one of Ø, {σ1}, {σ1,σ2}, ... , {σ1,...,σM}.

For instance, if S = {a,b,c,d} and σ = (b,d,a,c), the following subsets of S are covered by σ: Ø, {b}, {b,d}, {a,b,d}, {a,b,c,d} = S.

In the following we use the notation C(a,b) for the binomial coefficient a choose b.

Theorem. C(N,floor(N/2)) is the minimum number of distinct permutations of S jointly covering all the subsets of S.

Proof. Let P be the power set of S partially ordered by inclusion. The sets covered by a permutation of S form a maximal chain of P, and this correspondence between permutations and maximal chains is clearly one-to-one. So, the minimum number of permutations of S required to cover S is the same as the minimum number of chains partitioning P. By Dilworth's Theorem, this number is equal to the partial order width of P, that Sperner's Theorem shows to be C(N,floor(N/2)).

The first values of C(n,floor(n/2)) are: 1, 1, 2, 3, 6, 10, 20, 35, 70, 126... The following table shows some possible permutation covers for |S| = 1,...,5.

Spermutation cover
{a}(a)
{a,b}(ab), (ba)
{a,b,c}(abc), (bca), (cab)
{a,b,c,d}(abcd), (acbd), (bcda),
(bdac), (cdab), (dabc)
{a,b,c,d,e}(abcde), (bcdea), (cdeab), (deabc), (eabcd),
(acdbe), (adbce), (bdeac), (becad), (ceabd)

The proof of the theorem does not provide an efficient algorithm to construct a permutation cover. Finding such an algorithm is an interesting problem that we will address in a later entry.

Friday, August 29, 2008

Stable vectors

Extremely convenient as they are, std::vectors have a limitation that many novice C++ programmers frequently stumble upon: iterators and references to an element of an std:vector are invalidated when a preceding element is erased or when the vector expands and needs to migrate its internal storage to a wider memory region (i.e. when the required size exceeds the vector's capacity). We say then that std::vectors are unstable: by contrast, stable containers are those for which references and iterators to a given element remain valid as long as the element is not erased: examples of stable containers within the C++ standard library are std::list and all the associative containers.

Sometimes stability is too precious a feature to live without. One particular property of std::vectors, namely element contiguity, makes it impossible to add stability to this container. So, provided we sacrifice element contiguity, how much can a stable design approach the behavior of std::vector (random access iterators, amortized constant time end insertion/deletion, minimal memory overhead, etc.)?

The following image describes the layout of a possible data structure upon which to base the design of a stable vector:

Each element is stored in its own separate node. All the nodes are referenced from a contiguous array of pointers, but also every node contains an "up" pointer referring back to the associated array cell. This up pointer is the key element to implementing stability and random accessibility:

  1. Iterators point to the nodes rather than to the pointer array. This ensures stability, as it is only the pointer array that needs to be shifted or relocated upon insertion or deletion.
  2. Random access operations can be implemented by using the pointer array as a convenient intermediate zone. For instance, if the iterator it holds a node pointer it.p and we want to advance it by n positions, we simply do:
    ‎it.p = *(it.p->up+n);
    That is, we go "up" to the pointer array, add n there and then go "down" to the resulting node.

In a later entry we will present a full implementation of an STL-conformant stable vector and compare its characteristics (space/time complexity, exception safety) with those of std::vector.

Monday, August 25, 2008

Cpp bignum arithmetic with memoization

The multiplication algorithm we implemented for C preprocessor bignums incurs a certain amount of repetitive work: multiplying bn1 by bn2 = bn21 bn22···bn2m, involves calculating the set of intermediate products bn1·bn21, ... ,bn1·bn2m, which includes as many repeated values as equal digits are in the decimal expansion of bn2. We can avoid recalculating those by applying memoization to the BN_DIGIT_MUL macro:

‎#define BN_CACHED_DIGIT_MUL(bn,y,cache) \
‎BOOST_PP_IF( \
‎ BOOST_PP_EQUAL( \
‎ 1, \
‎ BOOST_PP_SEQ_SIZE(BOOST_PP_SEQ_ELEM(y,cache))), \
‎ BN_CACHED_DIGIT_MUL_CASE1, \
‎ BN_CACHED_DIGIT_MUL_CASE2)(bn,y,cache)
‎
‎#define BN_CACHED_DIGIT_MUL_CASE1(bn,y,cache) \
‎BN_CACHED_DIGIT_MUL_CASE1_IMPL(BN_DIGIT_MUL(bn,y),y,cache)
‎
‎#define BN_CACHED_DIGIT_MUL_CASE1_IMPL(bny,y,cache) \
‎(bny)(BOOST_PP_SEQ_REPLACE(cache,y,(~)bny))
‎
‎#define BN_CACHED_DIGIT_MUL_CASE2(bn,y,cache) \
‎(BOOST_PP_SEQ_TAIL(BOOST_PP_SEQ_ELEM(y,cache)))(cache)

BN_CACHED_DIGIT_MUL(bn,y,cahe) accepts a cache memory in the form of a Boost.Preprocessor sequence storing those of the values bn·0, bn·1, ..., bn·9 calculated so far (with a special format not worth discussing in detail here). If the cache already has the requested multiplication, then this is used, otherwise we calculate the value using BN_DIGIT_MUL and update the cache accordingly. The return value is a pair containing both the result and the updated cache, which can be passed later to subsequent invocations to BN_CACHED_DIGIT_MUL. To make BN_MUL benefit from the usage of BN_CACHED_DIGIT_MUL we have to add the corresponding cache as an additional member of the state structure that constitutes the core of the multiplication algorithm.

‎‎#define BN_MUL(bn1,bn2) \
‎BN_MUL_STATE_RESULT( \
‎ BOOST_PP_SEQ_FOLD_LEFT( \
‎ BN_MUL_OP, \
‎ ((~))(bn2) \
‎ (((~)(0))((~)bn2)((~))((~))((~))((~))((~))((~))((~))((~))) \
‎ ((0)), \
‎ BOOST_PP_SEQ_REVERSE(bn1)))
‎
‎#define BN_MUL_OP(s,state,x) \
‎BN_MUL_OP_IMPL( \
‎ x, \
‎ BN_MUL_STATE_SHIFT(state), \
‎ BN_MUL_STATE_BN2(state), \
‎ BN_MUL_STATE_CACHE(state), \
‎ BN_MUL_STATE_RESULT(state))
‎
‎#define BN_MUL_OP_IMPL(x,shift,bn2,cache,result) \
‎BN_MUL_OP_IMPL_RETURN( \
‎ BN_CACHED_DIGIT_MUL(bn2,x,cache),shift,bn2,result)
‎
‎#define BN_MUL_OP_IMPL_RETURN(bn2x_cache,shift,bn2,result) \
‎(shift(0)) \
‎(bn2) \
‎(BOOST_PP_SEQ_ELEM(1,bn2x_cache)) \
‎(BN_ADD( \
‎ result, \
‎ BOOST_PP_SEQ_ELEM(0,bn2x_cache)BOOST_PP_SEQ_TAIL(shift)))
‎
‎#define BN_MUL_STATE_SHIFT(state) BOOST_PP_SEQ_ELEM(0,state)
‎#define BN_MUL_STATE_BN2(state) BOOST_PP_SEQ_ELEM(1,state)
‎#define BN_MUL_STATE_CACHE(state) BOOST_PP_SEQ_ELEM(2,state)
‎#define BN_MUL_STATE_RESULT(state) BOOST_PP_SEQ_ELEM(3,state)

The initial cache value is marked in red above, note that it already contains precomputed values for the easy cases bn2·0 and bn2·1.

We can also apply memoization to the implementation of BN_DIV: the macro BN_QDIGIT_REMAINDER(bn1,bn2), which returns the largest decimal digit q such that bn2·q ≤ bn1, along with bn1 − bn2·q, can be supplemented with a cache to store the values bn2·0, bn2·1, ..., bn2·9. The implementation details are entirely similar to those involved in memoizing BN_MUL. A full implementation of the memoized bignum arithmetic operations is provided.

Let us measure the improvement brought about by memoization. These 10-, 20- and 30-digit random numbers were selected with the aid of random.org:

n1 = 8579726378,
n2 = 88242457695260718048,
n3 = 7278842148,
n4 = 17478148223952531376,
n5 = 22737602045089519821,
n6 = 859621743146723715335628844223,
n7 = 97249055978154178611,
n8 = 502003375419877211491785910042,

and the following operations were timed for the plain and memoized versions of bignum multiplication and division macros; figures are averages of several individual measurements, tests were run with GCC 3.4.4 for Cygwin in a Windows box with a 1.66 GHz Intel Core 2 Duo and 1 GB RAM:

operationplain version
(s)
memoized version
(s)
speedup
factor
n1 · n211.2
9.1
19%
n2 · n113.3
9.7
27%
n3 · n49.8
7.0
28%
n4 · n312.0
9.7
19%
n5 · n627.2
20.6
24%
n6 · n530.0
22.3
25%
n7 · n827.9
19.9
28%
n8 · n731.7
22.0
30%
n2 / n18.9
7.8
13%
n4 / n35.9
4.9
17%
n6 / n511.7
9.5
19%
n8 / n711.2
9.8
12%

The speedup factor is defined as (p − m)/p, where p is the time taken by the plain version and m the time with memoization. Improvements are noticeable though not dramatic. Multiplication could be further accelerated by using alternative algorithms like for instance Karatsuba's, but we decide to leave it at this for the moment.