Best Practices

George E. Hrabovsky

MAST

Introduction

In this lesson we will examine useful tips and ideas to make life, and code, better in MMA/WL. I will try to organize these by what I consider the most important ideas first. Unfortunately this is a personal choice on my part and nothing can be done about that.

The Most Important Things

To Do Right Away Before Starting Anything Else

Go to the Edit Menu. Then go to Preferences.

Uncheck the Show suggestions bar after last output. This is responsible for throwing lots of errors.

Activate the button Automatically insert matching delimiters while typing. In version 12,3 the default is unchecked, so you should activate it. In version 13 this is the default state.

No Autosave

Save your work often. There is no autosave.

Use the ?

If you forget how to use a command type a new cell with ?command to get a description of it. If you type ??command you will also get a list of function attributes.

l5_1.png

l5_2.png

l5_3.png

l5_4.png

Referring to Previous Output

Never, never, NEVER, use % to refer to previous output. Assign a symbol to any output so you can refer to it later.

Aborting a Command

You can either go to the Evaluation Menu and select Abort Evaluation, or hold down the [ALT] key and type . .

If you can’t abort the command, then you will have to go to the Evaluation Menu, then Quit Kernel, then choose Local. This will stop all evaluations and reset the system. It will not save your work. If MMA/WL becomes unstable and you can’t do anything with it, then use the system in your operating system to kill the process. This will destroy all unsaved work. Save your work often.

Important Things

Avoid Iterative Loops

Avoid iterative programming, use functional recursions instead. For example.

l5_5.png

l5_6.png

l5_7.png

l5_8.png

l5_9.png

l5_10.png

l5_11.png

l5_12.png

Look Up the Syntax

Get to know the syntax of the WL. In the documentation system go to the Guide Wolfram Language Syntax. From there there are two things to get to know: the first is the associated Guide Wolfram Language Syntax Characters. The second is a link to the tutorial Textual Input and Output. You can also type into the Search Bar Operator Input Forms, this links to an included Tech note of the same name that lists all of these things.

Using Transpose on Datasets

Say that you have two data sets that you need to merge for a function, say a ListPlot. Use Transpose to link them element by element. Here is an example.

l5_13.png

l5_14.png

l5_15.png

l5_16.png

l5_17.png

l5_18.png

l5_19.png

l5_20.gif

Make sure that the two original data files are the same length.

Weak Typing

MMA/WL have what is called “weak typing” that is it does not enforce hard rules for establishing symbol typing. This is an advantage most of the time, as it lends flexibility. It can cause problems if you change code, as you might inadvertently change the type of a variable in your mind without remembering to treat the symbol that way in the code.

A Note About Associations

Associations are memory hungry.

Navigating Code

Use [CTRL]. to select groups of symbols.

Use [CTRL][SHIFT]→ or [CTRL][SHIFT]← to extend your selection by one token in either direction.

Use [CTRL]↑ of [CTRL]↓ to jump up or down three line while the cursor stays in its current location.

Autocompletion

Take advantage of autocompletion where possible, you can enter this manually by using [CTRL]k

Contexts

If you ever want a list of variables and functions you have defined in your session use the names under the notebook context. You can find the name for the context by using the Context command.

l5_21.png

l5_22.png

or we can use this.

l5_23.png

l5_24.png

For a more in-depth look, we can write this.

l5_25.png

l5_26.png

From this we see that the notebook has introduced a context and that the system has also introduced a context.

To find the names under the notebook context write this.

l5_27.png

l5_28.png

If you want to clear all of the names used in the context write this.

l5_29.png

If you want to keep the names, but clear all definitions and attributes use this command.

l5_30.png

The Remove command should resolve most variable conflicts.

Contexts are the names of work environments produced by the MMA/WL system. Each package you load will introduce a new context. You can create new contexts.

l5_31.png

l5_32.png

Turning Off System Complaints

If you are doing something you know is correct, but it will generate warnings, end the code with //Quiet.

Things

Indexed Variables

If you must use indexed variables it is best to use an association as this allows you to bind many values to a variable name by position.

l5_33.png

l5_34.png

l5_35.png

l5_36.png

To display indices you can use DownValues to assign the value as a rule to a function head.

l5_37.png

l5_38.png

l5_39.png

l5_40.png

l5_41.png

l5_42.png

Function Naming Convention

