6/6/10

Understanding Parallel Performance

By Herb Sutter, October 31, 2008
Understanding parallel performance. How do you know when good is good enough?
Herb is a bestselling author and consultant on software development topics, and a software architect at Microsoft. He can be contacted at www.gotw.ca.
--------------------------------------------------------------------------------
Let's say that we've slickly written our code to apply divide-and-conquer algorithms and concurrent data structures and parallel traversals and all our other cool tricks that make our code wonderfully scalable in theory. Question: How do we know how well we've actually succeeded? Do we really know, or did we just try a couple of tests on a quad-core that looked reasonable and call it good? What key factors must we measure to understand our code's performance, and answer not only whether our code scales, but quantify how well under different circumstances and workloads? What costs of concurrency do we have to take into account?

This month, I'll summarize some key issues we need to keep in mind to accurately analyze the real performance of our parallel code. I'll list some basic considerations, and then some common costs. Next month, I have a treat in store: We'll take some real code and apply these techniques to analyze its performance in detail as we successively apply a number of optimizations and measure how much each one actually buys us, under what conditions and in what directions, and why.

Fundamentals
To understand our code's scalability, we need to know what to measure and what to look for in the results. First, identify the workload variables: What are the key different kinds of work and/or data? For example, we may want to measure how well a producer-consumer system performs with varying numbers of producer threads and consumer threads, or measure a container by how well it scales when holding data items of different sizes.
Second, use stress tests to measure throughput, or the total amount of work accomplished per unit time, while varying each of these dimensions so that we can measure their relative impact. Look for scalability trends, the change in throughput as we add hardware resources: Can we effectively use more cores to either get the answer faster or to get more work done?
Figures 1 and 2 show two useful visualization tools that will help us understand our code's parallel performance. Figure 1 shows a sample scatter graph that charts throughput results for a selected algorithm against different numbers of two kinds of workers: producer threads and consumer threads. The larger the bubble, the greater the throughput. We can get a sense of how this particular algorithm scales, and in what directions, by examining how and where throughput grows and shrinks. In this example, we have good scalability up to a total of about 15 threads before we start to peak and realize no further gains, and we can see that scalability is better when there are somewhat more producers than consumers in the system.

Figure 1: Sample graph for measuring scalability of the same algorithm for different workloads.
Figure 2 directly compares different candidate algorithms running the same kind of workload. Peak throughput occurs, naturally enough, at the peak of each curve. Scalability shows up directly as the left-hand ascending side of the curve; the steeper it is, and the farther to the right that it goes before topping out, the more scalable our code will be. Here, the blue algorithm demonstrates the horror of negative scalability; it actually manages to get less work done using additional cores, which probably won't earn us our next raise.

Figure 2: Sample graph for measuring scalability of alternative algorithms for the same workload.
But both figures also let us see two basic penalties. Contention arises when different workers interfere with each other by fighting for resources, such as contending for mutexes, cache space, or cache lines via false sharing. In the most extreme case, adding a new worker might actually cost more in contention than it adds in extra work, resulting in less total work being done, and we can see this extreme effect in both graphs: In Figure 1, in several directions we reach areas where adding more workers makes total throughput actually go down. In Figure 2, we see the same effect in the form of the right-hand downslope where adding more work actually decreases throughput even when there are otherwise-idle cores. But Figure 2 also lets us more clearly see the effect of contention before it gets that far: On the left-hand upslope, even as throughout is still rising, the rate of increase is slowing down as the curve begins to bend. That's a classic effect of growing contention.
The other basic penalty is oversubscription, or having more CPU-bound work ready to execute than we have available hardware. These samples were taken from test runs on a 24-core machine; sure enough, in Figure 1 we see a faint diagonal line where #producers + #consumers = 24, above which throughput is noticeably thinner; sometimes the result is even more dramatic. Similarly, in Figure 2 we see even the best algorithms can't scale beyond the available cores, and incur a penalty for trying to exceed that number by adding contention at least for CPU time and often also for other resources.
With these fundamentals in mind, let's consider a few specific costs that arise and impact scalability because of contention, oversubscription, and other effects.

Sources of Overhead, and Threads versus Pools
We incur a basic concurrency overhead from just expressing code in a parallel way. Consider the following toy example that performs three independent subcomputations to generate a result:
// Example 1: Sequential code in MyApp 1.0
//
int NetSales() {
int wholesale = CalcWholesale();
int retail = CalcRetail();
int returns = TotalReturns();
return wholesale + retail - returns;
}

Assume that this code is entirely CPU-bound, and that the subcomputations really are independent and free of side effects on each other. Then we can get the answer faster on more cores by running the subparts in parallel. Here's some pseudocode showing how to accomplish this using futures and the convenience of lambda functions, but with a common mistake:
// Example 2 (flawed): Naïve parallel code for MyApp 2.0?
//
int NetSales() {
// perform the subcomputations concurrently
future wholesale = new thread( [] { CalcWholesale(); } );
future retail = new thread( [] { CalcRetail(); } );
future returns = new thread( [] { TotalReturns(); } );

// now block for the results
return wholesale.value() + retail.value() - returns.value();
}

Seeing the words new Thread explicitly in code is often an indicator that code may not be as scalable as it could be. In most environments, it's much less efficient to spin up a new thread for each piece of work than to run it on a thread pool: First, spinning up a new thread and throwing it away again each time incurs substantially more overhead than giving work to an existing pool thread. Second, spinning up a number of threads and turning them loose to fight for available cores via the operating system scheduler can cause needless contention when we spin up more work than there are cores currently available, which can happen not only on low-core hardware but also on many-core hardware if the application or the system happens to be doing a lot of other work at that moment. Both situations are different kinds of oversubscription, and some threads will have to incur extra context-switching to interleave on an available core. Instead, sharing the core by running one after the other would be both more efficient and more cache-friendly.
Thread pools address these problems because a pool is designed to "rightsize" itself to the amount of hardware concurrency available on the machine. The pool will automatically try to maintain exactly one ready thread per core, and if there is more work than cores the pool naturally queues the work up and lets the machine concentrate on only as many tasks at a time as it has cores to perform. Here's pseudocode for a revised version that uses pools instead:
// Example 3 (better): Partly fixed parallel code for MyApp 2.0
//
int NetSales() {
// perform the subcomputations concurrently
future wholesale = pool.run( [] { CalcWholesale(); } );
future retail = pool.run( [] { CalcRetail(); } );
future returns = pool.run( [] { TotalReturns(); } );

// now block for the results
return wholesale.value() + retail.value() - returns.value();
}

The good news is that this can enable us to get the answer faster on more cores, at least up to three cores. But there are costs too: With today's thread pools, we typically pay a tax of two context switches when we ship work over to a pool thread and then ship the result back. How can we reduce this cost?

Reducing Context Switches
We can eliminate some of the context switches by being smarter about the last line that combines the results, because just calling .value() three times may wake up the calling thread twice only to immediately have to sleep again; instead, use a "wait for a group of futures" facility if your futures library has one, as a well-written version can eliminate the needless wakeups.
We can also avoid a switch by observing that the calling thread isn't going to do anything anyway besides wait for the results, and so it's often a good idea to keep the tail chunk of work and do it ourselves instead of needlessly idling the original thread.
Example 4 shows both techniques in action:
// Example 4: Improved parallel code for MyApp 2.0
//
int NetSales() {
// perform the subcomputations concurrently
future wholesale = pool.run( [] { CalcWholesale(); } );
future retail = pool.run( [] { CalcRetail(); } );
int returns = TotalReturns(); // keep the tail work

// now block for the results—-wait once, not twice
wait_all( wholesale, retail );
return wholesale.value() + retail.value() - returns;
}

Naturally, what matters most is not the total overhead, but how big it is compared to the total work. We want the cost of each chunk of work to be significantly larger than the cost of performing it asynchronously instead of synchronously.

The Cost of Unrealized Concurrency
A key cost in today's environments is the cost of unrealized concurrency. What's the cost of our parallel code compared to the sequential code in the case when the parallel algorithm actually ends up running sequentially? For example, what happens if our parallel-ready code executes on a machine with just one core, so that we don't actually get to realize the concurrency because the tasks end up running sequentially anyway (e.g., there's only one pool thread)? We've added the overhead to express concurrency, and we pay for that overhead even if we don't get to benefit from it on a particular system.
If Example 1 is the code we shipped in MyApp version 1.0 and Example 4 is what we'll ship in MyApp 2.0, then an existing customer with a legacy single-core machine may find that the new application is actually slower than the old one, even though the new application will run better when more cores are available. To mitigate this on low- and single-core machines, we can reduce the overhead by adjusting granularity to use fewer and larger chunks of work, or even switch to a sequential implementation.

