1

Hey I am trying to express the spherical harmonics in a compact way. I can not figure out how to express this in a table I got the spherical Harmonics for l = 0,1,2 and m = -l, ...,+l in a list. But wanted a Table in the form:

 m -2 -1 0 1 2
l        
0        x
1      x x x
2    x x x x x

Does anyone know how to do this since I only worked out to create simpler tables with tabulate using with normal headers. I have got the functions in the list sph_harmonics[].

from sympy import Ynm
from tabulate import tabulate

sph_harmonics = []
for l in range (0, 3):
            for m in range(-l, l+1):
                print('l =', l)
                print('m =',m)
                print(sp.simplify(Ynm(l, m, theta, phi).expand(func=True)))
                sph_harmonics.append(sp.simplify(Ynm(l, m, theta, phi).expand(func=True)))
trynerror
  • 219
  • 2
  • 12

1 Answers1

1

Mathjax itself doesn't have the table/tabular environment, but still it's possible to use the array environment for this (link1 ; link2 ; link3).

So based on this, I wrote the following formatting function called fmt_table which formats the formulas like you mentioned:

from sympy import Ynm, simplify, symbols, latex
theta, phi = symbols('\Theta \phi')
from IPython.display import HTML, display, Math, Latex

def fmt_table(data,center_data=False,add_row_nums=False):
    from math import ceil
    buf='''
\\newcommand\\T{\\Rule{0pt}{1em}{.3em}}
\\begin{array}{%s}    
'''
    max_cols = max(len(r) for r in data)
    column_spec = '|' + '|'.join(['c']*max_cols) + '|'
    buf = buf % column_spec
    row_idx = 0
    for row_data in data:
        row = ''
        if add_row_nums and row_idx > 0:
            row += str(row_idx) + " & "
        if center_data and row_idx > 0:
            to_add = ceil( (max_cols - len(row_data))/2 )
            row += ' & '.join([''] * to_add)
        row += ' & '.join(row_data)
        if row_idx == 0:
            row = '''\\hline''' + row + '''\\\\\hline'''
        else:
            row += '''\\\\\hline'''
        row += "\n"
        buf +=row
        row_idx += 1
    buf += '''\\end{array}'''
    # print(buf)
    return buf
    

tbl = []
tbl.append(['\\texttt{m/l}','-2','-1','0','1','2'])
for l in range (0, 3):
    new_row = []    
    for m in range(-l, l+1):
        h = simplify(Ynm(l, m, theta, phi).expand(func=True))
        new_row.append(latex(h))
    tbl.append(new_row)
    

display(Math(fmt_table(tbl,add_row_nums=True,center_data=True)))

OUTPUT:

enter image description here

All the code in this answer is also available here.

wsdookadr
  • 2,584
  • 1
  • 21
  • 44