Tuesday, 9 October 2007

A First Guide to PostScript

What is PostScript?
PostScript is a programming language optimized for printing graphics and text (whether on paper, film, or CRT is immaterial). In the jargon of the day, it is a page description language. It was introduced by Adobe in 1985 and first (to my knowledge) appeared in the Apple LaserWriter. The main purpose of PostScript was to provide a convenient language in which to describe images in a device independent manner. This device independence means that the image is described without reference to any specific device features (e.g. printer resolution) so that the same description could be used on any PostScript printer (say, a LaserWriter or a Linotron) without modification. In practice, some PostScript files do make assumptions about the target device (such as its resolution or the number of paper trays it has), but this is bad practice and limits portability.

The language itself, which is typically interpreted, is stack-based in the same manner as an RPN calculator. A program pushes arguments for an operator onto a stack and then invokes the operator. Typically, the operator will have some result which is left at the top of the stack. As an example, let us say we want to multiply 12 and 134. We would use the following PostScript code:

12 134 mul

The first two words “12” and “134” push the numbers 12 and 134 onto the stack. “mul” invokes the multiply operator which pops two values off the stack, multiplies them, and then pushes the result back onto the stack. The resulting value can be left there to be used by another operator later in the program.

To follow the conventions used by Adobe in their manuals, I will synopsize operators using the following scheme: arg-1 arg-2 ... operator result. This scheme means that, to use operator, you must push arguments arg-1, arg-2, and so on before invoking the operator. operator will return the result: result. Many operators return no result (they have some side-effect); these will be shown as returning “-”.

Graphics Concepts
There are a few concepts that you need to know about before we dive into the language itself. These concepts are the concepts PostScript uses to describe and manipulate images on a page. There are really only a few.

Device Space
This is the coordinate space understood by the printer hardware. This coordinate system is typically measured in terms of the device’s resolution. There is really nothing else that can be said about this space, as PostScript programs are typically not expressed using it.
User Space
This is the coordinate system used by PostScript programs to describe the location of points and lines. User space is essentially the same as the first quadrant of the standard coordinate system used in high school math classes. Point (0, 0) is in the lower left corner. Coordinates are real numbers, so there is no set resolution in user space. The interpreter automatically converts user space coordinates to device space.
Current Transformation Matrix
The transformation of user space coordinates to device space coordinates is done through the current transformation matrix. This matrix is a three by three matrix that allows the user to rotate, scale, and translate the entire user space within the device space. This is the source of a lot of PostScript’s power, as will be demonstrated later.
Path
A path is a collection of (possibly disjoint) line segments and curves arranged on the page. The path does not describe actual ink on the paper; it merely describes an imaginary tracing over the page. There are operators which allow the user to draw ink along the path (stroke), fill an enclosed path with ink (fill), or clip out all future images that are outside the path (clip).
Current Path
This is the path that the PostScript program is creating at the moment. The current path is assembled piece by piece.
Clipping Path
The PostScript rendering system will ignore any part of a line segment, curve, or bitmap that extends outside a certain region; it will only draw the parts of those elements which are within the region. The region is described by a path called the clipping path. The clipping path is usually a rectangle about a quarter of an inch in from the edge of the page, but it can easily be set by the user to an arbitrary path.
Graphics State
This is a collection of various settings that describe the current state of the graphics system. Things like the current path, the current font, and the current transformation matrix make up the graphics state. Often, a program will need to temporarily save a graphics state to be used later. There are a couple of ways of doing this, but the easiest is to push the state onto a special graphics state stack and pop it back later. This can be accomplished with the gsave, and grestore operators.

Language Concepts
As a programming language, PostScript is particularly simple. There are really only a few concepts that need to be sketched out.

Comment
A comment in PostScript is any text preceded by a “%”. The special comment “%!” as the first two characters of a PostScript program is seen as a tag marking the file as PostScript code by many systems (including Unix’s lpr command). It is a good idea to start every PostScript document with a “%!”... doing so will ensure that every spooler and printer the document may encounter will recognize it as PostScript code.
Stack
There are several stacks in a PostScript system, but only two are important for this guide: the operand stack, and the dictionary stack. The operand stack is where arguments to procedures (or operators, in PostScript jargon) are pushed prior to use. The dictionary stack is for dictionaries, and it provides storage for variables.
Dictionary
A dictionary is a collection of name-value pairs. All named variables are stored in dictionaries. Also, all available operators are stored in dictionaries along with their code. The dictionary stack is a stack of all currently open dictionaries. When a program refers to some key, the interpreter wanders down the stack looking for the first instance of that key in a dictionary. In this manner, names may be associated with variables and a simple form of scoping is implemented. Conveniently, dictionaries may be given names and be stored in other dictionaries.
Name
A name is any sequence of characters that can not be interpreted as a number. With the exception of spaces and certain reserved characters (the characters “(”, “)”, “[”, “]”, “<”, “>”, “{”, “}”, “/”, and “%”) any character may be part of a name. The name may even start with digits (1Z is a name, for example), but you can get into problems with them (1E10 is a real number). A name is seen as being a reference to some value in a dictionary on the dictionary stack.

It should be noted that there are a couple of names that are legal in PostScript which do not follow the above definition. These are the “[” and the “]” operators. Yes, they are operators and are stored in the dictionary. Some other names that might surprise you are: “=”, “==”, “<<”, and “>>”.

If a name is preceded by a slash, PostScript will place the name on the stack as an operand. If the name has no slash, the interpreter will look up its value in the dictionary stack. If the value is a procedure object, the procedure will be evaluated. If the value is not a procedure, the value will be pushed onto the operand stack.

Number
PostScript supports integers and reals. You can express numbers in two forms: radix form, and scientific notation. Radix form is a number of the form radix#value where radix specifies the base for value. Scientific notation is the standard mantissaEexponent form used in most languages.
String
Strings are, of course, just strings of characters. There are two ways of expressing strings in Level 1 PostScript. The most common way is to wrap your text in parentheses. For example the string “This is a string” would be written as (This is a string). You can also express a string as hexadecimal codes in angle brackets. For example, the string “ABC” would be expressed as <414243>. There are several escape codes that may be used in the parenthesis format of strings.
Array
Arrays in PostScript are like arrays in any other language. Arrays may contain objects of different type, and they are written as a list of objects surrounded by brackets. For instance, [12 /Foo 5] is a three element array containing the number 12, the name Foo, and the number 5.
Procedure
A procedure is your way of defining new operators. A procedure is an array that is executable and is written with braces rather than brackets. For example, a procedure to square the top element on the stack might be written as: {dup mul}. We can define this procedure to be the square operator with: /square {dup mul} def.

Programming in PostScript
Programming in PostScript is really pretty easy. The fundamentals are that you push operands onto the operand stack by naming them, and then you invoke the operator to use them. That’s really all there is to it. The real art is knowing which operator to use. Operators to draw and put text on the screen will be covered later, and these make up the bulk of PostScript code, but there are a couple that are used mainly for maintaining the program itself.

The first of these operators is def. “def” is responsible for entering a definition into the top-most dictionary on the dictionary stack. The top operand on the operand stack is the value, and the operand below the value is the key (and should be a name). Let’s say that we wanted to define the name “x” to have a value of 5. The PostScript to do this is: /x 5 def. Notice the use of the slash on the “x”. The slash ensures that the name “x” will be pushed onto the stack and not any value it may already have in the dictionary stack.

“def” is also used to define new operators. The value in this case is just a procedure. The following code defines an operator “foo” which adds its top-most two operands and multiplies the result with the next operand on the stack: /foo {add mul} def. Remember, operators that return results push them onto the stack, where they may be used later.

An important point to know when defining procedures is that the elements in the procedure are not evaluated until the procedure is invoked. That means that in the procedure {1 2 add 3 mul}, the actual names “add” and “mul” are stored in the array that is the procedure. This is different from an actual array in which the components are evaluated when the array is created. For contrast, the array [1 2 add 3 mul] contains one object: the number 9.

This delayed evaluation of procedure components has two important effects. First, the definition of an operator used in a procedure is the one that is in effect when the procedure is run, not when it is defined. Second, because each operator has to be looked up each time the procedure is invoked, things can be a little slow. Fortunately, PostScript provides a handy operator to replace each name in a procedure object with its current definition. This operator is called bind, and it can speed up your program considerably. Bind is typically used as:

/foo {add mul} bind def

This defines foo to be a procedure array with two components: the procedures for add and mul. Note that, if add or mul is re-defined after defining foo, foo will have the same behavior as before. Without the use of bind, foo’s behavior would change.

Drawing and Filling Shapes
Principles

The main purpose of PostScript is to draw graphics on the page. One of the elegant aspects of PostScript is that even text is a kind of graphic. The main task that must be mastered, then, is constructing paths which may be used to create the image.

To draw and fill shapes, the basic sequence is:

* Start the path with the newpath operator.
* Construct the path out of line segments and curves (the path need not be contiguous).
* Draw the path with the stroke operator or fill it in with the fill operator.

This basic sequence can be modified to do more complicated things as we will see later.
Drawing a Box

In this first example, we will draw a square inch box toward the lower left corner of the page. We start off by defining a function to convert inches into PostScript's main unit, the point (a point is defined in PostScript as 1/72th of an inch, which is slightly shorter than a true printer’s point of 1/72.27 inch). The conversion is simple, we just multiply the number of inches by 72. This gives us the function

/inch {72 mul} def

To actually draw the square, we start a new path and move the current point to a point an inch in from both margins. This is accomplished with the code:

newpath
1 inch 1 inch moveto

At this point, the path contains only the point (72, 72). We add in line segments leading away from this point with the lineto operator. This operator adds a line segment from the current point to the point specified to lineto and makes that point the new current point. We can build three sides of the box as follows:

2 inch 1 inch lineto
2 inch 2 inch lineto
1 inch 2 inch lineto

We can add the last line by telling PostScript to close up the path with the smallest possible line segment. The closepath operator does this. This operator is especially useful if you need a closed figure for filling. Once we have closed the path, we can draw it with the stroke operator. We finish off the example by ejecting the page (if you are using a printer). PostScript ejects a page with the showpage operator:

closepath
stroke
showpage

You can view and try the complete example, if you like.
Refinements

The lineto operator works in absolute coordinates within user space. That is, 72 72 lineto adds a line segment from the current point to the point (72, 72) in user space. In drawing the box, however, it is more convenient to ignore the absolute coordinates of the box's vertexes and think instead of the lengths and directions of its sides. Fortunately, PostScript provides a version of lineto which takes relative coordinates instead. This is the rlineto operator. rlineto adds the coordinates given as operands to the coordinates of the current point in the path to find the destination point. That is, 10 20 rlineto will draw a line from the current point to a point 10 points to the right and 20 points toward the top of the page. This is in contrast to 10 20 lineto which adds a line segment which always ends at (10, 20).

To see how we can use rlineto, let's replace the lineto lines in the last example with the following code:

1 inch 0 inch rlineto
0 inch 1 inch rlineto
-1 inch 0 inch rlineto

This new example will draw the same figure, but it draws the lines using relative coordinates instead of absolute. This makes it a little easier to visualize and has the added benefit that the same code can draw the three lines at a different location. Note that a negative relative x coordinate moves the point in the left direction while a negative relative y coordinate moves the point down the page.
Filling Shapes

Filling a shape is just as easy as drawing it. You create the path using the standard path creation operators, but instead of calling stroke at the end, you invoke the fill operator. The fill operator will fill the path with the current ink settings. If you want to fill a shape with a pattern, you will need to do some special tricks which we will cover later. We will use the box from above as an example, but we replace the original invocation of stroke with fill.

Fill uses a simple winding rule (which is described in the Programming Language Reference Manual) to determine what parts of the page are inside or outside the path. The regions that are inside are painted. Note that arbitrarily complex shapes can be filled with this operator so long as you have enough memory on your PostScript interpreter. You can easily fill in different shades and even some patterns, but to fill an area with a complex image takes some special effects which we will cover later.
Shading and Width

In PostScript, you can view lines as being drawn by pens that have a given width and ink as having particular shades. You are not restricted to completely black ink and one-point wide lines. PostScript provides two handy operators to change these characteristics.

The setgray operator sets the intensity of the ink used in drawing lines and filling shapes (actually, setgray affects all subsequent markings made on the page). setgray takes a single numerical argument between 0 and 1. “0” signifies black, and “1” signifies white. Numbers between these two values signify various shades of gray.

The setlinewidth operator does just what its name suggests: it sets the width of lines to be drawn. It takes a single numerical argument which is the width of the line in points. setlinewidth affects all lines stroked after the operator is invoked.

Both of these operators affect the markings placed on the page after they are called... they do not effect the path until it is stroked or filled. In particular, you can not set the width or gray level for one part of the path and then change it for another... they are the same for all parts of the path, since it is stroked or filled only once. Also, both of these operators affect part of the graphics state and can be saved with gsave and restored with grestore.

I have worked up an example using both these operators. I also demonstrate how you can use gsave and grestore to control the graphics state.

Putting Text on the Page
Printing text on a page is, understandably, a simple process. It consists basically of these main steps:

* Set up a font to use
* Set the current point to where the lower left corner of the text will be
* Give the string to print to the show operator

The show operator is the basic operator for printing strings of text. It takes a string and prints it out in the current font and with the lower left corner at the current point. After the text has been printed, the current point is at the lower right of the string.
Fonts

Fonts in PostScript are actually dictionaries. A font dictionary contains several operators. Most of these operators simply set up the path for a single character in the font. When PostScript needs to typeset an “A” in the current font, it finds the operator specified in the font for “A” and invokes it. This operator goes about the business of drawing the letter. This means that there is no fundamental difference between letters and any other kind of ink on the page: text is graphics. Furthermore, since a font is essentially just a program to draw things, the current graphics state applies to text just as much as it applies to lines and curves which your program draws. This is one of the most powerful features of PostScript, as we will see later.

The fonts themselves are stored in a special dictionary of fonts, and they are named. If you want to retrieve a font by name, you need to use the findfont operator. findfont retrieves the font from the dictionary (if it is there) and leaves the font on the stack. You can then specify how big the font should be and make it the current font. The basic process for setting the font is:

* Retrieve the font from the dictionary with findfont,
* Set the size of the font with scalefont,
* Make this new font the current font with setfont

scalefont takes two arguments, the lower argument on the stack is a font dictionary while the second is the size of the new font in points. scalefont returns a new font dictionary which is the same as the old one but scaled to the given size. setfont, on the other hand, takes a font dictionary and makes it the current font.

