R/finite.R

Defines functions finite_skolem_hull check_finite_embedding prewellorder_ranks finite_ultraproduct verify_finite_strategy solve_finite_game .game boolean_truth check_finite_generic compatible_conditions .poset finite_poset partition_relation_holds homogeneous_subset .combinations tree_branches .leaves .children .tree finite_tree transitive_collapse analyze_relation .analyze .edges evaluate_formula .structure finite_structure .sorted_rows .key .object .budget .domain analyze_finite_ideal laver_table difference_layers

Documented in analyze_finite_ideal analyze_relation boolean_truth check_finite_embedding check_finite_generic compatible_conditions difference_layers evaluate_formula finite_poset finite_skolem_hull finite_structure finite_tree finite_ultraproduct homogeneous_subset laver_table partition_relation_holds prewellorder_ranks solve_finite_game transitive_collapse tree_branches verify_finite_strategy

# Exact finite algorithms. Labels are strings; index conventions are language-neutral.
difference_layers <- function(domain,layers,max_steps=100000L) {
  dom <- .domain(domain)
  .require(is.list(layers),"Layers must be a concrete sequence")
  .require(max(1L,length(dom))*(length(layers)+1L)<=.budget(max_steps),"Difference-layer budget exceeded","RESOURCE_LIMIT")
  previous <- dom; sets <- list()
  for(layer in layers) {
    current <- .domain(layer)
    .require(all(current %in% previous),"Layers must be decreasing subsets of the domain")
    sets[[length(sets)+1L]] <- current; previous <- current
  }
  rows <- list(); members <- character()
  for(point in dom) {
    index <- length(sets)
    for(i in seq_along(sets)) if(!point %in% sets[[i]]) { index <- i-1L; break }
    selected <- (index %% 2L)==1L
    rows[[length(rows)+1L]] <- list(point=point,index=index,selected=selected)
    if(selected) members <- c(members,point)
  }
  .result("ESTABLISHED","FINITE_EXACT","decreasing_first_exit_odd",
    witness=list(members=.array(members),first_exit=rows,length=length(sets)),
    limitations="Finite alternating differences only; no infinite pointclass membership is certified.")
}

laver_table <- function(n,max_steps=1000000L) {
  .require(is.numeric(n) && length(n)==1L && is.finite(n) && n==floor(n) && n>=0L && n<=7L,
    "Laver table index must be an integer between 0 and 7")
  size <- 2^n
  .require(size^3+size^2<=.budget(max_steps),"Laver table budget exceeded","RESOURCE_LIMIT")
  table <- matrix(0L,nrow=size,ncol=size)
  table[size,] <- seq_len(size)
  if(size>1L) for(a in seq.int(size-1L,1L)) {
    table[a,1L] <- a+1L
    for(b in seq.int(2L,size)) table[a,b] <- table[table[a,b-1L],a+1L]
  }
  for(a in seq_len(size)) for(b in seq_len(size))
    if(any(table[a,table[b,]] != table[table[a,b],table[a,]])) stop("Internal Laver table law check failed")
  .result("ESTABLISHED","FINITE_EXACT",list(laver_table_order=n,size=size),
    witness=list(table=lapply(seq_len(size),function(a) .array(table[a,])),left_distributive=TRUE,
      triples_checked=size^3,first_column_successor_mod_size=TRUE),
    limitations="This finite algebra is not an elementary rank embedding and proves no large-cardinal existence or infinite freeness assertion.")
}

