Cách sử dụng Mathematica từ Python
Tôi đã sử dụng các dòng mã sau để tạo hình học 3D ( ref ). Đầu vào edges, vd, vlvà ewđến từ Python trong các định dạng sau
edges = [(1,2), (1,3), (1,4), (2,5), (2,6), (5,6), (3,4), (3,7), (6,7), (7,8), (2,9)];
vl = [1,2,3,4,5,6,7,8,9]
ew = {(1, 2) : 49.6, (1,3): 74.4, (1, 4) : 49.6, (2,5): 37.2, (2, 6) : 74.4, (5, 6): 49.6,
(3, 4) : 37.2, (3, 7):24.8, (6, 7) : 62, (7, 8) : 37.2, (2, 9) : 24.8}
vd = {1:[75., 25., 0], 2:[115., 45., 0], 3:[10., 5., 0], 4:[45., 0, 0],
5:[90., 60., 0], 6:[45., 55., 0], 7:[0, 25., 0], 8:[10., 50., 0], 9:[115., 25.,0]};
Tôi chuyển đổi thủ công ở trên sang các định dạng đầu vào được sử dụng trong Mathematica. Tôi muốn biết cách tránh chuyển đổi thủ công này và tích hợp trực tiếp và chạy mã Mathematica từ Python.
edges = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 5, 2 <-> 6, 5 <-> 6,
3 <-> 4, 3 <-> 7, 6 <-> 7, 7 <-> 8, 2 <-> 9};
vd = {{75., 25., 0}, {115., 45., 0}, {10., 5., 0}, {45., 0, 0},
{90., 60., 0}, {45., 55., 0}, {0, 25., 0}, {10., 50., 0}, {115., 25.,0}};
vl = Range[Length@vd];
vcoords = MapIndexed[#2[[1]] -> # &, vd];
ew = {1 \[UndirectedEdge] 2 -> 49.6, 1 \[UndirectedEdge] 3 -> 74.4,
1 \[UndirectedEdge] 4 -> 49.6, 2 \[UndirectedEdge] 5 -> 37.2,
2 \[UndirectedEdge] 6 -> 74.4, 5 \[UndirectedEdge] 6 -> 49.6,
3 \[UndirectedEdge] 4 -> 37.2, 3 \[UndirectedEdge] 7 -> 24.8,
6 \[UndirectedEdge] 7 -> 62, 7 \[UndirectedEdge] 8 -> 37.2,
2 \[UndirectedEdge] 9 -> 24.8}
g3d = Graph3D[vl, edges, VertexCoordinates -> vcoords,
EdgeWeight -> ew, VertexLabels -> Placed["Name", Center],
EdgeLabels -> {e_ :> Placed["EdgeWeight", Center]},
VertexSize -> .3, VertexStyle -> Red]
vars3d = Array[Through[{x, y, z}@#] &, Length @ vd];
λ = 1/100.;
obj3d = Total[(Norm[vars3d[[First@#]] - vars3d[[Last@#]]] - # /. ew)^2 & /@
EdgeList[g3d]] + λ Total[Norm /@ (vars3d - vd)];
lbnd = 0;
ubnd = 500;
solution3d = Last@Minimize[{obj3d, And @@ Thread[lbnd <= Join @@ vars3d <= ubnd]},
Join @@ vars3d];
edgeLengths3d = # -> Norm[vars3d[[First@#]] - vars3d[[Last@#]]] /.
solution3d & /@ EdgeList[g3d];
Grid[Prepend[{#, # /. ew, # /. edgeLengths3d} & /@
EdgeList[g3d], {"edge", "EdgeWeight", "Edge Length"}],
Dividers -> All]
Các đề xuất về cách tiến hành và giao diện Mathematica từ Python sẽ thực sự hữu ích.
CHỈNH SỬA: Câu trả lời được đăng bên dưới giúp truyền các đối số đầu vào từ Python bằng cách sử dụng PythonExpression. Tiếp theo, tôi muốn đánh giá các biểu thức Mathematica này từ một tập lệnh python. Dựa trên các nhận xét bên dưới, tôi đã cài đặt wolframclient và làm như sau
from wolframclient.evaluation import WolframLanguageSession
session = WolframLanguageSession()
from wolframclient.language import wlexpr
session.evaluate(wlexpr('')) # I would like to know how to inclide Mathematica expressions here
EDIT2: Tôi có thể làm được không
session.evaluate(wlexpr(
'edges = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 5, 2 <-> 6, 5 <-> 6, 3 <-> 4, 3 <-> 7, 6 <-> 7, 7 <-> 8, 2 <-> 9};'
'vd = {{75., 25., 0}, {115., 45., 0}, {10., 5., 0}, {45., 0, 0},{90., 60., 0}, {45., 55., 0}, {0, 25., 0}, {10., 50., 0}, {115., 25.,0}};'
'vl = Range[Length@vd];'))
Tôi đã thử,
from wolframclient.evaluation import WolframLanguageSession
session = WolframLanguageSession()
from wolframclient.language import wlexpr
session.evaluate(wlexpr(
'edges = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 5, 2 <-> 6, 5 <-> 6, 3 <-> 4, 3 <-> 7, 6 <-> 7, 7 <-> 8, 2 <-> 9};'
'vd = {{75., 25., 0}, {115., 45., 0}, {10., 5., 0}, {45., 0, 0},{90., 60., 0}, {45., 55., 0}, {0, 25., 0}, {10., 50., 0}, {115., 25.,0}};'
'vl = Range[Length@vd];'
'vcoords = MapIndexed[#2[[1]] -> # &, vd];'
'ew = {1 \[UndirectedEdge] 2 -> 49.6, 1 \[UndirectedEdge] 3 -> 74.4,'
'1 \[UndirectedEdge] 4 -> 49.6, 2 \[UndirectedEdge] 5 -> 37.2,'
'2 \[UndirectedEdge] 6 -> 74.4, 5 \[UndirectedEdge] 6 -> 49.6,'
'3 \[UndirectedEdge] 4 -> 37.2, 3 \[UndirectedEdge] 7 -> 24.8,'
'6 \[UndirectedEdge] 7 -> 62, 7 \[UndirectedEdge] 8 -> 37.2,'
'2 \[UndirectedEdge] 9 -> 24.8};'
'g3d = Graph3D[vl, edges, VertexCoordinates -> vcoords,EdgeWeight -> ew, VertexLabels -> Placed["Name", Center],'
'EdgeLabels -> {e_ :> Placed["EdgeWeight", Center]},'
'VertexSize -> .3, VertexStyle -> Red];'
'vars3d = Array[Through[{x, y, z}@#] &, Length @ vd];'
'λ = 1/100.;'
'obj3d = Total[(Norm[vars3d[[First@#]] - vars3d[[Last@#]]] - # /. ew)^2 & /@EdgeList[g3d]] + λ Total[Norm /@ (vars3d - vd)];'
'lbnd = 0;'
'ubnd = 500;'
'solution3d = Last@Minimize[{obj3d, And @@ Thread[lbnd <= Join @@ vars3d <= ubnd]},Join @@ vars3d];'
'edgeLengths3d = # -> Norm[vars3d[[First@#]] - vars3d[[Last@#]]] /.solution3d & /@ EdgeList[g3d];'
'Grid[Prepend[{#, # /. ew, # /. edgeLengths3d} & /@EdgeList[g3d], {"edge", "EdgeWeight", "Edge Length"}],Dividers -> All];'
'z1 = Values[solution3d] // Partition[#, 3] &;'
'theFile = File["op.txt"];'
'Export[theFile, z1, "Table"];'
))
Nhưng tôi gặp lỗi sau,
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList]. Undefined message MessageName[Message, msgl] with arguments {$MessageList} The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution. String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Undefined message MessageName[Message, msgl] with arguments {$MessageList} String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Further output of MessageName[StringForm, string] will be suppressed during this calculation.
The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution.
String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList]. Undefined message MessageName[Message, msgl] with arguments {$MessageList} The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution. String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Undefined message MessageName[Message, msgl] with arguments {$MessageList} String expected at position 1 in StringForm[MessageName[General, msgl], $MessageList].
Further output of MessageName[StringForm, string] will be suppressed during this calculation.
The problem may be unbounded. Specifying a value for MaxIterations greater than 5000 may improve the solution.
Bạn có thể vui lòng đề nghị làm thế nào điều này có thể được sửa chữa? Như hình dưới đây, không có vấn đề gì khi chạy các biểu thức tương tự trong sổ ghi chép MMA.
Trả lời
Đây là một cách để làm những gì bạn muốn trong Mathematica.
Đầu tiên, sử dụng "PythonExpression" có thể hữu ích để nhập / xuất những thứ:
{edges,vl,ew,vd}=ImportString[#,"PythonExpression"]&/@ {"[(1,2),(1,3),(1,4),(2,5),(2,6),(5,6),(3,4),(3,7),(6,7),(7,8),(2,9)]",
"[1,2,3,4,5,6,7,8,9]","{(1,2):49.6,(1,3):74.4,(1,4):49.6,(2,5):37.2,(2,6):74.4,(5,6):49.6,(3,4):37.2,(3,7):24.8,(6,7):62,(7,8):37.2,(2,9):24.8}",
"{1:[75.,25.,0],2:[115.,45.,0],3:[10.,5.,0],4:[45.,0,0],5:[90.,60.,0],6:[45.,55.,0],7:[0,25.,0],8:[10.,50.,0],9:[115.,25.,0]}"};
Rất tiếc, Đồ thị chưa hoạt động với các Hiệp hội, vì vậy bạn cần danh sách và các cạnh phải sử dụng các ký hiệu như UndirectedEdgehoặc DirectedEdge:
edges = UndirectedEdge @@@ edges; vcoords = List @@ vd;
ew = Normal @ KeyMap[UndirectedEdge @@ # &,ew];
g3d = Graph3D[vl, edges, VertexCoordinates -> vcoords,
EdgeWeight->ew, VertexLabels->Placed["Name",Center],
EdgeLabels->{e_:>Placed["EdgeWeight",Center]}, VertexSize->.5, BaseStyle->16]
Tính toán của bạn gần như đã hoạt động, nhưng bạn cần biến các cạnh thành các quy tắc:
vars3d = Array[Through[{x, y, z}@#] &, Length@vd];
\[Lambda] = 1/100.; lbnd = 0; ubnd = 500;
obj3d = Total[(Norm[vars3d[[First@#]] - vars3d[[Last@#]]] - # /. (Rule @@@ ew))^2 & /@ EdgeList[g3d]] + \[Lambda] * Total[Norm /@ (vars3d - Values@vd)];
solution3d = Last @ Minimize[{obj3d, And @@ Thread[lbnd <= Join @@ vars3d <= ubnd]}, Join @@ vars3d]
Sau đó, nó hoạt động tốt:
edgeLengths3d = # -> Norm[vars3d[[First@#]] - vars3d[[Last@#]]] /.
solution3d & /@ EdgeList[g3d];
ResourceFunction["PrettyGrid"][{#, # /. ew, # /. edgeLengths3d} & /@
EdgeList[g3d], "ColumnHeadings" -> {"edge", "EdgeWeight", "Edge Length"}]
Xin lỗi, tôi đã nhầm và không nhớ rằng bạn muốn sử dụng MMA từ Python chứ không phải ngược lại. ExternalEvaluate ["Python", str] là một lệnh MMA, không phải Python.
Cách cung cấp đầu vào MMA từ Python được mô tả tại đây: "https://reference.wolfram.com/language/workflow/EvaluateAWolframLanguageExpressionFromPython.html".
Sau khi khởi động Python, bạn thực thi bằng Python:
from wolframclient.evaluation import WolframLanguageSession
session = WolframLanguageSession()
from wolframclient.language import wlexpr
session.evaluate(wlexpr('myCommandString'))
trong đó myCommandString là chuỗi chứa các câu lệnh Mathematica của bạn. Ví dụ: trong Python:
myCommandString="a=1;b=2;a+b"
Hoặc nếu bạn muốn điều này trên một số dòng:
myCommandString="a=1;"
myCommandString=myCommandString+"b=2;"
myCommandString=myCommandString+"a+b"
hi vọng điêu nay co ich.
Nếu bạn có một khối mã kéo dài trên nhiều dòng, có thể hữu ích khi đặt nó vào tệp .m và Gettệp từ python. Đây là một ví dụ:
Đầu tiên, hãy tạo một tệp và viết mã Ngôn ngữ Wolfram mà bạn muốn đánh giá trong đó. Hãy gọi tập tin /tmp/test.m.
Bây giờ bằng Python:
from wolframclient.evaluation import WolframLanguageSession
from wolframclient.language import wl
# important note: the session is automatically closed.
with WolframLanguageSession() as s:
s.evaluate(wl.Get('/tmp/test.m'))
Đừng quên đóng WolframLanguageSessionnếu không bạn sẽ nhận được hạt nhân mồ côi (thêm thông tin tại đây ).
Như bạn có thể thấy, bước đánh giá bây giờ nằm gọn trong một dòng. Bạn có thể tự do cập nhật mã của mình trong trình chỉnh sửa yêu thích của mình. Đó chính xác là những gì tôi đã làm với mã ban đầu của bạn, tôi chỉ thêm hai dấu chấm phẩy bị thiếu và xuất kết quả như được thực hiện sau này.
Đây là /tmp/test.mtệp của tôi :
edges = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 5, 2 <-> 6, 5 <-> 6,
3 <-> 4, 3 <-> 7, 6 <-> 7, 7 <-> 8, 2 <-> 9};
vd = {{75., 25., 0}, {115., 45., 0}, {10., 5., 0}, {45., 0, 0}, {90.,
60., 0}, {45., 55., 0}, {0, 25., 0}, {10., 50., 0}, {115., 25.,
0}};
vl = Range[Length@vd];
vcoords = MapIndexed[#2[[1]] -> # &, vd];
ew = {1 \[UndirectedEdge] 2 -> 49.6, 1 \[UndirectedEdge] 3 -> 74.4,
1 \[UndirectedEdge] 4 -> 49.6, 2 \[UndirectedEdge] 5 -> 37.2,
2 \[UndirectedEdge] 6 -> 74.4, 5 \[UndirectedEdge] 6 -> 49.6,
3 \[UndirectedEdge] 4 -> 37.2, 3 \[UndirectedEdge] 7 -> 24.8,
6 \[UndirectedEdge] 7 -> 62, 7 \[UndirectedEdge] 8 -> 37.2,
2 \[UndirectedEdge] 9 -> 24.8};
g3d = Graph3D[vl, edges, VertexCoordinates -> vcoords,
EdgeWeight -> ew, VertexLabels -> Placed["Name", Center],
EdgeLabels -> {e_ :> Placed["EdgeWeight", Center]},
VertexSize -> .3, VertexStyle -> Red];
vars3d = Array[Through[{x, y, z}@#] &, Length@vd];
\[Lambda] = 1/100.;
obj3d = Total[(Norm[vars3d[[First@#]] - vars3d[[Last@#]]] - # /.
ew)^2 & /@ EdgeList[g3d]] + \[Lambda] Total[
Norm /@ (vars3d - vd)];
lbnd = 0;
ubnd = 500;
solution3d =
Last@Minimize[{obj3d,
And @@ Thread[lbnd <= Join @@ vars3d <= ubnd]}, Join @@ vars3d];
edgeLengths3d = # -> Norm[vars3d[[First@#]] - vars3d[[Last@#]]] /.
solution3d & /@ EdgeList[g3d];
z1 = Values[solution3d] // Partition[#, 3] &;
Export["/tmp/result.txt", z1, "Table"];
```