g1=Graph[{UndirectedEdge[a,b]}];
GraphQ[g1]
(*
OUT: True
*)
(*Needs["Combinatorica`"]*)
PlanarQ[g1]
(*
OUT: PlanarQ[.-.]
*)
Combinatorica`PlanarQ[g1]
(*
OUT: Combinatorica`PlanarQ[.-.]
*)
Why doesn't PlanarQ give back "True" or "False" ?
Your graph is not a Combinatorica graph, rather it is a System graph. You'll need to specify the contexts explicitly.
Needs["GraphUtilities`"];
g1 = System`Graph[{UndirectedEdge[a, b]}];
Combinatorica`PlanarQ[
GraphUtilities`ToCombinatoricaGraph[g1]]
This returns True but, in general, this process is a pain and rather buggy. I believe that Combinatorica is on the way out and I'd recommend trying to get by without.
You probably need:
Needs["GraphUtilities`"]
Needs["Combinatorica`"]
cg1 = ToCombinatoricaGraph[g1];
PlanarQ[cg1]
I don't have v8 to check, however.
Just a note, Combinatorica is on the way out. However, three months ago a lead on the Graph project told me there were no plans to re-implement algorithm specific interfaces like BrelazColoring for System Graph. So, some things may need Combinatorica for a while, and one way to deal with this is to try to use System'Graph for everything, keep Combinatorica out of package path, and get to Combinatorica functions by explicitly converting your Graph objects to Combinatorica'Graph objects, calling Combinatorica`function and then converting back to system graph. Here is some discussion with the details
For posterity, here's the relabelGraph function I use to solve the ordering issue reported by TomD,
relabelGraph[g_Graph,labeling_]:=Module[{vcoords,gstyle,labelMap,adjMat,newOrder,newCoords,verts},
verts=VertexList#g;
vcoords=VertexCoordinates/.AbsoluteOptions[g,VertexCoordinates];
gstyle=GraphStyle/.AbsoluteOptions[g,GraphStyle];
labelMap=Thread[Range[Length[verts]]->labeling];
adjMat=Normal#AdjacencyMatrix[g];
newOrder=Ordering[VertexList[g]/.labelMap];
newCoords=Thread[(VertexList[g]/.labelMap)->vcoords];
AdjacencyGraph[adjMat[[newOrder,newOrder]],VertexCoordinates->newCoords,GraphStyle->gstyle]
];
One way of using it is below. This produces result similar to IndexGraph, but with sorted VertexList
g=relabelGraph[g,Range#Length#VertexList#g];
Some other of my "annoyance fixing" functions are described in graphUsage.nb in the package here
This is also just a note.
I want to specifically draw attention to a possible bug in ToCombinatoricaGraph and a possible workaround. It may have no relevance to the original question.
Also, I am using Mma 7, so things may be fixed in v8.
If I define a graph as follows
Needs["Combinatorica`"]
Needs["GraphUtilities`"]
gr1 = {2 -> 4, 4 -> 3, 3 -> 1}
GraphPlot of gr1
Compare the following:
EdgeList#gr1
EdgeList#ToCombinatoricaGraph#gr1
Edges#ToCombinatoricaGraph#gr1
Output
{{2, 4}, {4, 3}, {3, 1}}
{{1, 2}, {2, 3}, {3, 4}}
{{1, 2}, {2, 3}, {3, 4}}
The workaround I use is to ignore, as far as is possible, ToCombinatoricaGraph and instead convert to a Combinatorica graph using FromOrderedPairs.
For example
Edges#FromOrderedPairs#EdgeList#gr1
EdgeList#FromOrderedPairs#EdgeList#gr1
Output
{{2, 4}, {4, 3}, {3, 1}}
{{2, 4}, {3, 1}, {4, 3}}
Another example, Degrees
Compare
Degrees#MakeSimple#ToCombinatoricaGraph[gr1]
VertexList#MakeSimple#ToCombinatoricaGraph[gr1]
Output
{1, 2, 2, 1}
{1, 2, 3, 4}
with
Degrees#MakeSimple#FromOrderedPairs#EdgeList#gr1
VertexList#MakeSimple#FromOrderedPairs#EdgeList#gr1
{1, 1, 2, 2}
{1, 2, 3, 4}
I'll also include an example with Prufer codes, as here I was badly 'caught out' (I did not know about SO then)
LabeledTreeToCode#MakeSimple#ToCombinatoricaGraph#gr1
LabeledTreeToCode#MakeSimple#FromOrderedPairs#EdgeList#gr1
Output
{2, 3}
{3, 4}
(Only the second answer is correct)
I have reported this to Wolfram. Seemingly, it is connected to reordering of vertices on graph creation by ToCombinatoricaGraph. Here is part of the reply (2009)
The reason that Edges and EdgeList
don't function on ToCombinatoricaGraph
objects because the Combinatorica package was developed prior to these
functions, and the structure hasn't yet been adapted to operate
with these
functions.
Our development team is currently working to update the Combinatorica
package so that these functions will be compatible. If you happen to
run
across any other issues, or have any questions come up, please do let
me
know.
In my view, ToCombinatoricaGraph needs to be used with care (and avoided whenever possible). However, there are probably many cases (including the uses given in other answers to the original question) where it makes no difference.
Personally, I would not like to see the Combinatorica package go. It contains many useful functions (if very badly documented).
Related
I have a matrix in Mathematica defined as A = {{"a", 1, 2}, {"b", 3, 4}}.
How do I select row "a" by name??
Everything I try just returns {}.
Thanks
Untested, no Mathematica installation on this computer
Cases[A, {"a",_,_}]
As usual with Mathematica, there are likely to be other ways too. Probably best not to think of A as a matrix either, but as a list of lists. And for future reference: you should really report everything you have tried.
If I want to do the following:
getCH[pts_List] := Module[{t}, t = ConvexHull[pts]; Map[Part[pts, #] &, t]];
or
Map[Function[{x}, Part[#, x]], ConvexHull[#]]&
What are other ways to write this? And how do you normally do for speed and efficiency?
Edit
BTW, I am asking this in a generic way, not for this particular problem. I sometimes feel the lack of brain power to think in terms of functional programming in mma. Just want to expand my arsenal with various other ways to write function compositions and learn the analysis of their complexity/efficiency. So please add similar problems.
I don't know what a ConvexHull is but I'll assume I understood the problem
getCH[pts_]:=pts[[ConvexHull[pts]]]
getCH[pts_]:=Extract[pts, Transpose#{ConvexHull[pts]}]
If you want pts to appear only once for some reason you could always use With, Module or Block. I think most important is to say that I don't see the point in doing that. With, effectively replaces each appearance of pts with the list of points. Seems like an overkill for this but feel free to write
getCH[pts_]:=With[{p=pts},p[[ConvexHull[p]]]]
Module creates a new variable. It's usually slower than With for cases in which your variable doesn't need to be asigned a value. In other words, With is faster for defining constants. Block I think is also faster than Module (slightly) but its dynamic scoping (against Module's lexical scoping) makes it a little bit weirder. Lots of threads about these.
I don't think there's any built-in function that takes a list and a function or symbol, and extracts elements on that list indexed by the result of evaluating the function on that same list, if that's what you were looking for for your "generic" problem. Of course you can create one easily and then use it in the future. I think it's too much for such a simple issue but perhaps its the functional programming you were aiming for
ExtractIndexed[l_List, fun_]:=l[[fun[l]]]
getCH[pts_]:=ExtractIndexed[pts, ConvexHull]
You can initialize variables in a Module like this
Module[{t = ConvexHull[pts]}, Map[Part[pts, #] &, t]]
But in this case, you aren't redefining t, so it is a local constant and you are better off using With.
With[{t = ConvexHull[pts]}, Map[Part[pts, #] &, t]]
Or just
Map[Part[pts, #] &, ConvexHull[pts] ]
Or
Part[pts, #] & /# ConvexHull[pts]
This question is related: Using nested slots. It is not recommended to nest pure functions without naming variables.
You could “invert” your function like so, but I can't guarantee it works.
Function[x,Part[#,x]]& /# ConvexHull[#] & # pts
Perhaps try using Through:
Part ## Through[
List[ Identity, Graphics`Mesh`ConvexHull][{{0, 0}, {1, 0}, {.5, .5}, {1, 1}, {0, 1}}]
]
This one gives a warning (because Part evaluates), but then 'works':
Through[
Part[Identity, Graphics`Mesh`ConvexHull][{{0, 0}, {1, 0}, {.5, .5}, {1, 1}, {0,
1}}]]
I think this is a way around the Part evaluating issue above:
Through[
Unevaluated[
Part[
Identity, Graphics`Mesh`ConvexHull][
{{0, 0}, {1, 0}, {.5, .5}, {1, 1}, {0, 1}}
]]]
In preparing a response to An unexpected behavior of PatternTest in Mathematica I came across an unexpected Mathematica behavior of my own.
Please consider:
test = (Print[##]; False) &;
MatchQ[{1, 2, 3, 4, 5}, {x__?test, y__}]
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
False
Since, as Simon's quote of the documentation concisely states:
In a form such as __?test every element in the sequence matched by __
must yield True when test is applied.
I am wondering why Mathematica is testing the first element of the list four separate times. Of course there are four ways to make up the underlying pattern {x__, y__} and if this were a Condition test then all elements that make up the sequence x would need to be tested, but I don't think that is the case here.
Does the logic not hold that if the first element of the list fails PatternTest then given pattern cannot match?
If it does hold, why is Mathematica not making this simple optimization?
Borrowing an example from yoda's answer, here is another example of what appears to be excess evaluation:
In[1]:= test2 = (Print###; Positive###) &;
MatchQ[{1, 2, 3, 4, -5}, {x__?test2, y__?Negative}]
During evaluation of In[1]:= 1
During evaluation of In[1]:= 1
During evaluation of In[1]:= 2
During evaluation of In[1]:= 1
During evaluation of In[1]:= 2
During evaluation of In[1]:= 3
During evaluation of In[1]:= 1
During evaluation of In[1]:= 2
During evaluation of In[1]:= 3
During evaluation of In[1]:= 4
Out[2]= True
I admit to having never explored this aspect of pattern matching before, and I am disturbed by the seeming inefficiency of this. Is this really as bad as it looks, or is some kind of automatic caching taking place? Print appears to indicate against that.
Is there a more efficient pattern based way to write this?
Is this level of redundancy required for correct pattern matching behavior, and why?
I made a false assertion in haste, but I leave it because good answers below address it. Please ignore it in future answers.
It is easy to demonstrate that a similar optimization is made in other
cases:
MatchQ[{-1, 2, 3, 4, 5}, {__?Positive, y__?test}]
(Nothing is printed.)
False
Here Mathematica correctly never even tests any elements for y.
I think everyone is forgetting about the side effects that are possible in test functions. Here is what I think is happening: as Mr.Wizard and others mentioned, there are several ways the pattern may match, just combinatorially. For each combination of {x} and {y}, the x pattern is first tested. By the way, there is no point in defining functions of multiple arguments (##), since, as #Simon explained, the test function is applied separately to each element in the sequence. And this also explains why only the first element (-1) is printed: as soon as the first non-matching element is found, the pattern-matcher stops and goes on to test the next available combination.
Here is a more illustrative example:
In[20]:=
MatchQ[{-1,2,3,4,5},{_,x__?(Function[Print[#];Positive[#]])}]
During evaluation of In[20]:= 2
During evaluation of In[20]:= 3
During evaluation of In[20]:= 4
During evaluation of In[20]:= 5
Out[20]= True
Now it prints all of them, since the function is applied to them one by one, as it has to in this case.
Now to the crux of the matter. Here I set up a test function with a side effect, which decides to change its mind after it tests the very first element:
Module[{flag = False},
ClearAll[test3];
test3[x_] :=
With[{fl = flag},
If[! flag, flag = True];
Print[x];
fl
]
];
The first combination (which is {-1},{2,3,4,5} will be rejected since the function gives False at first. The second one ({-1,2},{3,4,5}) will be accepted however. And this is exactly what we observe:
In[22]:=
MatchQ[{-1,2,3,4,5},{x__?test3,y__}]
During evaluation of In[22]:= -1
During evaluation of In[22]:= -1
During evaluation of In[22]:= 2
Out[22]= True
The printing stopped as soon as the pattern-matcher found a match.
Now, from here it must be obvious that the optimization mentioned in the question and some other answers is not generally possible, since pattern-matcher has no control over the mutable state possibly present in the testing functions.
When thinking about the pattern-matching, we usually view it as a process separate from evaluation, which is largely true, since the pattern-matcher is a built-in component of the system which, once patterns and expressions evaluate, takes over and largely bypasses the main evaluation loop. There are however notable exceptions, which make the pattern-matching more powerful at the price of getting it entangled with the evaluator. These include the uses of Condition and PatternTest, since these two are the "entry points" of the main evaluation process into the otherwise isolated from it pattern-matching process. Once the pattern-matcher hits one of these, it invokes the main evaluator on the condition to be tested, and anything is possible then. Which brings me once again to the observation that the pattern-matcher is most efficient when tests using PatternTest and Condition are absent, and the patterns are completely syntactic - in that case, it can optimize.
Just a quick guess here, but {__?Positive, y__?test} must match the beginning of the list through to the end. So, {-1, 2, 3, 4, 5} fails on the first element, hence no print out. Try replacing Positive with ((Print[##];Positive[#])&), and you'll see it behaves in the same manner as the first pattern.
I think that your premise that Mathematica optimizes the pattern test is incorrect. Consider the pattern {x__, y__}. As you rightly say, there are 4 ways in which {1,2,3,4,5} can fit into this pattern. If you now add a pattern test to this with ?test, MatchQ should return True if any of the 4 ways match the pattern. So it must necessarily test all possible options until a match has been found. So the optimization is only when there are positives, and not when the pattern fails.
Here's a modification of your example with Positive, that shows you that Mathematica does not make the optimization as you claim:
test2 = (Print###; Positive###) &;
MatchQ[{-1, 2, 3, 4, 5}, {x__?test2, y__}]
It prints it 4 times! It terminates correctly with one print if the first element is indeed positive (thereby not having to test the rest). The test for the second element is applied only if the first is True, which is why the test for y was not applied in yours. Here's a different example:
test3 = (Print###; Negative###) &;
MatchQ[{1, 2, 3, 4, -5}, {x__?test2, y__?test3}]
I agree with your logic that if the first fails, then given that every element ought to match, all subsequent possibilities will also fail. My guess is that Mathematica is not that smart yet, and it is simpler to implement identical behaviour for any of _, __, or ___, rather than a different one for each. Implementing a different behaviour depending on whether you use __ or ___ will mask the true nature of the test and make debugging harder.
ok I'll have a go.
MatchQ[{1, 2, 3, 4, 5}, {x__?test, y__}]//Trace
shows that slot sequence is redundant because only one element, in this case the first one in the sequence, is tested. e.g.
MatchQ[{1, 2, 3, 4, 5}, {_, x__?test, y__}] // Trace
Now prints 3 twos. If you change the first pattern to BlankSequence more permutations are generated and some of these have different first elements
MatchQ[{1, 2, 3, 4, 5}, {__, x__?test, y__}] // Trace
In your final example
MatchQ[{-1, 2, 3, 4, 5}, {__?Positive, y__?test}]
the first element always fails the test. If you change this to
MatchQ[{1, 2, -3, 4, 5}, {__?Positive, y__?test}]
you will see something more along the lines of what you expected.
Given some list
numbers = {2,3,5,7,11,13};
How do I translate this to
translatedNumbers = {{1,2},{2,3},{3,5},{4,7},{5,11},{6,13}}
concisely?
I am aware of how to do this using the procedural style of programming as follows:
Module[{lst = {}, numbers = {2, 3, 5, 7, 11, 13}},
Do[AppendTo[lst, {i, numbers[[i]]}], {i, 1, Length#numbers}]; lst]
But such is fairly verbose for what seems to me to be a simple operation. For example the haskell equivalent of this is
numbers = zip [1..] [2,3,5,7,11,13]
I can't help but think that there is a more concise way of "indexing" a list of numbers in Mathematica.
Potential Answer
Apparently I'm not allowed to answer my own question after having had a lightbulb go off unless I have 100 "rep". So I'll just put my answer here. Let me know if I should do anything differently then I have done.
Well I'm feeling a little silly now after having asked this. For if I treat mathematica lists as a matrix I'm able to transpose them. Thus an answer (perhaps not the best) to my question is as follows:
Transpose[{Range#6, {2, 3, 5, 7, 11, 13}}]
Edited to work for arbitrary input lists, I think something like:
With[{lst={2, 3, 5, 7, 11, 13}},Transpose[{Range#Length#lst,lst}]]
will work. Could I do any better?
One thing to consider is if the transformation will not unpack the data. This is important for large data sets.
On["Packing"]
numbers = Developer`ToPackedArray#{2, 3, 5, 7, 11, 13};
This will unpack
MapIndexed[{First[#2], #1} &, numbers]
this will not
Transpose[{Range[Length[#]], #}] &[numbers]
Off["Packing"]
I would use MapIndexed instead
MapIndexed[{First[#2], #1} &, numbers]
Well, my „solution“ is perhaps not as smart as the solution from cobbal, but when I test it with long arrays, it is faster (factor of 5!).
I am simply using:
newList = Transpose[{Range[Length[numbers]], numbers}]
AHH! ruebenko posted a similar answer during I have written my post. Sorry for this almost superfluous post. Well, perhaps it is not so superfluous. I have tested my solution with and without packing, and it works at fastest without packing.
I'm trying to visualize some graphs and am looking for alternate ways to style the edges. I'm not entirely sure if changing the edge style would improve the representation, but even so I'm curious.
For example:
GraphPlot3D[{2 -> 3, 2 -> 4, 2 -> 5, 3 -> 4, 3 -> 5, 4 -> 5},
EdgeRenderingFunction -> Dotted,
]
Doesn't work. Something like EdgeRenderingFunction -> (Cylinder[#1, 0.05] &), doesn't work well at all because the number of edges I am working with makes this incredible slow and doesn't look as good as the default line anyway.
Is there a way to systematically see what options Mathematica will accept? Any suggestions as to
Systematic way is look through the list of options in Help. In GraphPlot3D's help, in PlotStyle section, there are examples how to make dotted edges.
Additionally, if you do GraphPlot3D[{2 -> 3}]//FullForm you will see that edges are drawn with Line primitive, so look in Line help pages under PlotStyle for more supported properties. So for instance, PlotStyle->Thick works for GraphPlot3D even though it's not mentioned on GraphPlot3D's help page.
If you want to see undocumented options, you could do Options[GraphPlot3D], Information[GraphPlot3D], and if you really want to dig into undocumented stuff, look at Simon's comment in this question
One example:
GraphPlot3D[{2 -> 3, 2 -> 4, 2 -> 5, 3 -> 4, 3 -> 5, 4 -> 5},
VertexLabeling -> True,
EdgeRenderingFunction -> ({Blue, Dotted, Thick,
Arrowheads[{0.00, .03}], Arrow[#1, .05]} &)]
I'm not sure if this is the type of edge modification you want.