analyze_finite_ideal <- function(domain,members,max_steps=100000L) {
  dom <- .domain(domain,16L)
  .require(is.list(members),"Ideal members must be a concrete finite table")
  size <- length(members)
  .require(size*size+size*length(dom)<=.budget(max_steps),"Ideal table budget exceeded","RESOURCE_LIMIT")
  family <- list(); keys <- character()
  for(row in members) {
    subset <- .domain(row,16L)
    .require(all(subset %in% dom),"Ideal member is outside the domain")
    key <- .key(subset); .require(!key %in% keys,"Duplicate ideal member")
    family[[length(family)+1L]] <- subset; keys <- c(keys,key)
  }
  family <- .sorted_rows(family)
  family <- family[order(lengths(family),method="radix")]
  violation <- NULL
  if(!.key(character()) %in% keys) violation <- list(law="empty_set",sets=list(list()))
  else if(.key(dom) %in% keys) violation <- list(law="proper",sets=list(.array(dom)))
  else {
    for(subset in family) {
      for(x in subset) {
        missing <- setdiff(subset,x)
        if(!.key(missing) %in% keys) {
          violation <- list(law="downward_closed",sets=list(.array(subset),.array(missing))); break
        }
      }
      if(!is.null(violation)) break
    }
    if(is.null(violation)) for(left in family) {
      for(right in family) {
        combined <- sort(union(left,right),method="radix")
        if(!.key(combined) %in% keys) {
          violation <- list(law="union_closed",sets=list(.array(left),.array(right),.array(combined))); break
        }
      }
      if(!is.null(violation)) break
    }
  }
  witness <- list(violation=violation)
  if(is.null(violation)) {
    support <- sort(unique(as.character(unlist(family,use.names=FALSE))),method="radix")
    atoms <- setdiff(dom,support)
    witness <- c(witness,list(principal_support=.array(support),quotient_atoms=.array(atoms),
      quotient_cardinality=as.character(2^length(atoms)),least_saturation=as.character(length(atoms)+1L),
      complete=TRUE,equivalence_test="equal_intersection_with_quotient_atoms"))
  }
  .result(if(is.null(violation)) "ESTABLISHED" else "REFUTED","FINITE_EXACT",
    "finite_proper_ideal_and_quotient",witness=witness,
    limitations="Every finite ideal is principal. Finite quotient properties do not witness infinite saturated ideals or large cardinals.")
}

