How to make development faster, and debugging easier

By James Choi

How to write Wolfram Language Code

Spell out each step, as opposed to clustering into one line.

Don’t do it like this.

{area,shape,boundingBox}=MaximalBy[Values@ComponentMeasurements[Binarize[,0.3],{"Area","Shape","BoundingBox"}],#[[1]]&][[1]]

Do it like this.  View the output every step of the way making every variable immutable.

image=

binary=Binarize[image,0.3]

components=Values@ComponentMeasurements[binary,{"Area","Shape","BoundingBox"}]

{area,shape,boundingBox}=MaximalBy[components,#[[1]]&][[1]]

largestGrain=ImageTrim[image,boundingBox]

SetAlphaChannel[largestGrain,FillingTransform@shape]

Then put them together into a function.

Clear[removeBackground]
removeBackground[image_Image]:=Module[{binary,components,area,shape,boundingBox,largestGrain},
binary=Binarize[image,0.3];
components=Values@ComponentMeasurements[binary,{"Area","Shape","BoundingBox"}];{area,shape,boundingBox}=MaximalBy[components,#[[1]]&][[1]];largestGrain=ImageTrim[image,boundingBox];SetAlphaChannel[largestGrain,FillingTransform@shape]
]

When a subroutine malfunctions, either make the local variables global by commenting out the local variable list to examine the output.

Clear[removeBackground]
removeBackground[image_Image]:=Module[{(*binary,components,area,shape,boundingBox,largestGrain*)},
binary=Binarize[image,0.3];
components=Values@ComponentMeasurements[binary,{"Area","Shape","BoundingBox"}];{area,shape,boundingBox}=MaximalBy[components,#[[1]]&][[1]];largestGrain=ImageTrim[image,boundingBox];SetAlphaChannel[largestGrain,FillingTransform@shape]
]

Use a small subset of the data set first to estimate the computation time by extrapolation

allCities=;
Length[%]

AbsoluteTiming[population={#->CityData[#,"Population"]}&/@allCities[[1;;17]]]

It is more accurate to use RandomSample than Part

AbsoluteTiming[population={#->CityData[#,"Population"]}&/@RandomSample[allCities,17]]

Use Dynamic to view how much work is left, or observe the variable.  Use Dynamic and a new window to have “watch” simulation.  If necessary, leak the variable into global for inspection.

count=0;
Do[
Pause[0.1];
count++;
,{i,20}]

Dynamic[count]

MapIndexed[Pause[0.5];#^2&,Range[101,110]]

Dynamic[#]

MapIndexed[(Pause[0.5];t=#;#^2)&,Range[101,110]]

Dynamic[t]

MapIndexed[(t=#2[[1]];Pause[0.5];#^2)&,Range[101,110]]

Dynamic[t]

Use different cores to run while another process is running

Use Speak[“some messsage”] to notify when it is done.

When you are running several machines, you can have it say different messages.

Speak["Machine 3 Run 5 is done"]

Use “out of core” processing when experiencing frequent crashes

When faced with frequent crashing, use file to process one data point at a time, then store that data.  This way, you can resume the computation in the middle.
See “02 Out of Core Processing.nb” notebook for details