Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions resource/cluster/blocks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package cluster

import (
"encoding/json"
"fmt"
"path/filepath"
"strconv"
"strings"

"github.com/tamnd/math2-agent/resource/spill"
)

// blockFiles is the number of groups of the blocks of C4. All the blocks of one author go to one group, so that a group holds a block and the block of the next year.
const blockFiles = 128

// member is one record in one block of C4.
type member struct {
Node int32 `json:"n"`
Block string `json:"b"`
R Record `json:"r"`
}

// blockSet collects the records of the blocks of C4 for the partition. Pass C4 joins two records of one block, or of the blocks of one author in two years that follow, only when their score is at or above Middle. So the partition joins only these pairs, and not all the records of a block. With a directory, the blocks go to spill files, and a group is in memory only while its pairs are scored.
type blockSet struct {
dir string
ws []*spill.Writer
mem [][]member
err error
}

func newBlockSet(dir string) *blockSet {
b := &blockSet{dir: dir}
if dir == "" {
b.mem = make([][]member, blockFiles)
}
return b
}

func (b *blockSet) file(n int) string {
return filepath.Join(b.dir, fmt.Sprintf("blocks-%04d.gz", n))
}

// add puts the record of the node in the block, in the group of the key.
func (b *blockSet) add(node int32, group, block string, r *Record) {
if b.err != nil {
return
}
n := int(keyHash(group) % blockFiles)
if b.dir == "" {
b.mem[n] = append(b.mem[n], member{Node: node, Block: block, R: *r})
return
}
if b.ws == nil {
b.ws = make([]*spill.Writer, blockFiles)
for i := range b.ws {
if b.ws[i], b.err = spill.Create(b.file(i)); b.err != nil {
return
}
}
}
b.err = b.ws[n].Write(member{Node: node, Block: block, R: *r})
}