.domain <- function(values, max_size=1000L) {
  .budget(max_size)
  .require(length(values)<=max_size,"Finite domain limit exceeded","RESOURCE_LIMIT")
  .require((is.list(values) || is.character(values)) && all(vapply(as.list(values),function(x) .scalar_string(x) && nzchar(x),logical(1))),"Domain labels must be nonempty strings")
  vals <- unlist(values,use.names=FALSE)
  .require(length(vals)<=max_size,"Finite domain limit exceeded","RESOURCE_LIMIT")
  .require(!length(vals) || (is.character(vals) && !anyNA(vals) && all(nzchar(vals))),"Domain labels must be nonempty strings")
  .require(!anyDuplicated(vals),"Duplicate domain labels")
  sort(as.character(vals),method="radix")
}
.budget <- function(x) {
  .require(is.numeric(x) && length(x)==1L && is.finite(x) && x==floor(x) && x>0 && x<=10000000,"Budget must be an integer between 1 and 10000000"); x
}
.object <- function() setNames(list(),character())
.key <- function(x) as.character(jsonlite::toJSON(.array(x),auto_unbox=TRUE))
.sorted_rows <- function(rows) {
  if(!length(rows)) return(list())
  width <- max(lengths(rows))
  if(width==0L) return(rows)
  columns <- lapply(seq_len(width),function(i) vapply(rows,function(r) if(length(r)>=i) r[[i]] else "",character(1)))
  rows[do.call(order,c(columns,list(method="radix")))]
}
finite_structure <- function(domain, relations=list(), constants=list(), max_size=1000L) {
  domain <- .domain(domain,max_size); .require(length(domain)>0L,"First-order structures require a nonempty domain")
  .require(is.list(relations) && (!length(relations) || (!is.null(names(relations)) && !anyDuplicated(names(relations)))),"Expected named relation tables")
  tables <- .object()
  for(name in names(relations)) {
    item <- relations[[name]]
    .require(.fields(item,c("arity","tuples")),"Relations require arity and tuples")
    arity <- item$arity
    .require(is.numeric(arity) && length(arity)==1L && !is.na(arity) && arity==floor(arity) && arity>=0L && arity<=8L,"Invalid relation arity")
    rows <- lapply(item$tuples,function(x) {
      .require((is.list(x) || is.character(x)) && all(vapply(as.list(x),.scalar_string,logical(1))),"Relation tuples require string labels")
      .array(unlist(x,use.names=FALSE))
    })
    .require(length(rows)<=100000L,"Relation table limit exceeded","RESOURCE_LIMIT")
    .require(all(vapply(rows,function(x) length(x)==arity && all(unlist(x)%in%domain),logical(1))),"Relation tuple is outside its domain/arity")
    .require(!anyDuplicated(vapply(rows,.key,character(1))),"Duplicate relation tuple")
    if(name=="in") .require(arity==2L,"Membership must be binary")
    tables[[name]] <- list(arity=arity,tuples=.sorted_rows(rows))
  }
  if(!length(constants)) constants <- .object()
  .require(is.list(constants) && (!length(constants) || (!is.null(names(constants)) && !anyDuplicated(names(constants)))) &&
    all(vapply(constants,function(x) .scalar_string(x) && x %in% domain,logical(1))),"Invalid constant interpretation")
  list(type="finite_structure",domain=.array(domain),relations=tables,constants=constants)
}
.structure <- function(x) {
  .require(is.list(x) && identical(x$type,"finite_structure"),"Expected a finite structure")
  finite_structure(x$domain,x$relations,x$constants)
}
evaluate_formula <- function(expr, structure, assignment=list(), max_steps=100000L) {
  .require(inherits(expr,"lc_expression") && expr$sort=="formula","Expected a formula")
  model <- .structure(structure); dom <- unlist(model$domain,use.names=FALSE)
  if(!length(assignment)) assignment <- .object()
  .require(all(unlist(assignment,use.names=FALSE)%in%dom),"Assignment outside the finite domain")
  .require(all(free_variables(expr)%in%names(assignment)),"Missing free-variable assignment")
  for(node in .walk(expr)) {
    .require(node$sort%in%c("formula","set"),"Finite relational evaluator supports only set-sorted terms","UNSUPPORTED")
    if(node$op%in%c("pred","in")) {
      key <- if(node$op=="in") "in" else node$name
      .require(key%in%names(model$relations) && model$relations[[key]]$arity==length(node$args),"Missing relation or inconsistent predicate arity")
    }
    if(node$op=="const") .require(node$name%in%names(model$constants),"Missing constant interpretation")
  }
  remaining <- .budget(max_steps)
  term <- function(e,env) if(e$op=="var") env[[e$name]] else model$constants[[e$name]]
  rec <- function(e,env) {
    remaining <<- remaining-1L; .require(remaining>=0L,"Finite evaluation step limit exceeded","RESOURCE_LIMIT")
    op <- e$op; args <- e$args
    if(op=="eq") return(identical(term(args[[1L]],env),term(args[[2L]],env)))
    if(op%in%c("pred","in")) {
      key <- if(op=="in") "in" else e$name
      row <- lapply(args,term,env=env)
      return(.key(row)%in%vapply(model$relations[[key]]$tuples,.key,character(1)))
    }
    if(op=="not") return(!rec(args[[1L]],env))
    if(op=="and") { for(a in args) if(!rec(a,env)) return(FALSE); return(TRUE) }
    if(op=="or") { for(a in args) if(rec(a,env)) return(TRUE); return(FALSE) }
    if(op=="implies") return(!rec(args[[1L]],env) || rec(args[[2L]],env))
    if(op=="iff") return(identical(rec(args[[1L]],env),rec(args[[2L]],env)))
    bound <- args[[1L]]; body <- args[[2L]]
    for(x in dom) {
      nextenv <- env; nextenv[[bound$name]] <- x; v <- rec(body,nextenv)
      if(op=="forall" && !v) return(FALSE)
      if(op=="exists" && v) return(TRUE)
    }
    op=="forall"
  }
  truth <- rec(expr,assignment)
  .result(if(truth) "ESTABLISHED" else "REFUTED","FINITE_EXACT",expr,
          witness=list(truth=truth,assignment=assignment,domain=model$domain),
          limitations="Only this finite structure is evaluated; it is not asserted to model ZF.")
}
.edges <- function(domain,pairs) {
  rows <- lapply(pairs,function(x) {
    .require((is.list(x) || is.character(x)) && all(vapply(as.list(x),.scalar_string,logical(1))),"Relation pairs require string labels")
    as.character(unlist(x,use.names=FALSE))
  })
  .require(all(vapply(rows,function(x) length(x)==2L && all(x%in%domain),logical(1))),"Invalid relation pair")
  .require(!anyDuplicated(vapply(rows,.key,character(1))),"Duplicate relation pair")
  rows
}
.analyze <- function(domain,pairs,max_steps=1000000L) {
  dom <- .domain(domain,100L); .require(length(dom)^3<=.budget(max_steps),"Relation analysis budget exceeded","RESOURCE_LIMIT")
  rel <- .edges(dom,pairs); keys <- vapply(rel,.key,character(1)); has <- function(x,y) .key(c(x,y))%in%keys
  reflexive <- all(vapply(dom,function(x) has(x,x),logical(1)))
  irreflexive <- all(vapply(dom,function(x) !has(x,x),logical(1)))
  transitive <- TRUE
  successors <- setNames(lapply(dom,function(y) dom[vapply(dom,function(z) has(y,z),logical(1))]),dom)
  for(a in rel) for(z in successors[[a[[2L]]]]) if(!has(a[[1L]],z)) transitive <- FALSE
  antisymmetric <- all(vapply(rel,function(x) x[[1L]]==x[[2L]] || !has(x[[2L]],x[[1L]]),logical(1)))
  total <- TRUE
  for(x in dom) for(y in dom) if(x!=y && !has(x,y) && !has(y,x)) total <- FALSE
  remaining <- dom; ranks <- .object()
  while(length(remaining)) {
    minimal <- remaining[vapply(remaining,function(x) !any(vapply(remaining,function(y) has(y,x),logical(1))),logical(1))]
    if(!length(minimal)) break
    for(x in minimal) {
      preds <- dom[vapply(dom,function(y) has(y,x),logical(1))]
      ranks[[x]] <- if(length(preds)) max(unlist(ranks[preds]))+1L else 0L
    }
    remaining <- setdiff(remaining,minimal)
  }
  list(reflexive=reflexive,irreflexive=irreflexive,transitive=transitive,antisymmetric=antisymmetric,total=total,
       well_founded=!length(remaining),ranks=if(!length(remaining)) ranks else NULL)
}
analyze_relation <- function(domain,pairs,max_steps=1000000L) {
  .result("ESTABLISHED","FINITE_EXACT","finite_relation_properties",witness=.analyze(domain,pairs,max_steps),
          limitations="Properties refer only to the finite input relation.")
}
transitive_collapse <- function(domain,pairs,max_steps=1000000L) {
  dom <- .domain(domain,100L); rel <- .edges(dom,pairs); keys <- vapply(rel,.key,character(1)); report <- .analyze(dom,pairs,max_steps)
  .require(report$well_founded,"Collapse requires a well-founded relation")
  predecessors <- setNames(lapply(dom,function(x) dom[vapply(dom,function(y) .key(c(y,x))%in%keys,logical(1))]),dom)
  .require(!anyDuplicated(vapply(predecessors,.key,character(1))),"Collapse requires extensionality")
  values <- .object(); remaining <- .budget(max_steps)
  for(x in dom[order(unlist(report$ranks[dom]),dom,method="radix")]) {
    preds <- predecessors[[x]]
    if(length(preds)) preds <- preds[order(vapply(values[preds],serialize,character(1)),method="radix")]
    values[[x]] <- unname(values[preds])
    remaining <- remaining-nchar(serialize(values[[x]])); .require(remaining>=0L,"Expanded collapse output limit exceeded","RESOURCE_LIMIT")
  }
  .result("ESTABLISHED","FINITE_EXACT","finite_transitive_collapse",witness=values,
          limitations="Nested arrays denote unordered finite sets in canonical construction order.")
}
finite_tree <- function(paths,max_nodes=10000L) {
  .budget(max_nodes); nodes <- list(list()); keys <- "[]"
  .require(is.list(paths),"Tree paths must be a concrete finite sequence")
  .require(length(paths)<=max_nodes,"Tree input limit exceeded","RESOURCE_LIMIT")
  for(path in paths) {
    .require(is.list(path) || is.character(path),"A path must be a concrete sequence of labels")
    path <- unlist(path,use.names=FALSE)
    .require(length(path)<=100L && (!length(path) || (is.character(path) && !anyNA(path) && all(nzchar(path)))),"Invalid tree path")
    for(i in seq.int(0L,length(path))) {
      prefix <- .array(path[seq_len(i)]); key <- .key(prefix)
      if(!key%in%keys) { nodes[[length(nodes)+1L]] <- prefix; keys <- c(keys,key) }
    }
    .require(length(nodes)<=max_nodes,"Tree node limit exceeded","RESOURCE_LIMIT")
  }
  nodes <- .sorted_rows(nodes)
  nodes <- nodes[order(lengths(nodes),method="radix")]
  list(type="finite_tree",nodes=unname(nodes))
}
.tree <- function(tree) {
  .require(is.list(tree) && identical(tree$type,"finite_tree"),"Expected a finite tree")
  expected <- finite_tree(tree$nodes)
  .require(identical(serialize(expected),serialize(tree)),"Tree must be canonical and prefix closed")
  tree$nodes
}
.children <- function(nodes,path) Filter(function(y) length(y)==length(path)+1L && identical(y[seq_len(length(path))],path),nodes)
.leaves <- function(nodes) Filter(function(x) !length(.children(nodes,x)),nodes)
tree_branches <- function(tree) {
  .result("ESTABLISHED","FINITE_EXACT","maximal_finite_branches",witness=.leaves(.tree(tree)),
          limitations="All branches in this object are finite.")
}
.combinations <- function(x,k) {
  if(k==0L) return(list(character()))
  if(k>length(x)) return(list())
  combn(x,k,simplify=FALSE)
}
homogeneous_subset <- function(vertices,arity,coloring,target_size,max_steps=100000L) {
  dom <- .domain(vertices,30L)
  .require(is.numeric(arity) && length(arity)==1L && arity==floor(arity) && arity>=1L && arity<=length(dom),"Invalid arity")
  .require(is.numeric(target_size) && length(target_size)==1L && target_size==floor(target_size) && target_size>=arity && target_size<=length(dom),"Invalid target size")
  .require(choose(length(dom),arity)+choose(length(dom),target_size)*choose(target_size,arity)<=.budget(max_steps),"Homogeneity search limit exceeded","RESOURCE_LIMIT")
  .require(is.list(coloring),"Coloring must be a concrete finite table")
  .require(length(coloring)==choose(length(dom),arity),"Coloring must cover every subset of the specified arity")
  needed <- vapply(.combinations(dom,arity),.key,character(1)); table <- .object()
  for(row in coloring) {
    .require(.fields(row,c("subset","color")),"Invalid coloring entry")
    .require((is.list(row$subset) || is.character(row$subset)) && all(vapply(as.list(row$subset),.scalar_string,logical(1))),"Expected a subset of domain labels")
    key <- .key(sort(unlist(row$subset),method="radix"))
    .require(key%in%needed && !key%in%names(table) && .scalar_string(row$color),"Invalid/duplicate color assignment")
    table[[key]] <- row$color
  }
  .require(setequal(names(table),needed),"Coloring must cover every subset of the specified arity")
  witness <- NULL
  for(h in .combinations(dom,target_size)) {
    keys <- vapply(.combinations(h,arity),.key,character(1))
    if(length(unique(unlist(table[keys])))==1L) { witness <- .array(h); break }
  }
  .result(if(!is.null(witness)) "ESTABLISHED" else "REFUTED","FINITE_EXACT","finite_homogeneous_subset",witness=witness,
          limitations="This is one finite coloring, not an infinite partition relation.")
}
partition_relation_holds <- function(n,target,arity=2L,colors=2L,max_cases=100000L) {
  .require(all(vapply(list(n,target,arity,colors),function(x) is.numeric(x) && length(x)==1L,logical(1))),"Expected integer parameters")
  pars <- c(n,target,arity,colors)
  .require(is.numeric(pars) && length(pars)==4L && !anyNA(pars) && all(is.finite(pars)) && all(pars==floor(pars)),"Expected integer parameters")
  .require(arity>=1L && target>=arity && n>=target && n<=20L && colors>=1L && colors<=10L,"Invalid finite partition parameters")
  budget <- .budget(max_cases); exponent <- choose(n,arity)
  .require(exponent<=1000L,"Coloring dimension exceeds limit","RESOURCE_LIMIT")
  count <- colors^exponent
  .require(is.finite(count) && count*max(1,choose(n,target))*choose(target,arity)<=budget,"Exhaustive coloring budget exceeded","RESOURCE_LIMIT")
  edges <- .combinations(seq.int(0L,n-1L),arity); keys <- vapply(edges,.key,character(1))
  targets <- lapply(.combinations(seq.int(0L,n-1L),target),function(h) match(vapply(.combinations(h,arity),.key,character(1)),keys))
  claim <- list(n=n,target=target,arity=arity,colors=colors)
  for(index in seq.int(0,count-1)) {
    values <- numeric(exponent); residue <- index
    for(i in rev(seq_len(exponent))) { values[[i]] <- residue%%colors; residue <- floor(residue/colors) }
    if(!any(vapply(targets,function(h) length(unique(values[h]))==1L,logical(1)))) {
      witness <- lapply(seq_along(edges),function(i) list(subset=.array(edges[[i]]),color=values[[i]]))
      return(.result("REFUTED","FINITE_EXACT",claim,witness=witness,limitations="The counterexample refutes only the specified finite relation."))
    }
  }
  .result("ESTABLISHED","FINITE_EXACT",claim,witness=list(colorings_checked=count),limitations="Exhaustive finite check; no large-cardinal existence conclusion.")
}
finite_poset <- function(domain,order) {
  dom <- .domain(domain,100L); report <- .analyze(dom,order)
  .require(report$reflexive && report$antisymmetric && report$transitive,"Order is not a partial order")
  list(type="finite_poset",domain=.array(dom),order=lapply(.sorted_rows(.edges(dom,order)),.array),convention="smaller_is_stronger")
}
.poset <- function(poset) {
  .require(is.list(poset) && identical(poset$type,"finite_poset"),"Expected a finite poset")
  expected <- finite_poset(poset$domain,poset$order)
  .require(identical(serialize(expected),serialize(poset)),"Invalid finite poset record"); expected
}
compatible_conditions <- function(poset,left,right) {
  p <- .poset(poset); dom <- unlist(p$domain); keys <- vapply(p$order,.key,character(1))
  .require(left%in%dom && right%in%dom,"Unknown condition")
  witness <- dom[vapply(dom,function(x) .key(c(x,left))%in%keys && .key(c(x,right))%in%keys,logical(1))]
  .result(if(length(witness)) "ESTABLISHED" else "REFUTED","FINITE_EXACT","finite_compatibility",witness=.array(witness),limitations="Compatibility in the supplied finite partial order only.")
}
check_finite_generic <- function(poset,filter_members,dense_sets) {
  p <- .poset(poset); dom <- unlist(p$domain); keys <- vapply(p$order,.key,character(1)); has <- function(x,y) .key(c(x,y))%in%keys
  f <- .domain(filter_members,100L); .require(all(f%in%dom),"Filter contains an unknown condition")
  dense <- lapply(dense_sets,.domain,max_size=100L)
  .require(all(vapply(dense,function(d) all(d%in%dom),logical(1))),"Dense set outside poset")
  .require(all(vapply(dense,function(d) all(vapply(dom,function(x) any(vapply(d,function(q) has(q,x),logical(1))),logical(1))),logical(1))),"A supplied set is not dense")
  upward <- TRUE; directed <- TRUE
  for(x in f) {
    for(q in dom) if(has(x,q) && !q%in%f) upward <- FALSE
    for(y in f) if(!any(vapply(f,function(z) has(z,x) && has(z,y),logical(1)))) directed <- FALSE
  }
  meets <- vapply(dense,function(d) length(intersect(f,d))>0L,logical(1))
  truth <- length(f)>0L && upward && directed && all(meets)
  .result(if(truth) "ESTABLISHED" else "REFUTED","FINITE_EXACT","finite_family_genericity",
    witness=list(nonempty=length(f)>0L,upward_closed=upward,directed=directed,meets_dense_sets=.array(meets)),
    limitations="Only the supplied finite dense family is checked; no generic extension of V is constructed.")
}
boolean_truth <- function(expr,atoms,valuation) {
  universe <- .domain(atoms,1000L)
  for(node in .walk(expr)) {
    .require(node$op%in%c("pred","not","and","or","implies","iff"),"Only propositional formulas are supported","UNSUPPORTED")
    if(node$op=="pred") {
      .require(!length(node$args) && node$name%in%names(valuation),"Missing propositional valuation")
      .require(all(unlist(valuation[[node$name]])%in%universe),"Boolean value outside the atom set")
    }
  }
  rec <- function(e) {
    if(e$op=="pred") return(unlist(valuation[[e$name]],use.names=FALSE))
    vals <- lapply(e$args,rec)
    if(e$op=="not") return(setdiff(universe,vals[[1L]]))
    if(e$op=="and") return(Reduce(intersect,vals,init=universe))
    if(e$op=="or") return(Reduce(union,vals,init=character()))
    if(e$op=="implies") return(union(setdiff(universe,vals[[1L]]),vals[[2L]]))
    union(intersect(vals[[1L]],vals[[2L]]),setdiff(universe,union(vals[[1L]],vals[[2L]])))
  }
  .result("ESTABLISHED","FINITE_EXACT","finite_boolean_value",witness=.array(sort(as.character(rec(expr)),method="radix")),
          limitations="A Boolean value is returned, not a forcing theorem for an infinite universe.")
}
.game <- function(tree,payoffs) {
  nodes <- .tree(tree); leaves <- vapply(.leaves(nodes),.key,character(1)); outcomes <- .object()
  for(row in payoffs) {
    .require(.fields(row,c("path","winner")),"Invalid terminal payoff")
    key <- .key(row$path)
    .require(key%in%leaves && !key%in%names(outcomes) && is.numeric(row$winner) && length(row$winner)==1L && row$winner%in%c(0L,1L),"Invalid/duplicate terminal payoff")
    outcomes[[key]] <- row$winner
  }
  .require(setequal(names(outcomes),leaves),"Every terminal path needs a winner")
  list(nodes=nodes,outcomes=outcomes)
}
solve_finite_game <- function(tree,payoffs) {
  g <- .game(tree,payoffs); nodes <- g$nodes; win <- g$outcomes; choice <- .object()
  for(path in nodes[order(-lengths(nodes),vapply(nodes,.key,character(1)),method="radix")]) {
    children <- .children(nodes,path)
    if(length(children)) {
      player <- length(path)%%2L
      successful <- Filter(function(x) win[[.key(x)]]==player,children)
      selected <- if(length(successful)) successful[[1L]] else children[[1L]]
      win[[.key(path)]] <- win[[.key(selected)]]; choice[[.key(path)]] <- selected[[length(selected)]]
    }
  }
  winner <- win[["[]"]]; strategy <- list()
  visit <- function(path) {
    children <- .children(nodes,path); if(!length(children)) return(invisible(NULL))
    if(length(path)%%2L==winner) {
      move <- choice[[.key(path)]]; strategy[[length(strategy)+1L]] <<- list(path=path,move=move)
      visit(c(path,list(move)))
    } else for(child in children) visit(child)
  }
  visit(list())
  .result("ESTABLISHED","FINITE_EXACT","finite_game_solution",witness=list(winner=winner,strategy=strategy),limitations="Only this finite game is solved; AD is not asserted.")
}
verify_finite_strategy <- function(tree,payoffs,winner,strategy) {
  g <- .game(tree,payoffs); nodes <- g$nodes; outcomes <- g$outcomes; keys <- vapply(nodes,.key,character(1))
  .require(is.numeric(winner) && length(winner)==1L && winner%in%c(0L,1L),"Invalid player")
  moves <- .object()
  for(row in strategy) {
    .require(.fields(row,c("path","move")),"Invalid strategy row"); path <- row$path; key <- .key(path)
    .require(!key%in%names(moves) && key%in%keys && length(path)%%2L==winner && .key(c(path,list(row$move)))%in%keys,"Illegal or duplicate strategy move")
    moves[[key]] <- row$move
  }
  visit <- function(path) {
    key <- .key(path); if(key%in%names(outcomes)) return(outcomes[[key]]==winner)
    children <- .children(nodes,path)
    if(length(path)%%2L==winner) {
      .require(key%in%names(moves),"Strategy is missing a reachable decision")
      return(visit(c(path,list(moves[[key]]))))
    }
    all(vapply(children,visit,logical(1)))
  }
  truth <- visit(list())
  .result(if(truth) "ESTABLISHED" else "REFUTED","FINITE_EXACT","finite_strategy_wins",witness=list(winner=winner,wins=truth),limitations="All continuations in the supplied finite tree are checked.")
}
finite_ultraproduct <- function(structures,principal_index) {
  .require(is.list(structures) && length(structures)>0L,"A nonempty family of structures is required")
  models <- lapply(structures,.structure)
  .require(is.numeric(principal_index) && length(principal_index)==1L && principal_index==floor(principal_index) && principal_index>=0L && principal_index<length(models),"Invalid zero-based principal index")
  signature <- function(x) lapply(x$relations,`[[`,"arity")
  .require(all(vapply(models,function(x) identical(serialize(signature(x)),serialize(signature(models[[1L]]))) && setequal(names(x$constants),names(models[[1L]]$constants)),logical(1))),"All factors must have the same signature")
  .result("ESTABLISHED","FINITE_EXACT","principal_finite_ultraproduct",witness=models[[principal_index+1L]],limitations="Every ultrafilter on a finite index set is principal; no measurable cardinal is witnessed.")
}
prewellorder_ranks <- function(domain,order) {
  dom <- .domain(domain,100L); rel <- .edges(dom,order); keys <- vapply(rel,.key,character(1)); has <- function(x,y) .key(c(x,y))%in%keys
  report <- .analyze(dom,order)
  .require(report$reflexive && report$transitive && report$total,"Expected a total preorder")
  classes <- list(); seen <- character()
  for(x in dom) if(!x%in%seen) {
    group <- dom[vapply(dom,function(y) has(x,y) && has(y,x),logical(1))]
    seen <- union(seen,group); classes[[length(classes)+1L]] <- .array(group)
  }
  scores <- vapply(classes,function(g) sum(vapply(classes,function(h) has(h[[1L]],g[[1L]]) && !has(g[[1L]],h[[1L]]),logical(1))),integer(1))
  classes <- classes[order(scores)]; ranks <- .object()
  for(i in seq_along(classes)) for(x in classes[[i]]) ranks[[x]] <- i-1L
  .result("ESTABLISHED","FINITE_EXACT","finite_prewellorder_ranks",witness=list(classes=unname(classes),ranks=ranks,length=length(classes)),limitations="These are finite quotient ranks, not projective ordinals.")
}

