"""Lectura por rangos explícitos; no mapea el archivo residual completo."""
import os
import numpy as np

class ResidualReader:
 def __init__(self,path,n,width=768):
  self.n=int(n);self.width=int(width);self.path=path
  assert os.stat(path).st_size==self.n*self.width*2
  self.stream=open(path,'rb',buffering=0)
 def __len__(self):return self.n
 def read(self,start,end):
  start=int(start);end=int(end)
  assert 0<=start<=end<=self.n
  count=(end-start)*self.width*2
  self.stream.seek(start*self.width*2)
  buf=bytearray(count);view=memoryview(buf);pos=0
  while pos<count:
   got=self.stream.readinto(view[pos:])
   if not got:raise EOFError(f'Lectura incompleta {self.path}: {pos}/{count}')
   pos+=got
  view.release()
  return np.frombuffer(buf,dtype='<f2').reshape(end-start,self.width)
 def close(self):self.stream.close()
