text:
Clock and Data Recovery/Introduction/Jitter is far from sinusoidal..

The study of the CDR system frequency responses (that is the functions that have j$$\omega$$ as the independent variable) gives in actuality a representation of the CDR behaviour in the presence of sinusoidal jitter.

Sinusoidal jitter is best for modeling, for measuring and to retain some margin, but real jitter is essentially noisy

 * Some periodicity in the bit stream due to framing, or to periodic data patterns, may induce -via intersymbol interference- periodic components of jitter, but the real jitter will be essentially noisy.

 * in general, system descriptions (like jitter, error, jitter transfer, noise transfer and the jitter tolerance) in the frequency domain are the most used, effective and are familiar to all electronic engineers
 * in particular, sinusoidal jitter represents the worst case jitter with respect to jitter tolerance.  Sinusoidal jitter can be seen as the concentration of the total of the jitter power at a single frequency !

 * Therefore sinusoidal jitter considerations are extremely useful in most cases ( and often even give some margin with respect to the reality of the circuit application! ).

 * The use of the CDR system frequency responses, that is the most important tool used in this book, may therefore be seen as a pretty good and safe tool to describe the CDR behavior.

Jitter has different spectra at different points of the CDR
A clock is ideally a pure tone (a line in the spectrum) but in practice is always a slightly jittered sine wave(a line collapsed into what looks very much - although still very high and thin - like the bell of a Gauss distribution).

In serial data communication, the transmitted signal spectrum does not normally exhibits any line at the clock frequency.
 * The data bits are transmitted without wasting transmit power for the waveform that clocks them, in all practical types of line codes.
 * NRZ is the most common choice, and by far so in very high speed signal transmissions.
 * At the clock frequency, the received signal spectrum exhibits a minimum (a theoretical zero).

The prime task of a CDR is the recovery of the clock, so that the data recovery can follow.

As a result, the study of CDRs deals mostly with jitter processing.

The jitter, at the different nodes of a CDR, appears in very different forms.

The linear models describe the phase (=jitter) signals at the various nodes of the PLL, but they describe it ALWAYS in the BASEBAND.
 * At the circuit nodes where the actual signal is a modulated, high frequency signal, the model just describes the modulating signal.
 * Linear processing (using mathematical linear models) neither generates nor fully cancels any frequency component of the signals described, even though different frequency components of the signals may be differently amplified or attenuated, Modulation and demodulation are instead inherently non-linear processes and they translate spectra to different frequency bands.

The spectrum of the jitter is extracted (as phase difference between the phase of the clock inherent to the received signal and the phase of the CDR local clock) by some essentially non-linear processing, and shifted to the baseband at the same time (phase comparison).
 * The two input signals to the Phase Comparator are to be seen as FM signals with the respective jitters as modulating signals, and the signal at the comparator output is to be seen as the baseband jitter difference signal (the phase comparator acts as a synchronous phase demodulator).

The jitter signal in the baseband is then filtered.

Finally, the filtered jitter is translated back upwards as close as possible to the line frequency using a FM modulator (the VCO).

The baseband low-pass filtering (from the third to the fourth frequency diagram in the figure above) can be concisely characterised by its equivalent Q factor. Aaron BUCHWALD and Kenneth W. MARTIN : INTEGRATED FIBER-OPTIC RECEIVERS, 1994 by Kluwer Academic Publishers http://course.ee.ust.hk/elec692e/IntegratedFiberOpticReceivers.pdf 4.4.3 Using PLLs to Synchronize a VCO to the Data Rate
 * .... A PLL with a lag-lead loop filter such that the closed-loop transfer function is of the second order with a damping ratio of ζ = 1/√2, and a natural frequency of fn =5 KHz, that locks into a clock tone of 10-GHz, exhibits an effective Q of approximately.

QPLL = 10 GHz / 2x5 kHz = 106 This effective Q can be interpreted considering that the PLL averages the phase-error over several cycles; in this case it takes approximately one-million clock-cycles before the loop filter can accumulate a large enough signal on the VCO control line to begin tracking an input phase deviation.

The PLL can also be seen as a flywheel that is spinning at a rate close to the data rate.

The flywheel has a timing mark on it. The input data signal acts like a strobe light that flashes every time that a data transition is detected, revealing the current phase-error of the timing mark.

The loop feedback is used to align the timing mark, as revealed by the strobing flashes, to the desired position. In other words the rising edge of the local clock, that corresponds to the timing mark, should typically lock its phase half a revolution away from the transitions, i.e. 180° out of phase with them.

Increasing the time constant of the loop filter is analogous to increasing the mass of the flywheel. A narrowband loop acts like a very heavy flywheel that takes a lot of energy to alter its momentum.

The effective Q of a band-pass filter is determined by how many cycles a free running response can oscillate (point of view in the pass-band), in a PLL the effective Q is determined by how many clock cycles it takes for the VCO to respond to a phase error (point of view in the base-band). ....

A linear wander must often be included to model and to simulate correctly
A CDR always deals with two clocks: the one embedded in the received data stream, and the local clock.

 * Sometimes (e.g. in phase aligners) the local clock is kept synchronous with the clock embedded in the received data stream because they belong to the same clock domain.

 * In other cases (e.g. in regenerators and end point CDRs), the local clock would run at a frequency of its own (uncorrelated with the incoming frequency of the remote master, embedded in the received data stream), unless forced by the PLL to deviate from its free-running frequency and to lock itself to the incoming signal.

 * In these cases the representation of the circuit shall either take into account this frequency difference in the input signal, description, or in the circuit description
 * More precisely, either:
 * the input jitter shall include a component (= a phase ramp):

$\phi (t) = (f_p - f_{fr}) t $      [ rad ]
 * where fp is the frequency of the received pulses (i.e. the frequency of the clock embedded in the received pulse stream) and ffr is the free-running frequency of the local oscillator,

 * or ffr in the model of the VCO center frequency shall be correspondingly offset from fp.

Jitter is a discrete time variable, and some jitter samples -as often as not- may be missing!
In a NRZ signal, a transition occurs when a bit 1 is followed by a bit 0, or viceversa.

In a digital transmission, the incoming signal carries its phase information by its transitions from one level to another.

The NRZ bit stream (the most often used for data transmission) has a variable density of transitions.

(Encoding or modulation may be used, but the problem of variable density of signal transitions, although mitigated, remains).

fp is the upper limit of linear models

 * A good part of all CDRs (mostly CDRs based on 2nd order architectures) react to the input phase variations only at frequencies significantly lower than the line pulse frequency fp.

 * Some aspects of the CDR may be studied without exploring the range of frequencies much higher (or the range of time intervals much lower) than the range important for the closed loop operation.
 * linear models are useful when the PLL bandwidth is much tighter than fp
 * The linear models of CDRs can be seen as models of discrete time systems, that are sampled at the frequency of the received pulses fp.
 * The jω representation of the system behavior is meaningful up to jωp (jfp = jωp/2π ), and repeats itself periodically at higher frequencies, without additional information to offer.
 * simulation is needed to investigate faster systems and transients
 * t he time steps for a numerical simulation can be chosen even smaller than the line pulse period, to investigate what happens in the short intervals between signal transitions.
 * Sometimes the study at frequencies lower than fp can be further simplified using normalised frequency and time scales (both in linear models or in numerical simulations)
 * The simplification associated with normalization of the frequency and time scales may still be adequate for the investigation.
 * The normalisation is made, for instance, with values of ω/ωn, or ω/ωn2, on the x axis.
 * This approach brings the focus on the fundamental concepts: concepts that become then easier to grasp, remember and use.
 * De-normalization puts the actual value of the natural angular frequency ωn, in the place of the value of 1 rad/sec.
 * The time τ that appears in the time functions shall be readjusted in the same way, rescaling 1 sec to its actual value of 1/(ωn) sec.
 * The angular frequency with which the signal pulsed are received, ωp does not always appear in models/simulations.
 * In fact the frequency of the received pulses fp ( fp = ωp/(2π)) is a fundamental circuit characteristic for the phase comparator and for the VCO.
 * The filter is the only block that does not have to process frequencies around fp, and very often only processes frequencies at least one or two decades lower that fp.
 * With closed loop, the study of the relation between phase of the input signal and phase of the output signal in the ω domain may be restricted to just the range of frequencies where the filter influences the loop!
 * Not infrequently, the actual value of fp is neglected in some descriptions of the PLL operation. In many cases, it does not appear in the linear modelling equations.
 * All in all, the line pulse frequency fp does not always appears in this book when one may expect! See for instance the last figure above.

The frequency of the jitter samples fp is jittered

 * The time instant of samples is jittered to start with.
 * The time interval between sample instants is not exactly constant - or else there would be no jitter!.
 * This is normally not a big concern in itself, and can often be neglected.
 * What really complicates things is the following point regarding missing transitions:

jitter information only comes when there is a level transition in the received signal

 * This is the big problem with CDRs (a problem that does not affect frequency synthesisers).
 * What happens when the received signal does not present, from a certain instant on, any more transition?
 * The phase comparator, the first block that compares input and feedback signals, cannot any longer make meaningful comparisons, and the PLL finds itself into “open loop” condition.
 * The loop phase error may drift and increase for some time, but a good lock will be found again if the phase information (signal level transitions) reappears shortly.
 * In the meantime the recovery (=regeneration) of the received pulses (all of the same level!) takes place correctly.
 * In all slave CDRs the sampling instant drifts away from the optimal position that corresponds to the locked condition of the  PLL,
 * while the feedback loop is open and can no longer keep the local oscillation phase locked to the input phase.

 * If the condition persists long enough, errors may appear in the data flow that comes out of the CDR, and even slips finally take place (slip = a lost or an added clock cycle with respect to the transmit clock).

 * Either an alarm circuit intervenes to declare a LOS (and replaces the regenerated bit flow with a telling pattern like an AIS = Alarm Indication Signal), or the CDR drifts to its free-running frequency and its output is unreliable!
 * (The slips that inevitably take place in that condition may generate by themselves a problem. If a section of the network downstream is slaved to this CDR, errors will result wherever (somewhere upstream for instance) the original clock domain is re-entered.).

 * As long as the lack of transitions persists, the situation worsens until the frequency of slips corresponds to the difference:

