atomlookup.go raw

   1  package iskra
   2  
   3  import (
   4  	"math"
   5  )
   6  
   7  // IngestStats counts the scoring events of a lookup run.
   8  type IngestStats struct {
   9  	TriFired           int32
  10  	TriConfirmed       int32
  11  	TriSwapped         int32
  12  	TriRescued         int32
  13  	CtxSimFired        int32
  14  	CtxSimBoosted      int32
  15  	DictConfirmFired   int32
  16  	DictAuthorityFired int32
  17  }
  18  
  19  // LookupAtomLink picks the destination atom for (srcLang, srcAtom) in dstLang.
  20  // ingest_pattern.mx LookupAtomLink, including its tiers, its bilateral
  21  // consistency ratio, the context and tri-gram bonuses, and its 0.1 cutoff
  22  // against the best aggregate score inside a tier.
  23  //
  24  // The function is carried into Go with float64 scoring because the source
  25  // scores in float64; nothing here is an exact integer distance.
  26  func LookupAtomLink(idx *AtomIdx, srcLang, dstLang uint8, srcAtom, srcContext string, srcRole int32,
  27  	qArch, qDisc uint8, sigmaArch, sigmaDisc float64, stats *IngestStats) AtomLinkResult {
  28  	if idx == nil {
  29  		return AtomLinkResult{}
  30  	}
  31  	candidates := idx.FindBySrc(srcLang, srcAtom)
  32  	if len(candidates) == 0 {
  33  		return AtomLinkResult{}
  34  	}
  35  	gauss := func(rArch, rDisc uint8) float64 {
  36  		if sigmaArch <= 0 || sigmaDisc <= 0 {
  37  			return 1.0
  38  		}
  39  		da := float64(int32(rArch) - int32(qArch))
  40  		dd := float64(int32(rDisc) - int32(qDisc))
  41  		return math.Exp(-(da*da)/(sigmaArch*sigmaArch) - (dd*dd)/(sigmaDisc*sigmaDisc))
  42  	}
  43  	diversity := map[string]map[uint16]bool{}
  44  	for i := range candidates {
  45  		e := &candidates[i]
  46  		if e.DstLang != dstLang || gauss(e.RArchaic, e.RDiscourse) < diversityNearThreshold {
  47  			continue
  48  		}
  49  		coord := uint16(e.RArchaic)<<8 | uint16(e.RDiscourse)
  50  		if diversity[e.DstAtom] == nil {
  51  			diversity[e.DstAtom] = map[uint16]bool{}
  52  		}
  53  		diversity[e.DstAtom][coord] = true
  54  	}
  55  	baseScore := func(e *AtomIdxEntry) float64 {
  56  		div := float64(len(diversity[e.DstAtom]))
  57  		if div < 1 {
  58  			div = 1
  59  		}
  60  		return math.Log1p(float64(e.Weight)) * div * gauss(e.RArchaic, e.RDiscourse)
  61  	}
  62  	ctxTranslation := ""
  63  	if srcContext != "" {
  64  		var bestCtxW float64
  65  		for _, cc := range idx.FindBySrc(srcLang, srcContext) {
  66  			if cc.DstLang != dstLang {
  67  				continue
  68  			}
  69  			if w := float64(cc.Weight) * gauss(cc.RArchaic, cc.RDiscourse); w > bestCtxW {
  70  				bestCtxW = w
  71  				ctxTranslation = cc.DstAtom
  72  			}
  73  		}
  74  	}
  75  	biCheck := func(dstAtom string) float64 {
  76  		var best, src float64
  77  		for _, bc := range idx.FindBySrc(dstLang, dstAtom) {
  78  			if bc.DstLang != srcLang {
  79  				continue
  80  			}
  81  			w := float64(bc.Weight)
  82  			if w > best {
  83  				best = w
  84  			}
  85  			if bc.DstAtom == srcAtom && w > src {
  86  				src = w
  87  			}
  88  		}
  89  		if best <= 0 {
  90  			return 1.0
  91  		}
  92  		return (src + 1) / (best + 1)
  93  	}
  94  	type atomAgg struct {
  95  		best     *AtomIdxEntry
  96  		aggScore float64
  97  		tier     int
  98  	}
  99  	aggs := map[string]*atomAgg{}
 100  	var keys []string
 101  	for i := range candidates {
 102  		e := &candidates[i]
 103  		if e.DstLang != dstLang {
 104  			continue
 105  		}
 106  		ti := -1
 107  		switch e.Gen {
 108  		case GenContexted:
 109  			if e.ContextA == srcContext && int32(e.RoleA) == srcRole {
 110  				ti = 0
 111  			} else if int32(e.RoleA) == srcRole {
 112  				ti = 1
 113  			} else {
 114  				ti = 2
 115  			}
 116  		case GenLegacy:
 117  			ti = 3
 118  		}
 119  		if ti < 0 {
 120  			continue
 121  		}
 122  		key := string(rune('0'+ti)) + ":" + e.DstAtom
 123  		a := aggs[key]
 124  		if a == nil {
 125  			a = &atomAgg{tier: ti}
 126  			aggs[key] = a
 127  			keys = append(keys, key)
 128  		}
 129  		s := baseScore(e)
 130  		a.aggScore += s
 131  		if a.best == nil || s > baseScore(a.best) {
 132  			a.best = e
 133  		}
 134  	}
 135  	const topN = 8
 136  	type ranked struct {
 137  		entry    *AtomIdxEntry
 138  		aggScore float64
 139  	}
 140  	var top [5][topN]ranked
 141  	for _, key := range keys {
 142  		a := aggs[key]
 143  		slot := -1
 144  		for k := 0; k < topN; k++ {
 145  			if top[a.tier][k].entry == nil || a.aggScore > top[a.tier][k].aggScore {
 146  				slot = k
 147  				break
 148  			}
 149  		}
 150  		if slot < 0 {
 151  			continue
 152  		}
 153  		for k := topN - 1; k > slot; k-- {
 154  			top[a.tier][k] = top[a.tier][k-1]
 155  		}
 156  		top[a.tier][slot] = ranked{entry: a.best, aggScore: a.aggScore}
 157  	}
 158  	ctxMatch := func(e *AtomIdxEntry) bool { return ctxTranslation != "" && e.ContextB == ctxTranslation }
 159  	type scored struct {
 160  		entry    *AtomIdxEntry
 161  		combined float64
 162  	}
 163  	var viable []scored
 164  	for ti := 0; ti < 4; ti++ {
 165  		topAgg := 0.0
 166  		if top[ti][0].entry != nil {
 167  			topAgg = top[ti][0].aggScore
 168  		}
 169  		for k := 0; k < topN; k++ {
 170  			r := &top[ti][k]
 171  			if r.entry == nil {
 172  				continue
 173  			}
 174  			if topAgg > 0 && r.aggScore < topAgg*0.1 {
 175  				continue
 176  			}
 177  			combined := r.aggScore * (biCheck(r.entry.DstAtom) + 0.05)
 178  			if ctxMatch(r.entry) {
 179  				combined *= 1.5
 180  				if stats != nil {
 181  					stats.CtxSimFired++
 182  				}
 183  			}
 184  			viable = append(viable, scored{entry: r.entry, combined: combined})
 185  		}
 186  		if len(viable) > 0 {
 187  			break
 188  		}
 189  	}
 190  	if len(viable) >= 2 && stats != nil {
 191  		stats.TriFired++
 192  	}
 193  	var pick *AtomIdxEntry
 194  	var tier uint8
 195  	best := 0.0
 196  	for _, v := range viable {
 197  		if v.combined > best {
 198  			best = v.combined
 199  			pick = v.entry
 200  			tier = 4
 201  		}
 202  	}
 203  	if pick == nil {
 204  		return AtomLinkResult{}
 205  	}
 206  	return AtomLinkResult{
 207  		DstAtom: pick.DstAtom, DstRole: int32(pick.RoleB), DstContext: pick.ContextB,
 208  		Weight: pick.Weight, Generation: pick.Gen, Tier: tier,
 209  	}
 210  }
 211