\newcommand{\imag}{j}  %sqrt(-1) in math mode

\chapter{The 6.003 Toolbox}
\label{toolbox}

The Toolbox is a collection of Scheme procedures that are useful for
system and signal analysis.  These procedures are automatically loaded
when you start Scheme on a 6.003 Bobcat.  Included are procedures for
defining complex numbers and a variety of functions of complex
numbers, procedures for carrying out generic operations on
combinations of real or complex numbers or functions that return real
or complex values, and procedures for manipulating polynomials and
rational functions---including procedures for finding polynomial roots
and partial-fraction expansions.  Please tell us about any bugs you
find, as well as suggestions for additions and improvements.

\section{Complex numbers and operators}

The 6.003 Toolbox extends the ordinary Scheme arithmetic operations to
work on complex numbers.  For example, you can use the {\tt +}
operator to add {\tt 3+2j} and {\tt 1.5-3j} to obtain {\tt 4.5-1j}.
You
can also perform arithmetic on {\em operators}.  An operators is a numeric
function of a numeric argument.  For example, you can use Scheme {\tt +}
operations to add the operator $2s+3$ to $s^2-1$, obtaining the operator $s^2+2s+2$.

\subsection{Complex numbers}
\index{complex numbers}

Complex numbers can be created using the procedure {\tt
make-rectangular}, which returns a complex number with a specified real
and imaginary part.\schindex{make-rectangular}
You can also create a complex number using {\tt make-polar}, which
returns the complex number with a specified magnitude and angle.
Complex numbers are printed by Scheme in the form
{\tt a+bj} where {\tt a} and {\tt b} are ordinary numbers.  Scheme's
arithmetic operators work on complex numbers and on combinations of
real and complex numbers.  Here are some examples:

\begin{scheme}
(make-rectangular 3 4)   \ev   3+4j
(- 6 (make-rectangular 3 4)) \ev  3-4j
(/ 2 (make-rectangular 3 4)) \ev  .24-.32j
(* 3 (make-rectangular 3 4)
     (make-rectangular 5 6)) \ev  -27+114j
(abs (make-rectangular 3 4)) \ev 5

(make-polar (sqrt 2)
            (/ pi 4)) \ev 1.+1j

(sqrt -5) \ev 0+2.2360679775j
\end{scheme}

Section \ref{numbersection} provides a complete list of Scheme's
numerical procedures.

\subsection{Operators}
\index{operators}

An {\em operator} is a Scheme object that represents a (real or
complex-valued) numerical function of a single (real or complex)
number.  There is essentially no difference between an operator and
the single-argument procedure that it specifies---and Scheme provides
operations for converting between single-argument procedures and
operators, and for evaluating an operator at a specified value.
However, operators and procedures are maintained as distinct types of
objects for clarity in programming.

Operators can be created by transforming a single-argument procedure
into an operator using {\tt procedure->operator}, or by combining
other operators using Scheme's arithmetic operations.  For example, if
{\tt s} is the identity operator (i.e., the value of {\tt s} at any
number is the number itself) then {\tt (* s s)} is the operator whose
value at any number is the square of that number.


\begin{entry}{%
\proto{operator?}{ \var{obj}}{procedure}}

Returns \schtrue{} if \var{obj} is an operator.
\end{entry}

\begin{entry}{%
\proto{operator-value}{ \var{operator} \var{z}}{procedure}}

Returns the value of the operator when applied to the specified number.

\begin{note} If applying the operator to the value produces an
arithmetic overflow error (such as division by zero) {\tt
operator-value} will choose a slightly different value for the
argument and return the result at this new value.  For instance, if
the operator
represents a rational function, and you ask for its value at a pole,
you will obtain a large answer, but there will be no arithmetic overflow.
\end{note}
\end{entry}

\begin{entry}{%
\vproto{s}{variable}}

This is a predefined name for the identity operator.
\end{entry}

For most 6.003 applications, {\tt s} is the only primitive operator you
need worry about---all other operators you are likely to run across
will be created by starting with {\tt s} and applying numerical operations.
Scheme's numerical procedures work on operators to produce new
operators.  In general, a procedure $P$ applied to operators
$O_1,\ldots O_n$ produces the operator whose value at a number $z$ is
$P$ applied to $O_1(z),\ldots O_n(z)$.  Here are some examples:

\begin{scheme}
(operator-value s 27) \ev 27
(operator-value (+ 1 (* s s)) 5)
         \ev 26

(define (f x) (/ (+ x 1) (- (* x x) 1)))
(define h (f s))
(operator-value h (make-rectangular 0 1))
         \ev -.5-.5j

(define m (+ (* (sin s) (sin s)) (* (cos s) (cos s))))
(operator-value m .3)  \ev  1
(operator-value (+ s m) 10) \ev 11
\end{scheme}