fp frequency of received pulses – ffr frequency of the free running sampling frequency.

 * In some extreme cases, where the above difference is small, some transmission in the slave network section may still be possible, but with a heavy penalty in terms of error-ed bits and slips (= frequent retransmission of the blocks that are detected in error).

Start of reception
The CDR acquisition phase starts when a signal with sufficient power is detected by the LOS (Loss Of Signal) block, more precisely at the moment when the LOS is de-asserted. Acquisition time cannot be used for transferring useful bits of information bits because it may be affected by a significant number of errored bits.
 * 1) Burst mode. If the transmission system is meant to operate with intervals of no signal power alternated with intervals of normal transmission (Burst Mode System), the acquisition takes place very often. Not to take up a significant percentage of the total burst duration, acquisition must be fast and shall last no more than 20 to 50 line pulse periods. In burst-mode applications the CDR is based on a 1st order control loop.  This type of implementation is best fit for fast acquisition, but is not remarkable in presence of micro-interruptions nor of long sequences of pulses without level transitions.
 * 2) Continuous mode. If instead the start of reception is a exceptional occurrence in the system (Continuous Mode System), it may last correspondingly much longer without significant penalisation of the system efficiency. The CDR is often based on a 2nd order control loop, slower in the acquisition phases, but more resilient to long sequences of pulses without level transitions and to micro-interruptions.The acquisition is less repeatable and the circuit design and testing is more difficult.

Incomplete and irregular flow of incoming level transitions

 * A good part of all the possible transitions do not materialise because the level of the two pulses (before and after each instant of a possible transition) is the same.
 * If there was a transition every time it was be possible, the bit pattern would be predictable: when it is predictable it cannot carry information!
 * Level transitions take place in the transmitted signal less often than possible, and unpredictably.
 * These characteristics are a consequence of the randomness of the bits to be transmitted.
 * They can only be described statistically. The most used statistical quantities are:

 * For long term descriptions, parameters that describe average or integral properties:
 * - the transition density DT (average probability of a signal level change between adjacent pulses of the signal), that corresponds to the concept of the run-length, but from the long-term average point of view.
 * With reference to a given length of a serial signal, and in the hypothesis that it is the average that matters :

DT = actual number of transitions / maximum amount of transition [0% to 100%].
 * - the running disparity (running disparity: integral sum of the opposite polarities of all received bits), that measures the DC content of the received signal, and is especially important in burst-mode receivers.

 * For short term descriptions, two parameters that describe the peaks of irregularity:
 * - the maximum run length (the number of contiguous bit (runs) during which the signal does not change level), that concides with CID (consecutive identical digits) in NRZ coding) ;
 * - the latency of circuit blocks ( its effects cumulate with those of the run-length of the received signal to limit the response of the PLL).

 * In all practical cases, the original bit stream is processed before transmission, to make it easier to recover by the CDR.

 * Apart from modifying the NRZ coding with some sort of modulation (used to adapt NRZ spectrum to a transmission medium that is band-pass and/or frequency-dependent), the most common techniques for NRZ are:
 * - a change of the bits, according to a fixed rule that changes each bit taking into consideration it and a limited number of preceding bits, called scrambling
 * - an encoding that increases by some percent the bit rate of the original bit stream, either
 * - FEC, or
 * - line codes.
 * The most important line codes are presented in the following table:

 * With a rough approximation, the run-lengrth may affect the closed loop performance of the CDR in proportion to its value multiplied by:  1 / (fp - ffr ).
 * Depending on the specific CDR implementation, the jitter generation may be the performance more affected, or the jitter transfer, or the jitter tolerance.
 * In any case, the minimum and maximum values of DT that are specified for the application considered, do influence significantly both the design and the testing of a CDR.

 * The worst-case maximum run-length that must be tolerated in practice is 72 CID (Consecutive Identical Digits) in SDH systems, or something equivalent to not much more than 72 CID in optical links. A few repeated blocks of 72 CID, separated by just one or a few digits of opposite polarity, are unlikely but possible.

 * As a result, CDRs are frequently specified, designed and characterized in order to stay in phase lock even when input phase information disappears for a significant number of line pulse periods (hundreds or even a few thousands).


text:
Clock and Data Recovery/Introduction/Models can only be linear..

The reference models
Today' CDR circuits are implemented using a PLL architecture, and are realized mostly or entirely with CMOS digital circuitry. The complexity of the circuitry is often so large that -not unfrequently- the architecture is not clearly identified and consequently the circuit operation is not fully understood. It is very useful to make reference to relatively simple circuits that implement the CDR in a first or second order PLL architecture. The comprehension of the characteristics of the model and of the mathematical equations that describe its behaviour are well suited for the understanding of almost all the actual circuits and not unfrequently even allow a better design of them.

Mathematical descriptions
Block diagrams can be used to describe a physical system, or its schematic diagram can be used, or the set of mathematical equations characterizing its parts. However mathematical models, in the form of systems equations, are needed when detailed relationships are required.

Every control system may theoretically be characterized by mathematical equations. The solution of these equations represents the system’s behavior.

Often this solution is difficult if not impossible to find.

In these cases, certain simplifying assumptions must be made in the mathematical description.

Linear models
(Applicable to "small signal" conditions - linear equations and formulae - s and jω functions)

For a large number of control systems those approximations and simplifications lead to systems that can be described by linear ordinary differential equations. Techniques for solving these equations are well documented in the literature of mathematics and engineering.

More precisely, in a large subset of its field of operation, the PLL fulfills certain conditions: it is linear, time invariant, causal, sometimes altogether abbreviated into LTI.

Under these conditions the model is simplified:
 * 1) the differential equations become algebraic polynomial equations in the transformed domain.
 * 2) all solutions in the t domain are functions = 0 for all t < = 0,
 * 3) if the system is in steady state, the Laplace transform (functions of s) overlaps exactly the corresponding Fourier transform. It is enough to substitute s with 0 + jω in the former to obtain the latter.

 * In this book, the basic notions of the Laplace Transform are used to analyze of the circuits presented, identify poles and zeros etc.
 * For steady state phenomena (jitter transfer, jitter tolerance, noise shaping), the analysis is still made in the transformed domain, using the simpler Fourier Transform (obtained for s = 0 + jω)

 Jitter transfer function: the ratio of the output jitter to the input jitter (= the closed loop transfer function). The independent variable ω is the angular frequency of the sinusoidal jitter of the timing transitions.

1. Real independent variable. In steady state not all possible values of s are to be considered, but just those of its imaginary part ω, that is a real variable. The function of ω that is obtained still assumes complex values, like magnitude and argument or real and imaginary parts. 2. Real dependent variable. If the system is a minimum phase system (a reasonable assumption), just the magnitude (= absolute value) of the system frequency response shall be used, as it contains all the information. The magnitude is normally represented in a Bode magnitude plot. The argument is often neglected by the PLL engineers.
 * The simplification consists in the use of a real function of a real variable, the magnitude of the function of interest:

 * For transient phenomena, the functions in the Laplace domain are reverse transformed to obtain solutions in the form of time function (in this book, mostly the (Unit) Step Response).

In modern communication systems the implementation of the clock and data recovery circuits (CDR) is primarily digital, and the circuits can be very complex (in particular the loop filters and the local oscillator).

The designer sometimes may find it difficult to choose the right architecture and also to understand, in some conditions, the operation of the circuit itself.

Downstream in the product development, the engineers in charge of verification, validation, characterization and testing often do not even attempt to identify the fundamental architecture of the loop.

The best way to solve this is to choose a system architecture that corresponds to the structure of a well understood model of CDR, and to refer to its mathematical description to understand the closed loop operation in all conditions and to actually design the system circuitry blocks.

Reference to the fundamental structure and to the linear modeling that can be applied will also make easier and more effective the subsequent engineering tasks of industrialization, operation and maintenance.

The three model architectures of first order, type 1, and of second order, type 1 and 2, offer the best compromises between stability and performance for practical CDRs. They can also be well described mathematically and their operation can be easily understood.

Once familiar with their operation, the circuit designer will be able to decide what circuit choices to make, in terms of structure of the blocks and even of the order of its CDR.

Linear models of the circuit blocks → linear model of the whole circuit

Each circuit block can be described by a linear model in a certain range of the input signal as long as its parameters remain constant.

When -as is often the case in CDRs – the blocks are designed to operate with linear relation of input to output, the whole systems can be described by a linear model in a wide range of operation.

This book presents in detail three linear models, for the case where both the phase comparator block (based on a sawtooth and linear between the points of jumps to the previous and the next tooth) and the VCO (based on a frequency controlled oscillator with a continuos control and linear within the frequency extremes of the control range) can be described by a linear model.

The three models belong to the two fundamental architectures:
 * 1st order (type 1) loop
 * The (slave) CDR based on a second order PLL
 * 2nd order type 1
 * 2nd order type 2

Non linearities of some circuit blocks prevent their modeling → resort to the linear model of the architecture is still useful The usefulness of a linear model certainly applies to a system whose blocks can be individually modeled with linear equations.

But the usefulness of "linear" models extends beyond the study of the linear circuits they are meant to describe.

Even if for one or more blocks a linear model is not possible, the “linear” model of the whole structure can still be useful.

In many practical cases constraints of available technology or of cost prevent the use of “linear” phase comparators and/or of “linear” VCOs.

A non linear system (like a PLL based on a bang-bang phase detector) can be investigated using a linear model, with the restriction that the linear model is only useful in a limited range of the input signal variations. It is necessary that the system is restricted to a "small signal" condition, where the hard non-linearities do not make the system deviate too much from linearity.