The Double-Edged Sword of Fine-Grainedness
Even in Example 4, the code only scales to at most three cores. Can we do better? Yes, if we can make the work more fine-grained, slicing the work to be done more finely into smaller chunks. One approach in Example 4 would be to apply similar techniques within CalcWholesale, CalcRetail, and TotalReturns to further decompose their work into concurrent subtasks. Even better is when we can exploit natural parallelism in algorithms (e.g., divide-and-conquer algorithms like quicksort) and data structures (e.g., trees and graphs) to subdivide our work in a way that scales with the amount of data.
But now we encounter a fundamental tension between scalability and overhead: The smaller the chunks of work, the more chunks we have and the more easily we can distribute them to utilize larger number of cores to get an answer faster—but the more the overhead per chunk starts to dominate in our performance costs.
Let's consider quicksort as a common example. Can you spot the performance flaws in this code?
// Example 5 (flawed, today): Naïve parallel quicksort,
// sorts left and right subranges in parallel
//
void ParallelQuicksort( Iterator first, Iterator last ) {
Iterator pivot = Partition( first, last );
future f1 = pool.run( [&]{ ParallelQuicksort( first, pivot ); } );
future f2 = pool.run( [&]{ ParallelQuicksort( pivot, last ); } );
wait_all( f1, f2 );
}

We can improve this in at least two ways. First, as noted earlier, we should take the tail chunk of work and do it ourselves to mitigate the overhead of shipping work to a pool thread in today's environments. Second, we can notice that most of the spun-off work will be at the leaves of the computation containing subranges of a few elements or even just one. Even in sequential code, it's typical to switch to something like bubble sort when the subrange's size falls below a threshold; similarly in parallel code, for small ranges we should switch to a sequential sort. Example 6 incorporates both of these changes:
// Example 6: An improved parallel quicksort, still
// sorts subranges in parallel but more efficiently
//
void ParallelQuicksort( Iterator first, Iterator last ) {
if( distance(first,last) <= threshold ) {
SequentialSort( first, last );
} else {
Iterator pivot = Partition( first, last );
future f1 = pool.run( [&]{ ParallelQuicksort( first, pivot ); } );
ParallelQuicksort( pivot, last );
f1.wait();
}
}

In general, we want to slice the work as finely as possible, but not to the point where the work is comparable in size to the overhead.

Forward-Looking Note: Work Stealing
Future runtime systems will significantly drive down all of these costs, including the overhead per chunk and the cost of unrealized concurrency, to the point where we will often be able to ignore it and blithely write code like Example 5 without worrying about its performance most of the time.
The basic idea is to use work stealing whereby default "potentially asynchronous work" is actually not shipped elsewhere, but rather queued up to be executed on the original thread. Only if another core runs out of work and sees that our thread has waiting queued work to be performed, will the work be "stolen" and efficiently shipped to the other thread. The idea is to drive down the cost of unrealized concurrency by only actually incurring the overhead of running on another core if it's worth doing at that particular instant—on this hardware and with this amount of other work currently occupying the machine; and the very next execution of the very same function on the very same hardware might not steal, if all the cores are already busy. Sample current and upcoming technologies that feature work stealing runtimes include: Intel Threading Building Blocks; Microsoft's Parallel Patterns Library, Task Parallel Library, and PLINQ; Java 7's Fork/Join framework; and the granddaddy of them all, Cilk, which popularized the technique among implementers.

On Deck
To understand your code's scalability, first identify the key variables that affect the workload, and then measure throughput for workloads with different combinations of those variables. Look for scalability, and how it hits the contention and oversubscription barriers. Prefer thread pools (today) and work stealing (tomorrow).

Next month, we're going to apply the tools we discussed this month to analyze the performance impact of specific optimizations on concrete code. Fasten your seat belts. Sphere: Related Content

Fundamental Concepts of Parallel Programming

By Richard Gerber and Andrew Binstock , June 01, 2010
Parallel programming requires designers to rethink the idea of process flow
Richard Gerber has worked on numerous multimedia projects, 3D libraries, and computer games for Intel. Andrew Binstock is the principal analyst at Pacific Data Works and author of "Practical Algorithms for Programmers". They are the authors of Programming with Hyper-Threading Technology.
--------------------------------------------------------------------------------
Parallel programming makes use of threads to enable two or more operations to proceed in parallel. The entire concept of parallel programming centers on the design, development, and deployment of threads within an application and the coordination between threads and their respective operations. This article examines how to break up traditional programming tasks into chunks that are suitable for threading. It then demonstrates how to create threads, how these threads are typically run on multiprocessing systems, and how threads are run using HT Technology.

Designing for Threads
Developers unacquainted with parallel programming are generally comfortable with traditional programming models such as single-threaded declarative programs and object-oriented programming (OOP). In both cases, a program begins at a defined point -- such as main() -- and works through a series of tasks in succession. If the program relies on user interaction, the main processing instrument is a loop in which user events are handled. From each allowed event -- a button click, for example -- an established sequence of actions is performed that ultimately ends with a wait for the next user action.
When designing such programs, developers enjoy a relatively simple programming world because only one thing is happening at any given moment. If program tasks must be scheduled in a specific way, it's because the developer chooses a certain order to the activities, which themselves are designed to flow naturally into one another. At any point in the process, one step generally flows into the next, leading up to a predictable conclusion, based on predetermined parameters -- the job completed -- or user actions.
Moving from this model to parallel programming requires designers to rethink the idea of process flow. Now, they must try to identify which activities can be executed in parallel. To do so, they must begin to see their programs as a series of discrete tasks with specific dependencies between them. The process of breaking programs down into these individual tasks is known as decomposition. Decomposition comes in three flavors: functional, data, and a variant of functional decomposition, called producer/consumer. As you shall see shortly, these different forms of decomposition mirror different types of programming activities.

Functional Decomposition
Decomposing a program by the functions it performs is called "functional decomposition", also called "task-level parallelism". It is one of the most common ways to achieve parallel execution. Using this approach, individual tasks are catalogued. If two of them can run concurrently, they are scheduled to do so by the developer. Running tasks in parallel this way usually requires slight modifications to the individual functions to avoid conflicts and reflect that these tasks are no longer sequential.
If discussing gardening, functional decomposition would suggest that gardeners be assigned tasks based on the nature of the activity: If two gardeners arrived at a client's home, one might mow the lawn while the other weeded. Mowing and weeding are separate functions broken out as such. To accomplish them, the gardeners would make sure to have some coordination between them, so that the weeder is not sitting in the middle of a lawn that needs to be mowed.
In programming terms, a good example of functional decomposition is word processing software, such as Microsoft Word. When a very long document is opened, the user can begin entering text right away. While the user is doing this, document pagination occurs in the background, as can readily be seen by the quickly increasing page count that appears in the status bar. Text entry and pagination are two separate tasks that, in the case of Word, Microsoft has broken out by function and run in parallel. Had it not done this, the user would be obliged to wait for the entire document to be paginated before being able to enter any text. Many of you will recall that this wait was common on early PC word processors.

Producer/Consumer
Producer/consumer (P/C) is so common a form of functional decomposition that it is best examined by itself. Here, the output of one task, the producer, becomes the input to another, the consumer. The important aspects of P/C are that both tasks are performed by different threads and the second one -- the consumer -- cannot start until the producer finishes some portion of its work.
Using the gardening example, one gardener prepares the tools -- puts gas in the mower, cleans the shears, and other similar tasks -- for both gardeners to use. No gardening can occur until this step is mostly finished, at which point the true gardening work can begin. The delay caused by the first task creates a pause for the second task, after which both tasks can continue in parallel. In computer terms, this particular model occurs frequently.
In common programming tasks, P/C occurs in several typical scenarios. For example, programs that must rely on the reading of a file are inherently in a P/C scenario: the results of the file I/O become the input to the next step, which might well be threaded. However, that step cannot begin until the reading is either complete or has progressed sufficiently for other processing to kick off. Another common programming example of P/C is parsing: an input file must be parsed, or analyzed semantically, before the back-end activities, such as code generation in a compiler, can begin.
The P/C model has several interesting dimensions absent in the other decompositions:
•The dependence created between consumer and producer can cause formidable delays if this model is not implemented correctly. A performance-sensitive design seeks to understand the exact nature of the dependence and diminish the delay it imposes. It also aims to avoid situations in which consumer threads are idling while waiting for producer threads.
•In the ideal scenario, the hand-off between producer and consumer is completely clean, as in the example of the file parser. The output is context-independent and the consumer has no need to know anything about the producer. Many times, however, the producer and consumer components do not enjoy such a clean division of labor, and scheduling their interaction requires careful planning.
•If the consumer is finishing up while the producer is completely done, one thread remains idle while other threads are busy working away. This issue violates an important objective of parallel processing, which is to balance loads so that all available threads are kept busy. Because of the logical relationship between these threads, it can be very difficult to keep threads equally occupied in a P/C model.

Data Decomposition
Data decomposition, also known as "data-level parallelism", breaks down tasks by the data they work on, rather than by the nature of the task. Programs that are broken down via data decomposition generally have many threads performing the same work, just on different data items. For example, consider a program that is recalculating the values in a large spreadsheet. Rather than have one thread perform all the calculations, data decomposition would suggest having two threads, each performing half the calculations, or n threads performing 1/nth the work.
If the gardeners used the principle of data decomposition to divide their work, they would both mow half the property and then both weed half the flower beds. As in computing, determining which form of decomposition is more effective depends a lot on the constraints of the system. For example, if the area to mow is so small that it could not warrant two mowers, it would be better done by just one gardener -- functional decomposition -- and data decomposition could be applied to other task sequences, such as when the mowing is done and both gardeners begin weeding in parallel.

