Chapter 12
Contexts and Packages

from
Introduction to Programming with Mathematica
2nd Ed.

by
Richard J. Gaylord
Samuel N. Kamin
Paul R. Wellin

Copyright 1995 TELOS/Springer-Verlag

12.2 Using Packages

Code from book

Needs["Calculus`VectorAnalysis`"]

CrossProduct[{1.0, 2.0, 3.0}, {-1.0, -2.0, -3.0}]

12.3 Contexts

Code from book

f[x_] := x + 1

Global`f[3]

Global`f == f

System`Map[Global`f, {5, 7, 9}]

Begin["ContextA`"]

g[x_] := x + 2

g[3]

ContextA`g[3]

Map[g, {5, 7, 9}]

Map[Global`f, {5, 7, 9}]

End[]

g[x_] := x + 3

g[3]

ContextA`g[3]

Context[g]

Context[Map]

Context[ContextA`g]

?g

$Context

$ContextPath

Begin["ContextA`"]

$Context

$ContextPath

End[]

{$Context, $ContextPath}

Begin["A`"]         (* enter context A` *)

Begin["`B`"]        (* enter context A`B` *)

Begin["`C`"]        (* enter context A`B`C` *)

End[]               (* back in context A`B` *)

End[]               (* back in context A` *)

End[]               (* back in context Global` *)

Begin["A`"]

Begin["A`B`"]

Begin["A`B`C`"]

12.5 The BaseConvert Package

BeginPackage

BeginPackage["BaseConvert`"]

Usage statements

DefaultBase::usage = "Default base used by StringToInt."

StringToInt::usage = "StringToInt[str, b] converts str
to an integer, assuming it is written in base b.
StringToInt[str] is equivalent to StringToInt[str, DefaultBase]."

Begin private context

Begin["`Private`"]

Function definitions

