More servicesWindows Live
HomeHotmailSpacesOneCare
 
MSN
Sign in
 
 
Spaces home  XSLT: Riding the challen...ProfileFriendsBlogMore Tools Explore the Spaces community
View space
M. David Peterson

XSLT: Riding the challenge

All the things you thought impossible to do with XSLT
July 28

Part 2: The Swiss Army Knife of Data Structures ... in C#

Update: In a personal communication with Eric Lippert it was revealed that, in his words:
 
"I worked up a full implementation as well but I decided that it was too complicated to post in the blog. What I was really trying to get across was that immutable data structures were possible and not that hard; a full-on finger tree implementation was a bit too much for that purpose."
 
I am happy to correct my post and acknowledge that a previous C# implementation did exist. Hopefully, Eric will publish his implementation.
So, the work discussed here is most probably the first published Finger Tree  implementation in C#.
 
 
In Part 1 I described my experience in implementing the Finger Tree data structure in C#.
 
Here is a comparison of the performance of some common operations on sequences of length 100,000 as implemented by the C# Finger Tree and the .NET 3.5 Enumerable extension methods (applied on a List<UInt32> object).
 
Disclaimer: This comparison was carried out on my 4-year old PC, having CPU speed of 3GHz and RAM of 2GB and running Windows XP.  Results will largely vary on other configurations, depending on CPU and memory speed, available memory, cache size, ..., etc. Another factor to consider is the time necessary for jitting the .NET IL code on initial method execution. However the observed ratios (speedup) should remain closely the same. Below is a table, summarizing the results:
 

Performance Comparison:
FSeq   vs.
 .NET Collection with 100,000 elements

IEnumerable<uint>         vs.                 FSeq

 

Method

.NET Av. Time

FSeq Av. time

FSeq SpeedUp

Concat()

5268 µs

56 µs

94.07

ElementAt(),

[ ]

1 µs

46 µs

---

Skip()

2022 µs

49 µs

41.27

Take()

1513 µs

50 µs

30.26

Reverse()

4859 µs

93 µs

52.25

 

 

 
As seen from this comparison, using a Finger Tree as a general sequence data structure in .NET may speed up sequence operations (roughly) 30 to 94 times (extreme cases to more than 100 times). The only exception is element access, and only in the case of an array (note that the List<T> class in .NET is actually an ArrayList). If the instance on which the Enumerable methods are called is of some other type, say LinkedList<T>, then the speedup for all operations would be even bigger. Because the tested methods of Enumerable are using deferred execution, it was necessary to add an additional operation that references an item located the end of the result-sequence. 
 
Another problem I had to deal with was how to test for "typical" or "average" operations. In other words, how to make the tests representative. I ended up with the decision to include in the Concat(), Insert(), Remove() and Substr() tests strings with a maximum variety of lengths. What in contrast I call extreme cases is when the sequences/strings to be inserted/concatenated/removed/extracted are all with the same maximum length (close to the length of the first collection/string, on which the operation is performed -- in this case close to 100,000)
 
  

 

Another interesting comparison can be made if a string is represented as a sequence of characters. As the table below shows, for long strings the potential speedup of using a Finger-tree-based string implementation is 3 to 5 times (extreme cases 5 to 25 times):
 

Performance Comparison:
FString   vs.
 .NET string with 100,000 elements

string               vs.            FString

 

Method

.NET Av. Time

FString Av. time

FSeq SpeedUp

Concat(),  +

655 µs

129µs

5.08

Insert()

653 µs

220µs

2.97

Remove()

 

176 µs

55 µs

3.20

Substring()

167 µs

54 µs

3.09

 

 

 
The source code of the performance tests is here. Take notice that in its present state this code doesn't produce any output at all. To see the timing results, run under the VS2008 Debugger and put breakpoints at suitable locations.
 
In the third part of my Finger-Tree series I will present a brief performance comparison between a Finger-Tree-based sequence and XPath sequences, as implemented in existing XSLT 2.0 processors.
July 20

The Swiss Army Knife of Data Structures ... in C#

Actually, it is not a knife and is known under the name of Finger Tree.  Smile

 
Update: In a personal communication with Eric Lippert it was revealed that, in his words:
 
