bigram.mx raw

   1  package iskra
   2  
   3  import "git.smesh.lol/iskradb/lattice"
   4  
   5  // BigramKey constructs a 64-bit key for a segment pair (code lattice).
   6  func BigramKey(stage uint8, prev, next []byte) lattice.Key {
   7  	combined := []byte{:0:len(prev) + 1 + len(next)}
   8  	combined = append(combined, prev...)
   9  	combined = append(combined, '|')
  10  	combined = append(combined, next...)
  11  	return MakeCodeKey(stage, HashBytes(combined))
  12  }
  13  
  14  // BigramWalkKey constructs a domain-coord-scoped bigram key for lattice walks.
  15  // The key encodes (domain, coord, prev|next) so the same word pair at different
  16  // coords produces different keys - allowing context-sensitive transition weights.
  17  func BigramWalkKey(domain uint8, coord uint64, prev, next string) lattice.Key {
  18  	combined := []byte{:0:len(prev) + 1 + len(next)}
  19  	combined = append(combined, []byte(prev)...)
  20  	combined = append(combined, '|')
  21  	combined = append(combined, []byte(next)...)
  22  	return MakeKey(domain, coord, string(combined))
  23  }
  24  
  25  // BigramWeight returns the observed transition count from prev to next
  26  // at the given domain and coord. Returns 0 if the bigram has never been observed.
  27  // Bigrams are stored in Bcooccur branch.
  28  func BigramWeight(t *Tree, domain uint8, coord uint64, prev, next string) uint32 {
  29  	key := BigramWalkKey(domain, coord, prev, next)
  30  	ri := t.LookupRecIdx(lattice.Bcooccur, key)
  31  	if ri == lattice.NullRec {
  32  		return 0
  33  	}
  34  	m := t.metaGet(ri)
  35  	if m == nil {
  36  		return 0
  37  	}
  38  	return m.Count
  39  }
  40  
  41  // BigramWeightRelaxed performs the full relaxation cascade on both prev and next
  42  // context. Tries exact coord first, then relaxes coord until a non-zero weight
  43  // is found. Returns (weight, coord_that_matched). Returns (0, 0) if no bigram
  44  // exists at any relaxation level.
  45  func BigramWeightRelaxed(t *Tree, domain uint8, coord uint64, prev, next string) (uint32, uint64) {
  46  	for _, c := range RelaxCoord(coord) {
  47  		w := BigramWeight(t, domain, c, prev, next)
  48  		if w > 0 {
  49  			return w, c
  50  		}
  51  	}
  52  	return 0, 0
  53  }
  54  
  55  // IngestBigram records one observation of the (prev->next) transition at the
  56  // given domain and coord. If the bigram already exists, increments its count.
  57  // If new, inserts a record with count=1 and updates BigramIdx. Returns the record index.
  58  func IngestBigram(t *Tree, domain uint8, coord uint64, prev, next string) uint32 {
  59  	key := BigramWalkKey(domain, coord, prev, next)
  60  	ri := t.LookupRecIdx(lattice.Bcooccur, key)
  61  	if ri != lattice.NullRec {
  62  		if t.metaHas(ri) {
  63  			t.metaInc(ri)
  64  		}
  65  		return ri
  66  	}
  67  	form := prev | "|" | next
  68  	var rec lattice.Record
  69  	t.setFormOnRec(&rec, form)
  70  	rec.Branch = uint8(lattice.Bcooccur)
  71  	recIdx := t.db.InsertRec(lattice.Bcooccur, key, rec)
  72  	t.metaSet(recIdx, MetaEntry{Count: 1, StageTag: domain})
  73  	if !t.BulkMode {
  74  		if t.BigramIdx == nil {
  75  			t.BigramIdx = map[string][]uint32{}
  76  		}
  77  		t.BigramIdx[prev] = append(t.BigramIdx[prev], recIdx)
  78  	}
  79  	return recIdx
  80  }
  81  
  82  // IngestText walks a token sequence and populates bigram counts for all
  83  // adjacent pairs. coord is the base context for the sequence; individual
  84  // token coords can be refined by the caller before ingesting.
  85  func IngestText(t *Tree, domain uint8, coord uint64, tokens []string) {
  86  	if len(tokens) < 2 {
  87  		return
  88  	}
  89  	for i := 0; i < len(tokens)-1; i++ {
  90  		IngestBigram(t, domain, coord, tokens[i], tokens[i+1])
  91  	}
  92  }
  93  
  94  // RebuildBigramIdx reconstructs BigramIdx from existing Bcooccur records.
  95  // Call after loading a tree from disk to restore the secondary index.
  96  func RebuildBigramIdx(t *Tree) {
  97  	t.BigramIdx = map[string][]uint32{}
  98  	for ri := range t.RecMeta {
  99  		rec := t.db.GetRecord(uint32(ri))
 100  		if rec == nil || rec.Branch != uint8(lattice.Bcooccur) {
 101  			continue
 102  		}
 103  		if t.RecMeta[ri].Count == 0 {
 104  			continue
 105  		}
 106  		form := FormFromRecord(rec, t.StringPool)
 107  		for i := 0; i < len(form); i++ {
 108  			if form[i] == '|' {
 109  				prev := form[:i]
 110  				t.BigramIdx[prev] = append(t.BigramIdx[prev], uint32(ri))
 111  				break
 112  			}
 113  		}
 114  	}
 115  }
 116