Modeling of these blocks with linear equations is therefore limited only to very small variations of the signal close to the operating point. The parameters of the block(s) can be considered constant as long as the signal moves very liitle around the operating point.

Still the linear models of the “linear” case are useful (apart from being the only closed form tool available!).

The familiarity acquired with the model of the “linear” architecture can be very helpful to understand how the “non linear” circuit behaves in the neighborhood of a certain operating point.

When the signal excursions are large and the non linear aspects cannot be neglected, the linear models are no longer valid but simulations are stiil a valid tool left to the engineer.

Simulators can include some non-linearities
(Applicable to "large signal" conditions, simulations are to be recomputed case by case)

The formal modeling of systems is based on a mathematical model, which attempts to find analytical solutions enabling the prediction of the behaviour of the system from a set of parameters and initial conditions.

When the signals are large, the non-linearities of the circuit blocks can not be neglected and linear models are no longer accurate.

Computer simulation is then used as an adjunct to, or substitution for, mathematical models in the system conditions for which simple closed form analytic solutions are not any more accurate, for instance when some hard non-linearities are essential to make a prediction.

 * This is typically the case of the acquisition phase of a CDR.

 * Some modelling and simulation programs have been developed to verify the content of this book.
 *  In particular some have been developed to make a good prediction of the acquisition phase of a 1st or 2nd order CDR.
 *  Others generate Bode plots of jitter functions of the angular frequency ω.
 * Each of them includes as output a time and/or a frequency diagram, that have often been used as figures in this book.

 * They are all based on simple calculation sheets, written with free software programs (Apache Open Office and/or LibreOffice), and are available to the reader as free software pieces.

Just three architectures are of practical use
This book will show some possible model architectures for the CDR, and state that the practical choice is made among just three!

In all practical cases, one of those three models is the fundamental tool that gives a good understanding of the CDR operation.

Linear, time-invariant idealizations of the CDR circuits will be be described in detail.

The fundamental cases of: will be presented and emphasized as the only really important models to use (even when some blocks in the actual implementation are non linear). More details on why loops are identified by order and type are presented in a page a little further on in this book. Although such idealizations may not perfectly describe our circuit in some specific aspects (non-linearity of some circuit blocks, etc.) they serves to simplify the mathematics, keep us from getting lost in a welter of algebraic quantities, and –most of all- produce results that can be interpreted quite usefully. Further on in the book, a section called Structures and types of CDRs/Examples does show the characteristic functions of these three models, as well as the characteristic functions of some others. The other model architectures that are presented in Structures and types of CDRs/Examples are there only for didactic purposes, but are of no practical use for the electronic engineer. The three fundamental models instead, are further developed in three dedicated chapters :
 * 1) a first order loop for the burst-mode CDR (often, but not always, a phase aligner) (1st order type 1)
 * 2) a second order loop for the regenerator (slave) CDR (2nd order type 1)
 * 3) a second order loop for non linear blocks with widely variable gain  (2nd order type 2)
 * 1) 1st order (type 1) PLL
 * 2) 2nd order type 1 PLL
 * 3) 2nd order type 2 PLL.

First order systems
These systems only have one degree of freedom. In the study of 1st order PLLs the time constant of the pulse response, called τ (tau), is considered.

This time constant τ is exactly the inverse of the loop gain:

1 / τ = Gφ * Gf * GVCO = G and the natural frequency ωn1 is defined as 1/τ = G.  (The subscript n means natural, the subscript 1 - optional - means 1st order)

1st order systems are primarily used where fast acquisition of lock is important.

Fast acquisition means in actuality that τ/Tp ranges between 25 and 100, where  Tp = 1/ fp is the period of each received pulse.

It should be noted that Gφ and GVCO are almost always a inevitable consequence of the technology chosen to implement the circuit. The circuit designer shall therefore play mostly with Gf to obtain the desired value of τ.

Second order systems
These systems have two degrees of freedom.

In the models of 2nd order PLLs the quantities considered are the damping ratio ζ and the natural angular (undamped) frequency ωn2.

(the suffix 2- is added to ωn simply to remember that this parameter refers to a 2nd order system,

''the suffixes 21 or 22 are added to ωn and to ζ simply to remember that the parameter refers to a 2nd order system, either of type 1 or 2. Type 0 is not used for CDR applications)''

The damping ratio ζ, for the PLL to be of practical use inside a CDR, must be close to 1 (0.7 to 1.3), to ensure that the behavior of the loop is neither under-damped nor over-damped.

Saying that the second order loop has one more degree of freedom than the first order loop is therefore an overstatement.

It is more fair to say that in both cases the time (and frequency) response of the loop are primarily set by the gain G. In the case of the second order loop it is possible to have a slightly higher variability associated with the (limited) range of variation allowed for $$\zeta$$.

The natural angular frequency ωn2 in a 2nd order loop depends: If the frequency ωn1 is defined again as 1/G (like in the 1st order loop), the natural frequencies for the 2-1 and 2-2 loops are: ωn21 = 2 ωn1 ζ21 ; ωn22 = ωn1 / 2 ζn22 e.g. if ωn2 = ωn1, then, ζ = ½. 2nd order loops of type 1 and of type 2 differ substantially from each other and their architectures are used in different applications of CDRs, as the following pages of this book will emphasize.
 * on the loop gain (in analogy with the first order loop)
 * on the damping ratio ζ
 * but also on the type of the loop:

Third order systems

 * Unity Feedback
 * The PLL of a CDR is a unity feedback system because the output (the recovered clock) should be as close as possible to the input (the clock embedded in the incoming pulse stream), apart from the rejection of high frequency components of the latter.
 * Low Pass
 * The corner frequency of the PLL jitter transfer function (approximately ωnx where x is the loop order) indicates that lower frequencies of jitter are tracked, while higher input frequencies are not tracked (= rejected). Lower frequencies are supposed to be the ones needed for the acquisition transient and for tracking the jitter and wander inherent in the incoming signal.
 * Type 1 or 2, only
 * The PLL of a CDR is either a type 1 or a type 2 loop (Type means the number of poles of the open loop transfer function in the origin, that is, how many times the factor 1/s appears in the open loop transfer function). In a loop of either type 1 or of type 2 the average distance between the input and the output phase (the sampling error) is either finite or zero.
 * Compensator
 * The additional singularities (pole and zero) are added together so that the order of the loop is increased, but not its type. They make up a "compensator".

Without loss of generality, any CDR loop of the 3rd order can therefore be modelled as a 2nd order loop with the addition of a pole-zero pair (including the extreme cases where either the zero or the pole is at ω = 0 or is at ω = ∞ ) in the forward path of the PLL, increasing the complexity of the loop filter.

3rd order system models of CDRs (unity feedback)' are 2nd order loop with an additional pole-zero pair in the forward path.'

 * Lag compensator
 * The compensator must be a low pass ( ωp <  ωz, i.e. a "lag" compensator), as high frequency jitter and noise in the input signal must be more, and not less, rejected.

 * Compensation far away from ωn2
 * Not to interfere with the main characteristics of the CDR that is being retrofitted with the compensator, the compensator itself shall make its effect felt at frequencies at least 2 decades away from the ωn2 of the loop being compensated.
 * For instance, consider that the jitter transfer function should stay very close to a magnitude = 1 up to ωn2. Below ωn2, the spectrum of the regenerated clock shall replicate with neither selective emphasis nor selective de-emphasis the spectrum of the clock that is to be recovered from the incoming signal.
 * In the case of regenerator equipment or of clock distribution in the network, this requirement is explicit, and stringent.

 * This is the reason why the 2nd order models still describe the important performances of the loop, and why the possible compensation only compensates marginal performances. But 3rd order models are complex and are not worth the effort of keeping them in mind as such, as the fundamental performances depend on the underlying 2nd order system only.

 * The case of the lag compensator that retrofits a 2nd order system and operates in a higher range of frequencies is not very complex and is always pertinent in actuality. All real systems are limited in their frequency behaviour by high-frequecy poles that -inevitably- come from the limited bandwidth of the circuits involved. In CDRs moreover, at least one first high frequency pole is deliberately added (the low-pass at the output of the phase comparator or of the charge-pump), but at frequencies high enough not to interfere with the desired loop characteristics.

Such 2nd order type 1 system would apparently benefit from the compression to much lower values of the steady state (= sampling) error, that results from the added compensator. However, this improved performance only materialises long after the acquisition phase, proportionally to the ratio between the mean frequency of the pole/zero pair of the compensator and ωn2. This is an example of how the compensation of a CDR does not substantially alter the behaviour of the fundamental loop: in fact, the longer settling time would also be associated to a proportional reduction of bandwidth for tracking with the reduced sampling error.
 * The case of the lag compensator that retrofits a 2nd order system and operates in a lower range of frequencies would in principle be applicable, but only to 2 - 1 systems.  It would not improve a 2-2 CDR, that already has, in then open loop transfer function, very high gain at low frequencies.

The two fundamental 2nd order models ( that can be made more fitting as 3rd order systems incorporating a compensator ) remain the fundamental tools to keep in mind at all times to understand the important performances of the loop.

3rd order models are seldom used as such, although the simulations often do include the additional poles and/or compensator.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
User talk:24.67.96.244

I removed the speedy deletion tag you added to Collaborative Problem-Solving in Educational Settings as I do not feel that work meets the criteria for deletion - speedy or otherwise. If you care to contest that, please list the book on the votes for deletion page and the community can take a vote. --Jomegat (talk) 12:35, 30 April 2008 (UTC)

title: User talk:24.67.96.244


text:
Netherlands Immigrant Integration Guide/English Basic

The Inburgeringscursus for English speaking people living outside of the Netherlands is a course necessary for certain classes of non-EU citizens wishing to immigrate to Dutch society, while still living abroad. It is one of the conditions for immigration and is part of a larger Integration law for new immigrants to the Netherlands. The foreigner should do the exam at the nearest Dutch embassy in his or her country. Cost is as of 2008 Euro 350,- which should be paid to the Ministry of Foreign affairs (Dutch: Ministerie van Buitenlandse Zaken).

