File size: 1,505 Bytes
32d1b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Portable contextual exact decoder; no sample ID enters any computation."""
from pathlib import Path
import numpy as np


class ContextualDecoder:
    def __init__(self):
        import jax
        from context_model import probabilities
        from exact import make_decoder
        exact=make_decoder(10)
        @jax.jit
        def infer(weights,ds,context,static,base_logits,valid,masks,measured):
            p=probabilities(weights,ds,context,static,base_logits,valid)
            return exact(ds,p,masks,measured)
        self.infer=infer
        self.weights={}

    def predict(self,root,record,group_record,packed,num_detectors,batch=1024):
        import jax.numpy as jnp
        path=group_record['weights']
        if path not in self.weights:
            self.weights[path]={k:jnp.asarray(v) for k,v in dict(np.load(root/path,allow_pickle=False)).items()}
        plan=dict(np.load(root/record['contextual_plan'],allow_pickle=False))
        ds=np.unpackbits(packed,axis=1,count=num_detectors,bitorder='little')
        ds=np.pad(ds,((0,0),(0,201-num_detectors)))
        args=[plan[k] for k in ['context','static','base_logits','valid','masks','measured']]
        outputs=[]
        for begin in range(0,len(ds),batch):
            selected=ds[begin:begin+batch];n=len(selected)
            selected=np.pad(selected,((0,batch-n),(0,0)))
            outputs.append(np.asarray(self.infer(self.weights[path],selected,*args))[:n])
        return np.concatenate(outputs).astype(np.float32)