// pairs calls fn for each pair of nodes that pass C4 can join or queue, one group at a time. It gives the hashes of the blocks with more than MaxBlock records.
func (b *blockSet) pairs(fn func(x, y int32)) (map[uint64]bool, error) {
if b.err != nil {
return nil, b.err
}
for _, w := range b.ws {
if err := w.Close(); err != nil {
return nil, err
}
}
large := map[uint64]bool{}
for n := range blockFiles {
var ms []member
if b.dir == "" {
ms, b.mem[n] = b.mem[n], nil
} else if b.ws != nil {
if err := spill.Read(b.file(n), func(line []byte) error {
var m member
ms = append(ms, m)
return json.Unmarshal(line, &ms[len(ms)-1])
}); err != nil {
return nil, err
}
}
blocks := map[string][]int{}
for i := range ms {
blocks[ms[i].Block] = append(blocks[ms[i].Block], i)
}
compare := func(xs, ys []int, same bool) {
for a, i := range xs {
start := 0
if same {
start = a + 1
}
for _, j := range ys[start:] {
if ms[i].Node != ms[j].Node && Score(&ms[i].R, &ms[j].R) >= Middle {
fn(ms[i].Node, ms[j].Node)
}
}
}
}
for k, xs := range blocks {
if len(xs) > MaxBlock {
large[keyHash(k)] = true
continue
}
compare(xs, xs, true)
if after, ok := strings.CutPrefix(k, "a:"); ok {
i := strings.LastIndexByte(after, ':')
y, _ := strconv.Atoi(after[i+1:])
if ys := blocks["a:"+after[:i]+":"+strconv.Itoa(y+1)]; len(ys) > 0 && len(ys) <= MaxBlock {
compare(xs, ys, false)
}
}
}
}
return large, nil
}
67 changes: 23 additions & 44 deletions resource/cluster/partition.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,14 @@ func keyHash(k string) uint64 {
// mark is one join key of one node. A node is a record, an existing resource, a crosswalk link or a decision of a person.
type mark struct {
key uint64
next uint64 // of a block of an author: the block of the next year
node int32
kind uint8
}

const (
join uint8 = iota // a key that joins all the nodes that have it
weak // an id that joins its nodes only when a crosswalk or a translation_of edge names it
need // a crosswalk or a translation_of edge that names an id
block // a block of C4
join uint8 = iota // a key that joins all the nodes that have it
weak // an id that joins its nodes only when a crosswalk or a translation_of edge names it
need // a crosswalk or a translation_of edge that names an id
)

// joinSystem reports whether a shared value of the system can join two records in a pass: a strong id of C1, an ISBN of C3, an Open Library work id of C5 or an id that puts a filler on a group.
Expand All @@ -53,8 +51,10 @@ type Partition struct {

// partitioner collects the join keys of the nodes of a run. A node is a record, an existing resource, a crosswalk link or a decision of a person.
type partitioner struct {
ms []mark
nodes int32
ms []mark
nodes int32
blocks *blockSet
edges [][2]int32 // the pairs of C4 that can join or go to the queue
}

func (pt *partitioner) next() int32 {
Expand Down Expand Up @@ -84,11 +84,11 @@ func (pt *partitioner) record(r *Record) int32 {
}
fs := families(r)
if len(fs) > 0 && r.Year() > 0 {
a := "a:" + fs[0] + ":"
pt.ms = append(pt.ms, mark{key: keyHash(a + strconv.Itoa(r.Year())), next: keyHash(a + strconv.Itoa(r.Year()+1)), node: n, kind: block})
pt.blocks.add(n, "a:"+fs[0], "a:"+fs[0]+":"+strconv.Itoa(r.Year()), r)
}
if r.Venue != "" && r.Volume != "" && r.Page != "" {
pt.add("v:"+r.Venue+":"+r.Volume+":"+r.Page, n, block)
k := "v:" + r.Venue + ":" + r.Volume + ":" + r.Page
pt.blocks.add(n, k, k, r)
}
if t := WorkTitle(r.Title); len([]rune(t)) >= 12 && len(fs) > 0 {
pt.add("w:"+t+"|"+fs[0], n, join)
Expand Down Expand Up @@ -134,7 +134,11 @@ func (pt *partitioner) decision(d Decision) int32 {
}

// buckets joins the nodes into components and packs the components of the records into buckets of about size records, in the order of the records. It gives the bucket of each node, -1 for a node whose component has no record, and the partition with no Bucket.
func (pt *partitioner) buckets(records []int32, size int) ([]int32, *Partition) {
func (pt *partitioner) buckets(records []int32, size int) ([]int32, *Partition, error) {
large, err := pt.blocks.pairs(func(x, y int32) { pt.edges = append(pt.edges, [2]int32{x, y}) })
if err != nil {
return nil, nil, err
}
ms := pt.ms
slices.SortFunc(ms, func(a, b mark) int {
return cmp.Or(cmp.Compare(a.key, b.key), cmp.Compare(a.kind, b.kind), cmp.Compare(a.node, b.node))
Expand All @@ -155,48 +159,23 @@ func (pt *partitioner) buckets(records []int32, size int) ([]int32, *Partition)
parent[max(x, y)] = min(x, y)
}
}
p := &Partition{Large: map[uint64]bool{}}
blocks := map[uint64][]int32{}
p := &Partition{Large: large}
for i := 0; i < len(ms); {
j := i
for j < len(ms) && ms[j].key == ms[i].key {
j++
}
run := ms[i:j]
switch {
case run[0].kind == block:
// A block of C4 counts records, and a record is in a block once.
var recs []int32
for _, m := range run {
if len(recs) == 0 || recs[len(recs)-1] != m.node {
recs = append(recs, m.node)
}
}
if len(recs) > MaxBlock {
p.Large[run[0].key] = true
} else {
blocks[run[0].key] = recs
}
case slices.ContainsFunc(run, func(m mark) bool { return m.kind != weak }):
if run := ms[i:j]; slices.ContainsFunc(run, func(m mark) bool { return m.kind != weak }) {
for _, m := range run[1:] {
union(run[0].node, m.node)
}
}
i = j
}
for _, recs := range blocks {
for _, n := range recs[1:] {
union(recs[0], n)
}
}
for _, m := range ms {
if m.kind == block && m.next != 0 && blocks[m.key] != nil {
if next, ok := blocks[m.next]; ok {
union(m.node, next[0])
}
}
for _, e := range pt.edges {
union(e[0], e[1])
}
pt.ms = nil
pt.ms, pt.edges = nil, nil

count := map[int32]int{}
for _, n := range records {
Expand Down Expand Up @@ -228,12 +207,12 @@ func (pt *partitioner) buckets(records []int32, size int) ([]int32, *Partition)
}
out[i] = b
}
return out, p
return out, p, nil
}

// Partitioned gives the partition of the records of in into buckets of about size records.
func Partitioned(in Input, size int) *Partition {
var pt partitioner
pt := partitioner{blocks: newBlockSet("")}
recs := make([]int32, len(in.Records))
for i := range in.Records {
recs[i] = pt.record(&in.Records[i])
Expand All @@ -249,7 +228,7 @@ func Partitioned(in Input, size int) *Partition {
for _, d := range in.Decisions {
pt.decision(d)
}
of, p := pt.buckets(recs, size)
of, p, _ := pt.buckets(recs, size) // the blocks are in memory, so there is no error
at := func(ns []int32) []int {
out := make([]int, len(ns))
for i, n := range ns {
Expand Down
29 changes: 29 additions & 0 deletions resource/cluster/partition_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,32 @@ func TestPartitionLargeBlock(t *testing.T) {
t.Fatalf("buckets = %d, want 5", p.Buckets)
}
}

// The records of one block of C4 with low scores stay in separate components, and a pair with a high score is one component, in memory and with spill files.
func TestPartitionBlockPairs(t *testing.T) {
in := Input{Records: []Record{
{Source: "crossref", NativeID: "a", Kind: "article", Title: "Spectral gaps for random regular graphs", Creators: author("Ann Smith"), Date: "2000"},
{Source: "openalex", NativeID: "W1", Kind: "article", Title: "Spectral gaps for random regular graphs", Creators: author("Ann Smith"), Date: "2001"},
{Source: "crossref", NativeID: "b", Kind: "article", Title: "The cohomology of finite groups of Lie type", Creators: author("Ann Smith"), Date: "2000"},
{Source: "crossref", NativeID: "c", Kind: "article", Title: "Boundary layers in viscous fluids", Creators: author("Ann Smith"), Date: "2001"},
}}
p := Partitioned(in, 1)
if p.Components != 3 || p.Largest != 2 {
t.Fatalf("components = %d, largest = %d, want 3 and 2", p.Components, p.Largest)
}
if p.Bucket[0] != p.Bucket[1] || p.Bucket[0] == p.Bucket[2] || p.Bucket[2] == p.Bucket[3] {
t.Fatalf("buckets = %v", p.Bucket)
}
pt := partitioner{blocks: newBlockSet(t.TempDir())}
var recs []int32
for i := range in.Records {
recs = append(recs, pt.record(&in.Records[i]))
}
_, q, err := pt.buckets(recs, 1)
if err != nil {
t.Fatal(err)
}
if q.Components != 3 || q.Largest != 2 {
t.Fatalf("with spill files: components = %d, largest = %d, want 3 and 2", q.Components, q.Largest)
}
}
7 changes: 5 additions & 2 deletions resource/cluster/stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func RunFiles(in Input, files []string, tmp string, size int, root string, log i
name := func(kind string, n int) string { return filepath.Join(dir, fmt.Sprintf("%s-%04d.gz", kind, n)) }

// The keys of the nodes, and the partition.
var pt partitioner
pt := partitioner{blocks: newBlockSet(dir)}
exist := make([]int32, len(in.Existing))
for i := range in.Existing {
exist[i] = pt.resource(&in.Existing[i])
Expand All @@ -59,7 +59,10 @@ func RunFiles(in Input, files []string, tmp string, size int, root string, log i
recs = append(recs, pt.record(&rs[i]))
}
}
of, p := pt.buckets(recs, size)
of, p, err := pt.buckets(recs, size)
if err != nil {
return nil, err
}
st := &Stream{Records: len(recs), Joins: map[string]int{}, Skipped: len(p.Large), Partition: p}
_, _ = fmt.Fprintf(log, "cluster: %d records in %d buckets, %d components, the largest with %d records\n", len(recs), p.Buckets, p.Components, p.Largest)

Expand Down
Loading