\begin{entry}{%
\proto{procedure->operator}{ \var{proc}}{procedure}}

{\em Proc} should be a procedure of one argument.   Returns the
operator whose value at any $x$ is obtained by applying the procedure
to $x$.  You can use this to create primitive operators other than
{\tt s}.
\end{entry}

\begin{entry}{%
\proto{operator->procedure}{ \var{operator}}{procedure}}

Returns a procedure of one argument that performs the computation
specified by the operator.  In 6.003 you will normally keep things in
operator form, so that you will probably not use {\tt
operator->procedure}.

\end{entry}

\section{Polynomials}

A polynomial is represented by a list of (possibly complex) term
coefficients in {\em ascending} order of term powers, i.e., $a_0 + a_1
s + a_2 s^2 + \cdots + a_n s^n$ is represented as the list
{\tt ($a_0$ $a_1$ $a_2$ $\cdots$ $a_n$)}.
You should get used to typing in polynomials in this list notation.
The following {\tt display-poly} procedure is useful for checking
what you type.

\begin{entry}{%
\proto{display-poly}{ p}{procedure}}


\begin{scheme}
(display-poly '(2 -1 3))       \ev  \unspecified
;;computer prints $3x^2-x+2$
\end{scheme}

{\tt Display-poly} also displays rational functions: Given a list of
two polynomials $p_1$ and $p_2$, {\tt display-poly} will display
$p_1/p_2$.  Given a list of three polynomials $p_1$, $p_2$, $p_3$,
{\tt display-poly} will display $p_1+(p_2/p_3)$.

\begin{note}
{\tt Display-poly} only shows things on the screen---it does not
return a value that you can use in subsequent computations.
\end{note}
\end{entry}


\begin{entry}{%
\proto{add-poly}{ \vari{p} \varii{p}}{procedure}}

Returns the polynomial that is the sum of the polynomials, $p_1 + p_2$.
\begin{scheme}
(add-poly '(1 3 7 6)
          '(2 -1 3))  \ev  (3 2 10 6)
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{sub-poly}{ \vari{p} \varii{p}}{procedure}}

Returns the polynomial that is the difference of the polynomials, $p_1 - p_2$.
\begin{note}
Calling {\tt sub-poly} with a single argument leads to an error.
\end{note}
\begin{scheme}
(sub-poly '(1 3 7 6)
          '(2 -1 3))  \ev  (-1 4 4 6)
(sub-poly '(1 3 7 6))            \ev  error
(sub-poly '() '(1 3 7 6))        \ev  (-1 -3 -7 -6)
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{mul-poly}{ \vari{p} \varii{p}}{procedure}}

Returns the polynomial that is the product of the polynomials, $p_1 p_2$.
\begin{scheme}
(mul-poly '(1 3 7 6)
          '(2 -1 3))  \ev  (2 5 14 14 15 18)
\end{scheme}
\end{entry}


\begin{entry}{%
\proto{div-poly}{ \vari{p} \varii{p}}{procedure}}

Returns a list of two polynomials, the quotient and the remainder.  If
the degree of the numerator of $p_1$ is less than the degree of the
denominator $p_2$, the quotient is the empty list.
\begin{scheme}
(div-poly '(1 3 7 6)
          '(2 -1 3))  \ev  ((3 2) (-5 2))
\end{scheme}
\noindent
corresponding to
\begin{displaymath}
\frac{1+3x+7x^2+6x^3}{2-x+3x^2} = 3 + 2x + \frac{-5+2x}{2-x+3x^2}
\end{displaymath}
\end{entry}

\begin{entry}{%
\proto{scale-poly}{ factor poly}{procedure}}

Returns the polynomial whose coefficients are the coefficients of {\em poly}
multiplied by {\em factor}.
\begin{scheme}
(scale-poly 2 '(1 3 7 6))  \ev  (2 6 14 12)
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{poly->roots}{ poly}{procedure}
\proto{poly->roots}{ poly initial-guess}{procedure}}

Returns a list of the roots of {\em poly}.  The second argument, which is
optional, is the initial guess for the Newton iteration.  If omitted,
the default value is $0.1 + \imag$.
\begin{scheme}
(poly->roots '(2 4 3 1))  \ev  (-1+1j -1 -1-1j)

\end{scheme}
\end{entry}

\begin{entry}{%
\proto{roots->poly}{ root-list}{procedure}}

Returns the polynomial whose roots are in root-list.
\begin{scheme}
(roots->poly
 (list (make-rectangular -1 1)
       -1
       (make-rectangular -1 -1)))
             \ev  (2 4 3 1)
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{poly->proc}{ poly}{procedure}}

Returns a procedure whose value for any argument is the value of the
polynomial represented by {\em poly} evaluated at that argument.
\begin{scheme}
(define bar
  (poly->proc '(2 2 1))) \ev  \unspecified{}
;;the polynomial specified by the list is $2 + 2x + x^2$
(bar -1)                           \ev  1  ;$2 + 2(-1) + (-1)^2 = 1$
(bar (make-rectangular -1 1))      \ev  0 
\end{scheme}
\end{entry}

\section{Rational Functions}

A rational function is the ratio of a numerator polynomial and
a denominator polynomial.  It can also be represented in the form of a
partial fraction expansion, from which it is easy to derive the time
function whose Laplace transform is the rational function.  The
following procedures evaluate the relationships among these various
attributes of rational functions.
\begin{entry}{%
\proto{operator->rat-func}{ operator order}{procedure}}

Given an {\em operator} and an order $n$, this procedure attempts to
express the operator as a rational function whose numerator has degree
$n-1$ and whose denominator has degree $n$.  The procedure returns the
the numerator and denominator polynomials as lists of coefficients.
For example, the list {\tt ((a0 a1 a2) (b0 b1 b2 b3))}
corresponds to the rational function of 3rd order
\begin{displaymath}
\frac{a_2s^2+a_1s+a_0}{b_3s^3+b_2s^2+b_1s+b_0}
\end{displaymath}
The result is normalized so that the highest-order coefficient of the
denominator is equal to 1.
If the value of $n$ supplied is smaller than
necessary, the procedure will signal the error that $n$ is too small.
If the value of $n$ supplied is larger than necessary, the procedure
will work, although larger values of $n$ will require longer
computation time, and, due to roundoff error, the procedure may find
spurious high-order coefficients.

\begin{scheme}
(define n (+ (* 2 s) 3))
(define d (+ (* 4 s s) 5))

(operator->rat-func (/ n d) 2)
      \ev ((.75 .5) (1.25 0 1))
(operator->rat-func (/ n d) 3)
       \ev ((.75 .5) (1.25 0 1))
;;the second one takes longer

(operator->rat-func (/ d n) 2)
;;error -- n is too small: 2

(operator->rat-func (/ d n) 3)
        \ev ((2.5 0 2.) (1.5 1))
\end{scheme}

\begin{entry}{%
\proto{rat-func->pfe}{ numer-poly poles}{procedure}}

This procedure creates a partial fraction expansion of a rational
function, given the poles.  The procedure is based on the idea of
subtracting out pole terms one by one and expanding the remainder.
\begin{displaymath}
\frac{N(s)}{(s-s_0)D(s)}
  =  \frac{N(s_0)/D(s_0)}{(s-s_0)^n}
      + \frac{\frac{N(s) - (N(s_0)/D(s_0))D(s)}{s-s_0}}
             {(s-s_0)^{n-1}D(s)}
\end{displaymath}
As an example, consider
\begin{displaymath}
\frac{2s^5+9s^4-s^3-26s^2+5s-1}{(s+1)^2(s-1)^3(s+2)}
= \frac{3}{(s+1)^2} \frac{-2}{s+1} \frac{-1}{(s-1)^3} \frac{1}{(s-1)^2}
  \frac{3}{s-1} \frac{1}{s+2}
\end{displaymath}

\begin{scheme}
(rat-func->pfe '(-1 5 -26 -1 9 2) '(-1 -1 1 1 1 -2)) 
   \ev ((3 -2 -1 1 3 1) (-1 -1 1 1 1 -2))
\end{scheme}
\noindent
{\em Numer-poly} is entered as a list of coefficients in order of ascending
powers of terms.  {\em Poles} is a list of roots of the denominator
polynomial; repeated roots must be clustered together and roots should
be listed in order of increasing magnitude.  Note that the coefficient
of the highest-order power in the denominator polynomial is implicitly
assumed to be unity.  The result returned by {\tt rat-func->pfe} is a list
of two lists. The first list is called the \defining{residues} list (although
strictly-speaking only the coefficients of 1st-order terms are
properly called residues); the second is the list of {\em poles} .  The
order of the terms in the residues list is the same as the {\em poles} list;
for repeated roots, terms are listed in decreasing order of the pole.
\end{entry}

\begin{entry}{%
\proto{pfe->rat-func}{ residues poles}{procedure}}

This procedure reconstructs a rational function as a list of two terms
in the form {\tt (numer-poly poles)} from a partial fraction expansion
described by a {\em residues} list and a {\em poles} list.
\begin{scheme}
(pfe->rat-func '(3 -2 -1 1 3 1) '(-1 -1 1 1 1 -2))
     \ev  ((-1 5 -26 -1 9 2) (-1 -1 1 1 1 -2))
\end{scheme}
\end{entry}

\begin{entry}{%
\proto{pfe->time}{ residues poles}{procedure}}

This procedure returns an operator whose value
is the inverse Laplace transform of the rational function of complex
frequency described by the {\em residues} list and the {\em poles}
list.  For example, the rational function with unity residues and
poles at $\pm\imag$ is $2s/(s^2+1)$ and (from tables) has inverse
Laplace transform $2\cos t u(t)$:
\begin{scheme}
(define t-func
  (pfe->time
   '(1 1)
   (list (make-rectangular 0 1)
         (make-rectangular 0 -1))))

(operator-value t-func (/ pi 3)) \ev  1
(operator-value t-func (/ (- pi) 3)) \ev 0
\end{scheme}
\end{entry}


\section{Plotting}

The system can draw graphs of frequency responses on a linear or
logarithmic scale.  The graphs are drawn in various {\em graphics
fields} whose arrangement is controlled by {\tt set-fields!}.  Graphed
values are {\em memoized} as they are drawn, so that if you plot a
graph and then clear the screen, the graph can be redrawn quickly.

\begin{entry}{%
\proto{plot-f-resp}{ op df ymax field-number}{procedure}}

This plots the values of the operator 
{\em op}, for a sequence of values of frequency $s$.
The frequency increment is {\em
df}.  The function is plotted for values of $s=0, \imag df, 2jdf,
\ldots, 128jdf$.  {\em Ymax} is the largest value of the magnitude of
the function over the range.  {\em Field-number} specifies the
graphics field in which the plot is displayed (see {\tt set-fields!}
below). {\tt Plot-f-resp} creates two graphs---one for the magnitude
with range 0 through {\em ymax}, and one for the phase with range
$-\pi$ through $\pi$.
\end{entry}

\begin{entry}{%
\proto{bode-plot}{ op fmin ymax field-number}{procedure}}

{\em Op} is an operator.  {\em
Frequency} is the starting frequency.  Makes a log-log plot of the
magnitude (in decibels) of {\em op} over the range $\log_{10}s=0 +
\imag \log_{10}{\em fmin}$ through $\log_{10}s=0 + \imag
(7+\log_{10}{\em fmin})$.  {\em Ymax} is the maximum (in decibels) of
the magnitude---the decibels are scaled from ${\em ymax}-100$ through
{\em ymax}.  Also plots the phase on a scale $-\pi$ to $\pi$.
{\em Field-number} specifies the
graphics field in which the plot is displayed (see {\tt set-fields!}
below).
\end{entry}

\begin{entry}{%
\proto{set-fields!}{ horiz vert}{procedure}}

Controls the configuration of graphics fields on the screen.
{\tt Set-fields} configures the screen so that there are {\em vert}
rows, each containing {\em horiz} graphics fields.  The fields will be
numbered starting at the upper left and going across the first row,
then to the left of the second row, and so on.  When Scheme is
started, the default is two rows of two fields.
\end{entry}

\begin{entry}{%
\proto{list-graphs}{}{procedure}}

Graphed values are saved when they are drawn.  {\tt List-graphs} 
returns an index to the graphs currently stored, containing
a graph number, a description (such as ``Magnitude of Bode Plot'') and
a field number.  See {\tt regraph} and {\tt remove-graph}.
\end{entry}

\begin{entry}{%
\proto{regraph}{}{procedure}
\proto{regraph}{ \vari{n} \varii{n} \dotsfoo}{procedure}}

Redraws stored graphs.  With no arguments, redraws all the graphs in
the list shown by {\tt list-graphs}.  Arguments $n_i$ specify
particular graphs to be redrawn.  Positive values refer to the numbers
in the list shown by {\tt list-graphs}; negative values count back
from the current graph, e.g., $-1$ refers to the previous graph drawn.
\end{entry}

\begin{entry}{%
\proto{remove-graph}{ \vari{n} \varii{n} \dotsfoo}{procedure}}

Removes the graphs numbered $n_1, n_2, \ldots$ from the list of graphs
(see {\tt list-graphs}).  You should do this to reclaim storage after
you have drawn many graphs.  Negative values for the $n_i$ count back
from the current graph, e.g., $-1$ refers to the last graph drawn.
\end{entry}

\section{Other definitions}

For convenience, the following symbols are defined.

\begin{entry}{%
\vproto{pi}{variable}
\vproto{2pi}{variable}}

Variables whose values are (approximations to) $\pi$ and $2\pi$
respectively. 
\end{entry}

\begin{entry}{%
\vproto{j}{variable}
\vproto{-j}{variable}}

These variables, representing $\pm\sqrt{-1}$ are equal to {\tt
(make-rectangular 0 1)} and {\tt (make-rectangular 0 -1)} respectively.
\end{entry}