"I worked up a full implementation as well but I decided that it was too complicated to post in the blog. What I was really trying to get across was that immutable data structures were possible and not that hard; a full-on finger tree implementation was a bit too much for that purpose."
 
I am happy to correct my post and acknowledge that a previous C# implementation did exist. Hopefully, Eric will publish his implementation.
So, the work discussed here is most probably the first published Finger Tree  implementation in C#.

 

Background:
Created by Ralf Hinze and Ross Paterson in 2004, and based to a large extent on the work of Chris Okasaki on Implicit Recursive Slowdown and Catenable Double-Ended Queus, this data structure, to quote the abstract of the paper introducing Finger Trees, is:

"a functional representation of persistent sequences supporting access to the ends in amortized constant time, and concatenation and splitting in time logarithmic in the size of the smaller piece. Representations achieving these bounds have appeared previously, but 2-3 finger trees are much simpler, as are the operations on them. Further, by defining the split operation in a general form, we obtain a general purpose data structure that can serve as a sequence, priority queue, search tree, priority search queue and more."

Why the finger tree deserves to be called the Swiss knife of data structures can best be explained by again quoting the introduction of the paper:

"The operations one might expect from a sequence abstraction include adding and removing elements at both ends (the deque operations), concatenation, insertion and deletion at arbitrary points, finding an element satisfying some criterion, and splitting the sequence into subsequences based on some property. Many efficient functional implementations of subsets of these operations are known, but supporting more operations efficiently is difficult. The best known general implementations are very complex, and little used.
This paper introduces functional 2-3 finger trees, a general implementation that performs well, but is much simpler than previous implementations with similar bounds. The data structure and its many variations are simple enough that we are able to give a concise yet complete executable description using the functional programming language Haskell (Peyton Jones, 2003). The paper should be accessible to anyone with a basic knowledge of Haskell and its widely used extension to multiple-parameter type classes (Peyton Jones et al., 1997). Although the structure makes essential use of laziness, it is also suitable for strict languages that provide a lazy evaluation primitive.
"

Efficiency and universality are the two most attractive features of finger trees. Not less important is simplicity, as it allows easy understanding, straightforward implementation and uneventful maintenance.

Stacks support efficient access to the first item of a sequence only, queues and deques support efficient access to both ends, but not to an randomly-accessed item. Arrays allow extremely efficient O(1) access to any of their items, but are poor at inserting, removal, splitting and concatenation. Lists are poor (O(N)) at locating a randomly indexed item.

Remarkably, the finger tree is efficient with all these operations. One can use this single data structure for all these types of operations as opposed to having to use several types of data structures, each most efficient with only some operations.

Note also the words functional and persistent, which mean that the finger tree is an immutable data structure.

In .NET the IList<T> interface specifies a number of void methods, which change the list in-place (so the instance object is mutable). To implement an immutable operation one needs first to make a copy of the original structure (List<T>, LinkedList<T>, ..., etc). An achievement of .NET 3.5 and LINQ is that the set of new extension methods (of the Enumerable class) implement immutable operations.

In the year 2008, Finger Tree implementations have been known only in a few programming languages: in Haskell, in OCaml, and in Scala. At least this is what the popular search engines say.

What about a C# implementation? In February Eric Lippert had a post in his blog about finger trees. The C# code he provided does not implement all operations of a Finger Tree and probably this is the reason why this post is referred to by the Wikipedia only as "Example of 2-3 trees in C#", but not as an implementation of the Finger Tree data structure. Actually, he did have a complete implementation at that time (see the Update at the start of this post), but desided not to publish it.

My modest contribution is what I believe to be the first published complete C# implementation of the Finger Tree data structure as originally defined in the paper by Hinze and Paterson (only a few exercises have not been implemented).

Programming a Finger Tree in C# was as much fun as challenge. The finger tree structure is defined in an extremely generic way. At first I even was concerned that C# might not be sufficiently expressive to implement such rich genericity. It turned out that C# lived up to the challenge perfectly. Here is a small example of how the code uses multiple types and nested type constraints:

// Types:

//     U -- the type of Containers that can be split

//     T -- the type of elements in a container of type U

//     V -- the type of the Measure-value when an element is measured

public class Split<U, T, V>
   
where U : ISplittable<T, V>
       
where T : IMeasured<V>
{
// ..........................................................
}

Another challenge was to implement lazy evaluation (the .NET term for this is "deferred execution") for some of the methods. Again, C# was up to the challenge with its IEnumerable interface and the ease and finesse of using the "yield return" statement.

The net result: it was possible to write code like this:

public override IEnumerable<T> ToSequence()
{
     ViewL<T, M> lView = LeftView();
     yield return lView.head;

     foreach (T t in lView.ftTail.ToSequence())
          yield return t;
}

Another challenge, of course, was that one definitely needs to understand Hinze's and Ross' article before even trying to start the design of an implementation. While the text should be straightforward to anyone with some Haskell and functional programming experience, it requires a bit of concentration and some very basic understanding of fundamental algebraic concepts.  In the text of the article one will find a precise and simple definition of a Monoid. My first thought was that such academic knowledge would not really be necessary for a real-world programming task. Little did I know... It turned out that the Monoid plays a central role in the generic specification of objects that have a Measure.

I was thrilled to code my own version of a monoid in C#:

public class Monoid<T>

{

  T theZero;

  
  public delegate T monOp(T t1, T t2);

 

  public monOp theOp;

 

  public Monoid(T tZero, monOp aMonOp)

  {

    theZero = tZero;

 

    theOp = aMonOp;

  }

 

  public T zero

  {

    get

    {

      return theZero;

    }

  }

}

 

Without going into too-much details, here is how the correct Monoids are defined in suitable auxiliary classes to be used in defining a Random-Access Sequence, Priority Queue and Ordered Sequence:

 

public static class Size

{

    public static Monoid<uint> theMonoid =

         new Monoid<uint>(0, new Monoid<uint>.monOp(anAddOp));

       

    public static uint anAddOp(uint s1, uint s2)

    {

        return s1 + s2;

    }

}

 

 

public static class Prio

{

    public static Monoid<double> theMonoid =

         new Monoid<double>

            (double.NegativeInfinity,

             new Monoid<double>.monOp(aMaxOp)

             );

 

    public static double aMaxOp(double d1, double d2)

    {

        return (d1 > d2) ? d1 : d2;

    }

}

 

 

 

public class Key<T, V> where V : IComparable

{

    public delegate V getKey(T t);

       

    // maybe we shouldn't care for NoKey, as this is too theoretic

    public V NoKey;

 

    public getKey KeyAssign;

 

    public Key(V noKey, getKey KeyAssign)

    {

        this.KeyAssign = KeyAssign;

    }

}

 

public class KeyMonoid<T, V> where V : IComparable

{

    public Key<T, V> KeyObj;

 

    public Monoid<V> theMonoid;

 

    public V aNextKeyOp(V v1, V v2)

    {

        return (v2.CompareTo(KeyObj.NoKey) == 0) ? v1 : v2;

    }

 

    //constructor

    public KeyMonoid(Key<T, V> KeyObj)

    {

        this.KeyObj = KeyObj;

 

        this.theMonoid =

         new Monoid<V>(KeyObj.NoKey,

                       new Monoid<V>.monOp(aNextKeyOp)

                      );

    }

}

 

 

Yet another challenge was to be able to create methods dynamically, as currying was essentially used in the specification of finger trees with measures. Once again it was great to make use of the existing .NET 3.5 infrastructure. Below is my simple FP static class, which essentially uses the .NET 3.5 Func object and a lambda expression in order to implement currying:

 

public static class FP

{

  public static Func<Y, Z> Curry<X, Y, Z>
            (
this Func<X, Y, Z> func, X x)

  {

    return (y) => func(x, y);

  }

}

 

And here is a typical usage of the currying implemented above:

 

public T ElemAt(uint ind)

{
  return treeRep.Split

(new MPredicate<uint>

   (

      FP.Curry<uint, uint, bool>(theLessThanIMethod2, ind)

   ),

     0

      ).splitItem.Element;

}

 

