alfonsogonzalez / AWP

Astrodynamics with Python book, software, and videos. Spacecraft trajectory and attitude modeling and simulation
297 stars 72 forks source link

Python showing NameError "Mysteriously"! #42

Closed muneeb227 closed 1 year ago

muneeb227 commented 1 year ago

Hello, I have an OrbitPropagator file following this Youtube Video but then I'm testing the Orbit Propagation, it is giving NameError which is kind of mysterious to me as I have fixed the issue in OrbitPropagator.py.

Here is the full trackback:

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_22044/4038349985.py in <module>
      1 op = OP(r0,v0,tspan,dt,mu)
----> 2 op.propagate_orbit()
      3 op.plot_3d(show_plot=True)

~\Documents\Python Files\Muneeb's Files\OrbitPropagator.py in propagate_orbit(self)
     41         while self.solver.successful() and self.step<self.n_steps:
     42                 self.solver.integrate(self.solver.t+self.dt)
---> 43             self.ts[self.step] = self.solver.t
     44             self.ys[self.step] = self.solver.y
     45             self.step+=1

NameError: name 'step' is not defined

Here is code I put in OrbitPropagator.py:

    #!/usr/bin/env python
    # coding: utf-8

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.integrate import ode

    class OrbitPropagator:
        def __init__(self, r0, v0, tspan, dt, mu):
            self.r0 = r0
            self.v0 = v0
            self.tspan = tspan
            self.dt = dt
            self.mu = mu

        def propagate_orbit(self):
            #Initial number  of steps
            self.n_steps = int(np.ceil(self.tspan/self.dt))

            #Initialize variables
            self.ts = np.zeros((self.n_steps, 1))
            self.ys = np.zeros((self.n_steps,6))
            self.y0 = self.r0 + self.v0
            self.ts[0] = 0
            self.ys[0] = self.y0
            self.step = 1

            #initiate solver
            self.solver = ode(self.diffy_q)
            self.solver.set_integrator('lsoda')
            self.solver.set_initial_value(self.y0, 0)

            #propagate orbit
            while self.solver.successful() and self.step<self.n_steps:
                self.solver.integrate(self.solver.t+self.dt)
                self.ts[self.step] = self.solver.t
                self.ys[self.step] = self.solver.y
                self.step+=1
            self.rs = self.ys[:,:3]
            self.vs = self.ys[:, 3:]

        def diffy_q(self, t,y):
            rx,ry,rz,vx,vy,vz = y
            r = np.array([rx,ry,rz])
            v = np.array([vx, vy, vz])

            norm_r = np.linalg.norm(r)

            ax, ay, az = r*self.mu/norm_r**3

            return [vx, vy,vz, ax, ay, az]

        def plot_3d(self, show_plot = False, title = "Test Title"):
            fig = plt.figure(figsize = (18,6))
            ax = fig.add_subplot(111, projection = '3d')

            #plot trajectory

            ax.plot(self.rs[:,0],self.rs[:,1],self.rs[:,2], "w", label="Trajectory")
            ax.plot(self.rs[0,0],self.rs[0,1],self.rs[0,2], "wo", label="Initial Position")

            max_val = np.max(np.abs(self.rs))

            ax.set_xlim([-max_val, max_val])
            ax.set_ylim([-max_val, max_val])
            ax.set_zlim([-max_val, max_val])

            ax.set_xlabel(['X (km)'])
            ax.set_ylabel(['Y (km)'])
            ax.set_zlabel(['Z (km)'])

            #ax.set_aspect('equal')

            ax.set_title(title)

            plt.legend()

            if show_plot:
                plt.show()

Can someone help? TIA.

muneeb227 commented 1 year ago

Turns out to be a crazy indentation issue in line 43. Fixed:

    #!/usr/bin/env python
    # coding: utf-8

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.integrate import ode

    class OrbitPropagator:
        def __init__(self, r0, v0, tspan, dt, mu):
            self.r0 = r0
            self.v0 = v0
            self.tspan = tspan
            self.dt = dt
            self.mu = mu

        def propagate_orbit(self):
            #Initial number  of steps
            self.n_steps = int(np.ceil(self.tspan/self.dt))

            #Initialize variables
            self.ts = np.zeros((self.n_steps, 1))
            self.ys = np.zeros((self.n_steps,6))
            self.y0 = self.r0 + self.v0
            self.ts[0] = 0
            self.ys[0] = self.y0
            self.step = 1

            #initiate solver
            self.solver = ode(self.diffy_q)
            self.solver.set_integrator('lsoda')
            self.solver.set_initial_value(self.y0, 0)

            #propagate orbit
            while self.solver.successful() and self.step<self.n_steps:
                     self.solver.integrate(self.solver.t+self.dt)
                     self.ts[self.step] = self.solver.t
                     self.ys[self.step] = self.solver.y
                     self.step+=1
            self.rs = self.ys[:,:3]
            self.vs = self.ys[:, 3:]

        def diffy_q(self, t,y):
            rx,ry,rz,vx,vy,vz = y
            r = np.array([rx,ry,rz])
            v = np.array([vx, vy, vz])

            norm_r = np.linalg.norm(r)

            ax, ay, az = r*self.mu/norm_r**3

            return [vx, vy,vz, ax, ay, az]

        def plot_3d(self, show_plot = False, title = "Test Title"):
            fig = plt.figure(figsize = (18,6))
            ax = fig.add_subplot(111, projection = '3d')

            #plot trajectory

            ax.plot(self.rs[:,0],self.rs[:,1],self.rs[:,2], "w", label="Trajectory")
            ax.plot(self.rs[0,0],self.rs[0,1],self.rs[0,2], "wo", label="Initial Position")

            max_val = np.max(np.abs(self.rs))

            ax.set_xlim([-max_val, max_val])
            ax.set_ylim([-max_val, max_val])
            ax.set_zlim([-max_val, max_val])

            ax.set_xlabel(['X (km)'])
            ax.set_ylabel(['Y (km)'])
            ax.set_zlabel(['Z (km)'])

            #ax.set_aspect('equal')

            ax.set_title(title)

            plt.legend()

            if show_plot:
                plt.show()