Implications of Different Decompositions
Different decompositions provide different benefits. If the goal, for example, is ease of programming and tasks can be neatly partitioned functionally, then functional decomposition is more often than not the winner. Data decomposition adds some additional code-level complexity to tasks, so it is reserved for cases where the data is easily divided and performance is important.
However, the most common reason for threading an application is performance. And here the choice of decompositions is more difficult. In many instances, the choice is dictated by the problem domain: some tasks are much better suited to one type of decomposition. But some tasks have no clear bias. Consider for example, processing images in a video stream. In formats with no dependency between frames, programmers have a choice of decompositions. Should they choose functional, in which one thread does decoding, another color balancing, and so on, or data decomposition, in which each thread does all the work on one frame and then moves on to the next? To return to the analogy of the gardeners, the query would take this form: If two gardeners need to mow two lawns and weed two flower beds, how should they proceed? Should one gardener only mow -- that is, they choose functional -- or should both gardeners mow together then weed together?
In some cases -- for instance when a resource constraint exists, such as only one mower -- the answer emerges quickly. In others where each gardener has a mower, the answer comes only through careful analysis of the constituent activities. In the case of the gardeners, functional decomposition looks better, because the start-up time for mowing is saved if only one mower is in use. Ultimately, the right answer for parallel programming is determined by careful planning and testing. The empirical approach plays a more significant role in design choices in parallel programming than it does in standard single-threaded programming.
As mentioned previously, P/C situations are often unavoidable, but nearly always detrimental to performance. The P/C relation runs counter to parallel programming because it inherently makes two activities sequential. This sequential aspect occurs twice in a P/C situation: once at the start, when the consumer thread is idling as it waits for the producer to produce some data, and again at the end, when the producer thread has completed its work and is idling as it waits for the consumer thread to complete. Hence, developers who recognize a P/C relation are wise to try to find another solution that can be parallelized. Unfortunately, in many cases, this cannot be done. Where P/C cannot be avoided, developers should work to minimize the delay caused by forcing the consumer to wait for the producer. One approach is to shorten the activity required before the consumer can start up. For example, if the producer must read a file into a buffer, can the consumer be launched after the first read operation rather than waiting for the entire file to be read? By this means, the latency caused by the producer can be diminished. Table 1 summarizes these forms of decomposition.

Challenges
The use of threads enables performance to be significantly improved by allowing two or more activities to occur simultaneously. However, developers cannot fail to recognize that threads add a measure of complexity that requires thoughtful consideration to navigate correctly. This complexity arises from the inherent fact that more than one activity is occurring in the program. Managing simultaneous activities and their possible interaction leads to confronting four types of problems:
•Synchronization is the process by which two or more threads coordinate their activities. For example, one thread waits for another to finish a task before continuing.
•Resource limitations refer to the inability of threads to work concurrently due to the constraints of a needed resource. For example, a hard drive can only read from one physical location at a time, which deprives threads of the ability to use the drive in parallel.
•Load balancing refers to the distribution of work across multiple threads so that they all perform roughly the same amount of work.
•Scalability is the challenge of making efficient use of a larger number of threads when software is run on more-capable systems. For example, if a program is written to make good use of four processors, will it scale properly when run on a system with eight processors?

Each of these issues needs to be handled carefully to maximize application performance.
--------------------------------------------------------------------------------
This article is based on material found in book Programming with Hyper-Threading Technology by Andrew Binstock and Richard Gerber. Sphere: Related Content

Other Voices: An HTML5 Primer

By Michael Mullany, June 03, 2010
It's easy to get lost in the welter of HTML5-related standards

With Google and Apple strongly supporting HTML5 as the solution for rich applications for the Internet, it's become the buzzword of the month -- particularly after Google I/O. Given its hot currency, though, it's not surprising that the term is starting to become unhinged from reality. Already, we're starting to see job postings requiring "HTML5 experience," and people pointing to everything from simple JavaScript animations to CSS3 effects as examples of HTML5. Just as "AJAX" and "Web 2.0" became handy (and widely misused) shorthand for "next-generation" web development in the mid-2000's, HTML5 is now becoming the next overloaded term. And although there are many excellent resources out there describing details of HTML5, including the core specification itself, they are generally technical and many of them are now out of synch with the current state of the specs. So, I thought a primer on HTML5 might be in order.

HTML5 Core vs. The HTML5 Family
When many folks say "HTML5" (particularly when this is followed with "will replace Flash"), they mean (or at least I think they mean), the broad collection of next-generation technologies that are now being implemented in the Webkit-based browsers (Safari and Chrome), Opera and Firefox. Some of these (like CS S3) were never part of the HTML5 standards process, and some of these (like web workers) were originally part of the spec but were spun out separately. We think the right way to refer to this collection is "the HTML5 Family." The family members of HTML5 (like all families) are in very different stages of maturity and implementation. Some are fully implemented in latest revision browsers, some may never see the light of day, and some will become altered beyond recognition before they show up in the mainstream. As mentioned before, the core W3C HTML5 spec is just one part of the collection of related technologies. I list the following specs as members of the HTML5 Family (more or less):
•The HTML5 spec
•Cascading Style Sheets Version 3 (CSS3)
•Web Workers
•Web Storage
•Web SQL Database
•Web Sockets
•Geolocation
•Microdata
•Device API and File API

The Core HTML5 Spec
The central thrust of the core HTML5 spec is to evolve HTML from the XML-centric approach of the early 2000's that had poor traction among browser makers and developers. HTML5 substantially changes many aspects of the language, although most changes have not resulted in new features visible to most end-users. These "user-invisible" changes include a new content model, accessibility features and browsing contexts. In many cases, HTML5 allows what is currently done with styling, JavaScript or server workarounds to be done in HTML. This results in cleaner, human-readable HTML. Today's blizzard of div tags is replaced with meaningful markup like nav and aside. For example, HTML5 adds semantic tags for common content elements: One specific example is a special form field for email addresses. Another specific example is new markup for menus and navigation sections. For forms, HTML5 adds support for PUT and DELETE form actions, which will simplify server side processing. It also provides native support for adding form elements dynamically, which currently has to be done in JavaScript.

For users, the highest impact change in HTML5 is the addition of audio and video tags and a standard 2D bitmap drawing format (canvas). HTML5 audio and video tags allow playback without the use of plugins, and Canvas allows rich 2D bitmapped graphics.

There are many other features in the HTML5 spec, including a drag-and-drop API, cross-document messaging, persistent content caching directives, and user-editable content. Support for them is still being added to the latest browser revisions. Some parts may still end up being discarded before final implementation.

Finally, HTML5 removes many presentational markup elements that littered earlier HTML specs, like center and font. It also disallows direct table styling, and instead, requires the use of CSS. Frames are also officially eliminated.

CSS3
A lot of what people think is HTML5, is actually CSS3, which is itself a collection of sub-specifications. These are in various states of completion and browser implementation. For example, CSS Animations and CSS Transitions are sub-specs that provide rich dynamic 2D animations and effects for elements. CSS 3D and 2D Transformations provide animations for boxed content. The CSS3 spec family also includes standards for richer layout control, borders and backgrounds (the highly desired "rounded corners" ). It also includes more niche capabilities such as Ruby (not the language, Ruby with a small "r" means visual hints for meaning or pronunciation often used in ideogram based languages), aural style sheets and scrolling marquees.

Web Workers
Web Workers let an application spawn tasks for the browser to work on in the background without freezing the execution of the main application. There are a few types of workers that can be created with slightly different behavior. The intent of web workers is to give application developers the ability to specify what tasks within the application are parallelizeable (in the small), so that the browser can better schedule work for the rapidly increasing core count of today's (and tomorrow's) multi-core processors.

Web Storage and Web SQL
Web Storage is one of the more exciting parts of the HTML5 Family. Web Storage allows a page to store string data in a key-value pair database, specific to that domain. There are two varieties of Web Storage, the first is sessionStorage, that persists data only for a single session (think of it as a more functional cookie storage mechanism). The second is localStorage which allows a domain to store data locally across browser sessions (and system reboots). When you add localStorage to the cache manifest from the main HTML5 spec, you have the ability to run an offline application. The Web Storage spec is itself separate from the Web SQL Database spec which provides for a full SQL-addressable database that is accessible offline. Although varieties of this spec are in implementation by browser makers, the standardization process is blocking on the need for a second interoperable implementation that is not based on SQLite (which all the current versions are.)

Web Sockets
The Web Sockets protocol is in the first stage of the standards process and has also been submitted as an IETF draft because it is a networking protocol. It defines a non-http-based asynchronous client/server protocol that can be used in place of the current AJAX methods for asynchronous server communication. It uses an initial http: request to bootstrap the new protocol.