The examination consists of three parts.
 * Knowledge of Dutch society (Dutch: Kennis van de Nederlandse samenleving)
 * Very basic knowledge of Dutch language. See Dutch language course. This includes
 * List of antonyms (Dutch: lijst van tegenstellingen)
 * Repeating a story in the Dutch language

Apart from factual information about Dutch society and Dutch language, the Dutch government tries to educate the prospective immigrant into opinions and behavior that they consider appropriate, desirable and correct.


text:
User:Lifetiki

I am Lifetiki; my real name is Benjamin Smith. I am a high school student who loves math and science. I have been a reader of Wikipedia for quite some time, but now I have decided that I should contribute to its sister projects as a way of saying thanks for the wealth of knowledge it has taught me. I encourage you to do the same.

About Me
I live in a small town in West Virginia, USA. Although I have scored well on IQ tests and I make good grades, my goal is not to brag about my intelligence, but rather to improve society with my intelligence. I do not try to say I'm better than anyone else because I know that one head injury in a car accident or some other bad thing could make me lose it all. I thus want to help my fellow man by using my knowledge for the advancement of human civilisation.

I am a Christian who goes to a Baptist church. Because I believe in God, I will give him credit for the intellectual capacity he has granted me. Although I am a Christian, I will not try and force my beliefs on my fellow Wikibookians because it is not appropriate to do so in any place other than my user_talk page which I need to create sometime. Because I am told to tell you about my Lord and saviour Jesus Christ, (see Matthew 28:18-20) I will do it in the most appropriate manner I can. Thus I will eventually write a book on Wikibooks about the Bible and how to read it if an administrator says it is appropriate for Wikibooks. If he/she says it is not, I will not write it on Wikibooks.

Books I Intend to Write
As I written no books as of now, these are the topics of the books I intend to start and work on significantly:
 * 1) Math and Science related
 * 2) A book on math that I will write the content and formulæ and someone else can put in pictures.
 * 3) * Will rant about the evils of calculator abuse.
 * 4) A kids' book on physics
 * 5) A kids' book on chemistry
 * 6) Miscellanea
 * 7) A book on how to study the Bible
 * 8) A book on making an educated opinion
 * 9) *Will distinguish fact from opinion
 * 10) *Will teach that logic is good
 * 11) *Will have a section on faith and its definition
 * 12) *Will teach respecting others' opinion is a good way to win an argument.
 * 13) *Will try to be neutral

title: User:Lifetiki


text:
Working Rocrail with Hornby Elite DCC Controller

Purpose of this document
This document is for beginners to Rocrail who want to use a Hornby Elite DCC controller R8214 and Hornby Accessory Decoders R8216 and/or R8247.

It explains how Rocrail adjusts for quirks of the Hornby Elite controller, which is now fully supported by Rocrail using a specific elite sub-library.

A complimentary Wikibook is Introduction to model railways.

Drawing up a trackplan, identifying locomotives and motorised points to the system is covered by the Rocrail step by step quick start quide and the main on-line manual.

Rocrail nomenclature for points is switches and turnouts.

To progress to more complex train operations please read the Rocrail on-line manual in depth and filter out specific applicable information.

A layout will likely have to be reworked into isolated power districts and/or operational blocks with necessary sensors to provide feedback for say aspect lights or signals, train positioning, or allow trains to run automatically, or to schedules. Such activity is presently outwith the scope of this initial help document.

The Rocrail forum is a valuable user group facility worth checking periodically for applicable posts.

Introduction to Rocrail
Rocrail is a freeware project that enables computer control of a compatible digital command control (DCC) model railway layout under a Windows or Linux environment.

Control a basic layout, run locos and switch turnout-points from a computer by simple mouse clicks, operate advanced manual working with or without block control, and/or run fully automatic scheduled train operations.

This is achieved by a server and client arrangement installed on the same or different computers depending upon user requirements. Control can be from a single computer linked directly to Elite, or other computer(s) on a local area network (LAN) connected to Elite, or using a remote computer over the Internet, if this has client installed. Control is also possible using mobile devices such as mobile phones or tablets.

Click for picture:

Server is the engine room working in the background and client is a graphic user interface (GUI) connecting the human controller, footplate, signal box to a layout via Elite. The GUI is known in Rocrail as RocView but is referred to throughout this document as GUI.

Read the on-line manual for information on setting up these wider control methods.

Download and installation of Rocrail Files
Go to Rocrail and from the left hand column select the download link for your platform - e.g. Windows or Linux. At the linked location choose the correct file type for your operating system - e.g. unicode for Windows. Save this file to say a desktop folder. Svn snapshots are available from here as nightly builds to fix recent problems in various areas and may be used at risk. Check also the asociated build notes.

Important - Note that there are some performance issues running Rocrail under Windows and you must choose the file most suited to your version of Windows (Ansi or Unicode) - read the Rocrail manual section 'Running Under Windows' for more details.

If a layout computer does not have Internet access or files are being downloaded to a computer other than the one that will control the layout, save all files to a portable memory stick and transfer them onto the layout computer.

Once downloaded (and if necessary copied to layout computer) navigate to where the files are saved and double click the .exe file. After Rocrail has finished installation, access the applications from Start-All_Programs-Rocrail.

If you already have an earlier version of Rocrail installed a snapshot can be loaded over it without losing any trackplan or .ini file data.

Click for picture:

Or make shortcuts and place them on the desktop.

Updating Elite
The Elite must have at least firmware vers.1.2 installed (check for this at Elite start up). It is advised to download the latest update (currently v 1.44) and instructions from Hornby web-site and install on the Elite. Check the integrity of all locomotive addresses and that Elite still works the layout in Standard and Classic Modes after any update.

Full instructions are available on Hornby's website explaining how to upgrade the firmware, especially if you are using Win 7/8. The latest installer ensures reliable updates of the Elite firmware on all Windows machine types and OS versions from XP to 10.

Use the same USB cable to connect Elite to Rocrail pc as for the firmware update. For basic Rocrail operations an XpressNet cable is not required.

Amending Rocrail configuration (.ini) file
So that Rocrail software will recognise Elite as the interface unit, parts of the .ini file are changed to tell Rocrail which equipment is being used and then say how to find it.

Connect Elite to the running layout computer with USB cable and switch Elite ON. Look in Start-Control_Panel-System-Hardware-Device_Manager-Ports(COM & LPT) for the ‘com’ port number Elite is using (e.g. COM4). If Elite is not connected and switched ON there will be no ‘com’ port allocated. In Win 7/8 the port may not state Elite until the port driver is updated using the Elite driver.

The preferred way to amend the .ini file is from within Rocrail main screen - from File menu select in turn Rocrail Properties and then Rocview Properties. Fill in the required information fields and/or click radio buttons. In the Controller tab select and add Expressnet as the basic controller, amend this to read Elite and select the radio button for the Elite. Depending if you want to run in Elite Standard or Classic mode depends if you need to tick the V2 box - see later in turnout addressing. Save and close these files. Then save and close Rocrail and restart.

Note: .ini files can be manually amended using notepad or similar basic text editor if you are comfortable using this method.

Important – if manually editing .ini files carefully change only those bits of the file to read as shown in this link

Leave everything else alone then save the file – File-Save, and Exit the editor.

Getting started with Rocrail
Before a layout can be operated with Rocrail, the user must know how to correctly start and stop both server and client, draw a trackplan of a layout and tell Rocrail about locomotives and switches-turnouts-points. See the step by step guide and main manual for details.

Rocrail has introduced a 'Workspace' facility simplifying the final startup and shutdown procedures. This is best read about in the Rocrail manual, which explains how to set it up.

Some things to note about Rocrail
A trackplan, including the associated locomotive-switch-other tables should be saved to a meaningful name (e.g. Your-Railway.xml) using File-Save/Save_As before exiting server.

All changes thus saved are uploaded to server. Rocrail must be stopped and restarted for the file to become effective before it can be used. The chosen filename will also write into the configuration file so that Rocrail knows which trackplan to use as default.

Do not use Windows close ‘x’ symbol to close the server DOS window as it shuts down without carrying out the full save process. Using Ctrl+x, Ctrl+c and/or Ctrl+Alt+Del task manager methods will also abort Rocrail too early.

Using Rocrail Workspace precludes this problem. A workspace is a collection of files that Rocrail uses at startup to automatically load your track plan. Set it up initially from the File menu.

Simply close down Rocrail from drop down File menu – File-Exit or Shut down Rocrail and Server.

8051 is the default server monitor port allocated by NMRA to Rocrail. This is set in Rocrail properties from the File menu.

Rocrail can reset early Hornby locomotive decoders (R8215) during power up and power down sequences. It is recommended that if users have this problem they replace these decoders with latest Hornby production (R8249_v1.3 NMRA compliant or R8245 Sapphire) or other make decoders, preferably installed by way of a plug and socket. This is not a Rocrail fault.

For Rocrail to operate points correctly the inherent Elite points addressing differences between Standard and Classic modes (due to legacy problems catering for the Hornby Select command station) must be adjusted. Rocrail can be set to allow and adjust for the Elite being in either mode. See later in turnout addressing.

Rocrail on-line manual
The Rocrail on-line manual contains much information about equipment that Elite users may not need or do not have, and also tells how to operate beyond present Elite functional capability.

Refer also to the Rocrail quick start step by step guide.

The Rocrail on-line manual is a live Wiki document subject to frequent change, so please check periodically for updates.

Trackplan
To draw a trackplan refer to on-line manual section - Creating your first trackplan - for guidance.

Draw up a simple schematic of the layout. Do not bother with details like blocks or signals, etc yet. Just add basic track, straights, curves, turnouts, crossings, buffer, etc to mimic your layout. Do not make it too elaborate to start with as it will probably be amended later.

