I am trying to solve the following implementation problem in Mathematica 7.0 for some days now and I do not understand exactly what is happening so I hope someone can give me some hints.
I have 3 functions that I implemented in Mathematica in a source file with extension *.nb.
They are working okay to all the examples. Now I want to put these functions into 3 different packages. So I created three different packages with extension .*m in which I put all the desired Mathematica function.
An example in the "stereographic.m" package which contain the code:
BeginPackage["stereographic`"]
stereographic::usage="The package stereographic...."
formEqs::usage="The function formEqs[complexBivPolyEqn..."
makePoly::usage="The function makePoly[algebraicEqn] ..."
getFixPolys::usage="The function..."
milnorFibration::usage="The function..."
Begin["Private`"]
Share[];
formEqs[complex_,{m_,n_}]:=Block[{complexnew,complexnew1, realeq, imageq, expreal,
expimag, polyrealF, polyimagF,s,t,u,v,a,b,c,epsilon,x,y,z},
complexnew:=complex/.{m->s+I*t,n->u+I*v};
complexnew1:=complexnew/.{s->(2 a epsilon)/(1+a^2+b^2+c^2),t->(2 b
epsilon)/(1+a^2+b^2+c^2),u->(2 c epsilon)/(1+a^2+b^2+c^2),v->(-
epsilon+a^2 epsilon+b^2 epsilon+c^2
epsilon)/(1+a^2+b^2+c^2)};
realeq:=ComplexExpand[Re[complexnew1]];
imageq:=ComplexExpand[Im[complexnew1]];
expreal:=makePoly[realeq];
expimag:=makePoly[imageq];
polyrealF:=expreal/.{a->x,b->y,c->z};
polyimagF:=expimag/.{a->x,b->y,c->z};
{polyrealF,polyimagF}
]
End[]
EndPackage[]
Now to test the function I load the package
Needs["stereographic`"]
everything is okay. But when I test the function for example with
formEqs[x^2-y^2,{x,y}]
I get the following ouput:
{Private`epsilon^2 + 2 Private`x^2 Private`epsilon^2 +
Private`x^4 Private`epsilon^2 -
6 Private`y^2 Private`epsilon^2 +
2 Private`x^2 Private`y^2 Private`epsilon^2 +
Private`y^4 Private`epsilon^2 -
6 Private`z^2 Private`epsilon^2 +
2 Private`x^2 Private`z^2 Private`epsilon^2 +
2 Private`y^2 Private`z^2 Private`epsilon^2 +
Private`z^4 Private`epsilon^2,
8 Private`x Private`y Private`epsilon^2 +
4 Private`z Private`epsilon^2 -
4 Private`x^2 Private`z Private`epsilon^2 -
4 Private`y^2 Private`z Private`epsilon^2 -
4 Private`z^3 Private`epsilon^2}
Of course I do not understand why Private` appears in front of any local variable which I returned in the final result. I would want not to have this Private` in the computed output.
Any idea or better explanations which could indicate me why this happens?
Thank you very much for your help.
Best wishes,
madalina
Your problem is a common one when you are returning symbolic functions from a package, and when this happens to me, I view it as if I've done something wrong in writing the package. While prefixing all such symbols with Global will "fix" the problem, it defeats some of the purpose of a package: implementation hiding. Also, since it pollutes the global namespace with your symbols, you must be careful in how you run your code which further defeats the purpose of a package. Your package should not care what the global environment is like. If it needs anything, it can load it itself either in BeginPackage or using Needs within the private portion of the package.
Instead, you can do what functions like Plot do, accept a Symbol parameter, as follows:
(*Note: if z is not a symbol this won't work, i.e. if it is Set to some value.*)
In[1] := f[x_Symbol] := x^2
In[2] := f[z]
Out[2] := z^2
Internally, symbolic variables are referenced like normal, but your function will now return a symbolic expression using whatever global symbols you've chosen to use. This also decouples your choice of variable names with the implementation details of your function.
From the discussion here, it looks like assigning the symbols inside the package to the global context will make them be output without the private context prefix.
That is, any symbols that might form part of the output could be declared with a Global` prefix, as in this example:
BeginPackage["PackageContext`"];
Rule1::usage = "Rule1 is a test exported rule.";
Begin["`Private`"];
Rule1 = Cos[Global`x_]^2 + Sin[Global`x_]^2 :> Global`x;
End[];
EndPackage[];
In your package, it might look something like this:
formEqs[complex_,{m_,n_}]:=Block[{complexnew,complexnew1, realeq, imageq,
expreal,expimag, polyrealF, polyimagF,s,t,u,v,a,b,c,
Global`epsilon,Global`x,Global`y,Global`z},
complexnew:=complex/.{m->s+I*t,n->u+I*v};
complexnew1:=complexnew/.{s->(2 a Global`epsilon)/(1+a^2+b^2+c^2),t->(2 b
Global`epsilon)/(1+a^2+b^2+c^2),u->(2 c Global`epsilon)/(1+a^2+b^2+c^2),v->(-
Global`epsilon+a^2 Global`epsilon+b^2 Global`epsilon+c^2
Global`epsilon)/(1+a^2+b^2+c^2)};
realeq:=ComplexExpand[Re[complexnew1]];
imageq:=ComplexExpand[Im[complexnew1]];
expreal:=makePoly[realeq];
expimag:=makePoly[imageq];
polyrealF:=expreal/.{a->Global`x,b->Global`y,c->Global`z};
polyimagF:=expimag/.{a->Global`x,b->Global`y,c->Global`z};
edit: the Global variables need to be given the Global` prefix wherever they occur, as above
Try changing Begin["Private`"] to Begin["`Private`"].
You could use formal symbols instead of ordinary symbols to avoid your problem.
At the same time, using of formal symbols is more convenient way to output general expressions involving formal parameters. They have no values and values for them cannot be unintentionally set since they are Protected.
You can use "Special characters" palette to inter formal symbols.
Related
I do not see where s is defined. Guru will not tell me. All I get is "no object for identifier" but it knows about the k right beside it. Here is a snippet that is typical of the linked code:
func getIndexAndRemainder(k uint64) (uint64, uint64) {
return k / s, k % s
}
The one letter variable name definitely makes it harder to grep around for. I have looked for the usual suspects: var s uint64, s := ..., and nothing. Clearly it needs to be a global value defined somewhere.
This leaves me with two questions:
Where is s coming from?
How would I find it without asking here?
EDIT:
For others who stumble on this.
Guru failed me because I did not checkout the source for the package under a proper Go workspace by placing the git clone under /some/path/src and setting the GOPATH to /some/path. So while I thought GOPATH=. guru definition s would work, the GOPATH was ignored. guru could find k because it is in the file but it did not know how to look in other files.
My grep failed cause const uses a simple = not a :=. I will remember this when grepping in the future.
It is defined in go-datastructures/bitarray/block.go:
// s denotes the size of any element in the block array.
// For a block of uint64, s will be equal to 64
// For a block of uint32, s will be equal to 32
// and so on...
const s = uint64(unsafe.Sizeof(block(0)) * 8)
As the variable s was not defined in the function, and it was not prefixed by a package name or alias, it had to be a global (variable or constant) of the bitarray package.
Once that was known, I went through every file in the folder go-datastructures/bitarray that was not suffixed with _test and I looked for a top-level declaration for s.
It's defined in go-datastructures/bitarray/block.go, line #33:
const s = uint64(unsafe.Sizeof(block(0)) * 8)
"Modern" IDEs with Go support usually have the ability to go to the definition of a symbol / identifier your cursor is at or what you click on. For example in Atom with the Go-plus plugin you can go to the definition by holding down the CTRL key while clicking.
These IDEs use the godef open source tool to find the definition source file and line, you may also use it directly. You can find the godef documentation here: https://godoc.org/github.com/rogpeppe/godef
Another tool, guru is also capable of tracking the definition of it. Both guru and godef works in Atom, and were able to jump to block.go, to the definition of s. But it's much easier to use an "armored" IDE and just do a simple click.
Also note that the success of using grep and patterns is limited, as variable and constant declarations can be grouped, and the following are also valid declarations:
var (
longer = 3
s = uint64(3)
)
Or:
var (
s = someExpression
longer = 3
)
Or:
const (
p = uint64(iota)
s
x
)
For a Ruby project I need an OpenCPU server to process some statistics by R packages. OpenCPU has an JSON REST API, so with Ruby I can easily hook into that to communicate with R. So far, so good.
One of those packages has a strange (at least to me) syntax.
add <- function(.argument1, .argument2) {
return(.argument1 + .argument2)
}
So this is just an example, not the actual function. The part I found weird are those points in front of parameters. When I suggested to remove those points, the developer of the package said that it was meant to hide the variables from the overview of variables in IDE (R-Studio). It sounds to me like he wanted to make the parameters, what we call it, private, or at least to scope it somehow. I searched the internets to explain this feature of R, but found nothing.
The actual problem is: we use Ruby, Ruby translates data into JSON and sends it to OpenCPU. OpenCPU looks up for the right package/function, passes arguments and executes it. Then it returns to OpenCPU which makes a JSON response. Ruby's >1.9 Hash syntax that we prefer to work with looks like:
{ argument1: 4, argument2: 3 }.to_json
# => { "argument1": 4, "argument2": 3 }
instead of older forced by the package arguments:
{ ".argument1" => 4, ".argument2" => 3 }.to_json
# => { ".argument1": 4, ".argument2": 3 }
So in desperate search for an argument to convince the R-developer not to use the dots, my question was still unanswered: does this point in front of the parameters have a real functionality in R or is it just a hack to exclude the variables from the IDE?
I think you will find that the reason comes from the default behaviour of the ls function in R which does not return objects beginning with a point. This can be modified by the all.names parameter:
all.names a logical value. If TRUE, all object names are returned. If FALSE, names which begin with a . are omitted.
It is quite common for more technical functions or variables to be "hidden" in this way, e.g. .Machine, .Options, .Fortran, .dynLibs
What is the best way to generate a name for some temporary context which is guaranteed to be unique (context with this name must not exist in the system)?
The following expression will generate a context name that is guaranteed not to conflict with any loaded context:
First#Contexts[] //.
c_ /; MemberQ[Contexts[], c] :>
"Context"~~ToString[RandomInteger[1000000]]~~"`"
It makes no attempt to account for contexts that are not yet loaded. As written, this expression could be used up to 1,000,000 times before running out of names. Adjust the fixed string ("Context") and name count (1000000) to suit your taste.
Update
As #Leonid points out in a comment, empty contexts will not be listed in Contexts[]. Therefore, it is strictly speaking possible that this expression could return the name of an existing empty context.
UUIDs
For all practical purposes, generating a name from a number randomly selected from a large enough range would work, e.g.
"Context"~~ToString[RandomInteger[2^128]]~~"`"
In a similar vein, one could use a UUID. UUIDs are routinely used as identifiers that are phenomenally likely to be unique across all network nodes as well:
Needs["JLink`"]
LoadJavaClass["java.util.UUID"]
"Context"~~
StringReplace[JavaBlock#java`util`UUID`randomUUID[]#toString[], "-" -> ""]~~
"`"
I can suggest a function I used here:
Clear[unique];
unique[sym_] :=
ToExpression[
ToString[Unique[sym]] <>
StringReplace[StringJoin[ToString /# Date[]], "." :> ""]];
You can replace the ToExpression by StringJoin[...,"`"] to tailor it to your needs.
Another option would be to look at all starting contexts (before the first backquote), find their string length and then generate a string (maybe random, but that isn't necessary) that is at least one character longer than the others. This is guaranteed to be unique, and there isn't even a theoretical possibility of a collision as in some of the other solutions.
sl = (StringSplit[#, "`"][[1]] & /# Contexts[] // StringLength // Max )
Out[349]= 30
In[353]:= "c" ~~ ToString[10^sl] ~~ "`"
Out[353]= "c1000000000000000000000000000000`"
A disadvantage of this method would be that the context names get longer after each repeated application of this method. ;-) If that's a problem we could create a unique name based on the set of longest context names using Cantor's diagonal procedure.
Is Unique perhaps what you're looking for?
This is really an example illustrating Alexey's response to Sjoerd's answer/question. From a fresh kernel on my machine, the following code
Begin["myContext3`"];
Unique["myContext"]
Yields "myContext3". Thus, clearly, Unique (the first thing I thought of) does not work.
Incidentally, I would have just added a comment to Sjoerd's response, but I don't know how to include the accent symbol used to denote a context inline. Does anyone here know how to do this?
If you take a look at the Combinatorica package in Mathematica8 in (mathematicapath)/AddOns/LegacyPackages/DiscreteMath/Combinatorica.m you will find the definitions of functions. What I'm interested to know is how Mathematica knows how to format the usage messages. Something tells me that I'm not looking at the right file. In any case, lets try the following:
Cofactor::usage = "Cofactor[m, {i, j}] calculates the (i, j)th cofactor of matrix m."
This line is the 682 line in the file mentioned above. Now if we run it in a mathematica notebook and we use ?Cofactor we will see the exact same message. But if we get the package then the message is formatted. Here is a screenshot:
Notice how the m, i and j inside the function changed and a double arrow was added to the message. I think the arrow was added to the message because there exists documentation for it. Can someone explain this behavior?
EDIT:
This is a screenshot of my notebook file that autosaves to an m file.
As you can see, the L and M are in italic times new roman. Now I will load the package and see the usage.
So far so good. Now lets look at the Documentation center. I will look for the function LineDistance.
As you can see, it shows a weird message. In this case we only want to display the message without any styles. I still can't figure out how the Combinatorica package does this.
I followed this to make the index so that the doc center can display the summary. The summary is essentially the usage display. Let me know if I need to be more specific.
OK, here's the explanation.
Digging in the Combinatorica source reveals this:
(* get formatted Combinatorica messages, except for special cases *)
If[FileType[ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"]]===File,
Select[FindList[ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"],"Combinatorica`"],
StringMatchQ[#,StartOfString~~"Combinatorica`*"]&&
!StringMatchQ[#,"Combinatorica`"~~("EdgeColor"|"Path"|"Thin"|"Thick"|"Star"|"RandomInteger")~~__]&]//ToExpression;
]
It is loading messages from ToFileName[{System`Private`$MessagesDir,$Language},"Usage.m"], which on my machine is SystemFiles\Kernel\TextResources\English\Usage.m. This is why all usage messages are created conditionally in Combinatorica.m (only if they don't exist yet). If you look in Usage.m you'll see it has all the ugly boxes stuff that #ragfield mentioned.
I guess the simplest way to have formatted messages is to edit them in the front end in a notebook, and create an auto-save package. This way you can use all the front end's formatting tools, and won't need to deal with boxes.
I will answer on how the link in the Message is generated. Tracing Message printing shows a call to undocumented Documentation`CreateMessageLink function which returns the URL to the corresponding Documentation page if this page exists:
Trace[Information[Sin], Documentation`CreateMessageLink]
In[32]:= Documentation`CreateMessageLink["System", "Sin", "argx", "English"]
Out[32]= "paclet:ref/message/General/argx"
In some cases we can also see calls to Internal`MessageButtonHandler which further calls Documentation`CreateMessageLink:
Trace[Message[Sin::argx, 1, 1],
Internal`MessageButtonHandler | Documentation`CreateMessageLink,
TraceInternal -> True]
The way to embed style information in a String expression is to use linear syntax. For a box expression such as:
StyleBox["foo", FontSlant->Italic]
You can embed this inside of a String by adding \* to the front of it and escaping any special characters such as quotes:
"blah \*StyleBox[\"foo\", FontSlant->Italic] blah"
This should work for any box expression, no matter how complicated:
"blah \*RowBox[{SubsuperscriptBox[\"\[Integral]\",\"0\",\"1\"],RowBox[{FractionBox[\"1\",RowBox[{\"x\",\"+\",\"1\"}]],RowBox[{\"\[DifferentialD]\",\"x\"}]}]}] blah"
I am currently working on rewriting your ApplicationMaker for newer Mathematica-Versions with added functionalities and came to the exact same question here.
My answer is simple: Mathematica dont allowes you to use formated summaries for your symbols (or even build in symbols), so we have to unformate the usage-strings for the summaries. The usagestring itself can still have formatting, but one needs to have a function that removes all the formatingboxes from a string.
i have a solution that uses the UndocumentedTestFEParserPacket as described by John Fultz! in this question.
This funny named Tool parses a String Input into the real unchanged Mathematica BoxForm.
This is my example code:
str0 = Sum::usage
str1=StringJoin[ToString[StringReplace[#, "\\\"" -> "\""]]& /#
(Riffle[MathLink`CallFrontEnd[
FrontEnd`UndocumentedTestFEParserPacket[str0, True]]〚1〛
//. RowBox[{seq___}] :> seq /. BoxData -> List, " "]
/. SubscriptBox[a_, b_] :> a<>"_"<>b
/. Except[List, _Symbol][args__] :> Sequence##Riffle[{args}, " "])];
str2 = Fold[StringReplace, str1,
{((WhitespaceCharacter...)~~br:("["|"("|"=") ~~ (WhitespaceCharacter ...)) :> br,
((WhitespaceCharacter ...) ~~ br:("]"|"}"|","|".")) :> br,
(br:("{") ~~ (WhitespaceCharacter ...)) :> br,
". " ~~ Except[EndOfString] -> ". \n"}]
and this is how the Output looks like (first Output formatted fancy str0, second simple flat str2)
Code Explanation:
str0 is the formatted usagestring with all the StyleBoxes and other formatting boxes.
str1:
UndocumentedTestFEParserPacket[str0, True] gives Boxes and strips off all StyleBoxes, thats because the second argument is True.
First Replacement removes all RowBoxes. The outer BoxForm changed to a List of strings. Whitespaces are inserted between these strings the by Riffle. SubscriptBox gets a special treatment. The last line replaces every remaining FormatBox such as UnderoverscriptBox and it does that by adding Whitespaces between the arguments, and returning the arguments as a flat Sequence.
ToString[StringReplace[#, "\\\"" -> "\""]]& /#
was added to include more cases such as StringReplace::usage. This cases include string representations "" with Styles inside of a the usage-string, when "args" has to be given as strings.
str2:
In this block of code i only remove unwanted WhitespaceCharacter from the string str1 and i add linebreaks "/n" after the ".", because they got lost during the Parsing. There are 3 different cases where WhitespaceCharacter can be removed.
1 removing left-and right sided WithespaceCharacter from a character like "[".
2. and 3. removing WithespaceCharacter from left(2) or right(3) side.
Summary
Istead of summary-> mySymbol::usage, use summary -> unformatString[mySymbol::usage] with unformatString being an appropriate function that performes the unformating like descriped above.
Alternatively you can define another usage message manually like
f::usage = "fancy string with formating";
f::usage2 = "flat string without formating";
than use summary -> mySymbol::usage2
I have a common issue when working with code in the IDE:
string.Concat("foo", "bar");
and I need to change it to:
string.Concat("bar", "foo");
Often I have several of these that need to be swapped at once. I would like to avoid all the typing. Is there a way to automate this? Either a shortcut or some sort of macro would be great if I knew where to start.
Edit: changed to string.Concat to show that you can't always modify the method signature. I am only looking to change the order of the params in the method call, and nothing else.
<Ctrl> + <Shift> + <t> will transpose two words, so it would work in your case. Unfortunately I don't see this working (without multiple presses) for functions with larger parameter lists...
I had a lot of code with this function:
SetInt(comboBox1.Value + 1, "paramName", ...
SetInt(comboBoxOther.Value, "paramName", ...
And I needed to swap only the first two parameters;
I ended up using some text editor with regular expression management (like Scite), and using this one saved me hours:
Find: SetInt(\([.a-z0-9]+[ + 1]*\), \("[a-z0-9]+"\)
Replace: SetInt(\2, \1