And all the others…
Geolocation is a simple spec that provides a built-in a geolocation object that scripts can query. It also provides methods for defining location cache freshness requirements. This is fairly non-controversial and already in new browsers. File API allows single and multiple file uploads from the user desktop. It's unclear exactly who will support this, but there doesn't seem to be much confusion about what it's supposed to do. Microdata is a mechanism to allow communities of interest to mark up content with semantic tags (for example, tags that identify an address or a resume.) It doesn't specify what these semantic tags are, just how they should be implemented. Device APIs that allow web browser access to devices such as cameras, BlueTooth etc, are still an early work in progress. These hope to define standardized access to native hardware and sensitive data from web applications. Highest priority are a camera API, and APIs for contact list, SMS history etc. on mobile devices. From Google I/O it appears that Google is going to ship something sooner rather than later that allows camera access from a Chrome web application, but there have been no further details on this.

HTML5 Summed Up
It's easy to get lost in the welter of standards enumerated above. But stepping back you should get the sense that the HTML5 Family authors are on a mission to make web applications as powerful as native applications when it comes to user interface richness, offline capability and hardware access. Since HTML5 family apps will be deployed on the web, they'll have the added benefits that the web has always brought, which are:
• A universal client that works cross platform
• Easy searchability and indexing (including deep linking)
• The ability to trivially include third party services and mashups
• Zero hassle deployment and updating (after all, it's just on the web)

We're excited by our initial HTML5-based development, and we eagerly await these new features as they are implemented and stabilized in the latest browsers.

Recomended links about HTML5 Book: Deploying HTML5 Sphere: Related Content

5/6/10

Streaming API for XML (StAX)

Según se lee en InternetNews.com, BEA Systems después de estar dos años desarrollando proyectos para optimizar el procesado de ficheros XML ha lanzado la primera versión de StAX ( Streaming API for XML ).

Este API busca solucionar los problemas de DOM y SAX para el procesado de XML, proporcionando un acceso pull que nos permite analizar únicamente la parte del documento XML que nos interesa, sin tener que crear complejas estructuras arbóreas del documento o sin tener que analizar el documento en su totalidad.

Podéis ver mucha más información en la página web de StAX. Sphere: Related Content

XMLBeans de BEA: manipulación de XML desde Java

BEA ha donado el código de XMLBeans a Apache. El código fuente ya esta disponible en el repositorio CVS.
XMLBeans procesa un XSD (XML Schema) para generar código Java que permite navegar y manipular el XML respetando las restricciones impuestas por el XSD concreto.
Más información: Getting Started with XMLBeans

Numerosa documentación sobre XMLBeans
A las puertas de XMLBeans 2.0, BEA Systems ha publicado cuatro tutoriales sobre mapeo de objetos y XML utilizando su framework Open Source en su portal de desarrolladores dev2dev.

Los artículos son:
XML Processing with Java Object Technology de Scott Ryan.
Strongly Typed XML in Java with XMLBeans de Cezar Cristian Andrei.
Leveraging Complex Schema Features in Java the XMLBeans Way de Raj Alagumalai y Raju Subramanian.
Using XMLBeans in Web Service Clients and User Interfaces de Steve Hanson.

Para todos los que utilizais esta fenomenal libreria, os serán muy utiles.

Enlaces relacionados: The Server Side

W3C pública las especificaciones de XSLT, XML Query y XPath 2.0
El W3C ha publicado una versión "release candidate" de las especificaciones de XSLT, XML Query y XPath 2.0. Éstas especificaciones, que suponen un cambio mayor en XSLT, XML Query y XPath, ahora ya se encuentran en un estado suficientemente maduro para comenzar con las implementaciones.

Aquí os dejo vínculos a las especificaciones:
XSLT y XQuery:
* XSL transformaciones (XSLT) versión 2.0
* XSLT 2.0 y XQuery 1.0 serialización
* XML sintaxis para XQuery 1.0 (XQueryX)
XQuery y XPath:
* XQuery 1.0: un lenguaje de consultas XML
* XML Path Language (XPath) 2.0
* XQuery 1.0 y XPath 2.0 modelo de datos (XDM)
* XQuery 1.0 y XPath 2.0 funciones y operadores
* XQuery 1.0 y XPath 2.0 semántica formal

Enlaces relacionados: W3C - All Standards and Drafts Sphere: Related Content

Tutorial extenso sobre XMLBeans

XMLBeans es una librería Open Source de XML data binding, cedida por BEA hace unos meses a la Apache Software Foundation.

Su funcionamiento es muy similar a JAXB y básicamente nos permitirá transformar jerarquías completas de objetos Java a XML y viceversa, utilizando como guía de mapeo el esquema o el DTD del documento XML.

La potencia de estos frameworks es impresionante y agilizan mucho el desarrollo de aplicaciones. Sin embargo, sin tutoriales adecuados su utilidad se ve reducida considerablemente.

En javaBoutique han publicado un extenso tutorial de ocho páginas donde explican con detalle como utilizar XMLBeans en nuestras aplicaciones.

Desde luego es un gran recurso para iniciarse en esta librería. Espero que os sea útil. Sphere: Related Content

Patrones de diseño XML

XML ha pasado durante los últimos años de ser una tecnología oscura a ser parte del día a día del desarrollador. Poco a poco, este lenguaje se ha ido introduciendo en nuestras vidas y ya cada vez son más pocos los desarrollos que no utilizan algo de XML, ya sea explícitamente o implícitamente en alguna librería de terceros.

Este auge, y la proliferación de tecnologías basadas en XML ( XQuery, XPath, XML Schema, ... ) hace que sean cada vez más necesarias una serie de guías que nos ayuden en nuestro trabajo diario.

Eso es lo que nos ofrece XML Patterns, una bibilioteca de patrones de diseño que nos ayudarán a controlar la estructura de nuestros esquemas, dtds, crear correctamente nuestros documentos XML, etc. Sphere: Related Content

4/6/10

Mathematics Software for Linux

Mathematics Packages:

Octave
GNU Octave is a high-level language, primarily intended for numerical computations. It provides a convenient command line interface for solving linear and nonlinear problems numerically, and for performing other numerical experiments using a language that is mostly compatible with Matlab. It may also be used as a batch-oriented language.

Octave has extensive tools for solving common numerical linear algebra problems, finding the roots of nonlinear equations, integrating ordinary functions, manipulating polynomials, and integrating ordinary differential and differential-algebraic equations. It is easily extensible and customizable via user-defined functions written in Octave's own language, or using dynamically loaded modules written in C++, C, Fortran, or other languages.

R-Project
R is a language and environment for statistical computing and graphics. It is a GNU project which is similar to the S language and environment which was developed at Bell Laboratories (formerly AT&T, now Lucent Technologies) by John Chambers and colleagues. R can be considered as a different implementation of S. There are some important differences, but much code written for S runs unaltered under R.

R provides a wide variety of statistical (linear and nonlinear modelling, classical statistical tests, time-series analysis, classification, clustering, ...) and graphical techniques, and is highly extensible. The S language is often the vehicle of choice for research in statistical methodology, and R provides an Open Source route to participation in that activity.

bc
bc is an arbitrary precision numeric processing language. Syntax is similar to C, but differs in many substantial areas. It supports interactive execution of statements. bc is a utility included in the POSIX P1003.2/D11 draft standard.

Scilab
Scilab is a scientific software package for numerical computations providing a powerful open computing environment for engineering and scientific applications. It is developed since 1990 by researchers from INRIA and ENPC. Distributed freely via the Internet since 1994, Scilab is currently being used in educational and industrial environnments around the world.

Scilab includes hundreds of mathematical functions with the possibility to add interactively programs from various languages (C, Fortran...). It has sophisticated data structures (including lists, polynomials, rational functions, linear systems...), an interpreter and a high level programming language.

Yorick
Yorick is an interpreted programming language, designed for postprocessing or steering large scientific simulation codes. Smaller scientific simulations or calculations, such as the flow past an airfoil or the motion of a drumhead, can be written as standalone yorick programs. The language features a compact syntax for many common array operations, so it processes large arrays of numbers very efficiently. Unlike most interpreters, which are several hundred times slower than compiled code for number crunching, yorick can approach to within a factor of four or five of compiled speed for many common tasks. Superficially, yorick code resembles C code, but yorick variables are never explicitly declared and have a dynamic scoping similar to many Lisp dialects. The yorick language is designed to be typed interactively at a keyboard, as well as stored in files for later use. Yorick includes an interactive graphics package, and a binary file package capable of translating to and from the raw numeric formats of all modern computers.

Algae
Algae is an interpreted language for numerical analysis. Algae was developed because we needed a fast and versatile tool, capable of handling large problems. Algae has been applied to interesting dynamics problems in aerospace and related fields for more than a decade.

Yacas
YACAS is an easy to use, general purpose Computer Algebra System, a program for symbolic manipulation of mathematical expressions. It uses its own programming language designed for symbolic as well as arbitrary-precision numerical computations. The system has a library of scripts that implement many of the symbolic algebra operations; new algorithms can be easily added to the library. YACAS comes with extensive documentation (320+ pages) covering the scripting language, the functionality that is already implemented in the system, and the algorithms we used.

Rlab
Rlab is an interactive, interpreted scientific programming environment. Rlab is a very high level language intended to provide fast prototyping and program development, as well as easy data-visualization, and processing. Rlab is not a clone of languages such as those used by tools like Matlab or Matrix-X/Xmath. However, as Rlab focuses on creating a good experimental environment (or laboratory) in which to do matrix math, it can be called ``Matlab-like''; since the programming language possesses similar operators and concepts.

Euler
EULER is a program for quickly and interactively computing with real and complex numbers and matrices, or with intervals, in the style of MatLab, Octave,... It can draw and animate your functions in two and three dimensions.

Maxima
Maxima is a descendant of DOE Macsyma, which had its origins in the late 1960s at MIT. It is the only system based on that effort still publicly available and with an active user community, thanks to its open source nature. Macsyma was the first of a new breed of computer algebra systems, leading the way for programs such as Maple and Mathematica. This particular variant of Macsyma was maintained by William Schelter from 1982 until he passed away in 2001. In 1998 he obtained permission to release the source code under GPL. It was his efforts and skill which have made the survival of Maxima possible, and we are very grateful to him for volunteering his time and skill to keep the original Macsyma code alive and well. Since his passing a group of users and developers has formed to keep Maxima alive and kicking. Maxima itself is reasonably feature complete at this stage, with abilities such as symbolic integration, 3D plotting, and an ODE solver, but there is a lot of work yet to be done in terms of bug fixing, cleanup, and documentation. This is not to say there will be no new features, but there is much work to be done before that stage will be reached, and for now new features are not likely to be our focus.

JACAL
JACAL is an interactive symbolic mathematics program. JACAL can manipulate and simplify equations, scalars, vectors, and matrices of single and multiple valued algebraic expressions containing numbers, variables, radicals, and algebraic differential, and holonomic functions.


gTybalt
Symbolic calculations, carried out by computer algebra systems, have become an integral part in the daily work of scientists. The advance in algorithms and computer technology has led to remarkable progress in several areas of natural sciences. gTybalt was developed as a tool for certain kind of calculations. The characteristics of these calculations are: First of all, these tend to be "long" calculations, e.g. the system needs to process large amounts of data and efficiency in performance is a priority. Secondly, the algorithms for the solution of the problem are usually developed and implemented by the scientists themselves. This requires support from the computer algebra system for a programming language which allows to implement complex algorithms for abstract mathematical entities. In other words, it requires support of object oriented programming techniques from the system. On the other hand, these calculations usually do not require that the computer algebra system provides sophisticated tools for all branches of mathematics. Thirdly, despite the fact that these calculations process large amounts of data, the time needed for the implementation of the algorithms usually outweights the actual running time of the program. Therefore convenient development tools are also important.

Symaxx
Symaxx/2 is a graphical frontend for Maxima.

Singluar
SINGULAR is a Computer Algebra System for polynomial computations with special emphasis on the needs of commutative algebra, algebraic geometry, and singularity theory.

HartMath
HartMath is an experimental computer algebra system written in Java.

GiNaC
The name GiNaC is an iterated and recursive abbreviation for GiNaC is Not a CAS, where CAS stands for Computer Algebra System. It has been developed to become a replacement engine for xloops which is up to now powered by the Maple CAS. Its design is revolutionary in a sense that contrary to other CAS it does not try to provide extensive algebraic capabilities and a simple programming language but instead accepts a given language (C++) and extends it by a set of algebraic capabilities.

XLoops
Aim of this project is to provide a package that completely evaluates massive one- and two-loop Feynman diagrams to make calculations in high energy physics easier.

PARI-GP
PARI-GP is a software package for computer-aided number theory. It consists of a C library, libpari (with optional assembler cores for some popular architectures), and of the programmable interactive gp calculator. While you can write your own libpari-based programs, many people just start up a gp session, or have gp execute their scripts.

GRASS
GRASS GIS (Geographic Resources Analysis Support System) is an open source, Free Software Geographical Information System (GIS) with raster, topological vector, image processing, and graphics production functionality that operates on various platforms through a graphical user interface and shell in X-Windows. It is released under GNU General Public License (GPL).

Macaulay 2
Macaulay 2 is a software system devoted to supporting research in algebraic geometry and commutative algebra, whose development has been funded by the National Science Foundation.

NumExp
NumExp is a family of open-source applications for numeric computation. When it was created, the idea was to make a powerfull tool like Mathematica. Now, we know this is almost impossible without more open-source hackers. Meanwhile, we are trying to make, at least, an useful tool!

GtkGraph
GtkGraph is a simple graphing calculator written for X Windows using the Gtk+ widget set. It is intended as a replacement for a standalone graphing calculator, which typically costs over $80 USD, and has a tiny monochrome display driven by a CPU running at around 6 MHz with no FPU. GtkGraph can plot functions and solve arithmetic expressions using double precision arithmetic.

surf
surf is a tool to visualize some real algebraic geometry: plane algebraic curves, algebraic surfaces and hyperplane sections of surfaces. surf is script driven and has (optionally) a nifty GUI using the Gtk widget set.

The E Equational Theorem Prover
E is a a purely equational theorem prover for clausal logic. That means it is a program that you can stuff a mathematical specification (in clausal logic with equality) and a hypothesis into, and which will then run forever, using up all of your machines resources. Very occasionally it will find a proof for the hypothesis and tell you so ;-).