Place turnouts-points by picking Turnout left or right hand, clicking on grid, then re-orientating to suit. Other types of turnout are possible – crossing at right angles, double slip crossing (not diamond), or triple, 3-way. These won't work until they are listed - see later. You can also create your own track symbols - see on-line manual.

In automatic or manual operations modes point motors can be fired in sequence to set a route before a train moves.

The track plan background colour can be changed, select View-Track_Plan_Colour. Text can be placed single or multi-line, font resized and re-orientated to suit, but placing can obscure the track lines.

Save a new trackplan with a suitable name – e.g. Your-Railway2.xml using File-Save. If not Rocrail will save to the default name - plan.xml.

To get a trackplan to work with Elite it needs to be saved and Rocrail client closed down and restarted in sequence.

Server and client will by default be on same computer, unless operating over LAN using more than one computer or allowing friends to run (and probably trash) your trains over the web. If so read further into the manual and forums for how to set it up.

Listing locomotives
Read the Rocrail on-line manual, locomotive section to see what goes in which box, what is essential to make it work and what is just information.

Pictures of your locomotives can be added to the locomotives table. See the manual.

Listing Switches-Turnouts-Points
Rocrail calls them Switches in the manual so look for and read that section, but Rocrail calls them Turnouts in GUI area. Let’s generally call them Points for now unless otherwise stated.

Pull down menu Tables-Turnouts and define points in a similar way to locomotives, but only if they are solenoid motors and they are DCC controlled.

Manual points or solenoid point motors operated by analogue methods - passing contact/momentary switches, probe and stud, CDU or not, etc. are not able to controlled by computer. For other types of points motors, such as Tortoise, see the manual. Populate turnouts table as for locomotives.

ID is users preferred words or numbers to call each turnout e.g. Point-1, P2, Pt 3A-B, T5, etc. The rest as required but they can be amended later if necessary.

Address and Port - These instructions apply only to Hornby 4-port point and accessory decoders R8216 or R8247. For other make decoders refer to manufacturer's data. Hornby point and accessory decoders have 4 ports and normal practice is to connect 1 point motor to each port, although for a track crossover junction 2 motors can be wired to a port.