check_finite_embedding <- function(source,target,mapping,max_steps=100000L) {
  left <- .structure(source); right <- .structure(target)
  dom <- unlist(left$domain,use.names=FALSE); cod <- unlist(right$domain,use.names=FALSE)
  .require(is.list(mapping) && setequal(names(mapping),dom) && !anyDuplicated(names(mapping)) &&
    all(vapply(mapping,function(x) .scalar_string(x) && x %in% cod,logical(1))),"Expected a total map into the target domain")
  sig <- function(x) serialize(lapply(x$relations,`[[`,"arity"))
  .require(identical(sig(left),sig(right)) && setequal(names(left$constants),names(right$constants)),"Structures must have the same signature")
  budget <- .budget(max_steps); witness <- NULL
  if(length(dom)!=length(cod)) witness <- list(reason="finite_cardinality_mismatch",source_size=length(dom),target_size=length(cod))
  else if(anyDuplicated(unlist(mapping,use.names=FALSE))) witness <- list(reason="not_injective")
  else {
    for(name in sort(names(left$constants),method="radix")) {
      if(mapping[[left$constants[[name]]]]!=right$constants[[name]]) { witness <- list(reason="constant_not_preserved",symbol=name); break }
    }
    if(is.null(witness)) for(name in sort(names(left$relations),method="radix")) {
      src <- left$relations[[name]]$tuples; dst <- right$relations[[name]]$tuples
      budget <- budget-length(src)-length(dst); .require(budget>=0L,"Embedding table budget exceeded","RESOURCE_LIMIT")
      image <- lapply(src,function(row) .array(unlist(mapping[unlist(row,use.names=FALSE)],use.names=FALSE)))
      ikeys <- vapply(image,.key,character(1)); akeys <- vapply(dst,.key,character(1))
      if(!setequal(ikeys,akeys)) {
        different <- c(image[!(ikeys %in% akeys)],dst[!(akeys %in% ikeys)])
        witness <- list(reason="relation_not_preserved_and_reflected",symbol=name,tuple=.sorted_rows(different)[[1L]]); break
      }
    }
  }
  established <- is.null(witness)
  if(established) witness <- list(mapping=mapping,isomorphism=TRUE)
  .result(if(established) "ESTABLISHED" else "REFUTED","FINITE_EXACT","finite_elementary_embedding",witness=witness,
    limitations="Full first-order elementarity between these finite structures only; no class embedding or critical point is witnessed.")
}
finite_skolem_hull <- function(domain,operations,generators,max_steps=100000L) {
  dom <- .domain(domain,100L)
  .require(length(dom)>0L && is.list(operations) && (!length(operations) || (!is.null(names(operations)) && !anyDuplicated(names(operations)))),"Expected a nonempty domain and named operations")
  hull <- .domain(generators,100L); .require(all(hull %in% dom),"Generators lie outside the domain")
  tables <- .object(); budget <- .budget(max_steps)
  for(name in names(operations)) {
    operation <- operations[[name]]
    .require(nzchar(name) && .fields(operation,c("arity","table")),"Operations require arity and table")
    arity <- operation$arity; rows <- operation$table
    .require(is.numeric(arity) && length(arity)==1L && is.finite(arity) && arity==floor(arity) && arity>=0 && arity<=8 && is.list(rows),"Invalid operation arity/table")
    .require(length(dom)^arity<=budget,"Operation table budget exceeded","RESOURCE_LIMIT")
    .require(length(rows)==length(dom)^arity,"Operation table must be total")
    for(row in rows) .require(.fields(row,c("args","value")) && (is.list(row$args) || is.character(row$args)) &&
      length(row$args)==arity && all(vapply(as.list(row$args),function(x) .scalar_string(x) && x %in% dom,logical(1))) &&
      .scalar_string(row$value) && row$value %in% dom,"Operation row lies outside its domain/arity")
    keys <- vapply(rows,function(r) .key(r$args),character(1))
    .require(!anyDuplicated(keys),"Duplicate operation argument tuple")
    sorted <- .sorted_rows(lapply(rows,`[[`,"args"))
    tables[[name]] <- rows[match(vapply(sorted,.key,character(1)),keys)]
  }
  derivation <- list(); changed <- TRUE
  while(changed) {
    changed <- FALSE
    for(name in sort(names(tables),method="radix")) for(row in tables[[name]]) {
      budget <- budget-1L; .require(budget>=0L,"Closure computation budget exceeded","RESOURCE_LIMIT")
      if(all(unlist(row$args,use.names=FALSE) %in% hull) && !(row$value %in% hull)) {
        hull <- c(hull,row$value); changed <- TRUE
        derivation[[length(derivation)+1L]] <- list(operation=name,args=.array(row$args),value=row$value)
      }
    }
  }
  .result("ESTABLISHED","FINITE_EXACT","closure_under_supplied_operations",
    witness=list(hull=.array(sort(hull,method="radix")),derivation=derivation),
    limitations="This finite closure is not automatically an elementary substructure; completeness of a Skolem family is not asserted.")
}

Try the largecardinals package in your browser

Any scripts or data that you put into this service are public.

largecardinals documentation built on Nov. 25, 2026, 5:09 p.m.