TISEAN
TISEAN is free a software project for the analysis of time series with methods based on the theory of nonlinear deterministic dynamical systems, or chaos theory, if you prefer.

Plotting Software
Gnuplot
gnuplot is a command-driven interactive function plotting program. It can be used to plot functions and data points in both two- and three-dimensional plots in many different formats, and will accommodate many of the needs of today's scientists for graphic data representation. gnuplot is copyrighted, but freely distributable; you don't have to pay for it.

NCAR
The NCAR Command Language (NCL) is a programming language designed specifically for the access, analysis, and visualization of data. NCL can be run in interactive mode, where each line is interpreted as it is entered at your workstation, or it can be run in batch mode as an interpreter of complete scripts.

Gri
Gri is a language for scientific graphics programming. The word "language" is important: Gri is command-driven, not point/click. Some users consider Gri similar to LaTeX, since both provide extensive power as a reward for tolerating a learning curve. Gri can make x-y graphs, contour graphs, and image graphs, in PostScript and (someday) SVG formats. Control is provided over all aspects of drawing, e.g. line widths, colors, and fonts. A TeX-like syntax provides common mathematical symbols.

PLplot
PLplot is a library of functions that are useful for making scientific plots. PLplot can be used from within compiled languages such as C, C++, FORTRAN and Java, and interactively from interpreted languages such as Octave, Python, Perl and Tcl. The PLplot library can be used to create standard x-y plots, semilog plots, log-log plots, contour plots, 3D surface plots, mesh plots, bar charts and pie charts. Multiple graphs (of the same or different sizes) may be placed on a single page with multiple lines in each graph.

PGPLOT
The PGPLOT Graphics Subroutine Library is a Fortran- or C-callable, device-independent graphics package for making simple scientific graphs. It is intended for making graphical images of publication quality with minimum effort on the part of the user. For most applications, the program can be device-independent, and the output can be directed to the appropriate device at run time.

plotutils
The GNU plotutils package contains software for both programmers and technical users. Its centerpiece is libplot, a powerful C/C++ function library for exporting 2-D vector graphics in many file formats, both vector and raster. It can also do vector graphics animations.

SciGraphica
SciGraphica is a scientific application for data analysis and technical graphics. It pretends to be a clone of the popular commercial (and expensive) application "Microcal Origin". It fully supplies plotting features for 2D, 3D and polar charts. The aim is to obtain a fully-featured, cross-plattform, user-friendly, self-growing scientific application. It is free and open-source, released under the GPL license.

Grace
Grace is a WYSIWYG 2D plotting tool for the X Window System and M*tif.

Ptplot
Ptplot 5.2 is a 2D data plotter and histogram tool implemented in Java. Ptplot can be used as a standalone applet or application, or it can be embedded in your own applet or application.

DISLIN
DISLIN is a high-level plotting library for displaying data as curves, polar plots, bar graphs, pie charts, 3D-color plots, surfaces, contours and maps.

ImLib3D
ImLib3D is an open source C++ library for 3D (volumetric) image processing. It contains most basic image processing algorithms, and some more sophisticated ones. It comes with an optional viewer that features multiplanar views, animations, vector field views and 3D (OpenGL) multiplanar. All image processing operators can be interactively called from the viewer as well as from the UNIX command-line. ImLib3D's goal is to provide a standard and easy to use platform for volumetric image processing research. Focus has been put on simplicity for the developer. ImLib3D has been carefully designed, using modern, standards conforming C++. It intensively uses the Standard C++ Library, including strings, containers, and iterators.

GLgraph
GLgraph visualize mathematical functions. It can handle 3 unknowns (x,z,t) and can produce a 4D function with 3 space and 1 time dimension.