For each turnout location on the trackplan an Address and Port value is required. Various addressing methods are available in Rocrail but the preferred way for use with the Elite is PADA. Hornby sends a different value to either address or port according to which Elite mode is in use - Standard or Classic. Rocrail can adjust for this as explained in this Rocrail Wiki section relevant to the Elite [http://wiki.rocrail.net/doku.php?id=hornby-elite-en. It explains how to set Rocrail to allow for operating the Elite in Standard or Classic modes.

To invoke PADA addressing set all address blocks to 0, then number each port sequentially to match the turnout number - e.g. T1 = 1, T2 = 2 ... etc ... T99 = 99. There is no need to identify which accessory decoder you are using, just carry over the turnout number. Continue the addressing sequence for as many accessory decoders and turnouts you have.

Various other addressing methods are possible, e.g. NMRA, MADA and FADA. See the Rocrail manual for definition of these methods. Also see the basic Address-Port designation page. Scroll down to switch addressing for further details:.

Whichever addressing method is used Rocrail will recalculate addressing back to NMRA.

Again click Apply/OK and save to trackplan using File-Save, stop and restart Rocrail to make changes effective.

Programming track
CVs can be programmed directly from this tab:

Operating a trackplan
Connect Elite to computer and power up layout. Start Rocrail preferably using the Workspace facility.

A nag screen will appear requesting a donation. Please contribute if you can as Rocrail is run by volunteers with donor support.

The user's layout trackplan should appear on screen. If not pull down menu File and Upload user’s trackplan to a new tab on the trackplan. Pull down menu Trackplan. Select Operate. Select Power On - lightbulb button. Users will be able to pick from a list of their locos, run them to throttle and use trackplan to switch points.

Unless users are at a more advanced stage of having power districts, blocks and feedback incorporated into their trackplan the layout screen is mainly for show for basic operations, but can be used to switch turnouts-points and control locos.

Operating locomotives
A list of locos and some details will be seen at the left hand side of screen. Pick a locomotive from list and click on throttle slider. Increase power by moving slider up, watch the numbers in the adjacent box increase (0-100%) and locomotive will move off. Or use a wheel mouse to control speed. Note speed step at which locomotive moves off and if required, set this as starting voltage V-min on Interface tab. Similarly limit top speed. Check and fine tune as necessary. Pick another locomotive and do same for that. Check each locomotive obeys throttle and runs correct way.

Click for locomotives page:

Double clicking a loconame(s) will launch a floating throttle(s).

All trains can be started together (unwise) and all stopped together (handy – like the Elite Emergency Stop button) if required. Trains can all be run automatically, some automatically and some manually, or all manually.

GUI will echo all commands in the lower right hand window pane.

Operating switches, turnouts, points
Trackplan calls them turnouts so we will use that term here.

Click any turnout on trackplan and if address and port are correctly set the associated point motor will throw, using capacitor discharge unt (CDU) built into accessory decoder. Click again and it throws other way.

There is also a Switch Control button that will open a switchbox to allow turnouts to be operated.

When a turnout throws the physical layout, it switches on trackplan with coloured leg showing the track way setting. Check it throws on layout same way as it throws on trackplan. If it throws in wrong logic amend the switch table to invert logic. No need to rewire.

Any pairs of point motors can wired and addressed together to operate as one when switched on the user's layout, but how to echo/mimic this on trackplan is presently under investigation.

GUI will echo in the lower panes all turnout commands and logic sent and received by showing the associated address-port and if set straight or turn.

Switches can be made to fire in sequence either in Auto mode or by selecting a Route. Routes can be operated manually. See on-line manual for details.

External Infromation
Read the on-line manual, visit Rocrail user forums, etc.


text:
The Science of Programming/A Little of This, A Little of That

In the last chapter, you were introduced to the idea of a variable. A variable is a spot in the computer's memory where you can store a value:

sway> var x = 1000000; INTEGER: 1000000 sway> x;   INTEGER: 1000000

Here, I've named that spot x and I've stored the number 1000000 at that spot. Once, I've reserved that spot, I can change the value there by assigning a new value to the variable. Here's an example:

sway> x = 42; INTEGER: 42 sway> x;   INTEGER: 42

Notice that I did not use the word var this time. When I use var, it means reserve me a new spot. When I don't use var, it means update a previously reserved spot.

To learn more about assignment, please see Sway assignment.

What happens if we try to update a spot without reserving it first?

sway> y = 3; EVALUATION ERROR: :assignError stdin,line 3: assignment: variable y is undefined

We get a message that y is undefined. This is the interpreter's way of telling us that we forgot to reserve a spot for y using var. Sway knows we didn't define the variable because it looked for it in the current environment and, failing, in the context environment and, failing, in the context of the context, and so, until it ran out of places to look.

The word variable implies that the value can vary, which is exactly what we did with x; we changed its value. In some programming languages, there are analogous beasties named constants, only once created, you cannot vary them. In Sway, there are no constants, per se. Should we need a constant, we will use a variable instead, but we will make a pledge not to change a variable's value. To remind us that we should not change its value, we will use capital letters (mostly) in naming the variable:

sway> var PI = 3.14159; REAL_NUMBER: 3.1415900000

Making this pledge is known as following a convention. Note that variable names can be (and generally should be) more than a single letter. Note also that SPT in Chapter 3 of CME uses lower case letters early in the alphabet to indicate constants and lower case letters late in the alphabet to indicate variables. That is a different convention.

Adding a little bit
Here's a problem that is a little bit simpler than the one from CME : + + + + + + + + + + + + + + + +   +                             +    +                             +    +                             + h = w/2 +                            +    +                             +    + + + + + + + + + + + + + + + +                   w

Consider a rectangle whose width and height are related. Suppose we increase the width a little bit. What happens to the height, assuming the new height is still one half of the new width? Since the height is calculated from the width, we say that width is the independent variable and that height is the dependent variable. First, let's define a function that gives us the height, h, given the width, w:

function h(w) {       w / 2.0; }

Note that when we write functions like this, it is almost always the case that the dependent variable is the name of the function and the independent variable is the name of the formal parameter. Use this rule to help you define the functions you need.

We can test out our new function:

sway> h(100); REAL_NUMBER: 50.0000000

This confirms our suspicion that if the width is 100 units, the height must be 50 units.

Calculus is often concerned with the change in the dependent variable given a change in the independent variable, particularly the ratio of the two changes.

Now, let's figure out that ratio for the above rectangle, using a small change in width:

sway> var w = 100;               //width sway> var dw = 0.01;             //change in width sway> var dh = h(w + dw) - h(w); //change in height

The change in the height is simply the new height minus the old height. Now we can compute the ratio:

sway> dh / dw; REAL_NUMBER: 0.5000000000

Another thing Calculus is concerned with is does this ratio change with different amounts of change or different values for the independent variable? The lazy person's way to answer these questions is, you guessed it, to write a function to do the work.

function ratio(w,dw) {       var dh = h(w + dw) - h(w); dh / dw; }

Note that we pass in the values of w and dw and then compute the ratio. This allows us to try a wide variety of values quite easily:

sway> ratio(40,0.01); REAL_NUMBER: 0.5000000000 sway> ratio(40,0.0001); REAL_NUMBER: 0.5000000000 sway> ratio(20,0.0001); REAL_NUMBER: 0.5000000000

This ratio function is quite useful! We see that the ratio of $$\frac{dy}{dx}$$ does not seem to ever change. But suppose we now start looking at rectangles with a different relationship between width and height. All of a sudden, our ratio function is looking a lot less useful. This is because we hard-wired the height function. We can fix this by passing in the height function as a third argument. Now we can easily try out new height functions. By doing so, we have made the ratio computing function more general.

function ratio(w,dw,h) {       var dh = h(w + dw) - h(w); dh / dw; }

It should work just the same:

sway> ratio(40,0.01,h); REAL_NUMBER: 0.5000000000 sway> ratio(40,0.0001,h); REAL_NUMBER: 0.5000000000 sway> ratio(20,0.0001,h); REAL_NUMBER: 0.5000000000

Let's try a different height function:

function g(w) {       w * w;        }

With this height function, the height g, grows as the square of the width. What does ratio produce now? Let's try one width and ever smaller changes:

sway> ratio(100,1,g); INTEGER: 201 sway> ratio(100,0.1,g); REAL_NUMBER: 200.10000000 sway> ratio(100,0.01,g); REAL_NUMBER: 200.01000000 sway> ratio(100,0.001,g); REAL_NUMBER: 200.00100000

It's pretty clear that if the change in width becomes infinitely small, the ratio when the width is 100 will be 200.

Now let's try a different width and ever smaller changes:

sway> ratio(200,1,g); INTEGER: 401 sway> ratio(200,0.1,g); REAL_NUMBER: 400.10000000 sway> ratio(200,0.01,g); REAL_NUMBER: 400.01000000 sway> ratio(200,0.001,g); REAL_NUMBER: 400.00100000 sway> ratio(200,0.0001,g); REAL_NUMBER: 400.00009998

For this new width, 200, the ratio appears to converge on 400. Also, for the last test, we got a value that was a little unexpected. This should be a warning to you when dealing with real numbers.

For the height function g, we see that different starting widths yield different ratios. A good deal of calculus is for explaining why such ratios change. Also, this process of computing ratios is known as the ''taking the derivative''.

Questions
All formulas are written using Grammar School Precedence.

1. Does it matter what variable name we use as a formal parameter when defining a function?

2. Draw a picture of a labelled rectangle so that the height is the independent variable, keeping the relationship that the height is one half the width.

3. In the function ratio, dh is computed from $$h(w + dw) - h(w)$$. If we assume that $$(w + dh$$) is equivalent to $$(w) + h(dw$$) then dh is $$(w) + h(dw) - h(w)$$ or simply $$(dw)$$. Define a new function named ratio2 to test whether this assumption is valid.

4. Which function is better for very small changes? Why?

5. Consider a rectangle whose area never varies. That is, if the width is increased, the height decreases to compensate so that the area of the rectangle remains the same. Define a function that computes the height of this rectangle given the width and the area.

6. Do we observe the same behavior in the ratios as we did with function g?

7. "Change is constant," but does not have to be a constant. Most of us are comfortable with the notion of a constant rate of change. For instance the change in height versus distance as described by a straight line, for instance $$ y = 5 x + 4 $$. Use the ratio function to explore how y changes as x changes. Produce a table of y, x, and dy/dx.

8. The previous problem had a constant rate of change. Often, however, the rate of change of the dependent variable changes with the independent variable. Let's take as an example the function for area of a square, $$ y = x^2 $$. First of all, what is the change in the area as x changes from 2 to 4? Draw a sketch of this situation, labeling dy and dx. Do the same thing as x changes from 2 to 3, 2 to 2.5, 2 to 2.1, and 2 to 2.01. What do you observe? Try the same thing, but now start with x = 4. The point is that the rate of change in the area, itself changes depending on the length. The function of x that expresses this relationship between the change in y and x is called the derivative, dy/dx. Based on your experiments, what is the derivative of $$y = x^2$$?

9. The rate of damage reduction from armor is $$\mathit{Reduction} = \mathit{Armor} / (\mathit{Armor} + X) $$ where $$ X = 467 * \mathit{EnemyLevel} - 22167 $$. What is the relative growing of damage reduction with Armor? With EnemyLevel?


text:
Accountancy/Financial statements

We all remember Cuba Gooding Jr.’s immortal line from the movie Jerry Maguire, “Show me the money!” Well, that’s what financial statements do. They show you the money. They show you where a company’s money came from, where it went, and where it is now.

There are four main financial statements. They are: (1) balance sheets; (2) income statements; (3) cash flow statements; and (4) statements of shareholders’ equity. Balance sheets show what a company owns and what it owes at a fixed point in time. Income statements show how much money a company made and spent over a period of time. Cash flow statements show the exchange of money between a company and the outside world also over a period of time. The fourth financial statement, called a “statement of shareholders’ equity,” shows changes in the interests of the company’s shareholders over time.

title: Accountancy/Financial statements


text:
Introduction to Sociology/Being a Sociologist

Introduction
Now that you know what sociologists study, you might be wondering: What can you do with a degree in sociology? In an ideal world, just studying social problems would make them go away. But, alas, as you've learned from reading this book, we don't live in an ideal world and there is far more to do than just study social life with a degree in Sociology. The American Sociological Association, among others, has looked into this question and has some pretty intriguing answers. What follows is a brief explanation of what you can do with a degree in Sociology.

Sociology Majors
Despite the many tests that suggest otherwise, there is no correlation between personality and career choice. Thus, there is no particular "personality type" among sociology majors.

The average graduating sociology major is a young female (early 20s) who is white and single. Almost 80% of students graduating with sociology degrees are female, and nearly that many (75%) are white. Less than half of the parents of sociology majors have baccalaureate degrees of their own.

Many sociology majors choose the major because they found their first exposure to the discipline engaging (usually through an introductory course). Most sociology majors chose the discipline because they found the concepts discussed in their course interesting. Only 7% of sociology majors choose the discipline because it appears easy, and relatively few (5%) choose it because the major they wanted was unavailable. In other words, sociology majors find the discipline exciting and challenging and generally enjoy studying sociology.

By the time they graduate, 90% of sociology majors report understanding the basic concepts of the discipline (e.g., social structure, social stratification, etc.). Most also grasp the differences in the theoretical paradigms of sociology (e.g., structural functionalism, conflict theory, etc.). Sociology majors feel confident in the following skills as a result of their degree: identifying ethical issues in research, developing evidence-based arguments, evaluating different research methods, writing reports that are understandable by non-sociologists, forming causal hypothesis, using computers to develop reference lists, interpreting the results of data analysis, and using statistical software (though slightly less than 50% feel confident in their ability to use statistical software).

Sociology majors are generally satisfied overall with their experience earning a sociology degree. Most are also satisfied with the quality of teaching, the accessibility to technology and faculty, their interaction with other majors, and getting the courses they need to graduate. Unfortunately, most students (between 80% and 92%) are dissatisfied with the information provided on graduate school and career opportunities (hopefully this brief chapter will help fill this void).

Bachelor's Degree Occupations
What can you do with a Baccalaureate degree in Sociology? While it may not seem like it when you are deep into studying race relations or gender stratification, the training you receive as a sociology major is actually quite applicable outside academia as well. College graduates trained in sociology bring unique and valuable insights into business decisions concerning issues surrounding race, ethnicity, gender, age, education, and social class. To give a specific example, a sociology major could help a company like CVS realize the problem with tagging hair care items for African Americans with anti-theft measures while not doing the same for hair care items for whites. Practices like these may seem pragmatic to the managers of these stores, but they also alienate consumers.

College graduates trained in sociology bring many skills to their jobs, including: the ability to recognize trends and patterns, the ability to create concise reports and essays, strong critical thinking skills, oral presentation skills, strong interpersonal communication skills, skills in data collection and analysis using statistical software, grant writing skills, management skills, and planning and organizational skills. All of these skills are potentially invaluable contributions to workplaces.

Most graduating seniors (around 72%) plan on getting a job right out of college. Around 40% plan on going on to graduate school (these paths aren't mutually exclusive of course, you can work while going to graduate school). There are a number of institutions where sociologists find employment, including: schools, churches, hospitals, corporations, government, and social service agencies. For those planning on getting jobs, all of the following are career paths sociology majors are well-suited for: organizational planning, development, and training; human resource management; industrial relations; marketing; public relations; organizational research; and international business.

The Corporate World
Some sociologists find the adaptation of their sociological training and insights to the business world relatively easy. Corporations want and need to understand their customers' habits and preferences in order to anticipate changes in their markets. This drive to understand consumers is called consumer research and is a growing interest of corporations. Sociology majors are particularly well-suited for this type of research as the ultimate goal of empirical sociological research is to predict human behavior. This particular niche may be the single largest opportunity for sociologists in the corporate world.

Another budding area in modern retail firms is site selection, or the determination of the best locations for new stores. Site selection requires understanding human ecology and consumer spending patterns, both of which are addressed using the sociological imagination. Some additional direct applications of sociology include concept and product testing (which will put to good use training in research methods), the evaluating of global market opportunities (which will draw upon understandings of various cultures), long-range planning and forecasting (which draws on both statistics and futurist perspectives), marketing and advertising (which applies consumer studies directly), and human resource management (which relies on studies of organizational behavior).

One way to situate yourself well for the corporate world after earning your Bachelor's degree in Sociology would be to double major in Sociology and Business or minor in Business. This would give you the credentials that hiring departments in the business world are looking for while simultaneously allowing you to focus on Sociology. Another key to succeeding in the corporate world with a degree in Sociology is to market your specific skill set. As noted above, a degree in Sociology provides you with skills that many other college graduates lack. Emphasizing those skills on your resumes and in job interviews increases the odds of you being hired and you using those skills in your job. There is also evidence to suggest that sociology graduates who use their sociological training in their jobs post graduation are more satisfied with their jobs.

Non-Governmental Organizations
Non-Governmental Organizations (or NGOs) are legally constituted organizations created by private persons or organizations with no participation or representation of any government. Examples of NGOs include Oxfam, Catholic Relief Services, CARE International, and Lutheran World Relief. Many NGOs are concerned with the very social problems and social issues sociologists study, from poverty to gender stratification to world population growth. NGOs are ideal opportunities for sociology majors to apply what they have learned in college.

Continuing Your Education
For those planning on continuing their education, the table to the right breaks down the most frequently chosen fields of study for sociology majors:

Many professional degree programs (e.g., medical school and law school) do not, in fact, require someone to have a specific undergraduate degree. Sociology majors can carry the sociological imagination into medical practice, offering sociological insights while practicing medicine. In 2001, sociology majors had a 42% acceptance rate into medical school.

Sociology majors should view their undergraduate education as opening doors for them into many possible fields of work and study. Two factors seems to limit the occupational prospects of sociologists: The first limiting factor is their own imagination. The sociological imagination is applicable to almost every occupation and field of research, from studying how physicists do their work to union organizing. The second limiting factors is that many people do not know what sociologists are trained to do. This should only be a limiting factor up until they meet a sociology major!

PhD Degree Occupations
What can you do with a PhD in Sociology? A PhD in Sociology prepares an individual for a variety of career options, including all of those mentioned above for someone with a Bachelor's Degree in Sociology (e.g., marketing, non-governmental organizations, etc.), but it also means you will be much better qualified for these types of jobs. Graduate training in Sociology includes a greater emphasis on research methodology and statistics. It also often includes training in qualitative research methods, like content analysis. Additionally, graduate training includes much more in depth analysis and discussion of many of the topics discussed in your undergraduate training. The format of graduate training may also differ as many of the classes are designed as a seminar rather than a lecture-oriented class - students will come to class meetings having read the assigned readings and then discuss them under the supervision of a professor.

All of this additional training will prepare a PhD in Sociology for advanced careers in fields as diverse as corporate marketing and statistical forecasting to community organizing and lobbying. A PhD in quantitative research and demography could lead to a career at the Census Bureau or the World Bank.

Another obvious occupation one can pursue is as an academic sociologist, working at a college or university. Depending on the type of university or college where one works, the job description will vary substantially. Some colleges - typically four-year liberal arts colleges - focus on teaching. In contrast, research universities - which include PhD programs - focus on research. Thus, what your job description would be as an academic sociologist could range from a heavy emphasis on teaching undergraduates to a heavy emphasis on teaching graduate students. In both types of institutions, there are both tenure and non-tenure track jobs. Tenure refers to a lifetime appointment and carries with it a contractual right not to have the position terminated without just cause. Adjunct instructing is another option, which is usually teaching on a contract basis.

According to Forbes magazine, Sociology is one of the top-ten highest-paying rare jobs in the United States and is generally rated as one of the most satisfying occupations. This may be due to the fact that Sociologists are often engaged in trying to remedy social ills, which can be a very satisfying life pursuit.

According to data compiled in ASA’s 2007 “Beyond the Ivory Tower” report, one-fourth of PhD sociologists work outside academia. Of those in academia, as of April 2008, the average sociology faculty salary was $68,857, ranging from assistant professors making $53,844 to full professor earnings of $87,938.

Personal Experiences of Individuals With Degrees in Sociology

 * Joe Mercurio, retired strategist and researcher at Walgreens Co. http://www.asanet.org/footnotes/feb08/fn1.html
 * Karen Ehrhardt-Martinez, works for the NGO American Council for an Energy-Efficient Economy (ACEEE) http://www.asanet.org/footnotes/feb08/fn6.html

Discussion Questions

 * What are some jobs you can do with training in sociology?
 * What are some of the skills you would learn with training in sociology?
 * How might sociologists think about the world differently from other people?


text:
Metal Gear Series/Meryl Silverburgh

Meryl Silverburgh is a character in the Metal Gear series. Her first appearance is in Metal Gear Solid, and is also Colonel Roy Capmbell's daughter.

She is shot by Sniper Wolf whilst trying to help Snake and then taken to Liquid (Snake's) brother. At the end of Metal Gear Solid Liquid and Solid Snake both fight and Snake is able to save Meryl.

At the end Snake, Otacon and Meryl all leave Shadow Moses together.

title: Metal Gear Series/Meryl Silverburgh


text:
GIMP/Removal of Unwanted Elements in the Image

H7 Often there is a need to remove unwanted elements in an image, such as the background. There are multiple methods.

Method 1: Magic Wand
An easy method is to use the Magic Wand selection l.
 * 1) Firstly, right click on the layer you are working on and add an alpha channel if there is not already one. (Select Layer, Transparency, Add Alpha Channel.)
 * 2) Now switch to the Magic Wand tool. Make sure the mode is set to Add to the current selection. (Mode is on Toolbox palette, just below "Fuzzy select".)
 * 3) Select all the parts that you want to erase by simply clicking in the area.
 * 4) Press Delete.

