Polynomial representation of the affine part of the AES S-box
Your code is an attempt to implement the function $f$ which is a polynomial representation of the $\text{GF}(2)$ affine part of the S-box of the AES (usually referred to as $A$). Function $f$ is described on page 7 of the paper and your coefficients seems to be OK. 

Your code is mapping $\text a$ to $\text q$ such that $\text q=f(\text a)$.
You're however missing a huge part of the AES S-box, that is, the inversion in $\text{GF}(2^8)$. What you actually want is to map $\text a$ to $\text q$ such that $\text q=f(\text a^{-1})$ where the inversion takes place in your ring $\text R$. Note that you must handle the special case $0$ aside...