MayaVi
MayaVi is a free, easy to use scientific data visualizer. It is written in Python and uses the amazing Visualization Toolkit (VTK) for the graphics. It provides a GUI written using Tkinter. MayaVi is free and distributed under the conditions of the BSD license. It is also cross platform and should run on any platform where both Python and VTK are available (which is almost any *nix, Mac OSX or Windows).

Graphviz
Graph Drawing Programs from AT&T Research and Lucent Bell Labs

Numerical Libraries
GNU Scientific Library
The GNU Scientific Library (GSL) is a numerical library for C and C++ programmers. It is free software under the GNU General Public License.

The library provides a wide range of mathematical routines such as random number generators, special functions and least-squares fitting. There are over 1000 functions in total.

SAML
The "Simple Algebraic Math Library" is a C library for computer algebra, together with some application programs: a desktop calculator, a spreadsheet (sort of) and a program to factorize integers.

Numerical Python
Numerical Python adds a fast, compact, multidimensional array language facility to Python.

VTK
The Visualization ToolKit (VTK) is an open source, freely available software system for 3D computer graphics, image processing, and visualization used by thousands of researchers and developers around the world. VTK consists of a C++ class library, and several interpreted interface layers including Tcl/Tk, Java, and Python. VTK supports a wide variety of visualization algorithms including scalar, vector, tensor, texture, and volumetric methods; and advanced modeling techniques such as implicit modelling, polygon reduction, mesh smoothing, cutting, contouring, and Delaunay triangulation. In addition, dozens of imaging algorithms have been directly integrated to allow the user to mix 2D imaging / 3D graphics algorithms and data. The design and implementation of the library has been strongly influenced by object-oriented principles.

PDL
PDL (``Perl Data Language'') gives standard Perl the ability to compactly store and speedily manipulate the large N-dimensional data arrays which are the bread and butter of scientific computing.

LAPACK
LAPACK is written in Fortran77 and provides routines for solving systems of simultaneous linear equations, least-squares solutions of linear systems of equations, eigenvalue problems, and singular value problems. The associated matrix factorizations (LU, Cholesky, QR, SVD, Schur, generalized Schur) are also provided, as are related computations such as reordering of the Schur factorizations and estimating condition numbers. Dense and banded matrices are handled, but not general sparse matrices. In all areas, similar functionality is provided for real and complex matrices, in both single and double precision.

PARI-GP
PARI-GP is a software package for computer-aided number theory. It consists of a C library, libpari (with optional assembler cores for some popular architectures), and of the programmable interactive gp calculator. While you can write your own libpari-based programs, many people just start up a gp session, or have gp execute their scripts.

Python Number Crunching
This page lists a number of packages related to numerics, number crunching, signal processing, financial modeling, linear programming, statistics, data structures, date-time processing, random number generation, and crypto.

LINPACK
LINPACK is a collection of Fortran subroutines that analyze and solve linear equations and linear least-squares problems. The package solves linear systems whose matrices are general, banded, symmetric indefinite, symmetric positive definite, triangular, and tridiagonal square. In addition, the package computes the QR and singular value decompositions of rectangular matrices and applies them to least-squares problems. LINPACK uses column-oriented algorithms to increase efficiency by preserving locality of reference.

LINPACK was designed for supercomputers in use in the 1970s and early 1980s. LINPACK has been largely superceded by LAPACK, which has been designed to run efficiently on shared-memory, vector supercomputers.

ATLAS
ATLAS stands for Automatically Tuned Linear Algebra Software. ATLAS is both a research project and a software package. This FAQ describes the software package. ATLAS's purpose is to provide portably optimal linear algebra software. The current version provides a complete BLAS API (for both C and Fortran77), and a very small subset of the LAPACK API. For all supported operations, ATLAS achieves performance on par with machine-specific tuned libraries.

CLN
CLN is a library for computations with all kinds of numbers. It has a rich set of number classes... [see web page]

Colt
This distribution provides an infrastructure for scalable scientific and technical computing in Java. It is particularly useful in the domain of High Energy Physics at CERN: It contains, among others, efficient and usable data structures and algorithms for Off-line and On-line Data Analysis, Linear Algebra, Multi-dimensional arrays, Statistics, Histogramming, Monte Carlo Simulation, Parallel & Concurrent Programming. It summons some of the best concepts, designs and implementations thought up over time by the community, ports or improves them and introduces new approaches where need arises. In overlapping areas, it is competitive or superior to toolkits such as STL, Root, HTL, CLHEP, TNT, GSL, C-RAND / WIN-RAND, (all C/C++) as well as IBM Array, JDK 1.2 Collections framework, JGL (all Java), in terms of performance (!), functionality and (re)usability.

Programming Languages
Lush
Lush is an object-oriented programming language designed for researchers, experimenters, and engineers interested in large-scale numerical and graphic applications. Lush is designed to be used in situations where one would want to combine the flexibility of a high-level, loosely-typed interpreted language, with the efficiency of a strongly-typed, natively-compiled language, and with the easy integration of code written in C, C++, or other languages.

Nickle
Nickle is a programming language based prototyping environment with powerful programming and scripting capabilities. Nickle supports a variety of datatypes, especially arbitrary precision numbers. The programming language vaguely resembles C. Some things in C which do not translate easily are different, some design choices have been made differently, and a very few features are simply missing.

Nickle provides the functionality of UNIX bc, dc and expr in much-improved form. It is also an ideal environment for prototyping complex algorithms. Nickle's scripting capabilities make it a nice replacement for spreadsheets in some applications, and its numeric features nicely complement the limited numeric functionality of text-oriented languages such as AWK and PERL.

Open Dynamics Engine
ODE is a free, industrial quality library for simulating articulated rigid body dynamics - for example ground vehicles, legged creatures, and moving objects in VR environments. It is fast, flexible, robust and platform independent, with advanced joints, contact with friction, and built-in collision detection.

Blitz++
Blitz++ is a C++ class library for scientific computing which provides performance on par with Fortran 77/90. It uses template techniques to achieve high performance. The current versions provide dense arrays and vectors, random number generators, and small vectors and matrices.

FFTW
FFTW is a C subroutine library for computing the discrete Fourier transform (DFT) in one or more dimensions, of arbitrary input size, and of both real and complex data (as well as of even/odd data, i.e. the discrete cosine and sine transforms, the DCT and DST). We believe that FFTW, which is free software, should become the FFT library of choice for most applications.

Our benchmarks, performed on on a variety of platforms, show that FFTW's performance is typically superior to that of other publicly available FFT software, and is even competitive with vendor-tuned codes. In contrast to vendor-tuned codes, however, FFTW's performance is portable: the same program will perform well on most architectures without modification. Hence the name, "FFTW," which stands for the somewhat whimsical title of "Fastest Fourier Transform in the West."

GMP
GNU MP is a library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. It has a rich set of functions, and the functions have a regular interface.

NURBS++
Non-Uniform Rational B-Splines (NURBS) curves and surface are parametric functions which can represent any type of curves or surfaces. This C++ library hides the basic mathematics of NURBS. This allows the user to focus on the more challenging parts of their projects. The library also offers a lot of features to help generate NURBS from data points.

SciPy
SciPy is an open source library of scientific tools for Python. SciPy supplements the popular Numeric module, gathering a variety of high level science and engineering modules together as a single package.

SciPy includes modules for graphics and plotting, optimization, integration, special functions, signal and image processing, genetic algorithms, ODE solvers, and others.

Sites of Interest
The Linux Lab Project
The Linux lab project is intended to help people with development of data collection and process control software for LINUX. It should be in understood as software and knowledge pool for interested people and application developers dealing with this stuff in educational or industrial environment.

Programming Systems on GNU/Linux
This page deals with links to tutorials, documents, and Linux implementations for installing Linux on a PC, getting started with Linux, and then going a step further -- to optimise your PC for processing power, using multiple processors (Symmetric Muliti Processing - SMP); making a cheap, upgradeable, Supercomputing Linux cluster and finally links to software to do parallel programming on Linux.

Scientific Applications on Linux
SAL (Scientific Applications on Linux) is a collection of information and links to software that will be of interest to scientists and engineers. The broad coverage of Linux applications will also benefit the whole Linux/Unix community. There are currently 3,070 entries in SAL.

Netlib
Netlib is a collection of mathematical software, papers, and databases.