Method 2: Colour to Alpha
An alternative method is Colour to Alpha. This method works better with logos with fewer than 5 colours.
 * 1) Firstly, right click on the layer you are working on and add an alpha channel if required.
 * 2) Select   Colours > Colour to Alpha.
 * 3) Set the colour after the "From:" label to the colour that you would like to remove.
 * 4) Click OK.
 * 5) Repeat steps 1-4 for any other colours that you need to remove.

Method 3: Foreground Select
A new method is the Foreground Select tool. This is best when there is only one thing in the foreground which you want to keep.
 * 1) Firstly, select the Foreground Select tool.
 * 2) Mark out a rough area around the foreground.
 * 3) Scribble in the foreground only. Repeat scribbling until the coloured boundary is tightly around the foreground.
 * 4) Press ENTER.
 * 5) Go to   Select > Invert.
 * 6) Press Delete.

Method 4: Use Resynthesizer to remove timestamps
To remove items like timestamps with GIMP, you may use the Resynthesizer plugin. Just install it and try 'Filter' → 'Enhance' → 'Heal Selection'.

Method 5: Divide by a blurred version of the image

This method works best with sharp image content on blurry unwanted backgrounds such as the texture of white paper with some written text.

 * 1) Copy the whole image into a new layer. Now two layers with the same image exists.
 * 2) Select the top layer with the image and switch the mode from "normal" to "divide". The result is a blank white image.
 * 3) Select the top layer. In the menu select Filter -> Blur -> Gausian Blur...
 * 4) Adjust the parameters for optimal effect, then apply the filter.
 * 5) Go to layer -> merge down to combine the layers back to one single layer


text:
The Science of Programming/The Simplest Things

If you have studied Chapter 4 of CME, you will have learned the power rule for differentiating simple polynomial functions, known as terms. A term has the form:

$$ a x ^ n $$

with a being known as the coefficient of the term and n being known as the exponent of the term.

Here is the power rule for terms:

$$\frac{d(a x^n)}{dx} = a n x^{n - 1}$$

As example, consider the polynomial:

$$y = 2 x^3$$

If the power rule is correct, then the derivative should be:

$$\frac{dy}{dx} = 6 x^2$$

Let's test. We start out by defining a function to represent the polynomial:

function y(x) {       2 * (x ^ 3); }

As before, the dependent variable becomes the name of the function and the independent variable becomes the formal parameter.

Before we continue, now would be a good time to learn about using Sway with files, since typing into the interpreter can be rather painful for function definitions.

Thus for the rest of this book, even though interactions with the interpreter are shown, you should be storing Sway programs in files and running Sway programs from files.

The derivative, or $$\frac{dy}{dx}$$ can be written as this function:

function dy/dx(x) {       6 * (x ^ 2); }

Is there any way to test whether or not the power rule is correct? Recall our revised ratio function from the previous chapter:

function ratio(x,dx,y) {       var dy = y(x + dx) - y(x); dy / dx; }

As you should remember, the ratio it computes is an approximation for the derivative at a given x. Note that we've changed the names of the formal parameters, w to x, dw to dx, and h to y, to reflect the fact that we are working with polynomials now.

We believe that ratio (for small dx) produces a number that should be close to what the function dy/dx produces.

Let's define a testing function:

function test(x) {       var dx = 0.000001; println("for x = ",x); inspect(ratio(x,dx,y)); inspect(dy/dx(x)); println; }

Given a value for x, the test function will print out the two results. Time for some nomenclature. When we use our ratio function, we are finding the derivative numerically. That is to say, we use a small number for dx, find the resulting dy, and then compute the ratio $$\frac{dy}{dx}$$. On the other hand, using the power rule (as embodied in the function dy/dx), we find the derivative symbolically since we never actually compute an actual ratio.

sway> test(10); for x = 10 ratio(x,dx,y) is 600.00005965 dy/dx(x) is 600 sway> test(20); for x = 20 ratio(x,dx,y) is 2400.0001231 dy/dx(x) is 2400 sway> test(30); for x = 30 ratio(x,dx,y) is 5400.0001837 dy/dx(x) is 5400

For this test at least, we see that there is good agreement between our numeric and symbolic solutions.

Clearly, though, the symbolic solution is preferred because:

 * it is exact
 * it is easier to compute

You may be asking yourself, can we write a program to find a derivative symbolically?

A Shortcoming to Our Approach
It certainly would be nice if we could use the symbolic approach to finding derivatives instead of our numeric approach using ratios. The problem is that our function representing a term:

function y(x) {       2 * (x ^ 3); }

has the coefficient 2 and the exponent 3 hard-wired. If we are given such a function but aren't privy to the internal details (such as the value of the hard-wired exponent), we cannot create the derivative function since we need to know the value of the exponent to do so and have no way to get at it. We need to contrive a way to retrieve the exponent from the function so we can use it to construct the derivative function.

The next section is to give you an exposure to one approach for extracting the components of a function. The approach uses objects.

If you don't know what an object is or how to create one in Sway, please read about using objects in The Sway Reference Manual now.

OK, now that you are familiar with objects, we can begin to use objects to write a program that finds a derivative symbolically.

Polynomial Objects and the Power Rule
Instead of using a function to represent the polynomial y, we are going to use an object instead. From studying the reference manual, you know that an object is simply an environment and an environment is simply a table of variables and their values. You also know that you use a function to create an object and that a function that creates an object is conventionally known as a constructor. Finally, you know that to define a constructor function, you have that function return the predefined variable this.