DefaultBase = 10;
StringToInt[str_] := StringToInt[str, DefaultBase]
StringToInt[str_String, b_Integer] :=
   Which[Not[2 <= b <= 10],
	          Print["StringToInt: second argument is
		         inappropriate base."],
               Not[Apply[And,Map[(0<=numeralToInt[#]<b)&,
	                        ToCharacterCode[str]]]],
                  Print["StringToInt: first argument has
		         incorrect digits."],
               True, (* arguments are legal *)
	          Map[numeralToInt, ToCharacterCode[str]] . 
		     Table[b^i, {i,StringLength[str]-1,0,-1}]]

StringToInt[str_, b_] :=
         (If[Not[StringQ[str]],
	     Print["StringToInt: ", str, " is not a string."]];
          If[Not[IntegerQ[b]],
	     Print["StringToInt: ", b," is not an integer."]])

      StringToInt[x___] :=
         Print["StringToInt: called with ", Length[{x}],
	       " arguments; 1 or 2 arguments are expected."]

      numeralToInt[numeral_] :=
         numeral - ToCharacterCode["0"][[1]]

End private context

End[]

End package

EndPackage[]

Examples

Needs["BaseConvert`"]

StringToInt["123"]

DefaultBase = 5

StringToInt["123"]

StringToInt["123", 12]

StringToInt["123", 8]

12.6 The RandomWalks Package

Package

BeginPackage

BeginPackage["RandomWalks`"]

Importing packages

Needs["Graphics`ArgColors`"]

Usage statements

Walk1D::usage = "Walk1D[n] generates an n-step walk in one dimension.
Steps are of unit length.";

Walk2D::usage = "Walk2D[n] generates an n-step walk in two dimensions.
The default behavior gives a lattice walk with steps in one of the
four compass directions. Setting the option LatticeWalk->False will
generate an off-lattice walk.";

Walk3D::usage = "Walk3D[n] generates an n-step walk in three 
dimensions. The walk is executed on a cubic lattice with each
step in one of 8 lattice directions.";

LatticeWalk::usage = "LatticeWalk -> val is an option to Walk2D
that determines whether the random walk will be a lattice walk
or an off-lattice walk. Possible values are True and False.";

SquareDistance::usage = "SquareDistance[walk] computes the
square of the end-to-end distance of a two-dimensional lattice
walk. This can be thought of as the square of the diameter of
the walk.";

MeanSquareDistance::usage = "MeanSquareDistance[n, m] computes
the mean square end-to-end distance of m n-step lattice walks.";

MeanSquareRadiusGyration::usage = "MeanSquareRadiusGyration[m, n]
computes the mean square radius of gyration of a random walk. This
is the sum of the squares of the distances of the step locations
from the center of mass, divided by the number of step locations,
where the center of mass is the sum of the step locations divided
by the number of step locations.";

ShowWalk2D::usage = "ShowWalk2D[walk] displays a two-dimensional
random walk connecting each site with a line. Any Graphics options
can be passed to ShowWalk2D. E.g., ShowWalk2D[walk, 
Background->GrayLevel[0]] to produce a black background.";

ShowPointWalk2D::usage = "ShowPointWalk2D[walk, opts] displays a 
two-dimensional walk with each site shown as a point. Graphics
options can be passed to ShowPointWalk2D. E.g., ShowWalk2D[walk, 
Background->GrayLevel[0]] to produce a black background.";

ShowHistoryWalk2D::usage = "ShowHistoryWalk2D[walk, opts] displays
a two-dimensional random walk with each site shown as a point colored
according to its history in the walk. Graphics options can be passed 
to ShowHistoryWalk.";

ShowWalk3D::usage = "ShowWalk3D[walk] displays a three-dimensional
random walk connecting each site with a line. Any Graphics3D options
can be passed to ShowWalk3D. E.g., ShowWalk3D[walk, Boxed->False]
to inhibit the display of a bounding box.";

ShowCubeWalk3D::usage = "ShowCubeWalk3D[walk] displays a three-dimensional 
random walk displaying each site as a cube. Any Graphics3D options can
be passed to ShowCubeWalk3D. E.g., ShowCubeWalk3D[walk, Boxed->False] to 
inhibit the display of a bounding box.";

AnimateWalk2D::usage = "AnimateWalk2D[walk, opts] creates an animation of
a two-dimensional random walk. A red ball will be seen to move to the 
current position in the walk to aid in visualizing the animation.";

Options

Options[Walk2D] = {LatticeWalk -> True}

Begin private context

Begin["`Private`"]

The walks

Walk1D[n_] := 
   FoldList[Plus, 0, Table[(-1)^Random[Integer],{n}]]

Walk2D[n_, opts___] := Module[{lattice},
   lattice = LatticeWalk /. {opts} /. Options[Walk2D];
   If[lattice == True,
      FoldList[Plus, {0,0}, 
         {{0,1},{1,0},{0,-1},{-1,0}}[[
         Table[Random[Integer,{1,4}], {n}]]]],
      FoldList[Plus, {0,0},
         Map[({Sin[#], Cos[#]})&,
         Table[Random[Real, {0, N[2Pi]}], {n}]]
     ]]]

Walk3D[n_] := FoldList[Plus, {0, 0, 0}, 
	{{-1,1,1},{-1,-1,1},{1,-1,1},{1,1,1},
	 {-1,1,-1},{-1,-1,-1},{1,-1,-1},{1,1,-1}}[[Table[
	 	Random[Integer, {1, 8}], {n}]]]]

Numerical analysis of the walks

SquareDistance[walk_List] := 
	Apply[Plus, (Last[walk] - First[walk])^2]

MeanSquareDistance[n_Integer, m_Integer] := 
	N[Sum[SquareDistance[ Walk2D[n] ], {m}]/m]

MeanSquareRadiusGyration[m_Integer, n_Integer] := 
Module[{},
   squareRadiusOfGyration[s_Integer] := 
   Module[{locs, cm,choices = {{1,0},{-1,0},{0,1},{0,-1}}},
      locs = FoldList[Plus,{0,0}, choices[[Table[Random[Integer,{1,4}],{s}]]]];
      cm = N[Apply[Plus, locs]/(s+1)];
      Apply[Plus, Flatten[(Transpose[locs] - cm)^2]]/(s+1)
   ];
   N[Sum[squareRadiusOfGyration[n], {m}]/m]
]

Graphics

ShowWalk2D[coords_, opts___]:=
	Show[Graphics[Line[coords],
		opts,
		AspectRatio -> Automatic]]

(* colored according to distance from origin *)
ShowPointWalk2D[coords_, opts___]:=
	Module[{prwise, distances, c},
		prwise = Map[({First[coords],#})&, coords];
		distances = Map[N[Sqrt[Apply[Plus, (#[[1]] - #[[2]])^2]]]&,
			           prwise];
		colors = Map[Hue, distances / Max[distances]];
		
		Show[Graphics[Transpose[{colors, Map[Point,coords]}],
			opts, AspectRatio -> Automatic]]]

(* colored according to polar angle *)

ShowPolarWalk2D[coords_, opts___]:=
	Module[{comp,points,colors},
		comp = coords /. {a_,b_} -> Complex[a,b];
		points = Map[Point, coords];
		colors = Map[ArgColor, comp];
		Show[Graphics[{PointSize[.025], Transpose[{colors,points}]},
			opts, AspectRatio -> Automatic]]]

(* colored according to history *)
ShowHistoryWalk2D[coords_, opts___]:=
	Module[{len = Length[coords],points,colors},
		points = Map[Point, coords];
		colors = Map[Hue, Range[len]/len];
		Show[Graphics[{PointSize[.01], Transpose[{colors,points}]},
			opts, AspectRatio -> Automatic]]]

ShowWalk3D[coords_, opts___]:=
	Show[Graphics3D[Line[coords],
		opts, AspectRatio -> Automatic]]

ShowCubeWalk3D[walk_, opts___]:=
	Show[Graphics3D[Map[Cuboid, walk],
		opts, AspectRatio -> Automatic]]

ShowPointWalk3D[walk_, opts___]:=
	Show[Graphics3D[{GrayLevel[.6],Line[walk],
		PointSize[.015], Hue[.77], Map[Point, walk]},
		opts, AspectRatio -> Automatic]]

Animations

AnimateWalk2D[coords_, opts___]:=
	Scan[Show[Graphics[{
		{RGBColor[1,0,0],PointSize[.025],
		 Point[ coords[[#]] ]},
		Line[Take[coords, #]]}],
	   opts,AspectRatio -> Automatic,
	   PlotRange -> Map[{Min[#]-.2, Max[#]+.2}&,
		             Transpose[coords]]]&, 
	Range[2, Length[coords]]]

End private context

End[]

End package

EndPackage[]

Examples

Options[Walk2D]

Names["RandomWalks`*"]

ShowWalk2D[ Walk2D[100] ]

ShowWalk2D[ Walk2D[200, LatticeWalk->False],
	Frame->True]

ShowCubeWalk3D[ Walk3D[75] ]