Now, for everyone who have reached this point of my post, here is the link to the complete implementation.

Be reminded once again that .NET 3.5 is needed for a successful build.

In my next posts I will analyze the performance of this Finger Tree implementation and how it fares compared to existing implementations of sequential data structures as provided by different programming languages and environments.

June 04

Oleg Tkachenko has joined Microsoft

Long time Microsoft MVP Oleg Tkachenko has joined Microsoft's Visual Studio team.

Oleg is well-known for his work on a number of popular XML/XSLT - related open source projects, such as EXSLT.NET, MVP.XML, nXslt.exe, the Iron XSLT project type of Visual Studio 2008,  ... , etc.

Oleg is also a member of the FXSL open source project.

I am glad for Oleg and want to congratulate him on his new role.

May 18

The Balisage conference program is available

The Balisage conference program is available and a quick  look  shows there are some very interesting presentations.

May 14

Access online the books you bought from Amazon


A few days ago Amazon Upgrade was announced, which lets you access (some of) the books you bought from them -- for a reasonable fee.

Here's how the announcement looks like:

 

Get online access to your physical books with Amazon Upgrade and you can:

  • Start reading the book immediately while you wait for your physical copy to arrive
  • Add notes, highlights, and bookmarks to any page
  • Print pages of the book, and even copy and paste the text

And you can do all this from any Internet-connected computer, meaning your book is always with you.
Learn more

Visit our Amazon Upgrade store                       
                                                                     
 

Online access to your books with Amazon Upgrade
Below is a list of books you've purchased from Amazon.com that you may upgrade to read online. Select the titles you wish to upgrade, and the total price appears automatically at the bottom.
If you'd like to be notified automatically when new books are added to your list, subscribe to our monthly e-mail that lets you know when you have new eligible books to upgrade.
Subscribe today.

Select All
|

| XPath 2.0 Programmer's Reference (Programmer to Programmer) by Michael Kay
Purchase date: September 01, 2004

Amazon Upgrade price: $6.99

XSLT 2.0 Programmer's Reference (Programmer to Programmer) by Michael Kay
Purchase date: September 01, 2004

Amazon Upgrade price: $7.99

0 title(s) selected.

Total: $0.00*

(Not all books are eligible. Why?)

* Sold by Amazon Digital Services, Inc. - Additional taxes may apply

 

 

 

Now, if only this book could also be made accessible:

XSLT 2.0 and XPath 2.0 Programmer's Reference (Programmer to Programmer)

March 16

Jeni's "Grouper" (or how to specify and parse additional rules to a grammar) is just a minor task for LBNF

In her recent post "RELAX NG for matching" Jeni Tennison said:

 

The “grouper” is the most interesting and difficult of these. It needs to act like a tokeniser, except use regular expressions over markup rather than over text. For example, say I had:

<number>06</number><punc>/</punc><number>03</number><punc>/</punc><number>08</number>

I want to be able to create a rule that says “any sequence that looks like a number element that contains a
two-digit number between 1 and 31, followed by a punc element that contains a slash, followed by another two-digit number between 1 and 12, followed by a punc element that contains a slash, followed by another two-digit number should be wrapped in a date element”.

Now this is something that XPath is really bad at. Try writing an expression that selects, from a sequence of elements that may contain other <number> and <punc> elements as well as other elements, only those sequences of elements that match the pattern I just described. It’s something like:

number[. >= 1 and . <= 31 and string-length(.) = 2]
      [following-sibling::*[1]/self::punc = '/']
      [following-sibling::*[2]/self::number[. >= 1 and . <= 12 and string-length(.) = 2]]
      [following-sibling::*[3]/self::punc = '/']
      [following-sibling::*[4]/self::number[string-length(.) = 2]]
  /(self::number, following-sibling::*[position() <= 4])

which is fiddly and messy and only works in this particular example because I know precisely how many elements there are
supposed to be in the group.

 

Then she proceeds by making the suggestion that

    "As a language, RELAX NG is really good at this"

 

Jeni ends with the following statement:

 