Here's a constructor for a simple polynomial object. We name the constructor term:

function term(a,n) {      function value(x) {          a * (x ^ n); }       this; }

Note that the constructor includes an internal function for computing the value of y given an x, just as before. We call that function by using the dot operator.

sway> var y = term(2,3); OBJECT:  sway> y. value(4); INTEGER: 128 sway> y. value(5); INTEGER: 250

Indeed, $$2 * 4 ^ 3$$ is truly 128 and $$2 * 5 ^ 3$$ is truly 250.

Now comes the good part! Storing a polynomial term as an object rather than a function allows us to extract the coefficient a and the exponent n:

sway> y. a;   INTEGER: 2; sway> y. n;   INTEGER: 3;

We can even pretty print the object y to see all its fields:

sway> pp(y); : context:  dynamicContext:  callDepth: 1 constructor:  this:  value:  a: 2 n: 3 OBJECT:

We see, among other fields, the correct values for a and n. Later on, you will understand the meaning and purpose of the predefined fields: context, dynamicContext, and constructor. The this field you already know.

We want access to a and n because the power rule needs them to compute the derivative polynomial. Now we can write an expression that allows us to compute the derivative:

sway> var coeff = y. a;   sway> var exp = y. n;

sway> var z = term(coeff * exp,exp - 1); OBJECT:

sway> z. a;   INTEGER: 6

sway> z. n;   INTEGER: 2

sway> z. value(4) INTEGER: 96

Of course, we could write a function to do this task for us:

function powerRule(t) {       var coeff = t. a;       var exp = t. n;       term(coeff * exp,exp - 1); }

Note that the powerRule function takes a term object as an argument and returns a new term object that represents the derivative. This is because the new term has a coefficient of a * n and an exponent of n - 1, just like the power rule dictates. Let's check and make sure our power rule works as intended:

sway> var y = term(2,3); sway> var z = powerRule(y); sway> y. value(4); INTEGER: 128 sway> z. value(4); INTEGER: 96

Indeed it does!

Moreover, pretty printing z shows us the correct values for a and n:

sway> pp(dy/dx); : context:  dynamicContext:  callDepth: 2 constructor: <function term(a,n)> this: <OBJECT 2922> value: <function value(x)> a: 6 n: 2 OBJECT: <OBJECT 2922>

You may not have noticed it, but we have a little lack of symmetry. While the term object has an internal function for computing its value, we use an external function, powerRule to compute its derivative. When we program using objects, we use internal functions when possible. So let's rewrite the term function so that it can compute its own derivative:

function term(a,n) {       function value(x) {           a * (x ^ n); }       function diff {           term(a * n,n - 1); }       this; }

We name this new internal function, diff, to indicate taking the differential of our object. Note how we have dispensed with the variables coeff and exp inside the diff function and just used a and n directly.

Finally, we add a third internal function to term. This one is used to visualize our object in a more concise way than using the pp function. By convention, we will call this function toString:

function term(a,n) {       function value(x) {           a * (x ^ n); }       function diff {           term(a * n,n - 1); }       function toString {           string(a) + "x^" + string(n); }       this; }

The toString function converts both the coefficient and the exponent to strings and then concatenates those strings together to form a string representation of the term:

sway> y = term(2,3); sway> z = y. diff;

sway> y. toString STRING: "2x^3"

sway> x. toString STRING: "6x^2"

Notice how much easier it is to pick out the coefficient and the exponent of a term by using the toString function. Another way to formulate the toString function takes advantage of the fact that if you add a string and a number (with the string on the left hand side of the plus sign, the number is automatically converted to a string. That, with the fact that Sway combines mathematical operators from left-to-right, lets us remove the string conversion of n:

function toString {       string(a) + "x^" + n;        }

If we use an empty string to start the expression, we can remove the first string conversion as well:

function toString {       "" + a + "x^" + n;        }

A Whole System of Objects
From here on out, we are going to develop a system for finding the derivative (and eventually, the integral) of many kinds of mathematical objects (limited only by our imagination and attention span). Each object in our system will do (at least) three things. The first is to compute its value at a given spot. The second is to compute its derivative (and eventually, its integral). The third is to compute its visualization. So all our mathematical objects will have value, diff, and toString internal functions or methods.

Even the simplest real-world mathematical objects such as numbers and variables will need to be re-created as Sway objects. That way, we can always take the derivative of an object without having to ask first if taking the derivative makes sense.

Questions
All formulas are written using Grammar School Precedence.

1. Why does the Sway implementation of $$2 x^3$$ have parentheses: <tt>2 * (x ^ 3)</tt>?

2. Using the powerRule function, can you take the derivative of a derivative? Explain.

3. Write a function that uses the power rule function to answer the following questions on p. 58 of Thompson: 1, 2, 4, 6, 7. Name your function p58. Your function should calculate, then print the answers to the questions.

4. Using pencil and paper, work exercises 3, 8, 9, and 10 on p. 58 of Thompson.


text:
Using Your Dealer Management System/Automatic Data Processing/WS1000

The w.e.b.Suite 1000 (herein WS1000) is handled internally by the Alliance Group at ADP HQ. WS1000 is not a true web (HTTP) application, though it can be accessed anywhere on the web. Technically it is a simple Microsoft Windows program running on an ADP-hosted Windows 2000 thin client server (à la Citrix or Windows Terminal Services). It is predominately marketed to small dealerships. You can access a WS1000 server by using the ADP Alliance website. You will have to log in, and then launch the application which establishes a connection using a signed Microsoft ActiveX Terminal Services applet.

ADP's official sales page for the w.e.b.Suite 1000 system.

Quick tips
To pull an inventory report: Vehicle Inventory Plus → All Iventory List - Mgr Long → OK → Print

Printer Support
For the w.e.b. Suite 1000 ADP is known to support only a subset of all printers, namely:
 * Fujitsu DL 3600
 * ADP 3410
 * ADP 80LQ
 * ADP 6350
 * HP Laserjet 4 plus


text:
The Sway Reference Manual/Objects

In the Sway world, an object is a simple a collection of related variables. You've already been exposed to objects, although you may not have realized it. When you created a variable, you modified the environment, which is an object. When you defined a function, you created an object. To view an object, we use the predefined function pp or ppObject. Evaluating the code:

function square(x) {       x * x;        } ppObject(square);

yields the following output:

: context:  prior: :null filter: :null parameters: (x) code: { x * x; } name: square

We see that the square function is made up of six fields. These fields are: context, prior, filter, parameters, code, and name.

Usually, an object lets you look at its individual components. For example:

println("square's parameters are: ",square . parameters);

yields:

square's parameters are: (x) We use the function '.' (usually called the dot operator) to extract the fields of an object.

It is easy to create your own objects. First you must make a constructor. A constructor is just a function that returns this. Suppose you want a constructor to create an object with fields name and age. Here is one possibility:

function person {       var name; var age; this; }

We can create an object simply by calling the constructor:

var p = person;

The variable p now points to the person object and we can use p and the dot operator to set the fields of the person object:

p. name = "Boris"; p. age = 33; inspect(p . name);

Evaluating this code yields the following output:

p. name is Boris

It is often convenient to give initial values to the fields of an object. Here is another version of person that allows us to do just that when we create the object:

function person(name,age) {       this; }   var p = person("Boris",33); inspect(p . name);

The output is the same:

p. name is Boris

In general, if a field is to be initialized when the object is constructed, make that field a formal parameter. If not, make the field a locally declared variable.

Adding Methods
Objects can have methods as well. Here's a version of the person constructor that has a birthday method.

function person(name,age) {       function birthday {           println("Happy Birthday, ",name,"!"); age = age + 1; }       this; }   var p = person("Boris",33); p. birthday; inspect(p . age);

The output of this code is:

Happy Birthday, Boris! p. age is 34

In summary, one turns a function into a constructor by making

this;

or

return this;

the last line of a function. The local variables, including formal parameters, become the fields of the function while any local functions serve as methods.

Objects and Types
If you were to ask an object, "What are you?", it would respond, "I am an object!". The type function is used to ask such questions:

var p = person("betty",19); inspect(type(p));

yields:

type(p) is :OBJECT

While this is useful at times, often we would like to know what kind of object the object is. For example, we might like to know whether or not p is a person object. One way to do this is to ask the constructor of the object if it is the person function. Luckily, all objects carry along a pointer to the function that constructed them:

var p = person("betty",19); inspect(p . constructor . name);

yields:

p. constructor. name is person

So, to ask if p is a person, we would use the expression

if (p . constructor . name == :person) ...

Since this construct is rather wordy, there is a simple function, named is, that you can use instead:

if (p is :person) ...

The is function works for non-objects too. All of the following expressions are true:

3 is :INTEGER 3.4 is :REAL "hello" is :STRING :blue is :SYMBOL list(1,2,3) is :LIST array("a","b","c") is :ARRAY person("betty",19) is :OBJECT this is :OBJECT

The is function also works for variables bound to values as well.

A formal view of object-orientation
Sway is a fully-featured object-oriented language. What does that mean exactly? Well, to begin with, a programming language is considered object-oriented if it has these three features:

 * 1) encapsulation
 * 2) inheritance
 * 3) polymorphism

Encapsulation in this sense means that a programmer can bundle data and methods into a single entity. We've seen that a Sway function can have local variables and local functions. So, if we consider local variables (including the formal parameters) as data and local functions as methods, we see that Sway can encapsulate in the object-oriented sense.

Inheritance is the ability to use the data and methods of one kind of object by another as if they were defined in the other object to begin with.

Polymorphism means that an object that inherits appears to be both kinds of object, the kind of object it is itself and the kind of object from which it inherits. We will learn more about inheritance and polymorphism in a later chapter.

Using the objects library
If you include the objects library, you can add toString methods to your objects. Then when you display the objects, the toString method is called to help generate the output.

title: The Sway Reference Manual/Objects