Project: s41467-024-54401-z | Function: P_ij (r)

system: You are an expert R programmer implementing algorithms from scientific papers.
Complete the masked function based on the algorithm description.
Follow R best practices and maintain consistent code style.
Return **only** the complete R function code.

user: Complete this R function:

**DESCRIPTION:** Calculates predation probability between predator i and prey j based on their body masses using allometric relationships. Core function for soil food web modeling.

**KEY TERMS:** {
  "pred_mass.mg": "predator body mass in mg",
  "prey_mass.mg": "prey body mass in mg",
  "mu_i": "optimal size ratio for predator i",
  "theta_i": "feeding probability parameter"
}

**CONTEXT CODE:** # Diplura
mat[c("plants",
      "detritus",
      "microbes",
      nematodes),    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$family %in% "Campodeidae"]] = c(.25,.25,.4, rep((.1)/length(c(nematodes)),
                                                                                                                          length(c(nematodes))))  
# Gastropoda
mat[c("plants",
      "detritus",
      "microbes"),    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$class == "Gastropoda"]] = c(.2,.4,.4)

# Coleoptera
mat["plants",    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$family %in% "Curculionidae"]] = 1

mat[c("plants",
      "detritus",
      "microbes",
      meso,macro),    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$family %in% "Elateridae"]] = c(1/4,1/4,1/4,rep((1/4)/length(c(meso,macro)), 
                                                                                                                          length(c(meso,macro))))
mat[c("microbes",
      meso,macro),    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$family %in% "Staphylinidae"]] = c(.2,rep(.8/length(c(meso,macro)), 
                                                                                                                    length(c(meso,macro))))
# Diptera
mat[c("detritus",
      "microbes",
      nematodes),    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$family %in% "Chironomidae"]] = c(1/3,1/3,rep((1/3)/length(nematodes),
                                                                                                                       length(nematodes)))
mat[c("plants",
      "detritus",
      "microbes",                                                                  
      nematodes),    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$taxon_name == "Nematocera_larva"]] = c(1/4,1/4,1/4,rep((1/4)/length(nematodes),
                                                                                                                                 length(nematodes)))
# Hemiptera (Sernoryncha)
mat["plants",    nem.mes.mac.taxonomy$taxon_name[nem.mes.mac.taxonomy$order == "Hemiptera"]] = 1


# now we split to mesocosm-specific matrices 

webb = vector(mode = "list", 
             length=length(attt))

for (h in 1:length(webb)) { 
  for (i in 1:length(attt[[h]])) {
    webb[[h]][[i]] = mat[att[[i]]$taxon_name, 
                         att[[i]]$taxon_name]
  }
}

# Li et al. 2023
# re-estimated for terrestrial invertebrates
P_ij = function(pred_mass.mg, prey_mass.mg) {
  stop("Function implementation has been masked")
}

set.seed(321)
for (h in 1:length(webb)) { 
for (i in 1:length(att)) {
  n = nrow(att[[i]]) - 3
  bodymat = matrix(0,n,n)
  
  fauna = intersect(colnames(webb[[h]][[i]]), c(nematodes,meso,macro))
  # vertical stratification similarity
  ver = attt[[h]][[i]] %>% 
    filter(taxon_name %in% fauna) %>% 
    select(above,epi,hemi,eu) %>% 
    # dissimilarity
    vegan::vegdist(method = "bray") %>% 
    as.matrix() 
  # similarity
  vertical = 1- ver
  
  # which cells in the interaction matrix are non zero
  ind = which(webb[[h]][[i]][fauna,
                             fauna] != 0, arr.ind = T)
  # we will use this to standardize animal predation in omnivores
  std = colSums(mat[c(nematodes,meso,macro), 
                    c(nematodes,meso,macro)])[fauna]
  
  # vector of bodymasses
  # this needs to be foodweb-specific and same order as in the web[[i]]
  meanmass = attt[[h]][[i]]$Bodymass.mg[attt[[h]][[i]]$taxon_name %in% fauna]
  
  for (j in 1:nrow(ind)) { # for every predator-prey pair
    # we calculate prey suitability based on Li et al. 2023
    prop = P_ij(meanmass[ind[j,][2]], # predator
                meanmass[ind[j,][1]]) # prey
    bodymat[ind[j,][1],ind[j,][2]] = prop
  }
  
  # now we multiply by three vectors that modify this relationship based on prey
  # agility, physical protection or metabolites 
  # and finally, a matrix of vertical stratification similarity
  props = bodymat*
    attt[[h]][[i]]$Agility[attt[[h]][[i]]$taxon_name %in% fauna]*
    attt[[h]][[i]]$PhysicalProtection[attt[[h]][[i]]$taxon_name %in% fauna]*
    attt[[h]][[i]]$Metabolites[attt[[h]][[i]]$taxon_name %in% fauna]*
    vertical
  
  # regulating cannibalism 
  # (prevents "Error in fluxing : model chosen is unable to determine fluxes accoringly to data")
  diag(props) = 0*diag(props)
  
  # now we make predation on different taxa also depend on their relative biomass
  rel.biomass = as.vector(vegan::decostand(attt[[h]][[i]]$Biomass.mg[attt[[h]][[i]]$taxon_name %in% fauna],"total", 2))
  props = props*rel.biomass
  
  # first standardization: animal preferences sum to 1
  props = vegan::decostand(props,"total", 2)
  # second, we have them sum to the complement of whatever else they eat
  # so if we expect that an omnivore eats 50% plants and 50% animals, animal preferences sum to .5
  # we do this by multiplying every column in the matrix with the std vector
  props = props*rep(std, each=ncol(props))
  webb[[h]][[i]][fauna,
                 fauna] = props
  
}
  ############################## Show loop progress ##############################
  cat('\014')
  cat(paste0(round((h/250) * 100), '% completed'))
  Sys.sleep(.05)
  if (h == 250) cat(': Done')
  ################################################################################
}





Complete the function implementation replacing "stop("Not implemented")".