For example, let us say that we want to start typesetting in Times Roman, and we want it to be set to 20 points. The following code would set up the correct font:

/Times-Roman findfont % Get the basic font
20 scalefont % Scale the font to 20 points
setfont % Make it the current font

Since the font “Times-Roman” is stored in a dictionary, we search for it using its PostScript name. Your printer will usually come with a set of built in fonts and will almost always allow you to add more. The names of the fonts available will vary from printer to printer, but Times is almost always present. Fonts typically come in families. “Times” is the name of the family we used here, and it has four member fonts: Times-Roman, Times-Italic, Time-Bold, and Times-BoldItalic.
Showing Text

The show operator is used to typeset text on the page. It takes a single argument: a string containing the text to be typeset. Text can be considered to be part of the path, so you must also have set the current point with call to moveto or an equivalent operator. A typical call to show might look like this:

newpath % Start a new path
72 72 moveto % Lower left corner of text at (72, 72)
(Hello, world!) show % Typeset "Hello, world!"

If we ran this code right after the font selection code above, we would get the string “Hello, world!” printed an inch in from the lower left corner, and it would be printed in 20 point Times-Roman. You can actually try this example.

Adding Color
In recent years, color printers have become more common... to the point where it is almost impossible to buy a black-and-white printer. Fortunately, PostScript handles color documents quite easily, and you do not have to learn much to add color to your documents.

There are many, many ways to specify color. The science of color reproduction and perception is very complex and encompasses physics, chemistry, physiology, and psychology. PostScript provides a great deal of flexibility on this front, providing several different methods for specifying color to let you get as close as possible to the color you want specifying it in the way that is most natural in your application. I will discuss only two methods here, however, because—frankly—I know as much about color as a bee knows about ancient Phoenician.
RGB

The first method I will mention is the so-called RGB colorspace. In this model, you specify the red, green, and blue components of the color you want to reproduce. This is model specifies color using the additive primaries and will be very familiar to those who work with monitors and computer graphics.

To specify a color using the RGB color space, you can use the setrgbcolor operator. This operator takes three operands: the red, green, and blue components of the color you want (0 means none, 1 means maximum). For example, to specify red, you can write 1 0 0 setrgbcolor; and to get a dark yellow, you can write 0.5 0 0.5 setrgbcolor. Black is 0 0 0 setrgbcolor, and white is 1 1 1 setrgbcolor.
CMYK

Another way to specify color is through the CMYK colorspace. In this model, you specify color using the subtractive primaries more common in the printing world: cyan, magenta, and yellow. To the primaries, a black component is added, to allow you to control the tone of the color (this is not necessary in the RGB model, since you are controlling the intensity of the light inherently).

To specify a color using the CYMK color space, you can use the setcymkcolor operator. This operator takes four operands: the cyan, yellow, magenta, and black components of the color you want (0 means none, 1 means maximum). For example, to specify red, you can write 0 1 1 0 setcymkcolor; and to get a dark yellow, you can write 0 1 0 0.5 setcymkcolor.

One convenient property of PostScript is that color is handled as a property of the ink in the graphics state just like the gray level. In fact, the gray level set by setgray is really just color. What this means is that you can set the color of a line, or the color of a fill in exactly the same way as you set the gray level. You just call the operator before you stroke the line or fill the path. You can even use it to set the color of text by calling the appropriate operator before you call show.

Since color works in such a similar way to the setgray operator, I am providing you with a complete example, but I will not break it down here.
A Warning

I have really simplified things considerably in this discussion. There are more than just two color spaces in PostScript, and there are several features in PostScript to allow for accurate color rendition. One thing that I’ve glossed over is that different devices reproduce color with different degrees of accuracy (and different pigments not only have different color-accuracy but will vary over time). Another thing that I have glossed over is the fact that these two models are focused around color reproduction: it is also possible to specify color based on how it is perceived.

If you do not care about color reproduction to that level of precision, then you do not need to worry about it. The color operators I have described are sufficient. If you do, you know far more about the matter than I do and will likely find the features you need described in the PLRM.

Transformations
The PostScript interpreter keeps track of a matrix called the current transformation matrix. When constructing an image, the interpreter uses this matrix to convert the world coordinates used by the program into device coordinates used by the printer itself. Generally, the actual contents of the matrix are of little interest to a well-written PostScript program; the reason for this is that the specific contents are device-dependent. A program that uses them might not work properly. PostScript does provide a number of operators, however, that transform the matrix in a device-independent way. These operators allow you to transform the way user space maps onto device space, and they modify the current transformation matrix with a simple matrix transformation. The basic transformation operators are:

* rotate
* translate
* scale

It is useful to realize that the current transformation matrix (and, hence the effect of all these operators) is part of the current graphics state and can be saved and restored using the gsave, and grestore operators. In addition, the transformations on the matrix affect path components constructed after the transformation. Even if a path is only partially constructed when a transformation is invoked, the parts of the path that were in place before the transformation will be unaffected.
Rotate

The rotate operator takes a single, numerical operand. This operand specifies how many degrees to rotate the user space around its origin (positive values specify counter clockwise rotations). This transform allows you to do some pretty neat tricks. For example, let’s say you have written a routine to draw some complex shape; and you have found that you need to draw it several times at different angles. In a more primitive graphics system, you might need to re-write to routine to take an angle as an argument, but in PostScript you only need to rotate the coordinates with the rotate operator.

As a concrete example, let’s say you want to draw lines in a circular pattern so that each line is ten degrees from its neighbors. Rather than figure out the coordinates for each of the 36 lines, we can just draw a horizontal line and rotate it repeatedly to different angles. To do the repeated looping, we can use the for operator. The for operator takes four arguments: an initial index value, a step size, a final index value, and a procedure. The operator increments an index from the initial value to the final value, incrementing it by the step size. For each index value, for will push the index on the stack and execute the procedure. This gives you a simple means of looping.

We start by setting up the for loop. At the beginning of the loop’s procedure, we start a new path and save the graphics state.

0 10 360 { % Go from 0 to 360 degrees in 10 degree steps
newpath % Start a new path
gsave % Keep rotations temporary

We next set the start of the line to (144, 144) and rotate the coordinates, we do not rotate before moving because (144, 144) would then be in a different location.

144 144 moveto
rotate % Rotate by degrees on stack from 'for'

We next draw just a horizontal line:

72 0 rlineto
stroke

Finally, we restore the old graphics state and end the loop.

grestore % Get back the unrotated state
} for % Iterate over angles

Translate

The translate operator takes two operands: an x-coordinate, and a y-coordinate. The translate operator sets the origin of user space to the point that was at the given coordinates in user space. The main use of the translate is to draw copies of a shape in different locations. Typically, a shape will be constructed at the origin, and the shape will be translated to the correct location before it is to be drawn. A simple example translates a box constructed at the origin to the point (72, 72) in the original user space.
Scale

The scale operator takes two arguments: an x scale factor, and a y scale factor. The operator scales each coordinate by its associated scale factor. That is, if you have an x scale factor of 0.5 and a y scale factor of 3, the x coordinate will be reduced by a factor of two while the y coordinate will be magnified by a factor of 3. This operator allows you to change the size and dimensions of objects quite easily.

A simple example can just scale text in a couple of ways: We can make things narrow:

gsave
72 72 moveto
0.5 1 scale % Make the text narrow
(Narrow Text) show % Draw it
grestore

We can make things tall:

gsave
72 144 moveto
1 2 scale % Make the text tall
(Tall Text) show % Draw it
grestore

We can distort the text completely:

gsave
72 216 moveto
2 0.5 scale % Make the text wide and short
(Squeezed Text) show % Draw it
grestore

Combining Transformations

Each of these transformations merely modifies the current transformation matrix. This means that these operators can be combined for some interesting effects. For example, you can take a normal document and print two of its pages on a single page (reduced and placed side-by-side) simply by translating the first page to one side, rotating the page by ninety degrees and then reducing the page so that it fits. The second page is handled in the same manner, but is translated to the other side of the page. This can be easily done by PostScript post-processors so long as they know where one page ends and the next begins (this is often accomplished using special comments). A somewhat simpler example is to draw a simple box and some text translated, rotated, and scaled in various ways. An important thing to remember when viewing this example is that translations are always relative to the current user space. This means that

0.5 0.5 scale
72 72 translate

will have a different effect on the image than does

72 72 translate
0.5 0.5 scale

In the first case, the origin will be half an inch in from the bottom and left margins. In the second case, the origin will be an inch in from the two margins.

Clipping for Effect
Within the graphics state of a PostScript system is a special path called the clipping path. Every bit of ink to be placed on the page is checked against this path. If PostScript determines that the ink would go outside the current clipping path, that portion of ink is ignored. If the ink would be within the clipping path, it is actually placed on the page. For the mathematically inclined, the clipping process is intersection: the set of pixels to be painted is intersected with the set of pixels within the current clipping path to get the set of pixels to paint. For objects that are partly inside and partly outside the clipping path, the natural implication is that only the part that is within the clipping path is drawn.

By default, the clipping path is defined to be a rectangle just within the boundary of the page (usually it is set to about a quarter of an inch). You can set your own clip path by constructing the path with the normal path construction operators and invoking the clip operator. There is only one difficulty: once you reduce the size of the current clipping path, there is no way to expand the size of the clipping path with clip. The only way to go back to a larger clipping path is to save the one you would like to restore with gsave and restore it later with grestore. In fact, it is always good policy to only set a clipping path withing a bracketing gsave/grestore pair. You will always be safe if you do this.
Clipping a Simple Path

As a simple example of clipping, let us say that we want to draw a box and fill it with text in such a way that some text is cut off. The effect we are wanting is that of a hole in a piece of paper over some newsprint, say. This can be done quite simply.

First, we set up the box to act as our window. We can set up the path, stroke it if we want to see it, and then clip to it:

gsave % Save the old clip path
72 72 box % Set up our box
gsave % Don't allow box to be lost after stroke
stroke
grestore % Restore the box path
clip % Clip to the box

The clip path is now established, and we can now go on to draw the text that should be clipped (note that there is a leading gsave... this is to keep us from loosing our old clip path which covered the whole page).

60 60 moveto
(This is Times-Roman clipped to a box) show
70 90 moveto
(This is Times-Roman clipped to a box) show
50 120 moveto
(This is Times-Roman clipped to a box) show

Once we have finished, we can just do a grestore to clean up after ourselves.

While there are some implementation limitations on the complexity of the clip path, in general you can have very complex paths... not just squares. Arcs, lines, even text can be used to create the clip path.
Clipping to Text

There may come a time when you will want to do some special effects with text. For example, you might want to print out “July 4” using letters that look like the flag. This is fairly easy to do using clipping. A somewhat simpler problem would be to draw text that looks like a sunburst (that is, the text is filled with a sunburst pattern). This is also fairly easy to do once you know how to clip to text. The secret is an operator called charpath. This operator takes a string and a Boolean and builds the path at the current point that would trace out the text of the string. The path, once created, can be stroked, filled, clipped, or any other combination of things; it is, after all, just a path. The Boolean which charpath requires is for handling special kinds of fonts, and it is generally left true.

As before, the steps to this example are to build the path, clip to it, and draw the image needing to be clipped.

Here we build the path by setting up our current point and string, and then invoking charpath:

gsave % Save old clip path
/Times-Roman findfont 60 scalefont setfont
72 72 moveto (Clipping) true charpath % Set up the text's path

Once we have the path, we can invoke clip to establish the complex path of the text as the current clip path. With the clip path established, we can draw our sunburst, which will be confined to the area inside the text:

clip
174 72 translate % Set our origin to middle
0 2 360 { % For every second degree of circle
newpath
gsave
rotate % Rotate to angle
0 0 moveto % From new origin
300 0 rlineto % Setup a 300 point long line
stroke % ... and draw it
grestore
} for

Again, because of our judicious use of gsave and grestore, a simple grestore cleans up the graphics state when we're done.

grestore

As you might imagine, this sort of effect is very powerful and can make it very easy for you to create some stunning images.

Raster Graphics
One of the common questions I have gotten over the years is how to handle other graphics file formats in PostScript. People often ask about including GIFs, JPEGs, and the like in a PostScript file. While this sort of thing is really beyond the scope of this guide, the basics of handling so-called raster graphics is not.
Raster Graphics Basics

Raster graphics is that style of graphics in which the image is broken up into a matrix of picture elements (pixels). The matrix will have a certain number of rows, each containing a certain number of pixels. Each pixel can be assigned any of a number of colors. The number of colors depending upon the “depth” of the image, often expressed as the number of bits needed to encode all the colors. Typical bit depths used today are: 1 (two colors, usually black and white), 2 (four colors, usually shades of gray), 4 (16 colors), 8 (256 colors), 16 (65,536 colors), 24 (so-called true color), and 32 (more colors than you can shake a stick at).

The numbers of rows and columns gives you the resolution. If there are c columns and r rows, the image is referred to as a r x c image. If the image is to have a certain physical size, this size combined with the number of pixels give you the number of dots-per-inch (DPI) of the image, which is a measure of its resolution. The higher the DPI, the smaller the dots, and the harder it is to see them as individuals.

Raster graphics are convenient in that they can represent photo-realistic images quite easily, but they have limitations. Because the pixels are arranged in a regular pattern, weird moire patterns can appear if they are displayed on a monitor incorrectly, or if they represent an image with a regular pattern that interacts badly with the pattern of the pixels. Likewise, if the resolution is too low and the contrast is too high, certain pixels can stand out and leave the image with the “jaggies.”
Raster Graphics in PostScript

Most graphics work in PostScript is done in vector graphics style. This style of graphics is where the image is composed of lines and curves that are described mathematically. It is the style of graphics we have used throughout the guide. The advantage of vector graphics is that you can do all sorts of mathematical operations on the image (rotate, scale, etc.) and still get a decent image. An implication of this is that vector graphics are device independent, since they do not care about the display resolution of the display device. Still, PostScript recognizes the need for support of raster graphics, and so it provides a set of operators just to display raster graphics.

The main operator is image, and it is fairly complex. Go grab yourself a cup of coffee, stretch your legs, and prepare to tuck in.

image takes five arguments that describe the image to be displayed and paints that image in a square with one corner at (0, 0) and the other at (1, 1) in the current coordinate frame. All the operands describe the image data and how it should be used to fill up that square. Of course, you probably do not want to draw images in the unit square at (0, 0) all the time, so you must use scale, rotate, and translate to move the unit square to the desired location (and size).

