-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsym.m
95 lines (61 loc) · 1.9 KB
/
sym.m
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
(* ::Package:: *)
(*
INPUT (common names for all modules);
time : time in seconds for running the procedure;
ncores : number of cores to be used;
uops : list of unary operations;
bops : list of binary operations;
vars : list of variables and constants;
nops : max number of operations used for building expression;
*)
(*
Runs symbolic Monte Carlo using multiple cores;
OUTPUT (list);
1st element is the accumulated list of top 100 models and corresponding error values;
2nd element is the total number of iterations;
*)
Search[time_,ncores_,uops_,bops_,vars_,nops_]:=Module[{arg,res},
arg=Table[time,ncores];
res=ParallelMap[Search1[#,uops,bops,vars,nops]&,arg];
{SortBy[Flatten[res[[All,1]],1],First][[1;;100]],Total[res[[All,2]]]}
]
(*
Runs symbolic Monte Carlo on a single core;
OUTPUT (list);
1st element is the list of top 100 models and corresponding error values;
2nd element is the number of iterations;
*)
Search1[time_,uops_,bops_,vars_,nops_]:=Module[{top100,nit,expr,error},
top100=Table[{Infinity,"???"},100];
nit=0;
TimeConstrained[
Quiet@While[True,
expr=RandomExpression[uops,bops,vars,nops];
error=Error[expr];
nit++;
If[(error<top100[[100,1]])&&(Select[top100[[All,2]],#==expr&]=={}),
top100=SortBy[Append[Most[top100],{error,expr}],First]]
]
,time];
{top100,nit}
]
(*
Generates a random expression from given operations and variables/constants;
OUTPUT (expression);
random expression
*)
RandomExpression[uops_,bops_,vars_,nops_]:=Module[{u,b,expr,leaf,nleaves,index,optype},
u:=RandomChoice[uops];
b:=RandomChoice[bops];
expr=leaf[1];
nleaves=1;
Do[
index=RandomInteger[{1,nleaves}];
optype=RandomChoice[{1,2}];
If[optype==1,
expr=(expr/.leaf[index]->u[leaf[index]]),
expr=(expr/.leaf[index]->b[leaf[index],leaf[nleaves+1]]);nleaves++
]
,RandomInteger[{0,nops}]];
expr/.leaf[_]:>RandomChoice[vars]
]