File: JuliaInterface.m2

package info (click to toggle)
macaulay2 1.24.11%2Bds-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 171,648 kB
  • sloc: cpp: 107,850; ansic: 16,307; javascript: 4,188; makefile: 3,947; lisp: 682; yacc: 604; sh: 476; xml: 177; perl: 114; lex: 65; python: 33
file content (224 lines) | stat: -rw-r--r-- 6,639 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
newPackage(
        "JuliaInterface",
        Version => "0.1", 
        Date => "July 10, 2018",
        Authors => {
	    {Name => "Tim Duff", 
	     Email => "tduff3@gatech.edu", 
             HomePage => "http://people.math.gatech.edu/~tduff3/"}
	      },
        Headline => "Interfacing Macaulay2 with Julia Homotopy Continuation",
	PackageImports => {},
	PackageExports => {"NumericalAlgebraicGeometry","MonodromySolver"},
        DebuggingMode => true
        )


export{"JuliaProcess", "solveJulia", "restartJulia","importJulia","writeJuliaFile",
    -- exported options below
    "IncludeTemplate","ImportList","WithImports","OnlyReal","OnlyFinite","TemplateText"
    }


----------------------------------------
---GLOBAL VARIABLES / INTERFACE SETUP
----------------------------------------

importJulia = (importList,f) -> f<<concatenate apply(importList,pkg->pkg | "\n")

juliaBinary="/home/tim/julia-d55cadc350/bin/julia"
JuliaProcess=openInOut("!" |juliaBinary)
noProcessError="JuliaProcess not currently open"
importJulia({"using HomotopyContinuation","import DynamicPolynomials: PolyVar"},JuliaProcess)

---------------------
--- PACKAGE IMPORTS
---------------------



--------------
---UNEXPORTED-
--------------

numberRegex="([0-9]|| |-|\\.|e|i|m|\\+|,)*" -- potentially useful

parsePolynomial = p -> replace("ii","im",replace("p[0-9]+","0",toExternalString p))

