如何解决mathematica 中的并行计算失败
考虑以下包含两个函数 NonCommutativeMultiply
和 xval
的代码。后者与前者一起工作,如下所示。在顺序模式下一切都很好。不幸的是,事情会同时变坏。
Unprotect[NonCommutativeMultiply];
Clearall[NonCommutativeMultiply]
NonCommutativeMultiply[] := 1
NonCommutativeMultiply[l___,r___] := 0
NonCommutativeMultiply[a___,1,b___] := a ** b
NonCommutativeMultiply[a___,Times[-1,b_],c___] := -a ** b ** c
NonCommutativeMultiply[a_] := a
SetAttributes[NonCommutativeMultiply,{OneIdentity,Flat}]
Protect[NonCommutativeMultiply];
Unprotect[NonCommutativeMultiply];
left___ ** HoldPattern[Times[z_,p : (a[x_] | ad[x_])]] ** right___ :=z*left ** p ** right
left___ ** HoldPattern[Times[u_[x_],p : (a[x_] | ad[x_])]] ** right___ := u[x]*left ** p ** right
left___ ** HoldPattern[Times[v_[x_],p : (a[x_] | ad[x_])]] ** right___ := v[x]*left ** p ** right
left___ ** HoldPattern[Times[z__,p : (a[x_] | ad[x_])]] ** right___ :=z*left ** p ** right
left___ ** Times[z___,y__NonCommutativeMultiply,x___] ** right___ := z*x*left ** y ** right
x___ ** y__Real ** z___ := y x ** z
x___ ** y__Integer ** z___ := y x ** z
l___ ** y__Power ** r___ := y l ** r
l___ ** Times[x__,y__] ** r___ := Times[x,y] l ** r
a[x_] ** a[x_] := 1;
ad[x_] ** ad[x_] := 1;
Protect[NonCommutativeMultiply];
xval[x___] := NonCommutativeMultiply[x];
xval[] := 1
xval[___ ** 0 ** ___] := 0
xval[x__Plus] := Map[xval,x]
xval[Times[x__,y_NonCommutativeMultiply,z___]] := x z xval[y] (* needed *)
xval[Times[x___,z__]] := x z xval[y]
xval[___ ** a[x_]] := 0;
让我们检查一下:
distribute[a[x] ** (0.244 a[x] ** a[x2] + 0.111 ad[x2] ** a[x1]) ** a[x]]
xval[distribute[a[x] ** (0.244 a[x] ** a[x2] + 0.111 ad[x2] ** a[x1]) ** a[x2]]]
(* output *)
0.244 a[x2] ** a[x] + 0.111 a[x] ** ad[x2] ** a[x1] ** a[x]
0.244
哪个是正确的
现在并行:
Quiet@LaunchKernels[];
distributeDeFinitions[NonCommutativeMultiply,xval]; (* can be omitted *)
ParallelEvaluate[a[x] ** a[x]]
ParallelEvaluate[xval[a[x] ** a[x]]]
ParallelEvaluate[
distribute[a[x] ** (0.244 a[x] ** a[x2] + 0.111 ad[x2] ** a[x1]) ** a[x]]]
ParallelEvaluate[xval[distribute[a[x] ** (0.244 a[x] ** a[x2] + 0.111 ad[x2] ** a[x1]) ** a[x2]]]]
CloseKernels[];
{1,1} (* correct *)
{0,0} (* wrong *)
{0.244 a[x2] ** a[x] + 0.111 a[x] ** ad[x2] ** a[x1] ** a[x],0.244 a[x2] ** a[x] + 0.111 a[x] ** ad[x2] ** a[x1] ** a[x],0.244 a[x2] ** a[x] + 0.111 a[x] ** ad[x2] ** a[x1] ** a[x]} (* wrong *)
{0,0} (* wrong *)
并行 xval
无法正常工作。从上面可以看出。具体来说,xval
似乎无法识别 a[x]**a[x]=1
任何想法如何解决这个问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。