"So I think a “grouper” component should use RELAX NG to identify sequences to be marked up. But I have no idea if there are RELAX NG libraries out there that can be used in this way: to identify and extract matching sequences rather than to validate entire documents"

 

It is obvious that the solution of this problem is not strictly bound to RELAX NG itself
(which just happens to be able to parse a schema defined using the RNC grammar). The tool Jeni reasons about would be any compiler writing system that allows additional grammar rules, that are not required to reach the start symbol of the language, but may be useful for other purposes.

Very fortunately, I know at least one such system:

         the Labelled BNF Grammar Formalism (LBNF).

 Jeni's "grouper" tool can be implemented by adding additional rules to the language being specified
using LBNF's "internal pragmas".
 

Here's how the authors of LBNF Markus Forsberg, Aarne Ranta from Chalmers University of Technology
and the University of Gothenburg describe LBNF's internal pragmas:
  

6 LBNF Pragmas

6.1 Internal pragmas

Sometimes we want to include in the abstract syntax structures that are not part of the concrete syntax, and hence not parsable. They can be, for instance, syntax trees that are produced by a type-annotating type checker. Even though they are not parsable, we may want to pretty-print them, for instance, in the type checker’s error messages. To define such an internal constructor, we use a pragma 

   
"internal" Rule ";"

where Rule is a normal LBNF rule. For instance,

   internal EVarT. Exp ::= "(" Ident ":" Type ")";

introduces a type-annotated variant of a variable expression.

Of course, LBNF is a very nice and cool tool to carry out a number of really important language development tasks, besides the "grouper".

November 09

Wide Finder in XSLT --> deriving new requirements for efficiency in XSLT processors.

With his twelve posts under the common title of "The Wide Finder Project" Tim Bray formulated a problem, which obviously has since then stirred some people, anxious to prove that their programming language of choice fares well in implementing solutions for this class of problems.

While I am not aware of any XSLT implementation that provides explicit or implicit support for parallel processing (with the obvious goal to take advantage of the multi-core processors that have almost reached a "prevalent" status today), I was curious to determine at least two things:

  • How well a good XSLT 2.0 processor and a straightforward solution fare against other languages/solutions?
  • Where is the XSLT code on the scale of "beautiful code"?

 

Before going further let me remind that there is a popular (and as we'll see unfounded!) belief that any XSLT solution must be hugely inefficient and that any XSLT code can only be ugly. In fact, the following comment to one of Tim's posts reflects exactly this mindset:

 

"From: Rornan (Sep 25 2007, at 08:31)

Tim,

If you had anything at all to do with creating XSLT, then you have no right at all to comment on any other language deficency ever ever again."

  

My initial XSLT solution to Tim's problem is below. No optimization attempts have been attempted, not only because I don't have an XSLT processor that utilizes multi-core processor, but also because it seems there's only a limited possibility for optimization (adding more CPU's is not likely to speed up the reading of a huge file from a single drive).

 

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xsl:output method="text"/>
<xsl:variable name="vLines" as="xs:string*" select= "tokenize(unparsed-text('file:///C:/Log1000000.txt'),'\n')"/>
<xsl:variable name="vRegEx" as="xs:string" select= "'^.*?GET /ongoing/When/[0-9]{3}x/([0-9]{4}/[0-9]{2}/[0-9]{2}/[^ .]+) .*$|^.+$'"/>
<xsl:template match="/"> <xsl:for-each-group group-by="." select= "for $line in $vLines return replace($line,$vRegEx,'$1')[.]"> <xsl:sort select="count(current-group())" order="descending" />
<xsl:if test="not(position() > 10)"> <xsl:value-of select=
"concat(count(current-group()),':',current-grouping-key(),'&#xA;')"/> </xsl:if> </xsl:for-each-group> </xsl:template> </xsl:stylesheet>

This 22-line-transformation is performed by Saxon 9.0 on a 3GHz DELL desktop. The file Log1000000.txt was constructed using the 10000 lines file provided by Tim and copying it into another file 100 times. The size of this file is about 200MB.

The results were produced in 36.175 seconds using about 929MB of RAM. Saxon should be timed using the -repeat:3 command-line option, which performs the transformation three times. Using only the results from the first/single transformation will be misleading, as they include the time for the Java VM startup.

 

