Mathematically, each level goes in powers of 3. The first line is 3^0, second = 3^1, third = 3^2 etc.
The sum of these is 3^0 + 3^1 + 3^2 + ... 3^n. The general formula for the sum of n tiers is given as something like:
s = (1 - 3^n)(1 - 3)
= (3^n - 1)/2
=> 2s = 3^n - 1
=> 2s + 1 = 3^n
=> n = log(2s + 1) / log(3)
= log(2s + 1, 3) //php notation
If the number isn't the exact total, it will return a number lower than the row they're on but greater than the row above, so ceil() it:
return ceil(log(2s + 1, 3));
As for the diagram bit, I'll leave that to you. It depends on how you want it displayed; with ascii or with graphics and the diagram itself would be a fair amount of code to be giving away for free.