The names of all Mathematica commands begin with a capital letter. I recommend that your user-defined functions do not, that makes it easier to tell the difference.

Never use an underscore in a name, it is reserved for patterns.

Avoid using single capital letters as names.

If You Must Perform a Procedural Iteration

Using Which is much more efficient than nested If statements.

Shadowing

If you load a package and a name is duplicated it can cause a shadowing error. This can happen is you use [Get[context`], or its short form <<Context`. You can avoid this by using Needs[Context`].

Less Important Things

Wrapping Forms Instead of Including Them

Don’t use TableForm or MatrixForm in table or matrix definitions. Wrap the definition in these commands instead. That way  the object is not defined in the formatted output form.

l5_43.png

l5_44.png

Note that we call the // symbol piping.

l5_45.png

l5_46.png

l5_47.png

l5_48.png

l5_49.png

l5_50.png

Finding Options

There are many functions that have hidden options or methods. This code is modified from the web page https://www.12000.org/my_notes/faq/mma_notes/MMA.htm.

l5_51.png

l5_52.png

# Option Options to this option
1 NDSolve`Adams
MaxDifferenceOrder→12
VariableStepCoefficients→Automatic
2 NDSolve`AnyEdge {}
3 NDSolve`Auxiliary
Method→Automatic
AuxiliaryTerms→Automatic
DampingFactor→0
4 NDSolve`BaderSequenceFunction {}
5 NDSolve`BDF
ImplicitSolver→NDSolve`Newton
MaxDifferenceOrder→5
VariableStepCoefficients→Automatic
6 NDSolve`BootstrapDenseOutput {}
7 NDSolve`BulirschSequenceFunction {}
8 NDSolve`Chasing
Method→Automatic
ExtraPrecision→0
ChasingType→LinearChasing
9 NDSolve`ChebyshevCoefficients {}
10 NDSolve`CheckMethodProperty {}
11 NDSolve`Composition
Coefficients→Automatic
DifferenceOrder→Automatic
Method→None
12 NDSolve`ComputeDerivatives
l5_53.png
CollocationDirection→Centered
MaxIterations→100
SecondDerivative→False
Verbose→False
ReturnResidualValue→False
13 NDSolve`ConsistentCoefficientsQ {}
14 NDSolve`Continuity {}
15 NDSolve`CountableCrossingEvent {}
16 NDSolve`CountableCrossingValue {}
17 NDSolve`CreateMethodData {}
18 NDSolve`CreateWorkspace {}
19 NDSolve`CreateWorkspaceList {}
20 NDSolve`CrossDiscontinuity {}
21 NDSolve`CubicHermite {}
22 NDSolve`DAEInitialize
CollocationDirection→Automatic
BasisType→Chebyshev
CollocationPoints→{Automatic,ExtraCollocationPoints→Automatic}
Verbose→False
DefaultStartingValue→Automatic
MaxIterations→100
CollocationRange→Automatic
23 NDSolve`DAEInitializeForProjection
SolvingMethod→LinearSolve
InitialConditionWeight→10
MaxIterations→Automatic
DefaultStartingValue→Automatic
Verbose→False
Method→Automatic
24 NDSolve`DAEInitializeReduced
Method→Automatic
DefaultStartingValue→Automatic
MaxIterations→Automatic
25 NDSolve`DAESensitivityInitialize {}
26 NDSolve`DCayleyInverse {}
27 NDSolve`DDEFunction {}
28 NDSolve`DelayDESteps
Method→Automatic
DerivativeEvaluation→Interpolation
29 NDSolve`DeltaDiscontinuity {}
30 NDSolve`Dethread {}
31 NDSolve`DExpInverse {}
32 NDSolve`DExpInverseCoefficients {}
33 NDSolve`DiscontinuityEvaluate {}
34 NDSolve`DiscontinuityExclusion {}
35 NDSolve`DiscontinuityReplace {}
36 NDSolve`DiscontinuityScan
Domain→Automatic
MaxContinuity→∞
Replacements→False
37 NDSolve`DiscontinuitySurface {}
38 NDSolve`DiscontinuityValues {}
39 NDSolve`DoubleStep
LocalExtrapolation→True
Method→None
StepSizeRatioBounds→Automatic
StepSizeSafetyFactors→Automatic
StiffnessTest→Automatic
40 NDSolve`EmbeddedExplicitRungeKuttaCoefficients {}
41 NDSolve`EstimateStartingStep {}
42 NDSolve`EvaluateJacobianWithSolutionData {}
43 NDSolve`EvaluateWithSolutionData {}
44 NDSolve`EventData {}
45 NDSolve`EventLocator
Direction→All
Event→None
EventAction:→StopIntegration
EventCondition→True
EventLocationMethod→Automatic
IncludeDerivatives→Automatic
CheckDerivatives→False
Method→Automatic
46 NDSolve`EventOrderBackward {}
47 NDSolve`EventOrderForward {}
48 NDSolve`ExplicitEuler {}
49 NDSolve`ExplicitMidpoint
l5_54.png
l5_55.png
50 NDSolve`ExplicitModifiedMidpoint
l5_56.png
l5_57.png
51 NDSolve`ExplicitRungeKutta
Coefficients→EmbeddedExplicitRungeKuttaCoefficients
DifferenceOrder→Automatic
EmbeddedDifferenceOrder→Automatic
StepSizeControlParameters→Automatic
l5_58.png
StepSizeSafetyFactors→Automatic
StiffnessTest→Automatic
52 NDSolve`Extrapolation
ExtrapolationSequence→Automatic
MaxDifferenceOrder→Automatic
Method→ExplicitModifiedMidpoint
MinDifferenceOrder→Automatic
OrderSafetyFactors→Automatic
StartingDifferenceOrder→Automatic
StepSizeRatioBounds→Automatic
StepSizeSafetyFactors→Automatic
StiffnessTest→Automatic
53 NDSolve`FallingEdge {}
54 NDSolve`FinalizeMethod {}
55 NDSolve`FiniteDifferenceDerivative
DifferenceOrder→4
PeriodicInterpolation→False
56 NDSolve`FiniteDifferenceDerivativeFunction {}
57 NDSolve`FiniteDifferenceWeights {}
58 NDSolve`FiniteElement
AccuracyGoal→Automatic
BoundaryTolerance→Automatic
ConstraintMethod→Automatic
InitializePDECoefficientsOptions→Automatic
IntegrationOrder→Automatic
InterpolationOrder→Automatic
LinearSolveMethod→Automatic
MeshOptions→Automatic
PDESolveOptions→Automatic
PrecisionGoal→Automatic
PrecomputeGeometryData→True
59 NDSolve`FixedPoint {}
60 NDSolve`FixedStep
Method→None
StepSize→Automatic
61 NDSolve`GetDefaultDifferenceOrder {}
62 NDSolve`GetDenseOutput {}
63 NDSolve`GetMethodOptionValues {}
64 NDSolve`GMRES
Preconditioner→Automatic
OrthogonalizationType→ModifiedGramSchmidt
MaxKrylovSubspaceDimension→Automatic
MaxKrylovRestarts→Automatic
65 NDSolve`HairerOstermannSequenceFunction {}
66 NDSolve`HarmonicSequenceFunction {}
67 NDSolve`IDA
MaxDifferenceOrder→5
ImplicitSolver→Newton
68 NDSolve`ImplicitRungeKutta
Coefficients→ImplicitRungeKuttaGaussCoefficients
DifferenceOrder→Automatic
ImplicitSolver→Newton
StepSizeControlParameters→Automatic
l5_59.png
StepSizeSafetyFactors→Automatic
69 NDSolve`ImplicitRungeKuttaAdjointCoefficients {}
70 NDSolve`ImplicitRungeKuttaCoefficients
Solve→Row
71 NDSolve`ImplicitRungeKuttaGaussCoefficients {}
72 NDSolve`ImplicitRungeKuttaLobattoIIIACoefficients {}
73 NDSolve`ImplicitRungeKuttaLobattoIIIBCoefficients {}
74 NDSolve`ImplicitRungeKuttaLobattoIIICCoefficients {}
75 NDSolve`ImplicitRungeKuttaRadauIACoefficients {}
76 NDSolve`ImplicitRungeKuttaRadauIIACoefficients {}
77 NDSolve`IndexReductionVisualizer
IndexGoal→Automatic
78 NDSolve`InitialHistory {}
79 NDSolve`InitializeMethod {}
80 NDSolve`InitializeSubmethod {}
81 NDSolve`InitializeSubmethods {}
82 NDSolve`IntraStepEvaluationData {}
83 NDSolve`InvokeMethod {}
84 NDSolve`iScaledVectorNorm {}
85 NDSolve`Iterate {}
86 NDSolve`iVectorNorm {}
87 NDSolve`iVectorNormWeights {}
88 NDSolve`iWeightedVectorNorm {}
89 NDSolve`KrylovIteration
BasisSize→Automatic
MaxIterations→Automatic
l5_60.png
90 NDSolve`LinearlyImplicitEuler
l5_61.png
LinearSolveMethod→Automatic
StabilityTest→True
91 NDSolve`LinearlyImplicitMidpoint
l5_62.png
LinearSolveMethod→Automatic
StabilityTest→True
l5_63.png
l5_64.png
92 NDSolve`LinearlyImplicitModifiedMidpoint
l5_65.png
LinearSolveMethod→Automatic
StabilityTest→True
l5_66.png
l5_67.png
93 NDSolve`LinearStabilityBoundary {}
94 NDSolve`LocalInterpolation {}
95 NDSolve`LocallyExact
SimplificationFunction→None
96 NDSolve`LocalSeries {}
97 NDSolve`LSODA
LinearSolveMethod→Automatic
MaxDifferenceOrder→12
98 NDSolve`MakeStateSpaceNumericalFunction {}
99 NDSolve`MassMatrix
Method→Automatic
100 NDSolve`MethodData {}
101 NDSolve`MethodOfLines
DifferentiateBoundaryConditions→Automatic
DiscretizedMonitorVariables→False
ExpandEquationsSymbolically→False
SpatialDiscretization→Automatic
TemporalVariable→Automatic
102 NDSolve`MethodSymbol {}
103 NDSolve`MultistepControllerQ {}
104 NDSolve`NDSolveFunction {}
105 NDSolve`NDSolveMessage {}
106 NDSolve`NDSolveParametricFunction {}
107 NDSolve`NewMethodNorm {}
108 NDSolve`Newton
LinearSolveMethod→Automatic
109 NDSolve`NonstiffTest
MaxRepetitions→{2,∞}
l5_68.png
110 NDSolve`NonstiffTestData {}
111 NDSolve`NumericalFunctionToEquations {}
112 NDSolve`ODEInitialize
MaxIterations→100
113 NDSolve`ODESensitivityInitialize {}
114 NDSolve`OptimalRoundingSequenceFunction {}
115 NDSolve`OrthogonalChebyshevCoefficients {}
116 NDSolve`OrthogonalProjection
Dimensions→{}
l5_69.png
MaxIterations→Automatic
Method→StiffnessSwitching
117 NDSolve`ParametricPlugInFunction {}
118 NDSolve`Parareal
MaxTimeUnit→10
ParallelMethod→None
SerialMethod→None
119 NDSolve`PararealInitialize {}
120 NDSolve`PararealParallelStep {}
121 NDSolve`PararealParallelSteps {}
122 NDSolve`PararealStateData {}
123 NDSolve`PredicateBoundaryFunction {}
124 NDSolve`ProcessEquations
AccuracyGoal→Automatic
Compiled→Automatic
DependentVariables→Automatic
DiscreteVariables→{}
EvaluationMonitor→None
InitialSeeding→{}
InterpolationOrder→Automatic
l5_70.png
MaxSteps→Automatic
MaxStepSize→Automatic
Method→Automatic
NormFunction→Automatic
PrecisionGoal→Automatic
StartingStepSize→Automatic
StepMonitor→None
WorkingPrecision→MachinePrecision
125 NDSolve`ProcessSolutions {}
126 NDSolve`Projection
AccuracyGoal→Automatic
Invariants→None
IterationSafetyFactor→1
LinearSolveMethod→Cholesky
MaxIterations→Automatic
Method→StiffnessSwitching
PrecisionGoal→Automatic
127 NDSolve`RealLine {}
128 NDSolve`ReduceIndex
IndexGoal→Automatic
ConstraintMethod→Automatic
Method→Automatic
129 NDSolve`Reinitialize
AccuracyGoal→Automatic
EvaluationMonitor→None
InitialSeeding→{}
InterpolationOrder→Automatic
l5_71.png
MaxSteps→Automatic
MaxStepSize→Automatic
NormFunction→Automatic
PrecisionGoal→Automatic
StartingStepSize→Automatic
StepMonitor→None
130 NDSolve`ReinitializeVector
AccuracyGoal→Automatic
EvaluationMonitor→None
InitialSeeding→{}
InterpolationOrder→Automatic
l5_72.png
MaxSteps→Automatic
MaxStepSize→Automatic
NormFunction→Automatic
PrecisionGoal→Automatic
StartingStepSize→Automatic
StepMonitor→None
131 NDSolve`RisingEdge {}
132 NDSolve`RombergSequenceFunction {}
133 NDSolve`SameDiscontinuities {}
134 NDSolve`SamePrecisionQ {}
135 NDSolve`ScaledVectorNorm {}
136 NDSolve`Self {}
137 NDSolve`SensitivityMethod
Method→Automatic
138 NDSolve`SetSolutionDataComponent {}
139 NDSolve`SetState {}
140 NDSolve`Shooting
DefaultStartingValue→0
ImplicitSolver→Automatic
MaxIterations→Automatic
StartingInitialConditions→Automatic
141 NDSolve`SimplifySystem {}
142 NDSolve`SlidingModeFunction {}
143 NDSolve`SolutionData {}
144 NDSolve`SolutionDataComponent {}
145 NDSolve`SolutionDataIndex {}
146 NDSolve`SolutionDataListQ {}
147 NDSolve`SolutionDataTemplate {}
148 NDSolve`SpectralRadius
MaxIterations→50
l5_73.png
SampleFrequency→Automatic
l5_74.png
149 NDSolve`SpectralRadiusOptionValues {}
150 NDSolve`Splitting
Coefficients→Automatic
DifferenceOrder→Automatic
Equations→{}
Method→None
151 NDSolve`StabilizedRungeKutta
Coefficients→OrthogonalChebyshevCoefficients
DifferenceOrder→Automatic
MaxStages→Automatic
SpectralRadius→Automatic
StepSizeControlParameters→Automatic
l5_75.png
StepSizeSafetyFactors→Automatic
152 NDSolve`StateData {}
153 NDSolve`StateDataQ {}
154 NDSolve`StateSpace
Method→Automatic
BlockLowerTriangular→Automatic
StepControl→None
155 NDSolve`StateSpaceFunction {}
156 NDSolve`StateSpaceFunctionQ {}
157 NDSolve`StepSizeControlData {}
158 NDSolve`StiffnessSwitching
NonstiffTest→Automatic
Method→{Automatic,Automatic}
159 NDSolve`StiffnessTest
MaxRepetitions→{3,5}
l5_76.png
160 NDSolve`StiffnessTestData {}
161 NDSolve`Streamline
Mesh→None
Method→Automatic
SinkTest→5
162 NDSolve`StructuralIncidenceArray {}
163 NDSolve`StructuralIndex
IndexGoal→Automatic
164 NDSolve`SubspaceIteration
BasisSize→Automatic
MaxIterations→Automatic
l5_77.png
165 NDSolve`SwitchingVariable {}
166 NDSolve`SymmetricCompositionCoefficients {}
167 NDSolve`SymmetricCompositionSymmetricMethodCoefficients {}
168 NDSolve`SymplecticPartitionedRungeKutta
Coefficients→SymplecticPartitionedRungeKuttaCoefficients
DifferenceOrder→Automatic
PositionVariables→{}
169 NDSolve`SymplecticPartitionedRungeKuttaCoefficients {}
170 NDSolve`TestImplicitSolver {}
171 NDSolve`ToSymbol {}
172 NDSolve`ValidNumericalFunctionQ {}
173 NDSolve`ValidScaledVectorNormQ {}
174 NDSolve`ValidStateDataQ {}
175 NDSolve`VariableData {}
176 NDSolve`VODE {}
177 NDSolve`$EventSolution {}
178 {NDSolve`ImplicitRungeKuttaGaussCoefficients,NDSolve`ImplicitRungeKuttaLobattoIIIACoefficients,NDSolve`ImplicitRungeKuttaLobattoIIIBCoefficients,NDSolve`ImplicitRungeKuttaLobattoIIICCoefficients,NDSolve`ImplicitRungeKuttaRadauIACoefficients,NDSolve`ImplicitRungeKuttaRadauIIACoefficients} {}
179 5 {}
Created with the Wolfram Language