# Calculate the probability of at least c of m shifts in morphological regime falling on the same branches of a phylogeny as e shifts in ecology ecolog
# Calcualtions assume that all branches have an equal likelihood of hosting a shift, and that no branch has more than shift in morphology or more than one shift in ecology. 

n = 129 # tips in the phylogeny
b = (2*n-2) # branches in the phylogeny (exclusive of root)
e = 36  # number of ecological shifts
m = 16  # number of morphological shifts
c = 10 # number co-occurrences

# probability of choosing i of the e branches with an ecological shift, when selecting from all b branches without replacement
# success <- (choose(e,i)*choose((b-e),(m-i)))/choose(b,m)

# set up dataframe for probabilities of getting i matches of ecological and morphological shifts
matches <- seq(0,m,1)
probabilities <- numeric(m+1)
table <- cbind(matches, probabilities)
table <- as.data.frame(table)


# calculate probablity of zero matches and insert into table
# probability of getting no matches at all
nomatches <- choose((b-e),(m))/choose(b,m)
table[1,2] <- nomatches

for (i in  1:m){table[i+1,2] <- (choose (e,i)*choose((b-e),(m-i)))/choose(b,m)}

#probabilility of at least c matches

answer<-sum(table$probabilities[(c+1):(m+1)])


