ubsuny / CP1-24-HW3

Homework 3 template for CP1-24
1 stars 16 forks source link

Python class conversion #34

Closed ojha-aditya closed 1 month ago

ojha-aditya commented 1 month ago

Has anyone encountered an error while adding two different class elements in Python for eg. Matrix to zero? I need help trying to resolve the following error message.

TypeError: cannot add <class 'sympy.matrices.dense.MutableDenseMatrix'> and <class 'sympy.core.mul.Mul'>
laserlab commented 1 month ago

It would help to see the code. Why don’t you start your POR and mention it is not done yet for the review

ojha-aditya commented 1 month ago

Sure I will do that. I figured out a workaround though, will put the details here shortly after creating the PR.

ojha-aditya commented 1 month ago

I almost forgot about this, so this is how I resolved the error:

def electric_field_expression(e_0, wave_vector, delta, f, polarisation):
    # generates Electric Field
    t, x, y, z = sp.symbols('t x y z')  # defining the positon and time variables
    omega = 2 * sp.pi * f   # defining the angular frequenc variable

    r = sp.Matrix([x, y, z])    # generating the position vector
    k = sp.Matrix(wave_vector)  # generating the wave vector

    norm_polarisation = np.linalg.norm(polarisation)    # norm of the polarisation vector

    polarisation_normalised = list(map(lambda a: a / norm_polarisation, polarisation))
    # normalising the polarisaion vector using map and lamda function
    n_hat = sp.Matrix(polarisation_normalised)
    # generating the normalised polarisation vector
    k_dot_r = r.dot(k)
    return e_0 * sp.cos(k_dot_r - omega * t + delta) * n_hat.T
    # returning the Electric Field in algebraic form

Earlier I had not used dot() function to take the dot product but rather used something like:

r.T @ k

Turns out both these functions give objects of different python classes and although it is same from a Physics perspective, it is not possible to add two diferent ython objects together.

ojha-aditya commented 1 month ago

A brief overview of different sympy classes is here: https://docs.sympy.org/latest/explanation/special_topics/classification.html https://docs.sympy.org/latest/modules/matrices/dense.html

Different commands give ojects of different classes: https://github.com/sympy/sympy/issues/23024

ojha-aditya commented 1 month ago

Closing this as well now.