Skip to main content

error trapping - Check does not interrupt evaluation of the expression when a Message is emitted



On the surface, Check looks like a good method to use when you need to abort the evaluation of an expression whenever a Message is emitted. Unfortunately, as the following code demonstrates, the evaluation of the expression is completed after a Message has occurred.


(* the test message *)
Test::wrpt = "Negative point at `1`";

dat = RandomReal[1, 500];

(* without Check *)
woCheck = MapIndexed[
If[# < 0,
Message[Test::wrpt, #2[[1]]]; Unevaluated[Sequence[]],

#] &,
{-1}~Join~dat];

(* with Check *)
res = {};
Check[
MapIndexed[
If[# < 0,
Message[Test::wrpt, #2[[1]]]; Unevaluated[Sequence[]],
res = {res, #}; #] &,

{-1}~Join~dat],
$Failed
]
(* Test::wrpt: Negative point at 1
$Failed
*)

But, when comparing the two


woCheck == Flatten@res
(* True *)


This implies, that for long running computations Check is not a good solution to abort a computation if an error Message is emitted. Can this be fixed?



Answer



A simple method for accomplishing this is to have Message Throw an error when it is called, interrupting the current execution. Here is a replacement for Check which does that, with the same calling signature:


ClearAll[InterruptingCheck]
SetAttributes[InterruptingCheck, HoldAll]

InterruptingCheck[expr_, failexpr_, msgs : {___MessageName } : {}] :=
Internal`InheritedBlock[{Message, $msgFlag},
(* Module localizes tag while not polluting the global namespace *)

Module[{ tag },
Unprotect[Message];
(*
Attach hook to message, where failexpr is thrown after the
first Message is raised. msgFlag is used to prevent recursion,
so that when msg is called the original def is used.
*)
msg : Message[m_, ___] /; ! TrueQ[$msgFlag] := Block[{$msgFlag = True},
msg;
If[Length@msgs == 0 || MemberQ[msgs, m], Throw[failexpr, tag]]];

Catch[expr, tag]
]
]

(* With Leonid's suggestion, this now works correctly. *)
InterruptingCheck[expr_, failexpr_, msgGroup_String] :=
Hold[msgGroup] /. $MessageGroups /.
Hold[messages_List] :> InterruptingCheck[expr, failexpr, messages]

\begin{Edit}



My original code for the supplying a message group failed to work correctly. The fix is shown above. It works by replacing msgGroup with the appropriate list of messages, but using Hold to prevent them from being replaced by their string equivalents. (That is part of the reason for the HoldAll attribute being used here, to begin with.) Then, the held messages are extracted from Hold and inserted into InterruptingCheck still held because of HoldAll.


\end{Edit}


When applied to the example in the question,


res2 = {};
InterruptingCheck[
MapIndexed[
If[# < 0,
Message[Test::wrpt, #2[[1]]]; Unevaluated[Sequence[]],
res2 = {res2, #}; #] &,
dat[[;; 10]]~Join~{-1}~Join~dat],

$Failed,
{Test::wrpt}
]
(* Test::wrpt: Negative point at 11
$Failed
*)

and res2 is


{0.288047, 0.026642, 0.361008, 0.28977, 0.573743, 
0.272747, 0.937062, 0.330572, 0.192807, 0.916764}


showing that it did stop execution at after the tenth element in the data.


Comments

Popular posts from this blog

plotting - Plot 4D data with color as 4th dimension

I have a list of 4D data (x position, y position, amplitude, wavelength). I want to plot x, y, and amplitude on a 3D plot and have the color of the points correspond to the wavelength. I have seen many examples using functions to define color but my wavelength cannot be expressed by an analytic function. Is there a simple way to do this? Answer Here a another possible way to visualize 4D data: data = Flatten[Table[{x, y, x^2 + y^2, Sin[x - y]}, {x, -Pi, Pi,Pi/10}, {y,-Pi,Pi, Pi/10}], 1]; You can use the function Point along with VertexColors . Now the points are places using the first three elements and the color is determined by the fourth. In this case I used Hue, but you can use whatever you prefer. Graphics3D[ Point[data[[All, 1 ;; 3]], VertexColors -> Hue /@ data[[All, 4]]], Axes -> True, BoxRatios -> {1, 1, 1/GoldenRatio}]

plotting - Filling between two spheres in SphericalPlot3D

Manipulate[ SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, Mesh -> None, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], {n, 0, 1}] I cant' seem to be able to make a filling between two spheres. I've already tried the obvious Filling -> {1 -> {2}} but Mathematica doesn't seem to like that option. Is there any easy way around this or ... Answer There is no built-in filling in SphericalPlot3D . One option is to use ParametricPlot3D to draw the surfaces between the two shells: Manipulate[ Show[SphericalPlot3D[{1, 2 - n}, {θ, 0, Pi}, {ϕ, 0, 1.5 Pi}, PlotPoints -> 15, PlotRange -> {-2.2, 2.2}], ParametricPlot3D[{ r {Sin[t] Cos[1.5 Pi], Sin[t] Sin[1.5 Pi], Cos[t]}, r {Sin[t] Cos[0 Pi], Sin[t] Sin[0 Pi], Cos[t]}}, {r, 1, 2 - n}, {t, 0, Pi}, PlotStyle -> Yellow, Mesh -> {2, 15}]], {n, 0, 1}]

plotting - Mathematica: 3D plot based on combined 2D graphs

I have several sigmoidal fits to 3 different datasets, with mean fit predictions plus the 95% confidence limits (not symmetrical around the mean) and the actual data. I would now like to show these different 2D plots projected in 3D as in but then using proper perspective. In the link here they give some solutions to combine the plots using isometric perspective, but I would like to use proper 3 point perspective. Any thoughts? Also any way to show the mean points per time point for each series plus or minus the standard error on the mean would be cool too, either using points+vertical bars, or using spheres plus tubes. Below are some test data and the fit function I am using. Note that I am working on a logit(proportion) scale and that the final vertical scale is Log10(percentage). (* some test data *) data = Table[Null, {i, 4}]; data[[1]] = {{1, -5.8}, {2, -5.4}, {3, -0.8}, {4, -0.2}, {5, 4.6}, {1, -6.4}, {2, -5.6}, {3, -0.7}, {4, 0.04}, {5, 1.0}, {1, -6.8}, {2, -4.7}, {3, -1....