-- the implementation here may need to change as the output of HomotopyContinuation evolves in future versions
parseSolutions = method(Options=>{OnlyReal=>false})
parseSolutions String := o -> out -> (
    outLines:=select("\\*.*",out);
    M:=new MutableList from {};
    stride:=12;
    numSols:=sub((length outLines)/stride,ZZ);
    for i from 0 to numSols-1 do (
    	s:=first select("\\[([0-9]|| |-|\\.|e|i|m|\\+|,)*\\]",outLines#(1+i*stride));
    	M#i=point{apply(separate(",",replace("\\[|\\]","",replace("im","*ii",s))),x->value x)};
	if match("nonsingular",outLines#(2+i*stride)) then M#i.SolutionStatus = Regular else M#i.SolutionStatus = Singular;
	);
    toList M
    )

--todo: write exported wrapper for first two signatures
writeSys = method(Options=>{IncludeTemplate=>false,WithImports=>false,
	                    ImportList=>{"using HomotopyContinuation",
				"import DynamicPolynomials: PolyVar"},
			    TemplateText=>false})
writeSys (PolySystem, File) := o -> (P,f) -> (
    R:=ring P;
    varString:=apply(gens R,g->(toString g));
    varCommas:=(P.NumberOfVariables-1):", ";
    eqnCommas:=(P.NumberOfPolys-1):", ";
    if o.WithImports then importJulia(o.ImportList,f);
    if o.TemplateText then f << "# We declare the variables of our polynomial system\n";
    f << concatenate(mingle(varString,varCommas))| " = " | "[PolyVar{true}(i) for i in [" | concatenate mingle(apply(varString,g-> "\"" | g | "\""),varCommas)|"]];\n";
    if o.TemplateText then f << "# We define the polynomial system in which solutions we are interested.\n";
    f <<"F = [" | concatenate mingle(
	apply(equations P,e->parsePolynomial e),eqnCommas)| "];\n";
    if o.TemplateText then (
	f<<"# Now we can solve the system\n";
	);
    )
writeSys (PolySystem, String) :=o -> (P,filename) -> (
    f := openOut filename;
    writeSys(P,f);
    close f;
    )
writeSys PolySystem := o -> P -> (
    if not isOpen JuliaProcess then error("JuliaProcess not open");
    writeSys(P,JuliaProcess)
    )


writeJuliaFile = method(Options=>{})
writeJuliaFile (PolySystem,String) := o -> (P,filename) -> (
    f := openOut(filename|".jl");
    f << read openIn "./jlHeader.jl";
    writeSys(P,f,TemplateText=>true);
    f << "result = solve(F)\n";
    f << read openIn"./jlTail.jl";
    close f;
    )    
    

-------------------------------------
--- EXPORTED FUNCTIONS AND METHODS---
-------------------------------------

restartJulia = () -> (
    if (isOpen JuliaProcess) then close JuliaProcess;
    JuliaProcess=openInOut("!" |juliaBinary);
    --needsPackage("JuliaInterface",Reload=>true)
    )


TEST ///
JuliaProcess
close JuliaProcess
assert(not isOpen JuliaProcess)
restartJulia()
assert(isOpen JuliaProcess)
///

-- todo: replace arbitrary variable name "f" for julia system
-- todo: remove bottom two lines from print
-- todo: parse other solutions info
-- todo: finite solutions only
-- todo: check all variables are used
solveJulia = method(Options=>{})
solveJulia PolySystem := o -> P -> (
    if not isOpen JuliaProcess then error(noProcessError);
--    print "Wait for system to be solved:\n";
    writeSys P;
    JuliaProcess<<flush;
    x:=read JuliaProcess;
    JuliaProcess<<"result=solve(F);\n";
--    JuliaProcess<<"x=[s.solution for s in sols];\n";
    JuliaProcess<<"show(IOContext(STDOUT, :compact=>false),[s.solution for s in result])\n";
    finished:="done!!!x";
    JuliaProcess<<"print(\"" | finished |"\")\n";
    out:="";
    cur:="";
    while not match(finished,cur) do (
	JuliaProcess<<flush;
	cur = read JuliaProcess;
    	out = out | cur;	
	);
    endIndex:=regex("Array\\{Complex",out);
    parseSolutions substring(out,0,first first endIndex)
    )

------------------------------------------
------------------------------------------
-- Documentation
------------------------------------------
------------------------------------------

beginDocumentation()


doc ///
    Key
        solveJulia
        (solveJulia, PolySystem)
    Headline
        interface to "solve" function
    Usage
        sols = solve P
        sols = solve L
    Inputs
        P:PolySystem
        L:List
	    containing elements from a common @TO Ring @
    Outputs
        sols:List
            each element of class @TO AbstractPoint @
    Description
        Text
            This is the basic interface to the @HREF("https://www.juliahomotopycontinuation.org/HomotopyContinuation.jl/latest/solving.html","\"solve function")@.
        Example
	    R=CC[x,y]
            importJulia({"using HomotopyContinuation","import DynamicPolynomials: PolyVar"},JuliaProcess)
	    f= x^2+y
	    g=y^2-pi*ii
	    sols=solveJulia polySystem {f,g}
///



end



uninstallPackage packageName
close JuliaProcess
restart
packageName = "JuliaInterface"
path=append(path,currentDirectory())
installPackage("JuliaInterface",MakeDocumentation=>false)

R=CC[x,y]
f= x^2+y
g=y^2-pi*ii
P= polySystem {f,g}
writeJuliaFile(P,"test")
sols=solveJulia P
peek first sols




writeSys(P,"test.jl",WithImports=>true)--option not working?

needs "./ExampleSystems/jointsR6.m2"
Q=polySystem jointsR6(CC_53)
sols=solveJulia Q;
ourSols = solveSystem Q
apply(
    sortSolutions ourSols, 
    sortSolutions sols,
    (a,b) -> areEqual(a,b)
    )
#sols--too many?
#ourSols