"""Deterministic integer-order and randomized Shannon entropy-rate intervals.""" from fractions import Fraction as Q import random from .arithmetic import positive_int from .numerics import log_bounds, spectral_bounds, sqrt_upper from .compiler import collision_matrix, target_mass def renyi_interval(source,depth,order,relative_precision=Q(1,10**10),max_states=500000): matrix,diagnostics=collision_matrix(source,depth,order,max_states) root=spectral_bounds(matrix,relative_precision) a=log_bounds(root["lower"])[0] b=log_bounds(root["upper"])[1] divisor=depth*(order-1) spectral_lo,spectral_hi=-b/divisor,-a/divisor split=source.split_bound(depth) error=log_bounds(source.states*split)[1]/depth # Edge alphabet size bounds the number of n-edge histories. beta_upper=source.field.embeddings(128)[3].hi ceiling=min(log_bounds(len(source.edges))[1],source.kmax*log_bounds(beta_upper)[1]) lo=max(Q(0),spectral_lo-error) hi=min(ceiling,spectral_hi) if lo>hi: raise ArithmeticError("inconsistent certified bounds") return {"order":order,"depth":depth,"interval_nats_per_branch":(lo,hi), "width":hi-lo,"spectral_proxy_interval":(spectral_lo,spectral_hi), "split_bound":split,"boundary_fibre_log_error":error, "moment_matrix":matrix,"spectral_radius":root,"diagnostics":diagnostics, "probabilistic":False,"source_stationary":source.stationary} def shannon_interval(source,depth,samples,confidence=Q(99,100),seed=None, numerical_width=Q(1,10**8),max_states=500000,rng=None): positive_int(depth,"depth");positive_int(samples,"samples") if not source.stationary: raise ValueError("the Shannon finite-block bracket requires an exactly stationary source") confidence,numerical_width=Q(confidence),Q(numerical_width) if not 0hi: # Bad concentration events can in principle create an empty intersection. # Report failure rather than inventing a valid confidence interval. return {"failure":True,"reason":"empty confidence/bound intersection","sampling_mode":mode} return {"order":1,"depth":depth,"samples":samples,"confidence":confidence, "interval_nats_per_branch":(lo,hi),"width":hi-lo, "sampling_mode":mode,"independent_exact_draws_required":True, "sampled_quantity":"H(X_n,Z_n | Z_0)/n", "surprisal_range_upper":B,"hoeffding_margin":margin, "finite_block_bias_upper":bias,"mean_surprisal_interval":(lower,upper), "maximum_fibre_layer_states":max(widths),"probabilistic":True}