The image operator is used in the following way: width height depth matrix data image -. The operands width and height define the size and shape of image matrix in terms of pixels (in the image data, not the display results). The operand depth describes the number of bits per pixels and, hence, the number of shades of gray. Legal values here are 1 (black and white), 2 (four shades), 4 (16 shades), 8 (256 shades), and 12 (4,096 shades). The operand matrix is a PostScript transform matrix that maps from the unit square to the image’s pixel coordinates. The image’s coordinates go from (0, 0) in the lower left to (width, height) in the upper right. The last operand, data is the source of the actual image data. In Level 1 PostScript, this is a procedure, but it can be any number of things in Level 2 and Level 3. Just sticking with Level 1 for now, this procedure is called to fetch all the data for the image, as needed. The procedure returns a string, and the bits within the string are taken and dismantled to create the image. If the procedure does not return enough data to cover the whole image, it is called repeatedly until all the pixels are accounted for. The order at which the pixels are handled is left to right, bottom to top.

Clear? I didn’t think so. Let’s take a look at a simple example that will show you the basics. Let’s draw a simple smiley face. First, let’s take a look at how the smiley face will be laid out in the matrix:
. . X X X X . . C3
. X . . . . X . BD
X . X . . X . X 5A
X . . . . . . X 7E
X . X . . X . X 5A
X . . X X . . X 66
. X . . . . X . BD
. . X X X X . . C3

The left eight columns are the eight columns of the image. The “X” represents a black pixel, and the “.” represents a white pixel. Since black is represented by a 0 in PostScript, and white by a 1, we can convert this 8x8 matrix into an eight byte sequence. The ninth column is the hexadecimal encoding of the row... taking the others columns as a binary number with the dots representing 1’s and the X’s representing 0’s.

Now, let’s take this image data and try to build up an actual image. First, we need to map the unit square to the location we want to show the image in. Let’s make the image a 1 inch square image with the lower left corner at (72, 72).

gsave % We're mucking about with graphics state... save the original
72 72 translate % position the lower left at (72, 72)
72 72 scale % make the image 1 inch square

Now, we set up the actual image data.

8 % 8 columns in the image
8 % 8 rows in the image
1 % 1-bit per pixel: black and white
[8 0 0 8 0 0] % map the unit square to (0, 0) - (8, 8)
{} % the image data as a hex-encoded string
image % actually draw the image
grestore

Note that the pixel data maps left to right the same way the bits do when you write them in binary. That is, the left-most pixel for a given byte in the data maps to the left-most bit in the byte. Also, note the funny way the string is specified. It is written in hexadecimal using the < and > notation instead of the more usual parenthesis notation. This notation indicates that what is contained between the < and > is a string of 8-bit data bytes encoded in hex. You will see this notation fairly often in working PostScript, since it is a convenient way to store binary data in an ASCII format.
A Gradient