FSF Free Software Directory - Mathematics
[Collection of GPL'd and other Free Software] Sphere: Related Content

Conclusions on Parallel Computing

By Asaf Shelly (21 posts) on April 9, 2010 at 11:10 am

We have been dealing with parallel computing for some while now. Some of the ideas we had at the start proved to be wrong while others are only becoming relevant in the near future. No doubt about it, parallel computing was pushed and forced into the mainstream of computing just as Object Oriented was in the previous millennia.

Some History: Hardware

The first to deal with parallel computing were hardware developers because the hardware supports multiple devices working at the same time, with different operation rates and response times. Hardware design is also Event Driven because devices work independently and issue an Interrupt event when required. The computer hardware we know today is fully parallel however it is centralized with a single CPU (Central Processing Unit) and multiple peripheral devices.

Some History: Kernel

The next to support parallel computing was the software infrastructure which in modern operating systems is the Kernel. The Kernel must support multiple events coming in the form of Hardware Interrupts and propagated upwards as Software Events. Kernels are commonly distributed in design as several Drivers can communicate with each other. The centralized object in the system is allowing communication between the drivers and supports synchronization but is not supposed to contribute to the application's business logic in any form or way.

Some History: Network

UNIX is based on services. A Service is a way to call a function over network. Network technologies required distributed design in which every element is completely parallel to the next and there is no single 'processor unit' as the system's master. UNIX took this to the next level with technologies such as services, pipes, sockets, mailslots, Fork and more. At a time when programming was a tedious work, developing an operating system to support Fork meant extensive efforts. Still UNIX had built in support for that mechanism which solves so many problems... Only we forgot how to use it and I don't remember seeing a new system design that had Fork in it.

Some History: Applications

When I just started with C programming and have just found out about threads I tried doing things in parallel just to see how it works. The result was, as you can imagine, by far worse. The application runs much slower, there are "Random Bugs" and the code looks terrible. The explanation I got was that there is only one CPU and the different threads compete over it. No Multi-Core CPU means that there is no ROI (return on investment) for using multiple threads and the large efforts required for a parallel design. The only reason to use a thread is when you really have to for example when there is need to wait for hardware or a network buffer.

Parallel Computing Today

A few years ago CPUs got to a certain hardware limitation which would have required special cooling. At this point the race to reduce silicon size and increase clock frequency has ended. Instead of spending massive amounts of silicon on the CPU for advanced algorithms to improve instruction pre-fetch, smaller and simpler CPUs are used and there is room for more CPUs on the same silicon wafer. We got the Multi-Core CPU which practically means several CPUs on the same computer.

At first the cores of a Multi-Core CPU were simpler than the single core one. These cores also operated in a much lower frequency which meant that an application designed for a single task operation had a massive performance impact when moving to a new computer, for the first time ever.

Parallel Computing has become main stream. We started with a long series of lectures about parallel computing. It seemed that people wanted to know about this subject but there was so much overhead that Parallel Computing simply scared people away. There is a huge ramp before you can be a good parallel programmer. Just as there is for object oriented programming. This meant that team leaders and architects were at the same level as beginner programmers, or perhaps with some very little advantage. Add to this the fact that there are massive amounts of code already written for a single core CPU and good advantages can be achieved after at least some re-write. Last but most important reason to reject parallel computing was that it is easier and cheaper to buy another machine than to make the best out of the CPU cores. This was actually a boost for Cloud Computing.

Who is doing Parallel Computing

There are several types of parallel computing. The hardware is parallel so the Kernel is parallel. With this type of parallelism every worker is doing something else, and workers own their resources instead of sharing them. For a long while now DSP (Digital Signal Processing) chips are Multi-Core CPUs so that the algorithms executed on these chips can run faster. Algorithms and DSP chips are evaluated by MIPS which is the amount of instructions per time constant. Gaining performance increase with an algorithm means either using less instructions or adding more worker CPU cores. PCs also run algorithms such as face recognition, image detection, image filtering, motion detection, and more. The transition from single core CPU to a Multi-Core CPU was fast and simple.

Algorithm's increase in performance is relative to the amount of computations per data item. More computation more cores can be used. Image Blending (fade) is an example for an algorithm which cannot enjoy the use of more than a single core. Take an image and blend each pixel with the corresponding pixel of another image. Each pixel should be read from RAM then a simple addition and shift right are performed and then the result should be writen back to RAM. The CPU can operate at a rate of 3GHz and the RAM at 1GHz. For each pixel in the image we: Read pixel A, Read pixel B, Add, Shift, Write result pixel. Add another core and the CPU cores will mutually block on access to the memory. This is also true for Databases and database algorithms such as sort algorithms, linked lists, etc. For this reason the new Multi-Core CPUs have extensive support for parallel access to memory.

Parallel Computing ROI

Parallel Computing is the new future for computers. Object Oriented is no longer the new buzz word. I keep telling people that before they make an Object Oriented Design to their systems they should make flow charts. Good OOD is based on good system flow charts, whether you write them down or do it in your head as an art.

We all used to think that User Interface is the product and OOD is the way to do it. It now looks like we were wrong:

User Experience is the prodcut and Parallel Design is the way to do it. User Experience (UX) is not User Interface (UI). User Interface defines what the product would look like, or in other words UI defines what the product is. Object Oriented Design defines what the code looks like, or in other words OOD defines what the code is. Parallel Computing defines how the code works, or in other words Parallel Computing defines what the code does. User Experience defines how the application behaves, or in other words User Experience defines what the application does.

I am not using a C++ library because it is using linked-lists. I am using that library because it can sort.

I am not buying a product because it looks like I want it to look, for this I can buy a framed picture instead. I am buying a product because it is doing something I need and it is not doing what I do not need.

Parallel Computing is the basis for User Experience. Even if you have a single core it is better to have good parallel design. As customers you know this, you don't want to accidentally hit "Print" instead of "Save" and now wait for 5 seconds punishment for the dialog to open so you can close it. (see minute 43 for demo video)

Today we have so many good resources and tools. Now is the time to learn how to work parallel and produce good prodcuts with good UX.


Comments (7)
April 14, 2010 6:55 AM PDT


Peter da Silva I was doing parallel computing on single-CPU systems back in the late '70s and early '80s, without even thinking about it. It was mainstream. It was called the "UNIX command line". The UNIX pipes and filters model took advantage of parallelism on a single computer by allowing you to take advantage of parallelism inherent in teh division of work between I/O and computation. A UNIX pipeline allowed programs to accumulate and buffer data as fast as the disks could provide it, so that data was available for computation as soon as the CPU-intensive components of the pipeline were ready for it. When multiple CPUs became available, this just happened automatically.

For slow and latency sensitive devices, such as tape drives, one of the earliest tools for buffering I/O was simply to run the "DD" command with a large buffer multiple times in a pipeline: "tar cvf - | dd bs=16k | dd bs=16k | dd bs=16k > /dev/rmt0h" (this was on a PDP-11, 16k was a large buffer). The output of "tar" was uneven and bursty, because it was seeking all over the disk to collect the files for the archive, but the output of the final "dd" was smooth and the tape was able to stream for many megabytes at a time.

This had nothing to do with your proposed redefinition of parallel computing as a user experience design tool, it was a more or less automatic byproduct of good factoring of the problem. It was coarse-grained and could be bottlenecked by non-streaming operations (eg, sorts), but it was an early and effective tool. There have been similar tools created for specialized problem areas in GUI applications, such as MIDI apps that let you lay out multiple MIDI processing steps in two dimensions and hook them together by "wires", but the same kind of factoring of the problem space for GUI applications hasn't really been found.
April 14, 2010 8:34 AM PDT


Richard H. The image blending example only highlights the inherent non-parallel nature of memory-cpu bus contention. Current PCs with multi-cores aren't 100% parallel at the hardware level. ie. the Von-Neuman bottleneck is still present.
Lower your expectations, or get a system that really is parallel at the bus level.
April 14, 2010 8:35 AM PDT


Yves Daoust I don't quite share the comparison of parallel computing with object oriented design. I see the latter as a small step in the art of programming, as opposed to a giant leap for the former.

Anyone can write sequential programs after a few minutes of training on any procedural language. Most people end up writing well structured programs after a few years of practice and find no difficulty switching to Object Oriented Programming.

Writing concurrent programming is of another nature. It reserved for true experts, with a truly scientific understanding of the issues. Just think of the Dining Philosophers problem: even though the problem statement looks easy, I doubt that ordinary people can solve it correctly.

In fact, I consider that parallel programming is not within reach of ... the human brain, except in simple or symmetrical cases. As soon as there are two or three asynchronous agents, you lose the control :)
April 14, 2010 1:44 PM PDT


Thierry Joubert It is true that we see nowadays about as many conferences on Parallel Programmingin as we saw on OOP during the early 90's. From time to time, big actors have to convice the masses. Today, with Java and .NET, OOP has become the standard (try to give a C/C++ course to students if you are any doubt about this). The OOP "push" came from the software industry whose motivation was to provide efficient programming interfaces for programmable products like GUIs, Databases, system services, etc. OOP was a movement towards progress.

Parallelism is one of the oldest thing in computer science as stated in the article and several comments, but the Parallel Programming "push" we see nowadays is organized by silicon vendors who failed to keep up on the Moore's Law slope. OOP was not motivated by any limitation, and I see a noticeable difference here.
April 14, 2010 4:47 PM PDT


paul clayden Parallel is a fad and won't last. It's an interim measure to something much much bigger. Pretty soon we'll have analogue computing/quantum computing which is going to rock all our worlds.
April 14, 2010 8:11 PM PDT


Lava Kafle superb clarification, We have been using oparallelism in java oracle .Net CSharp whatever since very beginning of X64 Architectures supported by Intel
April 18, 2010 3:00 AM PDT

Asaf Shelly
Asaf Shelly Total Points:
1,930
Brown Belt
Hi All,