Discussion

 

To answer the questions:

1. How well a good XSLT 2.0 processor and a straightforward solution fare against other languages/solutions?

The non-optimized, uniprocessor version of this solution has a time of 36 seconds for processing about 200MB log file. It is likely the timing for the full , five times bigger log file used by Tim Bray, will be about 5 times bigger: 180 sec, or about 3 minutes. 3 minutes for processing 1GB of data is not a bad time for an XSLT transformation, considering that sizes even of a few hundreds of megs are still considered monstrous.

XSLT could be in fact one of the winners in the WF competition, had its creators stepped just a little bit further exploiting the natural, non-sequential XSLT processing model. Here I am talking about specifying a single f:parMap() function, which can be defined exactly as the current FXSL f:map() function:

   <xsl:function name="f:map" as="item()*">
      <xsl:param name="pFun" as="element()"/>
      <xsl:param name="pList1" as="item()*"/>

      <xsl:sequence select=
       "for $this in $pList1 return
          f:apply($pFun, $this)"
      />
    </xsl:function>


 

The only difference is that f:parMap() adds to the semantics of f:map() the hint to use as many available CPU processors as appropriate when evaluating the "for" expression in the code of the function.

Yes, this can be done for any "/" operator or for any "for" expression such as the one used in lines 13 - 14 in our XSLT solution:

"for $line in $vLines
     return replace($line,$vRegEx,'$1')[.]"

 

and for any <xsl:apply-templates .../> instruction, and for any <xsl:for-each .../> instruction, and for any <xsl:for-each-group ...> instruction and ... and ... and ...

 

Judging from the published results, this straightforward, non-optimized uniprocessor XSLT solution comes not too-far behind some of the optimized for multi-processing solutions. I hope that in the not so distant future there will be XSLT processors exploiting the inherent non-sequential nature of XSLT processing to implement highly-optimized multi-processing solutions.

2. Where is the XSLT code on the scale of "beautiful code"?

By its compactness (22 lines) it is in 3rd place and rivals the 2nd place (17 lines), as we could easily remove 4 lines (3 of them blank) used to add readability. One of Tim's criteria for "beautiful code" is avoiding awkwardness.He speaks about Ruby not needing ending semicolons or variable type declarations. However, Tim's solution still had to use two lines for defining a hash and setting its default to 0. By contrast, the XSLT solution above does not require the programmer to introduce and initialize a special data structure -- the support for grouping is right there in the core of the language. There is simply no way the programmer can do something wrong in declaring or using a hash table.

 

What could the XSLT processor do better?

Both the timing and especially the amount of RAM used indicate how the XSLT processor did its work:

  • It read all the text file in memory.
  • Then it produced all $vLines strings.
  • Then it produced the line replacements.
  • Then it did the grouping/sorting on the line replacements.

Imagine that the XSLT Processor is really lazy:

  • It will not read any contents of the file and will not do any tokenization, until absolutely necessary.
  • Whenever it is really necessary to use the next token (line), only the text necessary to determine that line shall be read.
  • Whenever a token/line is produced, all previously used / unused text shall be marked-for-garbage-collection/discarded/reused.
  • Whenever a string from $vLines is consumed and processed by the <xsl:for-each-group .../> instruction, this string is no-longer used and shall be marked-for-garbage-collection/discarded/reused.

Using these rules a truly lazy XSLT processor will only need space large enough for the longest line, and for a hash table to keep the keys and counters for all different articles being grouped. In this case there are just 562 unique values extracted from the strings of $vLines.

In this way, the processing -- reading a line, finding the article it contains and feeding this to the hash table --  could be accomplished in streaming mode while reading the text file. Upon reaching the end of the file, there would be very little left to do, and thus almost nothing to be further optimized.

 

Conclusion

I truly believe that the described improvements can be implemented by at least some of the best XSLT 2.0 processors around here. For many years I have been using Saxon and am very grateful to its developer Dr. Michael Kay. The performance efficiency has been constantly growing -- a very good example to follow by all other XSLT vendors and if they do there will be competition, and competition is good for us all.