This example is all well and good, but it is just black and white. How do you deal with gray scale images? The procedure is similar, you just specify a different bit depth and lay out your data in a slightly different manner (instead of a single bit per pixel, you will now need to map multiple bits per pixel. As an example, let’s try to make a horizontal gradient fill that goes through sixteen different shades:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Sixteen different shades implies 4 bits per pixel, which means that this data can be represented in 8 bytes again (2 pixels per byte). Encoded in hexadecimal again, the data for the above gradient is: 0123456789ABCDEF. Now, we just need to do with this data what we did before, with one exception. The image data no longer represents an 8x8 image, instead it represents a 16x1 image that is 4 bits deep... we need to modify the settings accordingly. Also, instead of scaling this image to a 1 inch square, let’s make it 2 inches high by 1 wide and set it next to the smiley face:

gsave
216 72 translate % lower-left of images at (216, 72)
72 144 scale % size of rendered image is 72 points by 72 points
16 % 16 pixels wide
1 % 1 pixel high
4 % 4 bits per pixel
[16 0 0 1 0 0] % transform array... maps unit square to pixels
{<0123456789ABCDEF>} % the image data itself
image % let's draw!
grestore

Note that, even though the image data is for a one line image, we can scale that single line to fill just about any area. By the way, drawing with the image operator is very much like drawing with any other operator. In particular, clipping can be used to control what parts of the page can be filled by image, so you can use it to do interesting effects like shapes (or text) with gradient fills or with a photographic image as a fill pattern.
The Basics of Color

So, these examples are nice and all, but they are in dull monochrome. What if you want to do color? PostScript does include a handy operator for color images called, creatively enough colorimage. The colorimage operator adds a number of operands to handle the addition of color and to provide for a number of ways of supplying the color data.

The first thing to consider is how you want to specify the colors. Is your image grayscale? RGB? CMYK? This information will indicate the number of color channels you need. Grayscale takes one. RGB takes three (one for red, one for green, and one for blue). Finally, CMYK takes four: cyan, magenta, yellow, and black. Next, you need to think about how these channels are going to be provided to the colorimage operator; will they be interleaved into a single data source string, or will they be broken out into separate data sources. These two decisions will determine the number of additional operands to colorimage: one specifies the number of channels, one specifies whether the channels are separate or interleaved, and then there is one for each channel data source.

To make this a bit more concrete, let’s take a look at a color gradient, which will be a variant of the previous gradient:
Gradient: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Red: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Green: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Blue: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

So, we will now lay this information out in a very similar manner to the original gradient. The example, however, will use three color channels, and they will be provided by separate data sources:

gsave
360 72 translate % set lower left of image at (360, 72)
72 144 scale % size of rendered image is 72 points by 72 points
16 % number of columns per row
1 % number of rows
4 % bits per color channel (1, 2, 4, or 8)
[16 0 0 1 0 0] % transform array... maps unit square to pixels
{<0000000000000000>} % the red image data
{} % the green image data
{<0123456789ABCDEF>} % the blue image data
true % pull channels from separate sources
3 % 3 color channels (RGB)
colorimage
grestore

Note that the bits-per-pixel operand is really a bits-per-pixel-per-channel operand. This is really no different than for image, it is just that image always works with a single channel. In fact the call:

w h bpp matrix data image

is exactly equivalent to:

w h bpp matrix data true 1 colorimage

Wrap-up

You have now seen a basic example of three different types of raster graphics in PostScript (you can view a complete example of all three). This is only a start, however.

Encapsulated PostScript
What is Encapsulated PostScript?

At some point, you may want to include some nice PostScript image into a document. There are a number of problems associated with this, but the main one is that your page layout program needs to know how big the image is, and how to move it to the correct place on the page. Encapsulated PostScript (EPS) is that part of Adobe’s Document Structuring Convention that provides this information.
What Is the Document Structuring Convention?

The DSC is a special file format for PostScript documents. The full details for the DSC can (and should) be gotten from Adobe. If you are writing a PostScript printer driver or other utility which will be used by a large number of people to create or manipulate PostScript documents, do not even think about writing it without making it DSC-compliant. You will save yourself and your users a lot of headaches.

Although the full DSC is beyond the scope of this guide, the most basic rules can be explained. A DSC-compliant document is an ordinary PostScript document with a number of comments added. These comments provide information to any post-processors which work with the files. Some comments strictly provide information, others are used to structure the document into sections, which may be shuffled or processed in other ways by the post-processor.

Every DSC-compliant document is indicated by having the comment %!PS-Adobe-3.0 as the first line. This comment is a flag to indicate that the document is compliant. You should never use this comment unless your document really is DSC compliant. There are many other parts to proper DSC. A document which follows the DSC can be manipulated in many ways. In particular, post-processors can shuffle the pages, print two or more pages on a side, and so on. The printer drivers from some notable companies do not follow the DSC, and their PostScript documents are, therefore, impossible to work with once they’ve been generated.
Now, What About EPS?

An EPS file is a PostScript file which follows the DSC and which follows a couple of other rules. These rules can be summarized as follows:

* The first line must be %!PS-Adobe-3.0 EPSF-3.0
* The file must make use of the BoundingBox comment
* The file should be a single page image (in DSC terms, the %%Pages comment must have a value of 0 or 1).
* The file should not use any operators which affect the global state.
* Finally, the EPS file should not use showpage. Actually, Adobe says that it is fine to use showpage in your EPS files. Officially, it is the responsibility of the importing application to redefine showpage so that the EPS file does not actually eject the page. Still, in creating EPS files, it would be wise not to use this operator.

BoundingBox

The BoundingBox comment is used in DSC to indicate where the actual image will be on a page. The comment describes a rectangle which completely encloses the image. The form of the comment is: %%BoundingBox: llx lly urx ury. For instance, suppose I have an image which extends from x=72 to x=144 and from y=150 to y=170. The BoundingBox comment in the document should then be: %%BoundingBox: 72 150 144 170.

Monday, 8 October 2007

PostScript语言

PostScript(PS)是主要用于电子产业和桌面出版领域的一种页面描述语言和编程语言。 PostScript是Adobe公司开发的一种设备无关的打印机程序语言,用来驱动数字印刷机和显示。

历史

PostScript语言的思想起源于John Warnock1976年在著名的计算机图形公司Evans and Sutherland时的想法。当时John Gaffney正在开发一个解释纽约港大型三维图形数据库的解释器。Gaffney设计了非常类似于Forth编程语言的Design System语言来处理图形。

1978年Evans和Sutherland要求Warnock离开旧金山湾到犹他州总部去,但是他并不想搬家到那里去。于是他后来加入了Xerox PARC与Martin Newell一起工作。他们重写了Design System开发出了用于VLSI设计和字体与图形打印研究的JaM (John and Martin)系统。这项工作后来发展成为一个名为InterPress的扩展系统。

在1982年12月Warnock和Chuck Geschke一起离开创建了Adobe Systems公司。他们开发了一种类似于InterPress名为PostScript的更简单的语言,这种产品在1984年推向市场。大概在这个时候,Steve Jobs参观了他们的工作,他敦促他们改进PostScript作为驱动激光打印机的语言,它添加到Canon打印机诞生了LaserWriter。

1985年3月,Apple LaserWriter是第一款带有PostScript的打印机,这也带来了二十世纪八十年代中期的桌面印刷革命。它的技术优点和广泛应用使得PostScript成为打印应用领域影像输出的一个选择。直到二十世纪九十年代,PostScript语言解释器(有时称作RIP(光栅图像解释器))曾经一度成为激光打印机的一个普通组成部分。

随着使用电子方式发布文档最终版本成为事实上的标准,PostScript就在这个领域不断地被它的后续版本Portable Document Format也就是PDF所超越,到了2001年更少有打印机支持PostScript,这主要是由于来自于非PostScript的廉价喷墨打印机的不断加剧的竞争(PostScript解释器将大幅度地增加打印机成本),以及在计算机上使用软件翻译PostScript图像的新方法可以用于任何的打印机,PDF就是这种方法之一。然而使用 PostScript的激光打印机仍然可以大幅度地减少计算机在打印、从计算机到打印机传输翻译出的PostScript图像方面的工作量。

PostScript经历了两次主要的更新。第一版称为PostScript Level 1在1984年发布。PostScript Level 2在1991年发布,它有几项增强的特性:提升了速度和可靠性;支持RIP内的分割;支持接压缩,这就意味着如JPEG这样的图像能够直接在PostScript程序中进行处理;支持复合字体以及缓存重用内容的Form机制。PostScript Level 3在1997年年底出现,许多旧版操作符变成了基于字典的新版本,它提供了更好的颜色处理以及新的允许在程序内进行压缩和解压的过滤器、程序chunking以及先进的错误处理。

在打印中的应用

在PostScript出现之前,打印机设计成将字符——通常是ASCII字符——打印出来。有许多技术用于这项工作,但是大多数都有一个共性也就是字符在物理上很难更改,就像在打字机键上的金属或者光学平板那样的条带。

随着点阵打印机的流行发生的一些变化,在这些系统上字符是用一系列的点“画”出来的,这些点在打印机中定义为字体表。随着他们越来越复杂,点阵打印机开始包含有几种内置的字体,用户可以选择所用字体,有一些型号甚至允许用户下载自己的字符图形到打印机中。

点阵打印机也带有打印光栅图形的能力,图形在计算机上进行解释并且使用一系列的转义序列将它们按照一系列的点发送到打印机。这种打印机控制语言所这打印机的不同而不同,这就要求程序员创建许许多多的驱动程序。

真正的图形打印是名为绘图仪的特殊的设备所完成的,绘图仪的确是共享一种常见的语言——HPGL,但是除了打印图形之外并没有多大用途。另外,它们通常价格昂贵,速度较慢,所以使用很少。

PostScript将打印机和绘图仪的优点组合在一起从而打破了传统。同绘图仪一样,PostScript具有高质量的曲线处理能力并且控制语言简单能够用于不同品牌的打印机;同点阵打印机一样,PostScript提供了一个生成文本和光栅图形的简单方法。与它们二者不同的是, PostScript能够将所有这些不同的内容放在同一页上,这样就比以前的打印机或者绘图仪提供了更具灵活性。

PostScript已经超出了普通的打印机控制语言,并成为一个完善的编程语言。许多应用程序能够将文档传送到一个PostScript程序中,它的输出结果就是原始文档。这个程序能够发送到打印机中的解释器上得到打印文档,或者发送到另外一个应用程序在屏幕上显示文档。由于文档程序与目的地无关,所以就被称为“与设备无关”。

PostScrip也非常擅长于实现rasterization;所有的东西,甚至是文本都可以用直线和立方贝塞尔曲线表示,贝塞尔曲线以前只有在CAD应用中才能见到,它允许任意的缩放、旋转或者其它变换。当解释PostScript程序的时候,解释器将这些指令转换成所需的点形成输出内容。

同PostScript一样复杂的是它的字体处理。丰富的字体系统使用PS基本图形(:en:graphics primitives)将字符画成艺术线条,艺术线条能够在任意的分辨率生成。尽管这听起来是很直观的概念,但是需要考虑许许多多的拓扑图形问题。

其中一个问题是字体在小尺寸的时候实际上并不是进行线性缩放,如果那样的话字体的某些部分就会不成比例地过大或者过小从而字体看起来不太正确。PostScript使用与字形曲线保存在一起的隐含信息避免了这个问题的发生,它们基本上是水平或者竖直方向条带上一些附加信息,用以标识光栅图像生成器需要维护的字体中的重要特征。甚至在很低的分辨率的时候字体也是非常好看;通常认为这是手工字体位图调整才能完成的任务。

当时,在字体中包含这种隐含信息的技术被细心地维护着,包含隐含信息的字体经过压缩、加密成为Adobe的Type 1 Font。Type 1是一个高效的仅仅用来保存字形信息的简化PS系统,而不是一个完善的语言,PDF也是一种类似的情况。Adobe向那些打算在自己的字体中添加隐含信息的厂商征收高额的Type 1技术授权使用费用。那些不愿意使用隐含信息或者不愿支付费用的用户只能使用Type 3 Font。Type 3字体允许使用除了标准的隐含信息之外的PostScript语言的所有复杂特性,后来又添加了一些其它的不同特点。

许多人认为授权的费用过于高昂,并且Adobe也不愿采用更具吸引力的费率,这样就导致了Apple在1991年左右开发了他们自己的系统TrueType。紧随着TrueType的发布,Adobe就公开了Type 1字体的规范。如Altsys Fontographer(1995年1月被Macromedia收购,自从2005年5月归FontLab所有)这样的零售系统加入了创建Type 1字体的能力。从那时开始,就出现了许多免费Type 1字体,例如TeX排版系统中所用字体就是这种格式。

在二十世纪九十年代早期还有其它几种基于字形的字体系统,如Bitstream和METAFONT开发的系统,但是它们都不包括通用的打印解决方案,所以并没有得到广泛应用。

在二十世纪九十年代,Abobe和微软公司一同开发OpenType,它基本上是Type 1和TrueType格式功能的超集。当打印到PostScript输出设备的时候,OpenType字体中不需要的部分就会被丢弃,驱动程序送到设备的内容与传送TrueType或者Type 1字体完全一样,根据OpenType字体中的外形不同而有所不同。

在二十世纪八十年代,Adobe利润的绝大部分都来自于用于打印机的PostScript实现(称为光栅图像处理器或者RIP)的高昂授权费用。RIP相当昂贵,并且通常只在少数一些特定的硬件上运行。二十世纪八十年代中期随着许多基于RISC的新平台出现,Abobe经常是在支持新机器方面落后一步。

因此第三方的PostScript实现变得很普遍,尤其是在授权费用是关键症结的低端打印机或者新硬件激发更快速度要求的高端拍板设备领域更加常用。一方面,微软公司和苹果公司联合起来努力将Adobe从独霸打印机的位置拉下马,微软公司将它购买的TrueImage PostScript解释器授权给苹果公司,苹果公司将它的新字体格式TrueType授权给微软公司。(苹果公司终止了与Adobe保持一致以及它的打印机使用Adobe公司真正的PostScript的策略,但是TrueType在微软视窗和Macintosh上都成为了标准的outline font。)一些第三方的PostScript的克隆产品仍在广泛使用,尤其是在作为惠普黑白激光打印机标准Phoenix Page的中仍在广泛使用。

许多基本的廉价激光打印机不支持PostScript,它们的驱动程序根本不使用PostScript。当这样的打印机需要支持PostScript的使用,可以使用名为Ghostscript的自由软件PostScript解释器。Ghostscript使用主计算机的CPU进行rasterization、将结果作为一个大幅的位图发送到计算机这样一种方式在非PostScript打印机上打印PostScript文档。Ghostscript也可以在计算机显示器上预览PostScript文档以及将PostScript转换成如TIFF和PNG这样的光栅图形或者如PDF这样的矢量格式。

分辨率非常高的设备,如imagesetter或者CTP platesetter超过2500dpi的分辨率也很常见,仍然需要带有大量内存和磁盘空间的外部光栅图像处理器。许多称为数字印刷的高端激光打印机系统也使用外部光栅图像处理器将容易升级的计算机系统与特定的打印硬件分开。如EFI和Xitron这样的公司专业从事这样的光栅图像处理器软件开发。

随着PostScript成为打印输出的事实标准,很自然人们也希望将它用来描述屏幕输出。二十世纪八十年代后期CPU性能的快速提升以及人们对于视窗系统兴趣的逐渐增加,促使人们多次试图开发使用PostScript作为主要的显示技术的显示系统。

使用PS作为显示系统有许多优点,其中之一就是在其它系统上用户不仅仅要为屏幕显示保留位图,而且要为打印机保留Type 1字体,在显示器上使用PS只需要保留一套从而可以弥补这个缺点。另外一个优点是就是允许“dumbling down”打印机。当LaserWiter发布的时候它是苹果公司产品线中功能最为强大也是最为昂贵的机器,这样它就需要相当大的处理能力和内存以在合理的时间内生成高达300dpi分辨率的页面。与之形成对比的是,使用NeXT平台的400dpi打印机根本都没有CPU,相反它是使用计算机的CPU进行页面生成,然后将生成的页面位图传送到打印机。

但是使用PostScript作为视窗系统的一个更为主要的优点是他让用户使用一组图形处理子程序就可以开发桌面印刷和其它大量使用图形的应用程序,在视窗上进行描画的程序同样也可以不经任何转换直接在打印机上描画。传统系统上的桌面印刷应用程序要求程序员在各个平台的图形系统上构建图形用户接口(如Macintosh上的QuickDraw和微软视窗上的图形设备接口 (GDI))编辑器,然后编写另外的程序将图形转换成正确的PostScript语言用于打印。这样的工作通常就会消耗项目的大部分编程工作,并且是程序错误的主要来源。

使用PostScript作为显示技术的两个主要的例子是Display PostScript (DPS)和NeWS,它们两者戏剧性地在在哪里应用显示逻辑发生了分歧,在DPS中view系统留给了OS去处理,然而在NeWS上整个显示系统是用用PS写成的并且在一个单一的复杂解释其中运行。

PostScript语言

PostScript是一个Turing-complete编程语言,通常PostScript程序不是人为生成的,而是由其它程序生成的。然而,仍然可以使用手工编制的PostScript程序生成图形或者进行计算。

PostScript是一个基于堆栈的解释语言(例如stack language),它类似于Forth语言但是使用从Lisp语言派生出的数据结构。这种语言的语法使用逆波兰表示法,这就意味着不需要括号进行分割,但是因为需要记住堆栈结构,所以需要进行训练才能阅读这种程序。大部分运算符(其它程序中称为函数)从堆栈中读取变量,并且将运算结构放到堆栈中。如数字这样的符号:en:Literal具有将它们自身副本放到堆栈的效果。


例如:

3 4 add 5 1 sub mul

将执行 (3 + 4) × (5 - 1) 这样的计算。

让我们详细地分析一下这是如何完成的:

3 和 4 都是符号,它们将自己放到堆栈中,在这两个命令之后,堆栈将变成这样:

4
3

add 是一个运算符,它将堆栈中最上面的两个元素取出(在我们的例子中是3和4)、将它们相加、然后将结果放到堆栈上:

7

下面又是两个符号,它们将把堆栈变成这样(需要注意的是操作仅仅局限在堆栈顶部,下面的元素不受影响):

1
5
7

另外一个运算符 sub,从堆栈顶取出两个元素、第二个减去第一个、然后将结果放到堆栈:

4
7

很显然 mul 同其它两个运算符一样,从堆栈取出两个元素、将它们的乘积放到堆栈:

28


上面的例子只是一个古老的逆波兰表示法计算,当然PostScript也使用变量。详细地说就是它有一个字典用来查找所有不是符号的东西;如果查到的话,那个名字下保存的值就会压缩到栈中(或者更应该说是执行——参见后面的内容);找不到就返回错误。将一个变量放到字典中需要使用def运算符,它用一个名字和一个值作为参数,通过在前面使用斜线构建一个名字。因此

/x1 15 def

首先将名字“x1”放到堆栈上、然后是值15、然后执行def,它将从堆栈中取出“x1”和15,并且将15写到字典中“x1”的下面。后面出现的“x1”(注意不要与“/x1”混淆)将会将15放到堆栈而变量并不改变。下面的代码会将x1的值增加2:

/x1 x1 2 add def

PostScript有几个操作符用于重组或者控制堆栈:复制(dup)、丢弃(pop)和交换(exch)在堆栈顶部进行操作,然而roll旋转堆栈中的某一部分,copy复制某个特定的部分,index允许象数组那样访问堆栈。

{ 和 }提供了一些编程的工具。{将解释器切换到延迟运行模式,所有的东西甚至是运算符和其它的可执行对象都放到堆栈中,其中一个例外就是},它将堆栈中从{开始的所有内容,绑定成一个(匿名)处理过程,然后将它放到堆栈上。

这种结构有几种不同的用途,如子程序定义(匿名程序赋给一个变量)、循环、条件等等:

x1 0 eq { 0 } { 1 x1 div } ifelse

这段代码首先使用eq测试 x1 是否是 0;根据结果的不同将真或者假放到堆栈上。在此之后,将两个过程放到堆栈上,然后执行ifelse,它从堆栈中取出三个参数,如果第三个参数是真就执行第二个否则就执行第一个。总之,如果 x1 是 0 结果就是 0, 其它情况结果就是 1/x1。

/inc3 { 3 add } def

Here def is used to place something in the dictionary, only this time it is a procedure instead of a simple integer. This works because the values coming from the dictionary are executed, not just pushed (as simplistically stated above). Since executing a literal amounts to pushing it, that did not make a difference before. Now executing "inc3" will first look it up in the dictionary, find the procedure object representing "{ 3 add }" and execute that. One value must reside on the stack for this to work, since add needs two arguments, only one of which is given in the procedure itself. Naturally, one passes arguments to procedures by placing them on the stack, so we can simply view "inc3" as a procedure that takes one argument. Example call: 这里def将内容放到字典中,仅仅在这个时候它是一个过程而不是简单整数。

71 inc3

将71放到堆栈上,inc3将它的值加3,这样就得到结果74。

To produce graphics, PostScript uses an ordinary cartesian coordinate system. 在生成图形的时候,PostScript使用普通的笛卡尔坐标系。

100 200 moveto 300 400 lineto stroke

将“光标”移到坐标点(100, 200)然后画线到(300, 400)。

50 70 moveto 100 200 50 80 100 100 curveto stroke

生成一个从(50, 70)到(100, 100)的立方贝塞尔曲线,控制点是(100, 200)和(50, 80)。

250 250 moveto (Wikipedia) show

在位置(250, 250)使用预先选择的字体画出文本“Wikipedia”,字体选择可以使用例如 /Courier findfont 12 scalefont setfont 这样的命令串。

图形最初在“用户坐标系”中创建,在复制到确定最后输出的“设备坐标系”之前它们可以进行旋转、缩放或者扭曲等变换。

200 300 translate 45 rotate

将用户坐标系中的内容上移 200 点、右移 300 点并且复制到设备坐标系时旋转 45 度。

字符“%”用来在PostScript程序中表示注释。作为一个通用的约定,每个PostScript都以字符“%!”开始这样所有的设备都会将它解释为PostScript。

Wednesday, 19 September 2007

Brief intro of life in Welcome Week

今天6点多就醒来了, 因为昨晚睡了太长的时间, 从下午5点起, 一直睡到今天的早上6点, 期间因为忍不住饿, 起来忍心泡了一包面, 现在想想为什么当初不多带些, 可以解决welcome week的中饭问题, 因为昨天在逛jubilee campus时, 在学校超市看到泡面的均价在8块人民币, 心碎到昨天中饭都没吃, 只为了一个目的那就是省钱。 在welcome week虽然可以免费住, 免费早饭和晚饭, 但是中饭还是要自己解决的, 昨天下午, 有几个同学实在忍不住了, 跑去要了一个鸡腿和薯条, 花去了3英镑, 回来直和我叫苦。 这几天实在太吃力了, 下午5点在床上一靠,就靠到了现在, 不光错过了难得的晚饭, 还靠出来了鼻血。 其实在飞机上的12个小时, 我就感觉到鼻子不对劲, 有一点点的鼻血, 因为空调的原因, 飞机上的空气太干, 吃的东西也不则样。 这让我特别怀恋家里的味道。 走之前也就是15号, 家里特地摆了一桌菜, 因为家里不能送我去机场, 只叫了些亲戚朋友, 那天爸爸特别高兴, 也特别的郁闷, 有很多话说, 可是都忍住了。亲爱的奶奶烧的菜, 是我小时候, 现在都很喜欢, 将来也会特别的怀念的。 可是现在她重病在身, 已经不能把话说清楚了, 我最担心的就是她了。次日, 便是我在家的最后一顿, 按照当地习俗,妈妈煮了长寿面, 妹妹和姑姑还有叔叔, 当然包括爷爷和奶奶, 这些人很难得聚在一起的。 7:25从千岛湖长途汽车站出发去上海。幸亏车子不拥挤, 我挑了个好位置来摆放我的行李和我自己。期间, 有两个日本人妞搭乘我们的大巴, 可是在车上一句话也没说, 挺佩服的, 两个人都挺瘦弱, 手里拿着一本旅行指南, 身上背着个包,就这样去做自己喜欢的事情。12:30到达上海, 司机念在我要出国读书, 当汽车到达上海南站的时候, 帮我把那个巨重的行李搬到了车下。出了南站, 对我来说就完全是陌生了, 幸亏我还能厚着脸皮, 到处问路。 为了省钱, 硬是拒绝了一个搬运工的生意, 自己拖着所有行李, 过隧道, 上楼梯, 过街, 然后上公交。 南站到飞机场有专门的公交专线, 机场7线, 票价20, 行程一个小时。当公交即将到达机场的时候, 心里蒙的一跳, 一辆磁悬浮从身边飞驰而过, 机舱更是雄伟。下了车, 终于可以不用在拖拉行李, 随手找到手推车, 放上行李, 顿时感觉如是副总。可是机场的staff并不怎么热情, 但有一些非常热情, 带我去商务中心打印, 还帮我问这问那, 但最后冒出一句话,非常让我吃惊, 他问我要不要住酒店, 这在中国看来是常见的现象了。 机场还不错, 都是中国人, 我在里面逗留了一个下午, 把所有东西都问清楚了。 在行李方面, 感觉有一点上当受骗的感觉。 电话问询航空公司, 他们说行李不能超过30kg等等, 其实在安检的时候根本就没有来查, 大致过了就可以了,手提行李里面只要没有违禁物品,就没有问题, 对大小和重量都没有问题。 这个消息对我来说很有用, 所以当晚我就准备了赛了更多的东西到我的包中去, 到了英国, 看了物价, 就在责问自己为什么没有赛更多。 不过站在他门的角度来想想, 的确也是的, 中国人就是喜欢转空子, 如果他们不把关好的话, 那很多人就会多带,飞机的承重能力有限, 最后损失的还是我们自己。机场给我的还有一个感觉就是贵, 我把护照复印了一份, 开价15rmb, 一份很小包的薯条30rmb。可是当你到了候机区, 那情况就完全不一样了, 那里有保税区, 我同学比较有从商经验, 看到万宝路才99RMB一条, 这个价格比国内的利群还要便宜一般, 就毫不犹豫的买了两条(每人购买的最高限), 准备带到英国高价卖出, 因为英国是不鼓励吸烟, 所以烟税很高。我当时就错过了这个机会, 都在到处拍照片。晚上在机场旁边,其实也比较远的地方找了个宾馆, 120RMB一晚, 已经相当便宜, 充实了一下我的行李, 吃了顿辣的, 睡了个好觉。第二天7点出发, 8点到达机场, 人已经排满了。 我在e区等待领取登机牌, 维珍的在L区。 慢慢的同学都来了, 大部分都有家长陪行, 个别几个像我这样的抱着不同目的单独一个人, 其中还有两个女生, 比较强悍,一个人, 两个大行李箱, 一个登山包。就这样准备浩浩荡荡的前往英国。 我发现了家长陪同的一个比较隐讳的目的, 在机场, 同学相见谈天, 家长也见面, 也聊天, 但同时还交换联系方式。11点正式航空公司检票和行李托运,在精心准备的情况下, 托运行李超重2公斤, 手提行李超重5公斤, 还有笔记本电脑包和腰包里面乱赛的东西, 肯定也是可以通过检查的, 可以说一路上畅通无阻。所有手续办完, 在候机厅候机的时候, 发现身上的1000元现金没及时存掉,问了几家银行, 他们居然说候机厅只能办理外国居民的对外换汇业务, 不受理人民币的存取业务, 看俩我只能是讲这些人民币带到英国,然后看着他在物价飞速上涨的情况下贬值。飞机上的经历是比较痛苦的, 需要坐12多个小时, 没有什么娱乐设施, 还不能开手机玩游戏, 我又没做在靠窗的位置, 最主要的是, 我睡不着, 12个小时里, 我的睡觉时间不过2小时, 其余的时间都不知道怎么过的。饭食一般, 且量很少, 少的可怜, 中饭就吃了一个包子,所以导致了我下飞机就很累, 没有即使调整好自己的时差。下了飞机, 出关检查, 有一点值得高兴的就是, 在宁波两年, 英语没有白读, 英国口音非常顺口, 所以出关没有遇到大问题, 由于我的行李箱硕大, 所以也是第一个找到行李。还有一个感触就是, 在英国, 只要你的态度好, 别人就会对你很热心, 按照这点, 我发现我来对了地方,对于一个做好吃苦耐劳的准备的人来说, 这里真的可以发展的很好, 因为没有人会干涉,反而会伸出援助之手。学校的coach开了3个多小时,一下飞机, 我们就感觉到了莫名了冷, 因为在中国,现在正短袖, 在英国, 早晚现在需要穿个厚衣, 才能不被冻死。coach的温度在8度左右, 就这样一直开, 我们也一直睡。 事后我和同学聊天, 大家都觉得在coach上睡的特别爽, 别飞机上那是好多了, 因为英国的马路很宽, 很平, 很干净, 而且英国的司机开车开的很快。回到学校, 大家都兴奋不以, 虽然当时是当地时间12点, 可是窗外的景色透过轮廓就可以感觉到他们的灵性。学校特地提供了披萨, 领我们去住处, 感觉很温馨, 住的地方不错, 一个人一间, 两人共用一个卫生间, 窗户很大, 而且我的窗可以看到日出, 看到学校的美景。寝室内和寝室外的温度那是相差大多了。 大家洗完澡, 聚在一起聊天, 然后睡觉, 这一觉真的很舒服, 但大部分人当地时间6点多就起床了, 因为睡不着, 这个时间对中国来说刚好是午睡时间, 这也直接导致了我到现在都还保持着的晚上10点左右就睡觉, 早上7到8点钟就醒的良好作息习惯。早上, 大家在寝室门口集合, 然后有人带我们去吃英式早饭, 需要排队, 有点像自助餐, 因为每个人的口味不一样, 所以餐厅索性就把所有东西都放好,然后喜欢吃冷的就直接拿, 喜欢吃热的,旁边就有加热设备。 我挑了培根(一开始我以为是猪肉), 香肠和烤土豆, 然后就是加热过的面包, 橙汁, 牛奶, 巧克力。 吃饭的地方据说是有点历史的,因为吃饭的时候旁边就刚好做了一个穿黄色衬衣的volunter, 交谈中才知道, 这里有很多19世纪中后期的痕迹, 后来几经装修依然保留了一下,现在这里变成了一个学术晚会据点。 它的名字也很有意思叫做Lincoln hall。 吃饭的时候, 每个人的行为和态度是不一样的,因为大家都是国际生, 来自不同地域, 拥有不同文化, 至少现在还没有被同化不少, 但有一点我发现是相同的, 那就是人都会不好意思。在这里,大家的态度都很好,都很讲礼貌, 很多事情我们觉得不好意思, 他们也会觉得不好意思。比如说, 第二天我去吃饭的时候,那个黄衬衣告诉我说,昨天准备了很多东西,后来都倒掉了,大家好像都没吃多少, 怕难为情, 都不敢去拿, 其实学校事先就告诉我们了, 中饭学校不提供午饭(因为中午大家时间不统一的), 所以就特意早上多准备些,希望大家多吃一些, 可是很多人都考虑太多了。还有一点就是出了国,这个民族感特别强, 什么事情都喜欢提高国家的程度, 那天早上, 我的一个同学一次性拿了两碗牛奶, 结果必定是溅出许多, 他以为没事情, staff马上就去拿了一个牌子上面写着:wet floor, take care。 然后很多同学看了不爽就纷纷指责说真他妈的丢中国人的脸,那个同学连忙去拿拖把把地板插干。吃完早饭, 感觉环境真好, 在中国也能看到如此美丽的景色, 但大部分都是自然景色, 没有人工的修饰, 在这里感觉会不一样, 这里的房屋似乎初看似乎比较人性化, 比较喜欢融入环境, 而不是带有强烈的战友欲望, 不知道这样的感觉还能保持多久, 当我在这里住久, 也许这种感觉就会相对来说减淡。 一架飞机非常安静的云间飞过, 留下一个清晰的白色丝带飘动在蔚蓝的天空, 我不知道为什么这里的天空是如此的明亮和干净。后来几天我发现每次早饭后我都能看到这条白色丝带。白天的活动还是比较多的,学校发的资料中, 有地图,有今天的形成表, 什么时候有什么活动都罗列在上, 你不需要每个都参加, 活动戳过了也没关系,过几天还有类似的活动, 所以什么都是自己安排,这个在宁波已经习惯了这样自己合理安排的生活了。 拿着地图, 用着还凑或的英语, 赶这个场赶那个场。 在宁波我学会一点,或者说改变了以前的一个思维习惯, 那就是要学会取舍, 学校一天有很多多动,不可能个个都参加, 也不是个个都适合自己, 抓关键点才是最重要的。走了一天很累, 为了节约, 没吃午饭,下午回到寝室, 倒头就睡, 任凭同学敲门, 呼唤, 都没醒过来, 最后还是在晚上9点钟, 被恶醒了, 花去了8快人民币一包的方便面。后面几天其实过得差不多, 只不过多了一些有意义的活动,比如说参观市区, 去beeston购物, 去新房子考察等等。 有点忙, 有点累, 但这都是我们必须要经历和尽力的

Sunday, 9 September 2007

Birthday

 
I am luck to remember one's birthday, send this as gift, best wishes
Posted by Picasa

Tuesday, 24 July 2007

月亮之上

月亮之上——凤凰传奇


我在仰望 月亮之上
有多少梦想在自由的飞翔
昨天遗忘啊 风干了忧伤
我要和你重逢在那苍茫的路上
生命已被牵引 潮落潮涨
有你的远方 就是天堂

谁在呼唤 情深意长
让我的渴望象白云在飘荡
东边牧马 西边放羊
热辣辣的情歌就唱到了天亮
在日月沧桑后 你在谁身旁
用温柔眼光 让黑夜绚烂

我等待我想象 我的灵魂早已脱僵
马蹄声起马蹄声落 看见的看不见的
瞬间的永恒的 青草长啊大雪飘扬

节奏响起 煽动了想象
让摇曳的身体开始开始思想
马头琴悠扬 马奶酒穿肠
我的爱情奔跑在呼伦贝尔草原上

你的善良 我不能不能抵抗
你的纯洁 将我的心紧紧捆绑
OH 你的笑容 让我找到了最后信仰
美丽的月亮 你让霓虹黯淡无光


Saturday, 21 July 2007

普适计算

主机计算(mainframe):多人共享一台计算机
桌面计算(personal computer):一人一台计算机
普适计算(ubiquitous computing):一人可使用多太计算机资源。

计算模式
主机计算模式--分时操作系统
桌面计算模式--个人操作系统, 图形用户界面

人的注意力得发展到目前为止并没有按照摩尔定理发展。
普适计算就是解放人的注意力。 所以它不是高端计算。

定义:
无论何时何地, 只要用户需要, 就可以某些设备访问到所需要的信息
移动设备+嵌入设备+固定设备+互联网
个性化, 自适应, 多摸态得人机的人机交互
无缝移动:在多个具有不同性能的设备上或提供多种不同服务的环境中自由移动, 但不影响或者很少影响用户的使用和操作
协同工作和计算资源的智能分配
普适计算的本质不在于开发新的设备, 在于一种计算模式的创新。

桌面计算模式的局限性:
以计算机为中心而不是以人为中心。
计算资源是私有的, 而不是共享的
计算是固定的, 而不是随时移动的

关键技术
开发针对普适计算的软件平台和中间件
建立新型的人与计算服务的交互通讯
建立面向普适计算模式的新型应用模型:感知上下文计算(context-awareness), 无缝移动(seamless mobility)
提供适合普适计算时代需求的新型服务:移动会议(mobile meeting), 灵感捕捉(notion capture)

思想最早有前xerox parc首席科学家mark weiser在1991年提出
以中间件为核心的企业计算, 让计算能力公用化的网格计算, 倡导平等共享的对等计算,和计算无处不在的普适计算。

mit的oxygen研究计划
未来世界将是一个到处充迟着嵌入式计算机的环境, 他们已经融入了人们的日常生活中。 oxygen希望充分利用这些计算资源, 达到做的更少, 完成更多的目的。人做的少一些,计算机做的多一些。

uc berkeley的endeavour计划
关键就是流体软件的开发, 他可以自适应的选择在何处执行, 在何处存储, 它通过协议获得可用资源并向其他实体的提供服务。

washington的portolano研究计划
根据用户的位置变化而自适应的改变软件的位置等。

cmu的aura研究计划
研究在普及计算时代, 在用户和计算环境之间增加一层软件层aura, 由aura代理用户区管理, 维护分布式计算环境中平凡变化,松散耦合的多个计算设备, 以完成用户的目标任务。人的精力是最宝贵的资源。应该让它集中在用户完成的事情上。

task-driven computing
energy-aware adapatation
multu-fidelity computation
intelligent networking
resource opportunism

task-driven computing
problem:
humans interact at two low a level with computer
result: consume moble user's attention
solution:
support user intentions
support mobility
support proactivity

some research challenges:
design of task definition language with rich expressive power
multi-modal interface for creating and modifying tasks
mechanisms for tracking , suspending and restoring task state
design of platform-independent task apl
platform-specfic implementations of task apl
triggering mechanism for pro-activity

percasive healthcare systems
普适计算是医院在电子化信息化发展中的必然结果
随时随地方便的获得和记录各种诊断信息是该项目的基本目标
项目可以分为移动计算和基于环境的计算两个部分
项目已经投入实际运行
从该项目从理论和实践对普适计算提出了许多新的问题。

操作系统:rtos
ipp for ia and intel sa
网络接口: can 总线
usb接口

计算机软件与网络的五年发展

由于微电子技术的发展, 所以计算机硬件每10年更换一代

50年软件业发展全景图
早期专业服务公司
早期软件产品公司
强大企业解决提供公司
客户大纵市场软件。
软件服务

计算机技术发展定律:
Driver law: 政府支持和市场驱动是计算机技术发展的永恒动力
Moore` law:硅芯片的功能和价格
10 year law: 计算机技术发展经过10年发展有革命性飞跃性发展。
computational force law:计算机资源和环境的不断增强和持续变迁, 软件处理能力极大提高, 渗透性应用能力极大提高,成为科学与技术发展的模仿仿真手段。

网络计算的技术发展趋势:
client/service->clienct/cluster->
client.networking->
smart client/virtual server environment
基于网络的虚拟服务环境是未来趋势

普适计算是21世纪的计算模式
internet计算环境的特征:
开放性
动态性
多态性
无统一控制的真分布性
节电的高度自治性和不可预测性
节电链接的开放性和动态性
人, 设备和软件的多重异构性
使用方式的个性化和灵活性
网络连接环境的多样性。

计算机应用:在计算能力和环境不断增强和持续变迁下, 不断拓展和升入
软件和网络已经作为国家战略的重要部分。
国家计划建以和实施项目预示软件发展的趋势

每年pitmc报告
美国1994年正式提出了高性能计算机系统-hpcc
1995年强调hpcc得好用性和建设国家信息基础设施-nii
1996年把通信置于计算前面, 建设分布协同信息处理环境-dcee
1997年重点转向网格, 提出了information -wide- area- year
1998年提出高端计算high end computing and computation-hecc
1999年提出了基于网格grid计算
2000年重视大规模和海量信息处理
2001年提出了高生产率的计算系统
2002年满足21世纪对高校,安全, 可裁减的网格计算的需求,
2003年开发高性能计算和网络环境和技术, 一切为了国土安全

软件体系概述
软件产品:独立的软件产品形态
嵌入式软件:
软件服务

软件体系:
完整的软件体系对竞争十分重要
开元软件已经形成一个初步完整的软件体系
开元软件已成为软件世界中的重要力量。

开放组织如W3C, OMG, IEFT等国际性中介机构都成为围绕着INTERNET得应用。

90年代, 操作系统似乎没有非常有影响的新的思想产生

近10年来, 嵌入式操作系统是热点。

操作系统未来趋势:
网络化趋势:浏览器应用
微型化趋势:嵌入式系统
构建化趋势:即插即用
专业化趋势:支持QOS服务
可信化趋势:

数据库乡小型化发展和网络应用发展

中间件和操作系统和数据库系成为基础软件体系的三大支柱

嵌入式系统是实现后PC时代数字化智能化产品。

网格计算:支持第三代INTERNET应用

网格:简单概念
在大型科学研究和工程领域, 高性能的网络应用, 如科学仿真, 药物开发等, 需要由各个合作机构的共同参与, 需要使用个机构的拥有的资源, 通过高速的网络共享合作伙伴所拥有的计算, 存储和显示资源来解决复杂的计算问题。 这些地理上分布的资源形成了资源网格, 利用资源网格上的资源进行的分布式计算被称为网格计算。
计算:
在硬件方面, GRID需要讲地理上分布在不同的地方的硬件资源,如网络,计算机,数据仓库以及可是华虚拟现实显示等有机的连接起来。
在软件方面, GRID的作用就像一个中间件, 它将需要的各种硬件和软件资源有机的集成起来以便这些不同的部件能够协同原作。

工业设计学科总述--设计, 创新,文化

工业设计不是工业产品的设计, 也不是工业领域的设计, 而是指形成于工业社会的一种不同于手工业设计与艺术设计的设计思想与设计方法。
它是一个新型的交叉学科, 结合了自然科学, 社会科学与人文科学三大人类知识领域各科学科, 对以工业产品为主的人造物进行系统的, 最优化的设计。 所以工业设计既不是工程设计, 也不是艺术设计,是产品的系统设计。

技术设计:
解决“物-物”关系
工程师
自然科学与工程技术知识
创造物的使用价值
本质是手段的设计(体力的解放)
共性

艺术设计:
解决“人-人”关系
人文知识与社会科学知识
创造审美价值
本质上是情感传递的介质设计(精神解放)
个性

工业设计:
解决“人-物”关系
设计师
自然科学知识, 工程技术知识,人文知识和社会科学知识
创物得文化价值
本质是人的生存方式的设计(目的设计)(体力与精神的追求)
共性与个性的结合

任何一个物得设计,都是在某一个系统中寻求一个使系统保持和谐与协调的过程和结果
工业设计是以设计物为对象, 载人-对象-环境系统中寻求和谐与协调的思想与方法

本质:创造更加合理的生存方式

物应该是人的镜子, 是人的生物特征与文化特征的投射
生存方式的设计, 有提升人的生村质量, 也有可能降低人的生存质量。
一个民族的生存方式就是一个民族的文化, 设计了生存方式也就是设计了文化。

智能信息技术

应用:
符号计算技术
模糊技术
人工神经网络技术
演化计算技术
广义计算技术

模糊技术
模糊性是人类思维和客观事物的普遍具有的属性之一:
世界模糊性
思维模糊性

模糊的普遍性
在客观事物质之间存在着中间过渡,促在着亦此亦彼现象及模糊现象
尽管事务的表现和内在属性尤其确定性, 但是由于观测有段和科研水平所限, 在科学发展的一定阶段上,人们对这些属性的认识带有模糊性
人类通常运用模糊的词语来交流思想,互通信息, 然后进行推理分析, 综合评判, 最后作出分类决策。

人脑的认知过程
获取模糊轮廓印象-〉联想与回忆-〉模糊推理和判断
人脑的重要特点之一就是能对模糊事务进行识别和判断, 人们的行为活动通常是从客观事物获取模糊的印象, 表象以及模糊概念的情况下展开和做出反应的。 人脑对于客观事物的认识,往往只要通过一些模糊的信息的综合便可获得足够精确的结论。

模糊集合的诞生:
正是针对自然环境和人类认识过程中存在的模糊性现象,美国控制论专拣,加利弗里亚大学教授L.A.Zadeh在1965年在Information and Control发表了开创论文Fuzzy sets, 第一次提出了模糊集合的概念, 这标志着数学的应用范围从精确现象扩大到模糊现象的领域, 从而建立了模糊信息处理的新课题。

模糊技术发展
1984年国际模糊系统联合会IFSA成立
1985年, ifsa年会在西班牙召开
1987年, ISFA第二届联辉在日本东京召开, 会上推出了10余套模糊控制软件与硬件
日本和一些发达国家先后掀起了异国模糊技术的热潮, 模糊控制思想广泛接受,特别是采用了魔术技术的新一代家电。

杂志:
中国的《模糊系统和数学》

模糊结合及其表示方法
普通集合式模糊集合的特列
模糊集合是普通集合的扩展

普通集合:
全集U, u是U中的元素, U上的普通集合A`可以用特征函数来表示
XA`(u)=1 UXA`(u)=1 U!
模糊集合
全集U中的元素可以部分的属于模糊集合A, 则模糊集合A可以隶属函数来表示:0<=UA(u)<=1. UA(u)就成为元素对模糊集合A的隶属度, 又称为A得隶属函数

集合元算和我们一般的集合运算相差不多,
模糊集合的运算满足补余律外的所有普通集合运算定律。

模糊检索的特点:
处理对象多样化
信息处理智能化
人机借口自然化

模糊查询
模糊词是表示模糊概念的单词。 模糊词可以用模糊集合来表示, 而模糊词可以用隶属函数来表示
模糊词通过并交补运算就成了模糊词组
语气算子ht是自然语言中这样一些词, 他们放在一个单词前面一加强或减弱与其。这里的t是一个正实数, 当t>1时就称为集中化算子, 当t<1时, 就称为散漫化算子。 可以适当起些名字。
模糊化算子f是自然语言中这样一些词, 他们点缀在一个单词前面, 使其语义模糊化。

有了上述基于模糊集合的定义, FIS得模糊查询q就是由语气算子ht, 模糊化算子f, 模糊词FW(包括清晰词)及其并,交, 补算子所组成。 表达式:q:[ht/f]FW{O[ht/f]FW} . 其中, {U, N, -}; []中的内容可缺省; {}中的内容可重复0次回多次。

模糊检索系统结构:
用户接口:允许用户使用自然语言
程序接口:系统维护
总控模块:接受用户接口以及程序借口送来的操作命令, 进行一系列的分析和处理, 将有关的参数信息转发给相应的处理模块, 并控制转到相应的处理模块执行。
模糊知识管理模块。
模糊检索模块:核心, 同时访问知识库和系统数据库
帮组模块:

其他应用
模糊决策
模糊模式识别: 手写输入识别, 癌细胞诊断。
。。。


人工神经网络技术
1943年, 心理学家McCulloch和数学家Pitts合作提出了形似神经元的数学模型--MP模型, 开创网络研究的时代。
1957年感知机
70年代后期, 已经认识到von neuman 体系结构的局限性,特别是与人脑的智力活动存在较大差异:
计算机布局别学习能力
对于不能用数学模型表达的问题无能为力。
日本第五代计算机计划失败。
许多学者开始转向神经网络计算。
Hopfield(加州工学院)1982年提出了HNN模型
Rumelhart提出了PDP(并行分布)理论, 致力于认知结构微观的探索, 并与1986年提出了多层网络的BP算法;
1987年, 国际神经网络学会诞生.


生物神经元模型:
神经元就是神经细胞, 使脑组织的基本单元。
神经信息处理结构:
信息输入(树突)-〉信息处理(细胞体)-〉(信息传输)轴突-〉信息输出(突触)
细胞体:细胞核, 细胞质, 细胞膜。
轴突:神经纤维, 相当于细胞的输出电缆, 其端部的神经末梢为信号输出端子, 用于传出神经冲动
树突:相当于输入端, 接受来自四面八方的传入神经冲动
突触:细胞与细胞之间通过轴突和树突相互连接, 接口就成为突触,每个细胞有1000-10000个突触, 突触有两种类型, 兴奋性和抑制性。
膜电位:细胞膜内外之间的电位差, 约20-100mv, 膜外为正, 膜内为负
结构可塑性:由于突触地信息传递性是可变的, 随着神经冲动的传递方式的变化, 其传递作用可以增强, 也可以减弱, 即细胞之间的连接是柔性的。
兴奋--当传入冲动的时空整合结果,使膜电位升高, 超过动作电位的域值(40mv)时, 细胞进入兴奋状态, 产生神经冲动, 由轴突输出
抑制--当传入冲动的时空整合结果,使膜电位低于动作电位的域值, 细胞进入抑制状态, 无神经冲动输出。
脉冲和电位转换:突触界面有脉冲/电位信号转换功能,由轴突传递的电脉冲为等幅,横宽, 编码的离散脉冲信号, 而细胞膜电位变化为连续的电位信号, 在突触接口处进行数/模转换是通过神经介质以量子化学方式实现的变幻过程。:电脉冲-〉神经化学物质-〉膜电位
由于突触地结构可塑性, 突触地传递作用有增强, 减弱, 饱和, 所以细胞有学习,遗忘和疲劳效应。

人工神经元是多输入单输出的非线性器件

典型的人工神经网络模型
感知机:分类器
BP网络:多层前向网络
自组织特征映射网络:用于最优映射
Hopfield网络:全廉洁网络, 用于解决组合优化问题, 给n各城市, 寻找一条不重复通过所有城市的最短路线。
双向联想存储器:模式识别。
人工神经网络模型的信息处理能力:
大规模并行分布信息处理(现在计算计只能串行离散符号处理)
分布信息处:信息存储体现在神经元互联的分布, 并以并行分布式处理(现在计算和存储是相互独立的)
高度的努棒性和容错性, 善于联想, 概括, 类比和推广, 任何局部损坏不会影响到整体结果
很强的自学习能力, 系统可以在学习过程中不断完善, 具有创新特点。
具有集体运算能力。

人脑学习学说:
化学学说:认为神经系统把学习后的结果记录在某些生物分子(蛋白质, 核酸, 神经递质)上, 就像遗传信息纪律在DNA上。
突触修正学说:认为学习过程中神经元之间的突触联系发生了变化, 人工神经网络按照突出修正学说来模拟人脑的学习过程。

学习规则:
误差修正学习:根据系统的期望输出与实际输出之间的误差作为连接全调整的参考, 最后减少这种误。
随机性学习:结合随即过程, 概率和能量的概念来调整网络的连接权, 从而使网络的能量大到最小。
毫不性学习:两个神经元同时学习,他们的联系需要加强。

应用:
模式识别
最优化问题
数据库知识获取
数学逼近映射
概率密度函数评估
自动控制
信息处理
风险识别

广义学习的理论基础:
大脑自适应原理:采用自顶向下的方法分析系统水平以及系统水平和回路之间的联系, 用自顶向上的方法分析细胞水平和回路水平及其他们之间的联系, 从而归纳出大脑的自适应原理。

广义学习系统的特点:
高度并行
有机融合
择优进化

广义计算与决策分析
数据库
知识库
。。。

广义计算与企业知识流
信息收集和处理
知识孵化:发现隐性知识
知识产品开发
企业知识控制:
知识管理技:员工知识素质管理与知识学习+ 知识创造+建立企业的知识体系
信息技术:数据仓库技术+知识工程技术+数据挖掘技术

电信行业的数据挖掘系统
分离大客户和普通客户, 进行专业的营销和服务。
TDMS的任务:
流失客户预测
欺诈客户识别
时间序列分析

信息技术和电子商务

概念:
电子商务并不是一个单纯的技术概念, , 也不是一个单纯的商业概念, 而是涉及到整个商务运作的全过程
电子商务的产生和发展与信息技术的发展和应用紧密相关。
从信息技术的角度:
web communications(tcp/ip)+web user interger(html)+web programming(java)+web data(xml)=e-business
电子商务发展背景
第一阶段:单项业务电子化--单机环境(50-60年代)
第二阶段:部门业务电子化--局域网环境(70-80年代)
大中型计算机+终端机+网络+数据库为框架的电子商务环境
第三阶段:综合业务电子化--互联网环境(90年代)
综合:点-〉线-〉面
电子商务发展过程
第一阶段:电子商务启动期(90年代中后期)
一大批以.com为代表的兴网络企业
开始建立自己的网站的传统企业
只有少数的新兴网络企业坚持下来, 很多传统企业怀疑电子商务的能力, 涌现出了一批成功的电子商务企业

浙江省块状经济区域网络化制造系统开发与应用。

工业革命到信息革命的三个世纪
19世纪:火车+铁路
20世纪: 汽车+ 高速公路
21世纪:电脑+ 网络
网络世界=第8大洲

信息商品交易的特殊性:
信息商品交易中的价格不确定性
信息商品在多次流通中的价格迅速递减规律
信息商品交易中的风险性

产品结构的特点:
知识-〉技术-〉产品的时间越来越短, 结构越来越复杂
现在市场上的电子产品周期0。5年

普及标准:30%的家庭才作为一项技术普及应用的标志。

制造业的标志性进展:
全数字化的定义--无直生产
数字化预装配--无金属样机的生产
广域网上的异地设计, 异地制造
基于step得数据交互
协同工作小组

自动化孤岛:信息集成
将自动化孤岛集成在一起
最有效率的方法就是创建一个集成平台--cims

中心的变化:产品-〉市场-〉客户

信息时代造成了跨国公司的垄断性
跨国公司的工业研制费占世界总值的80%

美国产业演变历程

电子商务的内容:
信息网:
金融网
运输网

信息技术的走势:
infinite bandwidth(无限带宽)[超摩尔定律]
service on demand(服务点播)[基于b/s结构的数据/过程/应用继承]
plug&play[即插即用][web服务, net, xml]
shared ontology(共享的领域概念框架)
pervasive(无处不在)[与移动/无线/即使的通讯结合]
ondemand(按需服务)

人工智能

turing test:为了回答人工智能能否真正实现的喜,怒, 哀, 乐得问题?
将人和计算机放在两个不同的房间,在另一个房间里通过网络与他们交谈。 当第三个房间里的人不能区别这两个房间里的回答问题得对象是否是人的时候, 就具备了人工智能。

目前的人工智能两个代表性的观点:
the emperor's new mind
Roger Penrose[uk]
Oxford university press.
观点:
电脑要超过人脑是不可能的
原因:人类不可能在物理层次上理解大脑, 要像人的大脑是不可能的。
电脑的设计的思维是算法的, 只相当于人的逻辑推理的思维方式, 这个方法高效并非一定有效, 而所有根本的, 决定性的判断则必须是创造性地或者是直观的, 如艺术,数学的研究。

K.Warwick[UK]
century-random houe, 1997
电脑--单面的人, 虽然愚蠢, 但能力很强, 且具有一定学习能力, 网络使得电脑成为超级电脑。
智能是否为人类存在的最大奥秘? 智能的主要体现于逻辑, 而逻辑未给错误留有余地, 回顾人类历史的错误, 或者错误才能使人类的最大的奥秘。
Kurt Godel:incompleteness theorem:
within a formal system questions exist that are neither provable on the basis of the axioms that define the system.
所以在人工智能中将思维形式化机器化是有极限的, 在理论上给出了有些事情是做不到的。

Douglas R.Hofstadter
Pulitzer Prize Winner, 1980.

计算机视觉中的困惑
计算机视觉相对于人工智能的其他领域中取得的巨大成功:
六条腿的机器人在月球上漫步
爱国者导弹准确拦截飞毛腿导弹
就同监控系统可以识别飞驰汽车上的号码
计算机可识别人的指纹
这些与人类的视觉活动相比, 显然微不足道, 人类视觉中的视觉含义的包我以及主观经验在视觉中的作用,是及其所不肯能拥有的。
计算机视觉过程:
feature detection and extraction -> texture -> pattern classification -> image interpretation
C.Bloomer 《视觉原理》:人类视觉系统有意义的视觉信息而忽略无意义的视觉信息。
人的头脑从外来的刺激中毫无节制的产生含义。
视觉理解发生的机制还知之不多,但可以肯定这含有非线性突变因素, 而且导致某种结果的因素是不确定的(蝴蝶效应)
这其中摸不去的主观因素不可能通过确定的算法给出。
所以天气预报中有很多不可预测的东西。

计算机下棋:
组成部分:
评估函数(evaluation function)
树状搜索算法(tree searching algorithm)
1940年荷兰心理学家葛鲁特发现:
大师: 组块; 5秒钟摆出一个实际的对局; 若出错,则涉及到一组局势但不影响全局, 并不搜索错祺。
新手:每个棋子的确切位置; 曼的多; 认为是完全不同的棋, 对所有可能进行遍历。
计算机的象棋水平大致相当于新手水平。

在计算机上要实现人的心智能, 充满困境, 要冲破这一困境, 必须有理论性的突破--大自然的机理+算法
目前出现了一些新的尝试:
生物计算
量子计算
光子计算

Wednesday, 18 July 2007

java assert

相信学过c,c++的朋友一定不会对断言感到陌生。下面介绍一下断言在JAVA中的使用,JAVA是从JDK1.4才开始支持断言的(添加了关键字assert),请注意老版的JRE不支持。

断言概述

编写代码时,我们总是会做出一些假设,断言就是用于在代码中捕捉这些假设
可以将断言看作是异常处理的一种高级形式
断言表示为一些布尔表达式,程序员相信在程序中的某个特定点该表达式值为真
可以在任何时候启用和禁用断言验证,因此可以在测试时启用断言而在部署时禁用断言。同样,程序投入运行后,最终用户在遇到问题时可以重新起用断言。
使用断言可以创建更稳定,品质更好且易于除错的代码
当需要在一个值为FALSE时中断当前操作的话,可以使用断言
单元测试必须使用断言(Junit/JunitX)
除了类型检查和单元测试外,断言还提供了一种确定个种特性是否在程序中得到维护的极好的方法
使用断言使我们向按契约式设计更近了一部

常见的断言特性

前置条件断言:代码执行之前必须具备的特性
后置条件断言:代码执行之后必须具备的特性
前后不变断言:代码执行前后不能变化的特性

断言使用方式

断言可以有两种形式
1.assert Expression1
2.assert Expression1:Expression2
其中Expression1应该总是一个布尔值,Expression2是断言失败时输出的失败消息的字符串。如果Expression1为假,则抛出一个 AssertionError,这是一个错误,而不是一个异常,也就是说是一个不可控制异常(unchecked Exception), AssertionError由于是错误,所以可以不捕获,但不推荐这样做,因为那样会使你的系统进入不稳定状态。

起用断言

断言在默认情况下是关闭的,要在编译时启用断言,需要使用source1.4标记 既javac source1.4 Test.java ,在运行时启用断言需要使用 -ea参数 。要在系统类中启用和禁用断言可以使用 -esa 和 -dsa参数。

例如:
public class AssertExampleOne{
public AssertExampleOne(){}
public static void main(String args[]){
int x=10;
System.out.println("Testing Assertion that x==100");
assert x==100:"Out assertion failed!";
System.out.println("Test passed!");
}
}

如果编译时未加 -source1.4,则编译通不过
在执行时未加 -ea 时输出为
Testing Assertion that x==100
Test passed
jre忽略了断言的就代码,而使用了该参数就会输出为
Testing Assertion that x==100
Exception in thread "main" java.lang.AssertionError: Out assertion failed!
at AssertExampleOne.main(AssertExampleOne.java:6)

断言的副作用

由于程序员的问题,断言的使用可能会带来副作用 ,例如:
boolean isEnable=false;
//...
assert isEnable=true;
这个断言的副作用是因为它修改了程序中变量的值并且未抛出错误,这样的错误如果不细心的检查是很难发现的。但是同时我们可以根据以上的副作用得到一个有用的特性,根据它来测试断言是否打开。

public class AssertExampleTwo{

public static void main(String args[]){
boolean isEnable=false;
//...
assert isEnable=true;
if(isEnable==false){
throw new RuntimeException("Assertion shoule be enable!");
}
}
}

何时需要使用断言

1.可以在预计正常情况下程序不会到达的地方放置断言 :assert false
2.断言可以用于检查传递给私有方法的参数。(对于公有方法,因为是提供给外部的接口,所以必须在方法中有相应的参数检验才能保证代码的健壮性)
3.使用断言测试方法执行的前置条件和后置条件
4.使用断言检查类的不变状态,确保任何情况下,某个变量的状态必须满足。(如age属性应大于0小于某个合适值)

什么地方不要使用断言

断言语句不是永远会执行,可以屏蔽也可以启用
因此:
1.不要使用断言作为公共方法的参数检查,公共方法的参数永远都要执行
2.断言语句不可以有任何边界效应,不要使用断言语句去修改变量和改变方法的返回值

参考:
http://jcp.org/en/jsr/detail?id=41
http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html
http://www-128.ibm.com/developworkers/cn/java/jdiag0723/
http://www-128.ibm.com/developworkers/cn/java/jmerlin/part9/

java native

The goal for this chapter is to introduce you to Java's native methods. If you are new to Java, you may not know what native methods are, and even if you are an experienced Java developer, you may not have had a reason to learn more about native methods. At the conclusion of this chapter you should have a better understanding of what native methods are, when and why you may want to use them, and the consequences of using them. You should also have a basic understanding of how native methods work. You will then be more than ready to tackle the next three chapters, which dive into the nitty-gritty details of Java's Native Methods.
What Is a Native Method?

Simply put, a native method is the Java interface to non-Java code. It is Java's link to the "outside world." More specifically, a native method is a Java method whose implementation is provided by non-Java code, most likely C (see Figure 30.1). This feature is not special to Java. Most languages provide some mechanism to call routines written in another language. In C++, you must use the extern "C" stmt to signal that the C++ compiler is making a call to C functions. It is common to see the qualifier pascal in many C compilers to signal that the calling convention should be done in a Pascal convention, rather than a C convention. FORTRAN and Pascal have similar facilities, as do most other languages.

Figure 30.1 : A native method is a Java method whose implementation is provided by non-java code.

In Java, this is done via native methods. In your Java class, you mark the methods you wish to implement outside of Java with the native method modifier-much like you would use the public or static modifiers. Then, rather than supplying the method's body, you simply place a semicolon in its place. As an example, the following class defines a variety of native methods:

public class IHaveNatives
{
native public void Native1( int x ) ;
native static public long Native2() ;
native synchronized private float Native3( Object o ) ;
native void Native4( int[] ary ) throws Exception ;
}

This sample class shows a number of possible native methods. As you may have noticed, native methods look much like any other Java method, except a single semicolon is in the place of the method body. Naturally, the body of the method is implemented outside of Java. What you basically define is the interface into this external method. This method declaration describes the Java view of some foreign code.

The only thing special about this declaration is that the keyword native is used as a modifier. Every other Java method modifier can be used along with native, except abstract. This is logical, because the native modifier implies that an implementation exists, and the abstract modifier insists that there is no implementation. Your native methods can be static methods, thus not requiring the creation of an object (or instance of a class). This is often convenient when using native methods to access an existing C-based library. Naturally, native methods can limit their visibility with the public, private, private protected, protected, or unspecified default access. Native methods can also be synchronized (see Chapter 7, "Concurrency and Synchronization"). In the case of a synchronized native method, the Java VM will perform the monitor locking prior to entering the native method implementation code. So, as in Java, the developer is not burdened with doing the actual monitor locking and unlocking.

The example uses a variety (although not all) of types. This is because a native method can be passed any Java type. There is no special procedure within the Java code to pass data to the native method. However, the developer of native methods must be careful that his native methods behave properly when manipulating Java datatypes. Native methods do not undergo the same kinds of checking as a Java method, and they can easily corrupt a Java datatype if care is not taken (see Chapter 31, "The Native Method Interface").

A native method can accept and return any of the Java types-including class types. Of course, the power of exception handling is also available to native methods. The implementation of the native method can create and throw exceptions similar to a Java method. When a native method receives complex types, such as class types (such as Object in the example) or array types (such as the int[] in the example), it has access to the contents of those types. However, the method used to access the contents may vary depending on the Java implementation being used. The major point to remember is that you can access all the Java features from your native implementation code, but it may be implementation-dependent and will surely not be as convenient or easy as it can be done from Java.

The presence of native methods does not affect how other classes call those methods. The caller does not even realize it is calling a native method, so no special code is generated, and the calling convention is the same as for any other method-the calling depends on the method being virtual or static. The Java virtual machine will handle all the details to make the call in the native method implementation. One minor exception may be with the methods marked with the final modifier. The Java implementation may take advantage of a final method and choose to inline its code. It would be doubtful that this could be achieved with a native final method, but this is an optimization issue, not one of functionality. When a class containing native methods is subclassed, the subclass will inherit the native method and also will have the capability of overriding the native method-even with a Java method (that is, the overridden method can be implemented in Java). If a native method is also marked with the final modifier, a subclass is still prevented from overriding it.

Native methods are very powerful, because they effectively extend the Java virtual machine. In fact, your Java code already uses native methods. In the current implementation from Sun, native methods are used in many places to interface to the underlying operating system. This enables a Java program to go beyond the confines of the Java Runtime. With native methods, a Java program can virtually do any application level task.
Uses for Native Methods

Java is a wonderful language to use. However, there are times when you either must interface with existing code, can't express the task in Java, or need the absolute best performance.
Accessing Outside the Java Environment

There are times where a Java application (or applet) must communicate with the environment outside of Java. This is, perhaps, the main reason for the existence of native methods. For starters, the Java implementation will need to communicate with the underlying system. That underlying system may be an operating system such as Solaris or Win32, or it may be a Web browser, or it may be custom hardware, such as a PDA, Set-top-device, and so forth. Regardless of what is under Java, there must be a mechanism to communicate with that system. At some point in a Java program, there will be that point where Java meets the outside world, an interface between Java and non-Java worlds. Native methods provide a simple clean approach to providing this interface without burdening the rest of the Java application with special knowledge.
Accessing the Operating System

The Java virtual machine describes a system that the Java program can rely on to be there. This virtual machine supports the Java Language and its runtime library. It may be composed of an interpreter or can be libraries linked to native code. Regardless of its form, it is not a complete system and often relies on an existing system underneath to provide a lot of support. More than likely, a full-fledged operating system, such as Solaris or Win32, resides beneath it. The use of native methods enables the Java Runtime to be written in Java yet have access to the underlying operating system, or even the parts of the Java virtual machine that may be written in a language such as C. Further, if a Java feature does not encapsulate an operating system feature needed by an application, native methods can be used to access this feature.
Embedded Java

It is conceivable to see a Java virtual machine embedded inside another program. Several WWW browsers come to mind. Perhaps this enclosing program is not implemented in Java. The Java Runtime may need to access the enclosing program for services to support the Java environment. Once again, native methods provide a clean interface for this access to the surrounding program. Furthermore, the vendor of the program may wish to expose some features of the program to a Java applet. The vendor would simply need to create a set of Java classes containing native methods, which provide the interface for the Java application into the program. The native method implementation would then be the "glue" between the Java applet and the internals of the enclosing program.
Custom Hardware

Another important possible application of native methods being used to access a non-Java world is providing Java programs access to custom hardware. Perhaps a Java virtual machine is running within a PDA or Set-Top-Device. A lot of what would normally be in an operating system may exist in hardware or software embedded in ROM, or other custom chip sets. Another possibility is that a computer may be equipped with a dedicated graphics card. It would be ideal to have Java make use of the graphics hardware. A set of Java classes with native methods defined would provide the Java program access to these features.
Sun's Java

In the current implementation from Sun, the Java interpreter is written in C and can thus talk to the outside environment as any normal C program can. A majority of the Java Runtime is written in Java and may make calls into the interpreter or directly to the outside environment, all via native methods. The application deals mostly with the Java Runtime, but it may also talk to the outside environment via native methods. For example in the class java.lang.Thread the setPriority() method is implemented in Java but calls the method setPriority0(), which is a native method in the Thread class. This native method is implemented in C and resides within the Java virtual machine itself. On the Windows 95 platform this native method will then call (eventually) the Win32 SetPriority() API. This is an example where the native method implementation was provided by the Java virtual machine directly. In most cases the native method implementation resides in an external dynamic link library (discussed in a following section), but the call still goes through the Java virtual machine.
Performance

Another major reason for native methods is performance. The Java language trades some performance for features like its dynamic nature, garbage collecting, and safety. Some Java implementations, like the current crop, may be interpreters, which also add extra overhead. The lost performance can be small as the implementation technology for Java systems improve, but until then and even after there may always be a small performance overhead for certain functionality a Java program may need. This functionality can be pushed down into a native method. That native method can then be implemented efficiently at the native lower level of the system on which the Java virtual machine is running. Once at the native implementation level, the developer can use the best-suited language, such as C or even assembler. In this way, maximum performance can be achieved in those specific areas while the bulk of the application is done within the safe and robust Java virtual machine. One area where you may choose to implement some parts of an application in native methods is time-intensive computations, such as graphics rendering, simulation models, and so forth.
Accessing Existing Libraries

The fact that Java is targeted at the production of platform-neutral code means that the current implementations may not access system features that you may need. An example is a database engine. If you need to, you can use the native method facility to provide your own interface to such libraries. Further, you may want to use Java to write applications that use existing in-house libraries. Again, the use of native methods enables you to make such an interface. This enables you to leverage off your existing code base as well as gradually introduce Java-based applications among your other applications coded in an older language.
Benefits and Trade-Offs

The presense of native methods offers many benefits, the biggest being the extension of Java power. However, there is always a downside to all good things, and native methods definitely have their downsides. Depending on what the goals of your application are, the downsides may not be that terrible. Foremost is the fact that, by definition, the use of native methods defeats several of Java's main goals: platform neutrality, system safety, and security.

Some of Java's attractive features help minimize the downsides, however. The best feature of all is that Java is such a nice language to develop in you won't want to use native methods unless you have to.
Platform Neutrality

Because a native method is implemented in a foreign language, the platform neutrality is limited to the language being used. Most likely, native methods are implemented in C or C++. Although those languages have standards, these standards leave a lot of room for implementation-defined attributes (even compilers on the same system may differ), so your mileage may vary. If the native method accesses the underlying system, you are tying your implementation to that system. For example, the file systems of UNIX and Win32 have some differences. There may even be differences between flavors of UNIX and Win32 (Win95 and WinNT are not identical). Once again, you may sacrifice your platform neutrality with your native method. This may cause you to have to support a limited number of platforms (rather than all Java platforms). Further, for each platform you choose to support, you may (probably will) have to implement several flavors of the native method.

The Java language and runtime provide a number of features that make applications more robust and safe. Java's memory management, synchronization features, and lack of address manipulation help prevent common programming mistakes from slipping through the development and testing phases of your product. However, once you drop out of Java into a native method, you are, once again, at the mercy of the language and system in which you are implementing the native method. If your native method implemented in C chooses to manipulate an address directly, you risk corrupting some part of memory, perhaps even the Java virtual machine itself.
Security Concerns

Additionally, the Java Language provides features to aid in the writing of secure applications. A Java virtual machine is much more capable of detecting an "evil" Java program than an application in other languages. Once you drop into a native method, the Java virtual machine can no longer verify, catch, or prevent the program from violating the security of the environment in which the Java virtual machine is running. This is the reason a Java-enabled Web browser typically does not allow a nontrusted native method to be called. In today's browsers, a trusted native method must be present on the local system in a certain location to be executed from an arriving applet (in other words, one loaded from a remote site). For more information on security, in general, see Part 6, "Security." For more information on how security applies to native methods, see Chapter 33, "Securing Your Native Method Libraries."
System Safety

Another potential hazard is the fact that a native method is not isolated. When a native method is entered, it not only accesses the environment outside the Java virtual machine, it also freely accesses the Java virtual machine directly. This is a necessary evil. It gives the native method quite a bit of power and flexibility, because it may need access to information kept within the virtual machine to do its job. This flexibility, however, exposes the internals of the Java virtual machine to the native method.
Dependence on the Java Implementation

It should be obvious that the implementation of native methods is also dependent on the Java implementation itself. This means that the native methods you write today for use with the Sun implementation of Java may not work with a Java implementation from another vendor.

The interface used for the Java virtual machine to call out to native methods and the interface that native methods use to access the internal functions and data structures of the Java virtual machine are not, currently, defined by either the Java Language Specification or the Java Virtual Machine Specification. A lot of native methods call back into the Java virtual machine for instantiating new objects, calling Java methods, throwing Java Exceptions, and so forth. Further, the method used to lay out Java types is also not defined. So, although your native method of today knows how to access the fields of an object, this could be different on the Java virtual machine of tomorrow. This oversight can be greatly helped if a standard API is defined for both how a Java program interacts with a native method and how a native method accesses data within the Java virtual machine. Even after such an API, implementation-defined behavior will likely still be present.
Java to the Rescue!

Recall that Java helps to minimize the damage of native methods. When you find yourself in the position that you must use native methods, you can take advantage of Java's features to help isolate the usage and perhaps maintain a fair amount of Java's advantages.
The Java Class System

Because Java narrows the use of native facilities to within the confines of a method, it does not affect the design of the program. A program is still a collection of classes and all classes still communicate with each other via their defined interface-that is, the classes' methods. Thus the callers of native methods do not know they are calling native methods. Because methods are discrete operations on the data of a specific object, they tend to be small chunks of code. This implies that native methods tend to be conceptually small, easily managed, pieces of code.
Java Still Works for You

Java will still perform a variety of duties-such as parameter checking, stack checking, synchronization, and so forth-before entering the actual native code. It greatly aids the developer in writing correct native methods. A native method is capable of creating new objects and calling Java methods, and it can even cause exceptions to be thrown. In the current implementation from Sun, an exception can be created by a native method and registered for throwing. When Java virtual machine gains control back from the native method, usually because of that method returning, the exception will then be thrown.

It's a good idea to make your native methods as small as possible and have them do a specific task. Do the work that needs to be done and pass the information back into the Java method. It's also wise to have your Java classes make the native methods private, then provide a public Java method that will call the private native method. This enables the Java method to perform error checks and other data manipulations, freeing your actual native method implementation to focus on its simple task.
How Does This Magic Work?

Much of the magic of making native methods work is provided in the next three chapters. This section provides an introduction, which neglects many of the details but should give you a good frame of reference for understanding the following chapters. If you don't really want to use native methods, but just want a basic understanding this discussion should satisfy your needs.
Sun's Implementation

Due to the lack of a well-defined interface between a Java implementation and its surrounding environment, the details of writing native methods will most likely be specific to the implementation of the Java system you are using. The next sections are based on the implementation provided by Sun on the Solaris-Sparc and Win32-Intel platforms.
Using Dynamic Linking

Sun's Java implementation interfaces to native methods by using the dynamic linking capabilities of the underlying operation system. The Java virtual machine is a complete program, which is already compiled for its respective platform. The nature of Java enables it easily to absorb a Java class and execute its behavior. However, for a compiled native method, things are not so simple. Somehow, the Java virtual machine must be taught how to call this native method. This is done by relying on the implementation of native methods to reside in a dynamic link library, which the operating system magically loads and links into the process that is running the Java virtual machine. On the Solaris platform, such a library is often called shared objects, or shared libraries, or simply dot-so's (.so's). On Win32 platforms, they are called dynamic link libraries (DLLs). This chapter uses DLL to refer to both.

Both Solaris and Win32 provide the necessary capabilities to achieve this dynamic linking. The dynamic linking facilities of both Solaris and Win32 are similar in concept, but differ in their details. This chapter does not attempt to describe the two in detail; however, if you wish to do native method programming, you should understand the mechanism used by your platform. On Solaris, you can begin by viewing the manual page on the dlopen() system call, and its relatives. On Win32, start with the help file on LoadLibrary() and its relatives. Further, you should understand the calling conventions and linking convention used by your compiler.

Sometime before a native method is invoked, the Java virtual machine must be told to find, load, and link the necessary DLLs, which contain the native method implementations. This is conveniently achieved by using the static method java.lang.System.loadLibrary( "mystuff" ). It is worth noting here that the name passed is not the actual filename of the DLL. Java maps the passed name into an expected filename, appropriate for the underlying system, of the DLL. In the call described previously, the string "mystuff" is mapped to a DLL named libmystuff.so on Solaris and mystuff.dll on Win32. If you run the Java program under a debugger, Java conveniently maps the same name "mystuff" to libmystuff_g.so and mystuff_g.dll. This enables you to supply two versions of the DLL-one with debug symbols, one without. Java magically finds the right one, dependent on whether you run under a debugger or not.
Defining the Calling Convention

In, essence, Sun defines the method its Java virtual machine will use to call external functions. In order to dynamically link and call the implementation of a native method successfully, the Java virtual machine must know several details. It must know the name of the function within the DLL (the implementation of the native method) to locate the symbol and its entry point. It also must know how to call that function (its return type, number of parameters, and types of parameters). The Java virtual machine expects the functions to be coded in C using the calling conventions appropriate for the underlying architecture (and compiler).

In simple terms, this means the actual function calls Java makes into the DLL must be known names; if you are trying to get Java to call into your existing library, unless your functions magically match the names Java expects (unlikely), you will usually have glue code, which sits between Java and your real functions. Java will call the glue functions, which in turn call in your functions. Alternatively, you can modify your functions to use the names and parameters Java expects, thus eliminating this extra call; however, in practice this is not always feasible, especially when calling existing libraries. Figure 30.2 shows the most likely scenarios of how your code will be segmented.

Figure 30.2 : Java's use of Dynamic Link Libraries.

The Sun JDK provides a tool, named javah, to help you create your native method implementation functions. The developer of native methods runs javah, passing it the name of a class. javah emits both a header file (.h) and a code file (.c) containing information about each native method and relevant type declarations. The .h file will contain the prototypes of the functions Java will call, and thus expect to find in the DLL. The .c file will contain stubs for each function. Thus, the developer needs to fill in only the details of the functions in the c file and build the DLL appropriately.
How the Virtual Machine Makes It Work

When a class is first used by Java, its class descriptor is loaded into memory. The class descriptor can be thought of as a directory for all services provided by the class-there is only one class descriptor loaded, regardless of how many instances of that class exist. Among its entries is a list of method descriptors, which contain information specific to methods, including where the code is, what parameters they take, and method modifiers.

If a method descriptor has its native modifier set, the block will include a pointer to the function that implements that native method. This function resides in some DLL but will be loaded into the Java processes address space by the operating system. At the time the class descriptor with native methods is loaded, the associated DLL does not have to be loaded, and thus the function pointer will not be set. Sometime prior to a native method being called, the associated DLL should be loaded. This is done via a call to java.system.loadLibrary(). When this call is made, Java will find and load the DLL but will still not resolve symbols; the resolution phase is delayed until the point of use. At the time of a call to a native method, Java will first check to see whether the native method implementation function has already been resolved-that is, its pointer is not null. If it has been previously resolved, the call is performed; otherwise, the resolution of the symbols is attempted. The resolution is performed by making an operating system call to see whether the symbol exists in the caller's address space. This includes the Java process and any DLLs loaded on its behalf. On Win32, this is done via a GetProcAddress() and on Solaris via a dlsym() call.

If the symbols are correctly resolved, the call is performed as if the Java virtual machine was making a standard C call to its own internal functions. If the resolution fails, the exception java.lang.UnsatisfiedLinkError will be thrown at the point of the native method call.
Summary

You should now have a basic understanding of how native methods enable a Java program to access the outside environment. Whether that consists of an operating system, a browser, or your own existing libraries, your Java code can reach them. It should now be clear that native methods do not come without some cost. You lose a lot of the benefits of the Java language. When there is no choice, however, native methods are there to be used. With the basic understanding of how native methods work you should be ready to tackle the next chapters, which provide more in-depth examples of native methods in action, as well as more tips and tricks to help you.

Tuesday, 17 July 2007

多媒体计算机网络

媒体:信息传播的中介, 信息的载体
计算机-信息处理机
用户-〉计算机-〉用户:键盘符号和终端图文都是媒体
计算机媒体:机器码, 符号码, 文字, 图形, 图像, 声音, 语言(符号解释器, 文字编辑器, 图象处理器, 语音识别器)

多媒体系统:同时抓取, 处理, 存储和显示两种两种以上不同的计算机媒体的系统
特点:计算机控制系统, 集成, 一体化系统, 数字化系统, 可交互系统。

音频, 视频的特点:
是当前多媒体系统的主角
数据量极大:
数字化普通话音:采样率8khz, 精度8bit, 每分钟产生3.84mbit。
数字化高保真话音:采样率44.1khz, 精度16bit, 每分钟产生42mbit。
数字化视频图像:640x480x24bitx30桢,每秒钟221mbit
要求连续,实时, 媒体间同步
数字化的媒体在计算机, 网络中存储, 传输需要较高的时间,空间上的消耗, 代价极大

多媒体对网络的要求
吞吐量:单位时间内通过网络的二进制的位(bit)数; 又称比特率--bps
传输延迟:延迟的变化--网络延迟不稳定引起。 一般用变化的方差表示
等时性:指延迟抖动较小的网络特性
误码率:传输过程中端到端数据变化的度量。

计算机网络的发展史:以太网-〉局域网-〉广域网-〉互联网
因特网:全球范围内各种广域网互联:特点:全球一统, 信息互通, 采用统一通讯协议-TCP/IP 统一的IP地址。
TCP/IP: 基于数据包结构:IP地址

互联网存在的问题
高通量:高速, 宽带:互联网:拥挤, 慢速, 等待
自良保证:连续,实时:互联网:断续, 迟缓
传播效率:广播, 组播

多媒体网络的关键技术
多媒体音频, 视频数据的压缩编码
网络得子良保证(QOS)
组播技术(MULTICASTING)

多媒体数据的压缩编码
目的:在保持信息不变的情况下, 减少总的BIT量;:
减少总的数据量, 缩短每个数据长度
寻找一种可逆得数字编码方法
编码后格式由较少BIT总量-又较少的数据或较小的数值
编码,解码必须是可逆的操作, 可以恢复

多媒体网络压缩技术
音频信号:MP3
视频信号:MPEG系列
MPEG1:VCD家用录像带质量
MPEG2: 广播电视DVD-HDVD
MPEG3: HDVD-取消
MPEG4:低频视频电话会议--互联网
MPEG7:基于内容结构--视频检索
MPEG21:多媒体框架,网络多媒体集成

网络多媒体的应用
IPTV:网络电视
电视频道采样器-〉压缩编码-〉视频服务器-〉调试计算机+遥控/信息计算机
VIDEO ON DEMAND
视频库-〉流媒体发送器-〉VOD点播服务器-〉调试计算机
VIDEO CONFERECING

新一代因特网的提出
世纪之交, 美国:
高性能因特网骨干网系统VBNS的投入运行
160所大学组成的INTERNET 2联盟-UCAID
克林顿宣布的下一代的因特网计划NGI
总称为新一代因特网

因特网的突起
WWW(一种软件)的出现和普及(94-95〕, 使INTERNET能传播图形, 语音等超级数据库; INTERNET开始进入千家万户, 成为各种阶层的喜闻乐见的信息交流形式。
GIGABIT, ATM, SDH高速传播手段, 使得INTERNET传播高质量的声音, 图像成为可能。

新一代的传输基础:DWDM--密集波分复用:以广波为载体传输
DWDM+线速路由+交换HUB组成了GIGABIT为特征的因特网传输基础网络, 称为GBIT网

关键技术:
IPV6
数据包结构:
version(4), prior(4), flow label(24), payload length(16), next head(8), hop limit(8), source address(128), destination address(128), content

ipv6特点之一:可选的扩展头部(next head)
分离放置, 路由器不必每次都检查,
长度可变, 但不超过40bite
增加可选内容:路由选择, 安全认证(authentication), 封装保密(encapsulation), 路由控制, 目标选择(附加终点信息)
ipv6特点之二:128bit的空间地址

关键技术3:mutilcasting
目的:按登记用户分组, 传播信息数据
要求:
同一小组用户只由同一类地址方式host address
用户小组可以使动态变化的(加入或退出)
小组用户分布无地理约束