Debian Codegraph @

formula/formula.go

raw symbols SCIP
1 package formula
2
3 import (
4 "fmt"
5 "strings"
6 "unicode"
7
8 "github.com/kshedden/dstream/dstream"
9 )
10
11 // Tokens that can appear in a formula.
12 type tokType int
13
14 // Allowed token types types.
15 const (
16 vname = iota
17 leftp
18 rightp
19 times
20 plus
21 icept
22 funct
23 )
24
25 // Func is a transformation of a numeric column to a column set.
26 type Func func(string, []float64) *ColSet
27
28 // Operator precedence values; lower number is higher precedence.
29 var precedence = map[tokType]int{times: 0, plus: 1}
30
31 // The token is either a symbol (operator or parentheses), a variable
32 // name, or a function
33 type token struct {
34 symbol tokType
35 name string // only used if symbol == vname
36
37 // Below are only used for functions
38 funcn string
39 arg string
40 }
41
42 // pop removes the last token from the slice, and returns it along
43 // with the shortened slice. nil is returned if the slice has length
44 // zero.
45 func pop(tokens []*token) ([]*token, *token) {
46 if len(tokens) == 0 {
47 return nil, nil
48 }
49 n := len(tokens)
50 tok := tokens[n-1]
51 tokens = tokens[0 : n-1]
52 return tokens, tok
53 }
54
55 // peek returns the last token from the slice. nil is returned if the
56 // slice has length zero.
57 func peek(tokens []*token) *token {
58 if len(tokens) == 0 {
59 return nil
60 }
61 n := len(tokens)
62 tok := tokens[n-1]
63 return tok
64 }
65
66 // push appends the token to the end of the slice and returns the new slice.
67 func push(tokens []*token, tok *token) []*token {
68 return append(tokens, tok)
69 }
70
71 // lex takes a formula and lexes it to obtain an array of tokens.
72 func lex(input string) ([]*token, error) {
73
74 var tokens []*token
75 rdr := strings.NewReader(input)
76
77 isValidContinuation := func(r rune) bool {
78 if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
79 return true
80 }
81 return false
82 }
83
84 for rdr.Len() > 0 {
85 r, _, err := rdr.ReadRune()
86 if err != nil {
87 return nil, err
88 }
89 switch {
90 case r == '(':
91 tokens = append(tokens, &token{symbol: leftp})
92 case r == ')':
93 tokens = append(tokens, &token{symbol: rightp})
94 case r == '+':
95 tokens = append(tokens, &token{symbol: plus})
96 case r == '*':
97 tokens = append(tokens, &token{symbol: times})
98 case r == '1':
99 tokens = append(tokens, &token{symbol: icept})
100 case r == ' ':
101 // skip whitespace
102 case unicode.IsLetter(r) || r == '_':
103 name := []rune{r}
104 for rdr.Len() > 0 {
105 q, _, err := rdr.ReadRune()
106 if err != nil {
107 panic(err)
108 }
109 if !isValidContinuation(q) {
110 _ = rdr.UnreadRune()
111 break
112 }
113 name = append(name, q)
114 }
115 tokens = append(tokens, &token{symbol: vname, name: string(name)})
116 default:
117 return nil, fmt.Errorf("Invalid formula, symbol '%s' is not known.", string(r))
118 }
119 }
120
121 tokens, err := lexFuncs(tokens)
122 return tokens, err
123 }
124
125 func lexFuncs(input []*token) ([]*token, error) {
126
127 output := make([]*token, 0, len(input))
128 i := 0
129 m := len(input)
130 for i < m {
131 if i+1 < m && input[i].symbol == vname && input[i+1].symbol == leftp && input[i+3].symbol == rightp {
132 // A function
133 name := fmt.Sprintf("%s(%s)", input[i].name, input[i+2].name)
134 newtok := &token{symbol: funct, name: name, arg: input[i+2].name, funcn: input[i].name}
135 output = append(output, newtok)
136 i = i + 4
137 } else {
138 // Not a function
139 output = append(output, input[i])
140 i++
141 }
142 }
143
144 return output, nil
145 }
146
147 // isOperator returns true if the token is an opertor (times or plus)
148 func isOperator(tok *token) bool {
149 if tok.symbol == times || tok.symbol == plus {
150 return true
151 }
152 return false
153 }
154
155 // parse converts the formula to RPN
156 // https://en.wikipedia.org/wiki/Shunting-yard_algorithm
157 func parse(input []*token) ([]*token, error) {
158
159 var stack, output []*token
160 var last *token
161
162 for _, tok := range input {
163
164 switch {
165 case tok.symbol == vname || tok.symbol == funct || tok.symbol == icept:
166 output = append(output, tok)
167 case isOperator(tok):
168 for {
169 last := peek(stack)
170 if last == nil || !isOperator(last) {
171 break
172 }
173 if precedence[tok.symbol] > precedence[last.symbol] {
174 stack, last = pop(stack)
175 output = append(output, last)
176 } else {
177 break
178 }
179 }
180 stack = push(stack, tok)
181 case tok.symbol == leftp:
182 stack = push(stack, tok)
183 case tok.symbol == rightp:
184 for {
185 stack, last = pop(stack)
186 if last == nil {
187 return nil, fmt.Errorf("unbalanced parentheses")
188 }
189 if last.symbol == leftp {
190 break
191 } else {
192 output = append(output, last)
193 }
194 }
195 }
196 }
197
198 for {
199 stack, last = pop(stack)
200 if last == nil {
201 break
202 }
203 if last.symbol == leftp || last.symbol == rightp {
204 return nil, fmt.Errorf("mismatched parentheses")
205 }
206 output = append(output, last)
207 }
208
209 return output, nil
210 }
211
212 // FormulaParser takes a formula and dataset, and produces a design
213 // matrix from them.
214 type FormulaParser struct {
215
216 // The formula defining the design matrix
217 Formulas []string
218
219 // Produces data in chunks
220 RawData dstream.Dstream
221
222 // Reference levels for string variables are omitted when
223 // forming indicators
224 refLevels map[string]string
225
226 // Codes is a map from variable names to maps from variable
227 // values to integer codes. The distinct values of a
228 // variable, excluding the reference level, are mapped to the
229 // integers 0, 1, ... Can be set manually, but if it is not
230 // will be computed from data. Not used if all variables are
231 // of float64 type.
232 codes map[string]map[string]int
233
234 // Map from function name to function.
235 funcs map[string]Func
236
237 // Variables to retain that are not in the formula
238 keep []string
239
240 // The final data produced by parsing the formula
241 Data *ColSet
242
243 ErrorState error
244
245 // Intermediate data
246 workData map[string]*ColSet
247
248 facNames map[string][]string
249 rpn [][]*token // separate RPN for each formula
250 rawNames []string
251 nvar int
252 names []string
253 }
254
255 // New creates a FormulaParser from a formula and a data stream.
256 func New(formula string, rawdata dstream.Dstream) *FormulaParser {
257
258 fp := &FormulaParser{
259 Formulas: []string{formula},
260 RawData: rawdata,
261 }
262
263 return fp
264 }
265
266 // RefLevels specifies the reference levels of a categorical covariate, which are
267 // omitted when building design matrices.
268 func (fp *FormulaParser) RefLevels(reflevels map[string]string) *FormulaParser {
269 fp.refLevels = reflevels
270 return fp
271 }
272
273 // Codes specifies a mapping from variable names (for categorical variables)
274 // to code maps, which the distinct levels of the variablle distinct integer
275 // codes.
276 func (fp *FormulaParser) Codes(codes map[string]map[string]int) *FormulaParser {
277 fp.codes = codes
278 return fp
279 }
280
281 // Funcs specifies the Go functions that can be used by name in th
282 func (fp *FormulaParser) Funcs(funcs map[string]Func) *FormulaParser {
283 fp.funcs = funcs
284 return fp
285 }
286
287 // Keep defines variables that are retained when generating the output
288 // data stream, even through they are not present in the formula.
289 func (fp *FormulaParser) Keep(vars ...string) *FormulaParser {
290
291 names := fp.RawData.Names()
292 mp := make(map[string]bool)
293 for _, na := range names {
294 mp[na] = true
295 }
296 for _, v := range vars {
297 if !mp[v] {
298 msg := fmt.Sprintf("Formula: variable '%s' not found", v)
299 panic(msg)
300 }
301 }
302
303 fp.keep = vars
304 return fp
305 }
306
307 // Done signals that the FormulaParser has been fully configured and is
308 // ready for use.
309 func (fp *FormulaParser) Done() dstream.Dstream {
310 err := fp.init()
311 if err != nil {
312 panic(err)
313 }
314 return fp
315 }
316
317 // NewMulti accepts several formulas and includes all their parsed
318 // terms in the resulting data set.
319 func NewMulti(formulas []string, rawdata dstream.Dstream) *FormulaParser {
320
321 fp := &FormulaParser{
322 Formulas: formulas,
323 RawData: rawdata,
324 }
325
326 return fp
327 }
328
329 // Close does nothing, it is here to satisfy the dstream interface.
330 func (fp *FormulaParser) Close() {
331 }
332
333 // ColSet represents a design matrix. It is an ordered set of named
334 // numeric data columns.
335 type ColSet struct {
336 Names []string
337 Data []interface{}
338 }
339
340 // Extend a ColSet with the data of another ColSet.
341 func (c *ColSet) Extend(o *ColSet) {
342
343 // Don't add duplicate terms (which may arise when parsing
344 // multiple formulas together or when using Keep).
345 mp := make(map[string]bool)
346 for _, na := range c.Names {
347 mp[na] = true
348 }
349
350 for j, na := range o.Names {
351 if !mp[na] {
352 c.Names = append(c.Names, na)
353 c.Data = append(c.Data, o.Data[j])
354 }
355 }
356 }
357
358 // checkConv ensures that the variables with the given names have been
359 // converted from raw to ColSet form.
360 func (fp *FormulaParser) checkConv(v ...string) {
361 for _, x := range v {
362 fp.convertColumn(x)
363 }
364 }
365
366 // NumObs is needed to implement the dstream interface, but
367 // calls to it will panic.
368 func (fp *FormulaParser) NumObs() int {
369 panic("FormulaParser does not know the sample size")
370 }
371
372 // NumVar returns the number of variables.
373 func (fp *FormulaParser) NumVar() int {
374 return len(fp.Data.Data)
375 }
376
377 // GetPos returns the data slice for the current chunk, corresponding
378 // to the variable in position j.
379 func (fp *FormulaParser) GetPos(j int) interface{} {
380 return fp.Data.Data[j]
381 }
382
383 // Get returns the data slice for the current chunk, corresponding
384 // the the named variable.
385 func (fp *FormulaParser) Get(na string) interface{} {
386
387 for j, nm := range fp.Data.Names {
388 if nm == na {
389 return fp.GetPos(j)
390 }
391 }
392
393 msg := fmt.Sprintf("Formula: variable '%s' not found", na)
394 panic(msg)
395 }
396
397 // setCodes inspects the data to determine integer codes for the
398 // distinct, non-reference levels of each categorical (string type)
399 // variable.
400 func (fp *FormulaParser) setCodes() {
401
402 fp.codes = make(map[string]map[string]int)
403 fp.facNames = make(map[string][]string)
404
405 // Codes requires resettable data, since we must read through
406 // all the data to get the code information.
407 fp.RawData.Reset()
408 names := fp.RawData.Names()
409
410 for fp.RawData.Next() {
411
412 nvar := fp.RawData.NumVar()
413 for j := 0; j < nvar; j++ {
414 v := fp.RawData.GetPos(j)
415 if v == nil {
416 break
417 }
418 na := names[j]
419 switch v := v.(type) {
420 case []string:
421 // Get the category codes for this
422 // variable. If this is the first
423 // chunk, start from scratch.
424 codes, ok := fp.codes[na]
425 if !ok {
426 codes = make(map[string]int)
427 fp.codes[na] = codes
428 }
429
430 ref := fp.refLevels[na]
431 for _, x := range v {
432 if x == ref {
433 continue
434 }
435 _, ok := codes[x]
436 if !ok {
437 // New code
438 fm := fmt.Sprintf("%s[%s]", na, x)
439 fp.facNames[na] = append(fp.facNames[na], fm)
440 codes[x] = len(codes)
441 }
442 }
443 }
444 }
445 }
446
447 fp.RawData.Reset()
448 }
449
450 // codeStrings creates a ColSet from a string array, creating
451 // indicator variables for each distinct value in the string array,
452 // except for ref (the reference level).
453 func (fp *FormulaParser) codeStrings(na, ref string, s []string) {
454
455 // Get the category codes for this variable
456 codes := fp.codes[na]
457
458 var dat []interface{}
459 for range codes {
460 dat = append(dat, make([]float64, len(s)))
461 }
462
463 for i, x := range s {
464 if x == ref {
465 continue
466 }
467 c := codes[x]
468 //_ = dat[c] TODO delete
469 //_ = dat[c][i] TODO delete
470 dat[c].([]float64)[i] = 1
471 }
472
473 fp.workData[na] = &ColSet{Names: fp.facNames[na], Data: dat}
474 }
475
476 func (fp *FormulaParser) getRawCol(na string) interface{} {
477
478 j := -1
479 for i, x := range fp.rawNames {
480 if x == na {
481 j = i
482 break
483 }
484 }
485
486 if j == -1 {
487 msg := fmt.Sprintf("Formula: variable '%s' not found.", na)
488 panic(msg)
489 }
490
491 return fp.RawData.GetPos(j)
492 }
493
494 // convertColumn converts the raw data column with the given name to a
495 // ColSet object.
496 func (fp *FormulaParser) convertColumn(na string) {
497
498 // Only need to convert once
499 _, ok := fp.workData[na]
500 if ok {
501 return
502 }
503
504 s := fp.getRawCol(na)
505 switch s := s.(type) {
506 case []string:
507 ref := fp.refLevels[na]
508 fp.codeStrings(na, ref, s)
509 case []float64:
510 fp.workData[na] = &ColSet{
511 Names: []string{na},
512 Data: []interface{}{s},
513 }
514 default:
515 panic(fmt.Sprintf("unknown type %T in convertColumn", s))
516 }
517 }
518
519 // doPlus creates a new ColSet by adding the columnsets named 'a' and
520 // 'b'. Addition of two ColSet objects produces a new ColSet with
521 // columns comprising the union of the two arguments.
522 func (fp *FormulaParser) doPlus(a, b string) *ColSet {
523
524 ds1 := fp.workData[a]
525 ds2 := fp.workData[b]
526
527 var names []string
528 var dat []interface{}
529
530 names = append(names, ds1.Names...)
531 names = append(names, ds2.Names...)
532 dat = append(dat, ds1.Data...)
533 dat = append(dat, ds2.Data...)
534
535 return &ColSet{Names: names, Data: dat}
536 }
537
538 // doTimes creates a new ColSet by multiplying the columnsets named
539 // 'a' and 'b'. Multiplication produces a new ColSet with columns
540 // comprising all pairwise product of the two arguments.
541 func (fp *FormulaParser) doTimes(a, b string) *ColSet {
542
543 ds1 := fp.workData[a]
544 ds2 := fp.workData[b]
545
546 var names []string
547 var dat []interface{}
548
549 for j1, na1 := range ds1.Names {
550 for j2, na2 := range ds2.Names {
551 d1 := ds1.Data[j1].([]float64)
552 d2 := ds2.Data[j2].([]float64)
553 x := make([]float64, len(d1))
554 for i := range x {
555 x[i] = d1[i] * d2[i]
556 }
557 names = append(names, na1+":"+na2)
558 dat = append(dat, x)
559 }
560 }
561
562 return &ColSet{names, dat}
563 }
564
565 // createIcept inserts an intercept (array of 1's) into the dataset
566 // being constructed and returns true if an intercept is not already
567 // included, otherwise returns false.
568 func (fp *FormulaParser) createIcept() bool {
569
570 _, ok := fp.workData["icept"]
571 if ok {
572 return false
573 }
574
575 // Get the length of the data set.
576 var nobs int
577 {
578 x := fp.RawData.GetPos(0)
579 switch x := x.(type) {
580 case []float64:
581 nobs = len(x)
582 case []string:
583 nobs = len(x)
584 default:
585 panic("unknown type")
586 }
587 }
588
589 x := make([]float64, nobs)
590 for i := range x {
591 x[i] = 1
592 }
593 fp.workData["icept"] = &ColSet{Names: []string{"icept"}, Data: []interface{}{x}}
594
595 return true
596 }
597
598 // Names returns the names of the variables.
599 func (fp *FormulaParser) Names() []string {
600 return fp.names
601 }
602
603 // init performs lexing and parsing of the formula, only done once.
604 func (fp *FormulaParser) init() error {
605
606 for _, fml := range fp.Formulas {
607 fmx, err := lex(fml)
608 if err != nil {
609 return err
610 }
611 rpn, err := parse(fmx)
612 if err != nil {
613 return err
614 }
615 fp.rpn = append(fp.rpn, rpn)
616 }
617
618 if fp.codes == nil {
619 fp.setCodes()
620 }
621
622 // Read one chunk to get the number of variables
623 ok := fp.Next()
624 if !ok {
625 return fmt.Errorf("Unable to read data")
626 }
627 if fp.ErrorState != nil {
628 return fp.ErrorState
629 }
630 fp.nvar = len(fp.Data.Names)
631 fp.names = fp.Data.Names
632 fp.RawData.Reset()
633
634 return nil
635 }
636
637 func (fp *FormulaParser) doFormula(rpn []*token) bool {
638
639 fp.runFuncs(rpn)
640
641 // Special case a single variable with no operators
642 if len(rpn) == 1 {
643 na := rpn[0].name
644 fp.checkConv(na)
645 fp.Data.Extend(fp.workData[na])
646 fp.workData = nil
647 return true
648 }
649
650 var stack []string
651
652 for ix, tok := range rpn {
653 last := ix == len(rpn)-1
654 switch {
655 case isOperator(tok):
656 if len(stack) < 2 {
657 fp.ErrorState = fmt.Errorf("not enough arguments")
658 return false
659 }
660
661 // Pop the last two arguments off the stack
662 arg2 := stack[len(stack)-1]
663 arg1 := stack[len(stack)-2]
664 stack = stack[0 : len(stack)-2]
665
666 fp.checkConv(arg1, arg2)
667 var rslt *ColSet
668 switch tok.symbol {
669 case plus:
670 rslt = fp.doPlus(arg1, arg2)
671 case times:
672 rslt = fp.doTimes(arg1, arg2)
673 default:
674 panic("invalid symbol")
675 }
676 if last {
677 // The last thing computed is the result
678 fp.Data.Extend(rslt)
679 }
680 nm := fmt.Sprintf("tmp%d", ix)
681 fp.workData[nm] = rslt
682 stack = append(stack, nm)
683 case tok.symbol == icept:
684 q := fp.createIcept()
685 if q {
686 stack = append(stack, "icept")
687 }
688 case tok.symbol == vname:
689 fp.checkConv(tok.name)
690 stack = append(stack, tok.name)
691 case tok.symbol == funct:
692 stack = append(stack, tok.name)
693 }
694 }
695
696 if len(stack) != 1 {
697 fp.ErrorState = fmt.Errorf("invalid formula [2]")
698 return false
699 }
700
701 return true
702 }
703
704 // Next builds a design matrix based on the formula for one chunk of data..
705 func (fp *FormulaParser) Next() bool {
706
707 fp.Data = new(ColSet)
708 if !fp.RawData.Next() {
709 return false
710 }
711
712 fp.rawNames = fp.RawData.Names()
713
714 for _, rpn := range fp.rpn {
715 fp.workData = make(map[string]*ColSet)
716 fp.doFormula(rpn)
717 }
718
719 for _, na := range fp.keep {
720 fp.Data.Names = append(fp.Data.Names, na)
721 fp.Data.Data = append(fp.Data.Data, fp.RawData.Get(na))
722 }
723
724 fp.workData = nil
725
726 return true
727 }
728
729 func (fp *FormulaParser) runFuncs(rpn []*token) {
730
731 for _, tok := range rpn {
732 if tok.symbol != funct {
733 continue
734 }
735
736 f := fp.funcs[tok.funcn]
737 x := fp.getRawCol(tok.arg)
738 switch x := x.(type) {
739 case []float64:
740 fp.workData[tok.name] = f(tok.name, x)
741 default:
742 panic("funtions can only be applied to numeric data")
743 }
744 }
745 }
746
747 // Reset changes the state of the formula parser so that subsequent
748 // reads start from the beginning of the dataset.
749 func (fp *FormulaParser) Reset() {
750 fp.ErrorState = nil
751 fp.RawData.Reset()
752 }
753
754 func find(s []string, x string) int {
755 for i, v := range s {
756 if v == x {
757 return i
758 }
759 }
760 return -1
761 }