I will start with thanking Peter for the extensive information. Truly something to respect.

This shows us that the basic ideas were already there and where somehow lost in time. Makes me wonder what else did we forget.

Back at the old days applications and drivers usually had only a few components. These were separated by using different source files. Later in time we had a massive upgrade to use classes and objects as part of the Object Oriented programming and design. C programmers did not have to write down the Object Design whereas C++ programmers found it almost intuitive and mandatory. C programming also defines procedures. Notice the name "Procedure", it means that the function is not a 3 line variable modification code, rather it is a whole procedure in the main process. The flow chart was also too often not written down but as we can see by the names the application was a 'Process' to perform which had a 'main procedure' and several other 'procedures'. Old school programming defined Procedures and Structures, we now go back to Tasks and Objects. This is why my website (where the video is found) says " Welcome to the Renaissance"...

I was slowly getting to reply to Yves Daoust's: "In fact, I consider that parallel programming is not within reach of ... the human brain". See minute 12:30 in the same video mentioned at the end of the post. Everything we do is parallel. If you work as part of a big organization then you probably do Object Oriented Design and manage the programming tasks using SCRUM methodology. Take a look at SCURM, copy the principles to your code and you have a good parallel application. I quote Wikipedia ("http://en.wikipedia.org/wiki/Scrum_(development)") : "...the 'ScrumMaster', who maintains the processes..." There is also sprint, backlog, priority, and daily sync meeting which is used to profile the operation and keep track of progress. There are also interesting things to learn from it, for example the daily sync meeting is where you report of all problems. This means that we don't raise an exception for every problem, instead we collect all the errors and report when the time it right. This might solve a few problems that parallel loops are struggling with.
The " Dining Philosophers problem" is a way to manage a proposed solution – Locks, it is not a way to solve the problem. If instead of using a set of locks you use a service for each resource the problem is completely different.

Is the image here http://www.9to5mac.com/intel-core-i7-mac-pro-xserve the answer to Richard's question?

Hi Thierry, I could respectfully argue that OOP was motivated by the limitation in managing large scale projects just as parallel programming is motivated by managing large scale systems. OOP is for the design time and parallel programming is for the run time. Not that I don't agree with you. It is possible that OOP was focused on so much for the past few years that programmers today think only in objects but find it very difficult to think in tasks.

I guess I have to say to Paul that parallel programming is ignorant to the engine. I am suggesting you use a word-processor instead of a typewriter. It does not matter whether you are using MS-Office for Mac, Open-Office, or something new that will be invented 5 years from now. Quantum computing or not, my application should still know how to cancel an operation when it is no longer required.

Thanks for the comment Lava.

Regards,
Asaf Sphere: Related Content

22/4/10

10 momentos importantes en la historia de la Informática

Por: Federico Reggiani @ miércoles, 23 de septiembre de 2009

1) 1959 - COBOL

Para muchos COBOL es el lenguaje de programación más importante de la historia. Muchos lenguajes actuales están basados en él (Pascal, BASIC, etc.). La prueba más grande que ha superado es la del tiempo, dado que todavía hoy hay miles de ordenadores corriendo aplicaciones COBOL, 50 años después. No es que COBOL haga cosas que otros OS no pueden hacer, pero es que trabaja lo suficientemente bien como para no tener que actualizarlo.

2)1969 – ARPANET

Arpanet es, nada menos, que la red que está detrás de Internet. Fue concebida con fines científicos y hoy terminó siendo el medio de comunicación más importante. Sin dudas, ARPANET cambió nuestras vidas.

3) 1970 – UNIX

No digo Linux, digo UNIX. Este sistema operativo abrió la puerta a cosas como el uso de ordenadores por varias personas (Multi-user). Esto es algo normal hoy en día, pero no lo era en esos tiempos. Esto no solo se refiere a la clave que pones para que tu familia no vea la clase de “películas” que ves, sino que es la base para los sistemas de seguridad que permiten que usemos email, Facebook, Tuenti, etc.

4) 1976 – Apple I

Apple I fue el primer ordenador que lanzó Apple. Pero fue también el primero de uso personal que se haya fabricado. Con él nacen las “Personal Computers”, antes los ordenadores solo eran para universidades y científicos. Pero Steve Jobs había visto un futuro mucho más prometedor y democrático para los ordenadores.
WordStar

5) 1978 – WordStar

¿Usar un ordenador para tareas hogareñas o de pequeñas oficinas? Wordstar nació para CP/M (el D.O.S. original que Microsoft compró) en 1978. Luego lanzó su versión 3.0 para D.O.S en 1982. WordStar abrió las puertas a una nueva etapa para la informática. ¡Ya no era solo para científicos! Además, ayudó a muchos de nosotros a terminar la escuela gracias a trabajos preciosamente terminados, que luego imprimíamos con nuestra impresora de puntos.

6) 1978 – BBS

Los BBS fueron los primeros sistemas en darnos una actividad social en red. Podíamos enviar emails, ver ficheros que otros dejaban para que veamos, compartir imágenes, software, etc. Fueron el principio de lo que hoy hacemos con Internet, o al menos el principio de las redes sociales actuales.

7) 1983 – Microsoft Mouse

Microsoft no inventó el mouse (o ratón), lo compraron hecho (¿de dónde me suena esto?). Sin embargo, ha sido la culpable de que el uso de este dispositivo sea masivo. Usar un ratón en el año 83 era ciencia ficción. ¿Mover una flecha en la pantalla con la mano? ¡Una locura!

8) 1991 – Linux

Con Linux no solo nace un sistema operativo, nace también una revolución. Así como Apple revolucionó el mundo con el lanzamiento de un producto “científico” para las masas, Linus Torvalds hizo lo suyo al lanzar un producto que antes solo hacían grandes corporaciones. Todos sabemos el provecho que saca Microsoft a Windows, ellos dominaban la informática, decidían quién podía usar un ordenador y quién no. Gracias a Linus ahora todos podemos tener un sistema operativo abierto y gratuito. Con ventajas o no, pero lo que Linux provocó es innegable.

Sir Tim Berners-Lee

9) 1992 – WWW

Tim Berners-Lee inventó la Web. A Tim se le ocurrió nada menos que inventar el Hipertexto, o HTML. Imagina por un momento Internet sin la Web. Es difícil porque la Internet que nos viene a la cabeza SIEMPRE incluye la Web. Claro que el chat y el email también son Internet, pero la Web es determinante en nuestras vidas. Alguna vez Tim dijo que “si hubiese sabido que el HTML se iba a transformar en Amazon, lo hubiera patentado”. Un grande. Robert Cailliau también participó, fue el único que le prestó atención cuando Berners-Lee presentó los primeros bocetos de la Web. Un dato: la WWW se creó en el mismo sitio que el LHC, el CERN de Suiza.

10) 1998 – Google

El dominio fue registrado en 1997, pero Google vio la luz en 1998. No solo veo en Google el buscador, sino también la empresa que está detrás de miles de servicios y productos. Desde Gmail a AdSense. Pasando por un largo etcétera. Sin dudas la creación de Google es muy importante en esta historia. Sobre todo por la especulación de lo que le queda aún por hacer.

Luego hubieron cosas como el P2P, Facebook y cloud computing. Lo que sucede es que todavía no tenemos bien en claro qué es lo que van a ofrecer, que sea realmente determinante en la historia de la informática y que no termine solo en lo comercial.

Quedan muchas cosas fuera. Cosas como: C y los lenguajes modernos, Fortran, Windows 95, Seti@Home y el principio de la nube, Apple Lisa (el primero con Interfaz Gráfica), Apple Newton precursora de las Palm, iPhones y SmartPhones actuales, la primera portátil. Vemos muchas menciones a temas relacionados a Internet, pero es que es el acontecimiento más importante junto con el primer ordenador personal.

También quedo fuera la venta de D.O.S. a IBM, que abrió las puertas a los ordenadores compatibles que permitieron bajadas de precio notables haciendo más popular el uso de PC en nuestros hogares.

¿Te parece que falta algo?

¡Claro! ¡Windows y D.O.S.!

No están en la lista porque a pesar de haber sido enormes éxitos comerciales, y haber realmente cambiado la historia, no fueron los primeros en hacer lo que hacen. Cuando saló Google ya existía Yahoo, vale, pero Google nunca funcionó como Yahoo. Yahoo era actualizado pro personas, y Google fue el primero en hacer un crawler automático.

Los que leen mis escasas notas pueden ver que no soy un Linuxero ni un Apple fanboy (aunque uso Linux y tengo un iPhone).

Pero de verdad me parece que Windows y D.O.S. fueron algo que terminó por suceder por la evolución de otras cosas.




Comentarios:
Esto me recuerda un documental muy bueno que vi, habla de la evolución de INTERNET, de como empezo y el porque. Tiene unas bases muy buenas, muchas de ellas no habia oído hablar, pero despues de buscarlo lo corrobore. A mí me gusto, ¿Y a vosotros?
http://www.youtube.com/watch?v=FGxDIh7OLno Sphere: Related Content