/
main_search.go
413 lines (345 loc) · 8.93 KB
/
main_search.go
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
"sort"
"strings"
"time"
config "github.com/verdverm/go-pge/config"
pge "github.com/verdverm/go-pge/pge"
probs "github.com/verdverm/go-pge/problems"
)
// defines the interface to a search type [GP,PE]
type Search interface {
// parse a params file
ParseConfig(filename string)
// initialize the search, sending signal on chan when done
// the input will be something for the search to connect to
// in order to provide updates, be monitored, and receive control signals
Init(done chan int, prob *probs.ExprProblem, logdir string, input interface{})
// start the actual search procedure (Init is required before a new call to Run)
Run()
// clean up internal structures (Init is required before a new call to Run)
Clean()
}
// parameters to a main search, which sets up the global system
// and instructs in where to find the sub-searches
type mainConfig struct {
dataDir string
cfgDir string
logDir string
probCfg string
srchCfg []string
}
func mainConfigParser(field, value string, config interface{}) (err error) {
DC := config.(*mainConfig)
switch strings.ToUpper(field) {
case "CONFIGDIR":
DC.cfgDir = value
case "DATADIR":
DC.dataDir = value
case "LOGDIR":
DC.logDir = value
case "PROBLEMCFG":
DC.probCfg = value
case "SEARCHCFG":
DC.srchCfg = strings.Fields(value)
default:
log.Printf("Main Not Implemented %s, %s\n\n", field, value)
}
return err
}
// defines the global level search, which may use different sub-searches one or more times
type MainSearch struct {
cnfg mainConfig
// problem and best results
prob *probs.ExprProblem
eqns probs.ExprReportArray
per_eqns []*probs.ExprReportArray
// sub-searches and comm
srch []Search
comm []*probs.ExprProblemComm
iter []int
// logs
logDir string
mainLog *log.Logger
mainLogBuf *bufio.Writer
eqnsLog *log.Logger
eqnsLogBuf *bufio.Writer
errLog *log.Logger
errLogBuf *bufio.Writer
}
func (DS *MainSearch) ParseConfig(filename string) {
fmt.Printf("Parsing Main Config: %s\n", filename)
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
}
err = config.ParseConfig(data, mainConfigParser, &DS.cnfg)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%v\n", DS.cnfg)
}
func (DS *MainSearch) Init(done chan int, input interface{}) {
fmt.Printf("Init'n PGE1\n----------\n")
DC := DS.cnfg
// read and setup problem
eprob := new(probs.ExprProblem)
fmt.Printf("Parsing Problem Config: %s\n", DC.probCfg)
data, err := ioutil.ReadFile(DC.cfgDir + DC.probCfg)
if err != nil {
log.Fatal(err)
}
err = config.ParseConfig(data, probs.ProbConfigParser, eprob)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Prob: %v\n", eprob)
fmt.Printf("TCfg: %v\n\n", eprob.TreeCfg)
// setup log dir and open main log files
DC.logDir += eprob.Name + "/"
if DC.srchCfg[0][:4] == "pge1" {
DC.logDir += "pge1/"
} else if DC.srchCfg[0][:3] == "pge" {
DC.logDir += "pge/"
}
os.MkdirAll(DC.logDir, os.ModePerm)
now := time.Now()
fmt.Println("LogDir: ", DC.logDir)
os.MkdirAll(DC.logDir, os.ModePerm)
DS.initLogs(DC.logDir)
DS.mainLog.Println(DC.logDir, now)
// // setup data
fmt.Printf("Setting up problem: %s\n", eprob.Name)
eprob.Train = make([]*probs.PointSet, len(eprob.TrainFns))
for i, fn := range eprob.TrainFns {
fmt.Printf("Reading Trainging File: %s\n", fn)
eprob.Train[i] = new(probs.PointSet)
if strings.HasSuffix(fn, ".dataF2") || strings.HasSuffix(fn, ".mat") {
eprob.Train[i].ReadLakeFile(DC.dataDir + fn)
} else {
eprob.Train[i].ReadPointSet(DC.dataDir + fn)
}
}
eprob.Test = make([]*probs.PointSet, len(eprob.TestFns))
for i, fn := range eprob.TestFns {
fmt.Printf("Reading Testing File: %s\n", fn)
eprob.Test[i] = new(probs.PointSet)
if strings.HasSuffix(fn, ".dataF2") || strings.HasSuffix(fn, ".mat") {
eprob.Test[i].ReadLakeFile(DC.dataDir + fn)
} else {
eprob.Test[i].ReadPointSet(DC.dataDir + fn)
}
}
DS.prob = eprob
fmt.Println()
// read search configs
for _, cfg := range DC.srchCfg {
if cfg[:4] == "pge1" {
GS := new(pge.PgeSearch)
GS.ParseConfig(DC.cfgDir + cfg)
DS.srch = append(DS.srch, GS)
} else if cfg[:3] == "pge" {
PS := new(pge.PgeSearch)
PS.ParseConfig(DC.cfgDir + cfg)
DS.srch = append(DS.srch, PS)
/************/
// temporary hack
DS.prob.MaxIter = PS.GetMaxIter()
/************/
if *arg_pge_iter >= 0 {
DS.prob.MaxIter = *arg_pge_iter
PS.SetMaxIter(*arg_pge_iter)
}
if *arg_pge_peel >= 0 {
PS.SetPeelCount(*arg_pge_peel)
}
if *arg_pge_init != "" {
PS.SetInitMethod(*arg_pge_init)
}
if *arg_pge_grow != "" {
PS.SetGrowMethod(*arg_pge_grow)
}
PS.SetEvalrCount(*arg_pge_evals)
} else {
log.Fatalf("unknown config type: %v from %v\n", cfg[:4], cfg)
}
}
// setup best results
DS.eqns = make(probs.ExprReportArray, 32)
DS.per_eqns = make([]*probs.ExprReportArray, len(DS.srch))
// setup communication struct
DS.comm = make([]*probs.ExprProblemComm, len(DS.srch))
for i, _ := range DS.comm {
DS.comm[i] = new(probs.ExprProblemComm)
DS.comm[i].Cmds = make(chan int)
DS.comm[i].Rpts = make(chan *probs.ExprReportArray, 64)
DS.comm[i].Gen = make(chan [2]int, 64)
}
DS.iter = make([]int, len(DS.srch))
fmt.Println("\n******************************************************\n")
// initialize searches
sdone := make(chan int)
for i, _ := range DS.srch {
DS.srch[i].Init(sdone, eprob, DC.logDir, DS.comm[i])
}
fmt.Println("\n******************************************************\n")
}
func (DS *MainSearch) Run() {
fmt.Printf("Running Main\n")
fmt.Println("numSrch = ", len(DS.srch))
for i := 0; i < len(DS.srch); i++ {
go DS.srch[i].Run()
}
counter := 0
for {
// fmt.Println("DS: ", counter)
DS.checkMessages()
// time.Sleep(time.Second / 20)
counter++
if DS.checkStop() {
DS.doStop()
break
}
}
for i, R := range DS.eqns {
if R == nil || R.Expr() == nil {
continue
}
trn := DS.prob.Train[0]
f_x := "df(" + trn.GetIndepNames()[DS.prob.SearchVar] + ")"
str := R.Expr().PrettyPrint(trn.GetIndepNames(), trn.GetSysNames(), R.Coeff())
fmt.Printf("%d: %s = %s\n%v\n\n", i, f_x, str, R)
}
DS.Clean()
fmt.Println("DS leaving Run()")
}
func (DS *MainSearch) Clean() {
fmt.Printf("Cleaning Main\n")
DS.errLogBuf.Flush()
DS.mainLogBuf.Flush()
DS.eqnsLogBuf.Flush()
}
func (DS *MainSearch) checkStop() bool {
if DS.iter[0] > DS.prob.MaxIter {
return true
}
return false
}
func (DS *MainSearch) doStop() {
done := make(chan int)
for i, _ := range DS.comm {
func() {
c := i
C := DS.comm[i]
go func() {
C.Cmds <- -1
fmt.Printf("DS sent -1 to Srch %d\n", c)
<-C.Cmds
done <- 1
}()
}()
}
cnt := 0
for cnt < len(DS.comm) {
DS.checkMessages()
_, ok := <-done
if ok {
cnt++
fmt.Println("DS done = ", cnt, len(DS.comm))
}
}
fmt.Println("DAMD checking last messages")
DS.checkMessages()
fmt.Println("DS done stopping")
}
func (DS *MainSearch) checkMessages() {
msg := false
for i := 0; i < len(DS.comm); i++ {
select {
case gen, ok := <-DS.comm[i].Gen:
if ok {
DS.iter[i] = gen[1]
if gen[0] == 0 {
fmt.Println("Gen: ", gen[1])
}
i--
msg = true
}
case rpt, ok := <-DS.comm[i].Rpts:
if ok {
msg = true
DS.per_eqns[i] = rpt
i--
}
default:
continue
}
}
if !msg {
time.Sleep(time.Millisecond)
}
DS.accumExprs()
}
func (DS *MainSearch) accumExprs() {
union := make(probs.ExprReportArray, 0)
for i := 0; i < len(DS.per_eqns); i++ {
if DS.per_eqns[i] != nil {
union = append(union, (*DS.per_eqns[i])[:]...)
}
}
union = append(union, DS.eqns[:]...)
// remove duplicates
sort.Sort(union)
last := 0
for last < len(union) && union[last] == nil {
last++
}
for i := last + 1; i < len(union); i++ {
if union[i] == nil {
continue
}
if union[i].Expr().AmIAlmostSame(union[last].Expr()) {
union[i] = nil
} else {
last = i
}
}
queue := probs.NewQueueFromArray(union)
queue.SetSort(probs.GPSORT_PARETO_TST_ERR)
queue.Sort()
copy(DS.eqns, union[:len(DS.eqns)])
// DS.eqnsLog.Printf("\n\n\nLatest Eqns:\n")
// DS.eqnsLog.Println(DS.eqns)
// DS.Clean()
}
func (DS *MainSearch) initLogs(logdir string) {
// open logs
DS.logDir = logdir
os.Mkdir(DS.logDir, os.ModePerm)
tmpF0, err5 := os.Create(DS.logDir + "main:err.log")
if err5 != nil {
log.Fatal("couldn't create errs log", err5)
}
DS.errLogBuf = bufio.NewWriter(tmpF0)
DS.errLogBuf.Flush()
DS.errLog = log.New(DS.errLogBuf, "", log.LstdFlags)
tmpF1, err1 := os.Create(DS.logDir + "main:main.log")
if err1 != nil {
log.Fatal("couldn't create main log", err1)
}
DS.mainLogBuf = bufio.NewWriter(tmpF1)
DS.mainLogBuf.Flush()
DS.mainLog = log.New(DS.mainLogBuf, "", log.LstdFlags)
tmpF2, err2 := os.Create(DS.logDir + "main:eqns.log")
if err2 != nil {
log.Fatal("couldn't create eqns log", err2)
}
DS.eqnsLogBuf = bufio.NewWriter(tmpF2)
DS.eqnsLogBuf.Flush()
DS.eqnsLog = log.New(DS.eqnsLogBuf, "", log.LstdFlags)
}