Debug: Database connection successful Python Computer Language / Science, Technology, and Astronomy / New Mars Forums

New Mars Forums

Official discussion forum of The Mars Society and MarsNews.com

You are not logged in.

Announcement

Announcement: This forum has successfully made it through the upgraded. Please login.

#1 2023-08-10 13:25:24

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Python Computer Language

This topic is offered for NewMars members who might wish to share their learning experiences with the Python language.

In recent days, encouraged by ChatGPT, I have ventured into this unfamiliar language, in order to try to use a computer to solve a calculus problem.

(th)

Offline

Like button can go here

#2 2023-08-10 13:29:14

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

The following Python program will run on any computer that is configured with python3, and the libraries pygame and pygame_gui.

This version (orbit12) runs, and although it is still in rough shape, it shows promise to become the program I am thinking of.

if you decide to try the program, use the Enter key to replay the current animation, and the space bar to enter new values for X and Y in the terminal window.

import pygame # orbit12.py
import pygame_gui
import math

pygame.init()

# Constants
WIDTH, HEIGHT = 800, 800
FPS = 60
G = 6.67430e-11
M = 5.972e24
R = 6371e3
SCALE = 10e6
SPEED = 100

# Colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
BLACK = (0,0,0)
GREEN = (0,255,0)
RED = (255,0,0)
BACKGROUND_COLOR = (0,0,0) # BLACK

# Pygame setup
WIDTH, HEIGHT = 800, 800
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Orbit Simulation orbit12")
FPS = 60

# Pygame GUI manager
manager = pygame_gui.UIManager((WIDTH, HEIGHT))

# Text Entry for velocities
vx_input = pygame_gui.elements.ui_text_entry_line.UITextEntryLine(
    relative_rect=pygame.Rect((50, 10), (70, 20)),
    manager=manager
)
vy_input = pygame_gui.elements.ui_text_entry_line.UITextEntryLine(
    relative_rect=pygame.Rect((150, 10), (70, 20)),
    manager=manager
)

# Variable to track if the program is waiting for velocity input
waiting_for_input = False

# Gravitational constant (Arbitrarily chosen for this simulation)
G = 1

# Mass of the earth and satellite
M_EARTH = 1000
M_SAT = 1

# Initial position and velocity of the satellite
pos = [400, 200]
vel = [0, 2]
new_vel = vel # Added to provide value for first re-start request 2023/08/09 (th)

# Draw a colored rectangle on the screen
rectangle_color_red = (128, 0, 0)  # Red color for the X rectangle left
rectangle_color_green = (0,128,0) # Green color for Y rectangle right
rectangle_rect_X = pygame.Rect((30, 30), (100, 50))  # Rectangle's position and size
rectangle_rect_Y = pygame.Rect((670, 30), (100, 50))  # Rectangle's position and size

def draw_window():
    win.fill((0, 0, 0))
    pygame.draw.circle(win, (0, 255, 0), (WIDTH//2, HEIGHT//2), 20)  # Draw Earth
    pygame.draw.circle(win, (255, 0, 0), (int(pos[0]), int(pos[1])), 5)  # Draw Satellite

    # Draw a colored rectangle on the screen
    pygame.draw.rect(win, rectangle_color_red, rectangle_rect_X)
    pygame.draw.rect(win, rectangle_color_green,rectangle_rect_Y)
    pygame.display.update()
   
def simulate(pos, vel):
    r = math.sqrt(pos[0] ** 2 + pos[1] ** 2)
    a = (-G * M / r ** 3) * pos[0]
    vel[0] += a * SPEED
    pos[0] += vel[0] * SPEED
    a = (-G * M / r ** 3) * pos[1]
    vel[1] += a * SPEED
    pos[1] += vel[1] * SPEED
    return pos, vel


def main():
    global pos
    global vel
    global new_vel
    global vx
    global vy
    vx = 0 # Starting value in case operator presses Enter 2023/08/09 (th)
    vy = 2
    clock = pygame.time.Clock()
    run = True
    simulation = True

    while run:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:  # Changed the indentation here
                if event.key == pygame.K_SPACE:
                    pygame.event.clear()  # Clear the event queue
                    vx = float(input("Enter x velocity: "))
                    vy = float(input("Enter y velocity: "))
                    new_vel = [vx, vy]
                    pos = [400, 200]
                    vel = new_vel
                    simulation = True
                elif event.key == pygame.K_RETURN:  # Enter key
                    pos = [400, 200]
                    new_vel = [vx, vy]
                    vel = new_vel
                    simulation = True
                                           
        if simulation:
            # Calculate the distance between the satellite and the Earth
            r = [WIDTH//2 - pos[0], HEIGHT//2 - pos[1]]
            dist = math.sqrt(r[0]**2 + r[1]**2)

            # Calculate the gravitational force using the inverse square law
            force = G * M_EARTH * M_SAT / dist**2

            # Calculate the direction of the force
            direction = [ri / dist for ri in r]

            # Calculate the acceleration of the satellite
            accel = [force / M_SAT * di for di in direction]

            # Update the velocity and position of the satellite
            vel = [vi + ai for vi, ai in zip(vel, accel)]
            pos = [pi + vi for pi, vi in zip(pos, vel)]

            draw_window()

            # Condition to reset the simulation if the satellite crashes into the Earth
            if dist < 20:
                simulation = False

    pygame.quit()

if __name__ == "__main__":
    main()

If you save the code above, give it the last name of .py (eg. orbit12.py)

If you are running Windows 10 or later, it should be possible for you to install Python3

https://www.python.org/downloads/release/python-3114/

For all options:
https://www.python.org/downloads/

In case you are a novice, the program is run in a Command (or Terminal in Linux) window, with the command:

python3 orbit12.py

(th)

Offline

Like button can go here

#3 2023-08-10 19:52:26

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

This evening I asked ChatGPT-4 about how to add functionality to the existing program to take input from the game screen.

In the working version posted earlier, input is obtained from the computer command window.

Our previous attempt to add input from the game screen resulted in the program not working at all.

I took ChatGPT's suggestion, and carefully added statements from orbit9 (which failed) to orbit7 (which worked).

ChatGPT-4 took a look at orbit13, and came back with several suggestions to (hopefully) allow for input from the game screen.

Here is a summary of the proposed updates:

def main():
    global waiting_for_input
    ...


time_delta = clock.tick(FPS) / 1000.0
manager.update(time_delta)


elif event.key == pygame.K_SPACE:
    pygame.event.clear()  # Clear the event queue
    simulation = False
    waiting_for_input = True
    vx_input.enable()
    vx_input.focus()


elif event.type == pygame_gui.UI_TEXT_ENTRY_FINISHED:
    if event.ui_element == vx_input:
        vel[0] = float(vx_input.get_text())
        vy_input.enable()
        vy_input.focus()
    elif event.ui_element == vy_input:
        vel[1] = float(vy_input.get_text())
        vx_input.disable()
        vy_input.disable()


manager.draw_ui(win)

(th)

Offline

Like button can go here

#4 2023-08-11 15:08:29

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

In working on orbit7.py, ChatGPT and I attempted to upgrade the program to take in input from the game screen.  This required adding pygame_gui library to the application, and it also revealed a large number of learning opportunities.

The work on orbit7 reached orbit15, at which point both ChatGPT and I threw in the towel.  ChatGPT provided a template of a simple program to do nothing but take in data from a window in the game screen.  That template did NOT work!  In tackling the simple little input program one step at a time, ChatGPT finally caught the missing program statement.  I was just along for the ride at that point.

The issue had to do with event handling.  The game library does event handling.  The operating system does event handling. And, last but definitely not least, the gui library does event handling.  Somehow in the process of blending the gui library into the orbit program, a single crucial statement was overlooked, and it's absence did NOT jump out when ChatGPT looked over the code of the original program.  It was only after repeated looks at the simple little input program that the missing element was recognized as missing.

The resulting program is working, and if there is a student of Python "out there" I am happy to provide it as a reference point.

One detail of working with the gui library is the need for "theme" data to be stored in an external file. I will provide that in this post as well, if Apache allows:

Save this in your working directory as "theme.json"

{
    "#vx_input": {
        "dark_bg": "#FFFFFF",
        "normal_text": "#000000"
    },
    "#vy_input": {
        "dark_bg": "#FFFFFF",
        "normal_text": "#000000"
    }
}

Here is a copy of the simple Python program:

import pygame # gameinput02 - needs theme.json in same folder
import pygame_gui

pygame.init()

# Constants
WIDTH, HEIGHT = 800, 800

# Setup
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("UITextEntryLine Test")

theme_path = "theme.json"
manager = pygame_gui.UIManager((WIDTH, HEIGHT), theme_path)

vx_input = pygame_gui.elements.ui_text_entry_line.UITextEntryLine(
    relative_rect=pygame.Rect((30, 60), (70, 20)),
    manager=manager,
    object_id='#vx_input'
)
vy_input = pygame_gui.elements.ui_text_entry_line.UITextEntryLine(
    relative_rect=pygame.Rect((670, 60), (70, 20)),
    manager=manager,
    object_id='#vy_input'
)

vx_input.enable()
vy_input.enable()

def main():
    clock = pygame.time.Clock()
    run = True

    while run:
        time_delta = clock.tick(60) / 1000.0
       
        for event in pygame.event.get():
            manager.process_events(event) # Pass the event to pygame_gui
            if event.type == pygame.QUIT:
                run = False
            elif event.type == pygame.KEYDOWN:
                print(pygame.key.name(event.key)) # added to help debug issue of no-echo
                if event.key == pygame.K_SPACE:
                    # print("Spacebar pressed")
                    vx_input.focus()
                    vy_input.unfocus()
                elif event.key == pygame.K_RETURN:
                    # print("Spacebar pressed")
                    vy_input.focus()
                    vx_input.unfocus()
        manager.update(time_delta)
       
        win.fill((0, 0, 0))
        manager.draw_ui(win)

        pygame.display.update()

    pygame.quit()

if __name__ == "__main__":
    main()

(th)

Offline

Like button can go here

#5 2023-08-24 19:15:10

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

orbit7.py was working on August 11th.  It uses input for X and Y values via the terminal window.

ChatGPT warned me that trying to take in values from a game window would prove challenging.  It sure was!

it is August 24th, and a preliminary version of the program is working with game screen input.

The link below is to the original version, which takes input from the terminal window.

A link to orbit7.py is here:
https://www.dropbox.com/scl/fi/hq1i22xl … xmzh6&dl=0

The link here is to orbit18.py which takes input from the game screen:
https://www.dropbox.com/scl/fi/9rgi5tab … rkly7&dl=0

If anyone decides to run the program, here are the rules:

python3 orbit18.py

1) At program start, the satellite falls directly into the Earth
2) Press "r" key to cause a repeat - note that the path is not the same from one repeat to the next, in this version
3) Press spacebar to set up input ... the cursor will be in the X window ... enter 2 and press the tab key
3) In this version, you have to press the tab key again to move the cursor to the Y window
4) Enter 4 and press Enter
Note that if you have the terminal window open, it will be showing input you have entered
5) Press Enter again .... the terminal window should show 2 entered for X and 4 entered for Y
6) Press "r" to restart the animation
The first time through the ball goes off screen
7) Press "r" to repeat ... this time the ball goes off the screen in another direction
8) Press "r" a third time and the program should settle into a long elliptical orbit.
9) Use Alt-F4 to stop the program or just click the X in the upper right corner.

For those who might be interested in learning a bit of Python .... this program uses the pygame library, and the pygame_gui library, as well as the math library to compute the orbit.

Update after investigating Python for Windows .... It appears that Windows 10 is still supported.
Goto www.python.org/downloads to download the package. 
My Windows 7 work horse is not supported.

The version that is available for Linux (current/Ubuntu) is Python3 (not sure of specific version).

(th)

Offline

Like button can go here

#6 2023-08-25 09:16:00

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

The little orbit18.py program downloaded and ran as expected on a different Linux box than the one where it was developed.

I would appreciate someone with Windows 10 (or later) downloading the program, and documenting (here) what steps are needed to prepare Python on the Windows box.  The language and runtime are available from www.python.org.

It appears that versions of Python that ran on Windows 7 (which I have) are no longer available from the python.org site.

Update later: By experimenting, I learned that a better (tighter) orbit is generated if X = 1.5 and Y = 1.5 at spacebar time.

After entering the values, press "r" to restart the simulation.

Please note that this version (orbit18.py) does NOT save the initial values for velocity, so random numbers are used by the program at restart time.  In the next version, I expect to have ** that ** problem resolved.

(th)

Offline

Like button can go here

#7 2023-08-26 08:27:05

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

python18.py is now running on two of my Windows 10 machines.  There was a trick to success that ChatGPT spotted. In Linux, to call the python runtime, it is necessary so specify "python3". In the windows environment, python3 works, ** but ** in order for python to find the pygame library, it appears to be necessary so use "python" to call the interpreter.

I was impressed by how much progress Microsoft has made over the years, in installing software. Linux has been far ahead for many years, and Microsoft appears to have made an effort to catch up. When I entered "python3" into the command window, Windows 10 brought up a "store" window and offered Python for download. I clicked on the button, and Windows not only downloaded the Python package, but installed it.  Then, when I entered "python3" into the command window, it ran immediately.

The next step was (is) to install the game library.

The command is: pip install pygame

pip3 appears to work as well.

To see the installed library, you can use the command: pip show : pip show pygame

Next, you need to install the pygame GUI library: pip install pygame_gui

At that point, if you type "python orbit18.py" the program should start.

This assumes you've downloaded orbit18.py using the link in an earlier post.

Future versions of the program are likely to use the Theme file below:

Save this in your working directory as "theme.json"

{
    "#vx_input": {
        "dark_bg": "#FFFFFF",
        "normal_text": "#000000"
    },
    "#vy_input": {
        "dark_bg": "#FFFFFF",
        "normal_text": "#000000"
    }
}

(th)

Offline

Like button can go here

#8 2023-08-26 20:22:40

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

orbit20.py is now available for download:

https://www.dropbox.com/scl/fi/a5okjmk1 … aq0q3&dl=0

This version is improved in small ways. 

The velocity values input by the operator are now saved and used by the restart feature "r"

Either Return or Enter should complete input of new X and Y values.

There is a problem with the X input window. For now, just enter whole numbers, such as 2.

A nice ellipse will appear if X is set to 1.5 and Y is set to 2.

(th)

Offline

Like button can go here

#9 2023-08-29 19:25:38

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

For a couple of days, ChatGPT and I have been battling with the GUI interface for Python.  There appear to be some quirks with the theme system, that is supposed to support the appearance of objects in the game environment, but we were never able to get it to work.  In desperation (if that is the right word for ChatGPT giving up) ChatGPT suggested trying the direct color set capability built into pygame, and this time it worked.  The first time we tried it did NOT work, which is why we went off on the theme wild-goose-chase in the first place.

Tor the record, and for anyone who might be studying Python, here is the winning formula...

For a text window that has a white background and black letters, use:

mport pygame
import pygame_gui

pygame.init()

WIDTH, HEIGHT = 800, 600
window_surface = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Theme Test")

clock = pygame.time.Clock()
manager = pygame_gui.UIManager((WIDTH, HEIGHT))

my_input_box = pygame_gui.elements.UITextEntryLine(
    relative_rect=pygame.Rect((350, 275), (100, 50)),
    manager=manager,
    object_id='#my_input_box'
)

# Test setting the text and text color directly
my_input_box.set_text('Test')

# Corrected attribute setting
my_input_box.text_colour = pygame.Color("black")
my_input_box.background_colour = pygame.Color("white")

# Rebuilding the UI to see if the change takes effect

my_input_box.rebuild()

Afterthought ... note the British spelling "colour" .... that is required, and it may be the reason the first attempt failed.

(th)

Offline

Like button can go here

#10 2023-08-30 14:26:14

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

The answer to the GUI problem reported in #9 has arrived, after quite a bit of back and forth with ChatGPT.  The answer turns out to be that there are two different subsystems able and willing to draw on the screen, and they are not compatible. 

The solution that I ** just ** discovered is that the delivery of colors to objects on the screen prescribed by one of the two methods can be seen if the animation is stopped.  That is fine with me, because I have to stop the animation anyway, in order to provide the operator with an opportunity to enter new velocity values. 

Once the input is finished, and the operator instructs the animation to resume, the objects colored while the animation was stopped are overwritten by the animation drawing procedures.

That too, is fine with me, since the input boxes are not needed during the animation.

However, we did find a limitation or two of ChatGPT's ability to deal with a complex problem such as this turned out to be.

The orbit program is now up to version 26, and ** it ** must be given quite a bit of attention to bring back functionality that had to be removed while the GUI problem was addressed.

(th)

Offline

Like button can go here

#11 2023-09-03 15:26:10

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Update 2023/09/03

orbit31.py is working with the GUI changes and some preliminary refactoring.

A detail of Python that seems a bit different from other languages is scope of variables.

ChatGPT scolded me about using global variables, and I understand the sentiment.

I might be willing to eliminate global variables and pass variables as parameters at some point.

That point is not now.

At ** this ** point, orbit31.py is dropping the satellite into the Earth, and performing "Restart" properly with the key "r"

In refactoring per suggestion from ChatGPT (ie, nagging) I moved key event handling out of the main() procedure, and I had to add a global variable in the new def, because of the quirks of variable scope.

Now, the program is working again, so development can proceed to add new keys for commands, and clean up existing ones.

***

At Borders this evening, I picked up a book on Python:

Details to follow ...
Title: Python Programming Third Edition
Michael Dawson
ISBN 13- 978-1-4354-5500-9
ISBN 10: 1-4354-5500-2

I note that the edition I have was printed November of 2022, so apparently sales are continuing.

Update 2023/09/07 .... I've completed a preliminary detailed scan of the book, and started word-for-word reading at the beginning.

The author's style is quite entertaining, while the coverage of programming essentials is among the best I've seen. The book is still available on Amazon, if anyone is inspired to consider learning a bit about Python.  The original publication date was 2010, so it is (probably) not surprising the the companion web site is no longer in service.  I've written to Mr. Dawson asking if the course files might be made available via Dropbox, as an alternative.

In reading the first chapter, I learned that the language was developed in 1991, and named for the then popular British Monte Python programs. 

Michael Dawson
Michael Dawson has worked as both a programmer and a computer game designer and producer. In addition to real world game industry experience, Mike earned his bachelor's degree in Computer Science from the University of Southern California. Currently, he teaches game programming in the Game Production Department of the Los Angeles Film School. Mike has also taught game programming to students through UCLA Extension and The Digital Media Academy at Stanford. He's the author of four books: Beginning C++ through Game Programming, Guide to Programming with Python, and C++ Projects: Programming with Text-Based Games. You can visit his website at www.programgames.com to learn more or to get support for any of his books.

(th)

Offline

Like button can go here

#12 2023-09-03 17:28:28

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

***
Here is a link to orbit31.py
https://www.dropbox.com/scl/fi/c692h0fi … 19rwl&dl=0

The program uses a theme.json file, but for some reason Apache is refusing to let me post the link. 

Here is the code that goes into the file:

{
    "#vx_input": {
        "dark_bg": "#FFFFFF",
        "normal_text": "#000000"
    },
    "#vy_input": {
        "dark_bg": "#FFFFFF",
        "normal_text": "#000000"
    }
}

Update next day ... after testing on two different PC's .... This version is buggy ... That is understandable, but annoying.  The bugs are in part due to a jump from Version 20 to Version 30, and incorporation of refactoring suggested by ChatGPT.  A large set of code was moved out of main() into it's own def, and I neglected to configure some variables that are defined as global (for now).  You'll run into one of those if you run orbit31.py.

On the ** other ** hand, orbit31.py can be teased into working, but I will make a priority to try to clean things up today.

There doesn't seem to be a great clamor of interest in this project, which is good, but even ** one ** dissatisfied "customer" is one too many.

(th)

Offline

Like button can go here

#13 2023-09-05 20:24:40

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Scope of variables is an issue to contend with in any computer language.

Python seems to have a quirk that someone wanting to learn Python would find interesting.

A variable defined in main() has global scope.

However, in order for a function to see that variable, apparently the variable must be preceded by the word "global" in both places.

That requirement tripped me up when I tried to refactor by moving code out of main() into a function (ie, def).

Here is a bit of a transcript with ChatGPT4 about the scope of variables in Python:

User
I'd like to close this discussion with a brief review of scope of variables in Python. In other sessions, you helped me to get a running start with a simple Python game program.  We got into trouble when I asked you to help me to change the program to accept user input via the game screen instead of using the terminal input() statement.  Little by little we overcame the problems, and the program is now far enough along that I am attempting to make needed changes myself.  I bought a book by an experienced Python game designer, and today I spent a couple of hours diving into the book.  Among the subjects I investigated was variable scope.  The issue of scope came up in our work on the simple game program.  You suggested avoiding global variables, and I recognize that eventually when everything is working and it is time for refactoring, I can eliminate global variables. For the time being, I intend to keep using them.  With this background, I have tried to set the stage for the specific question I'm planning to toss your way.  I understand (from the book) that the place to define global variables is in main().  According to the book, any variable defined in main() will have global scope.  My question is a simple one ... in order for a variable defined in main() to have global scope, do I need to precede the variable name with the word global?
ChatGPT
In Python, the global keyword is used within a function to indicate that a variable is a global variable, i.e., it exists in the global scope outside of the function. If a variable is defined in main() and you want to access or modify it from another function, you would still need to use the global keyword within that other function to indicate that you're referring to the global variable, not creating a new local one.

Here's a quick example to demonstrate:
Removed due to Apache Internal Server Error
So to clarify:

If you declare a variable in main() without the global keyword, it will not be globally accessible. It will be local to main().

If you declare a variable in main() with the global keyword, then it will be globally accessible. To access or modify it in another function, you'll still need to use the global keyword within that function.

Given your plan to refactor later and remove global variables, using them for now for prototyping is an approach some developers take, but be cautious as it can lead to code that is harder to debug and maintain. It's usually better to pass variables as function arguments and return values to make the flow of data through your program clearer.

(th)

Offline

Like button can go here

#14 2023-09-07 18:07:38

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Here is a link to orbit32.py

https://www.dropbox.com/scl/fi/qkakhqwe … k05bu&dl=0

The companion to this file is the theme.json file:

https://www.dropbox.com/scl/fi/itht2e37 … 72l9i&dl=0

This version of orbit now handles input (relatively) smoothly. 

When you start the program, the ball drops, and "r" repeats the drop

spacebar starts input ... enter 1.5 into the X window, press Enter, press Tab twice, and enter 1.1 into the right window.

Press Enter again. Data is stored for a new orbit.

Press "r" to restart

Press Alt-F4 to end the run.

My plan is to continue improving the input process until is is smooth, and to add Help using the "h" key.

(th)

Offline

Like button can go here

#15 2023-09-10 14:50:38

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Below is a link to a Demo program in Python, using tkinter.

tkinter is a module that supports advanced graphics.

The demo shows two windows opened in the same program.  One is for animation, and the other is for input.

ChatGPT put this together, when I asked about being able to have two windows open, and to dedicate one to input.

I had read about tkinter previously, but had not seen it in action.

https://www.dropbox.com/scl/fi/0wh4q4mk … ktw8j&dl=0

The file stored in Dropbox needs to have the first two lines commented... Just use Notepad to insert # in column 1 of the first two lines.
Put the program in a folder that you can reach easily using the command program.
Running the Command program, type python tkinterDemo01.py
If you have Python installed the program will run.
If you are on Windows and do not have Python installed, Windows will ask if you want to install it.

The tkinter library should be installed by default if you have Python, but you may have to install it separately.

(th)

Offline

Like button can go here

#16 2023-09-11 18:50:42

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

ChatGPT convinced me to convert the orbit program entirely to tkinter.

The result of the back-and-forth is available for download at Dropbox:
https://www.dropbox.com/scl/fi/cmrnrv4y … i3lkd&dl=0

This version has the title: tkinterOrbit36.py

We got rid of pygame and pygame_gui and theme.json altogether.  The input is now provided in a window separate from the animation window.  The "r" key and the spacebar work as before.  Use the spacebar to input new values for X and Y, and use the "r" key to repeat from initial position.  Values of 1.5 for both X and Y provide an ellipse with a reasonable excursion from "Earth". The run pace in this version is slower.

Update: Through experimentation, I've found that setting X to 2.3 and Y to 0 produces an orbit that is very near to circuler.

Update: It is possible to enable the program to run from the desk top, by creating an icon (shortcut) for it.  Apparently Windows can figure out what software to run so the program starts.

Update: I just heard from a member of the local Linux special interest group.  He experimented with values for X and Y using tkinterOrbit36.py, and found a nearly circular orbit on his Mac using 2.4 X and .4 Y.  I ran that set of numbers on one of my Linux boxes and the orbit is indeed close to circular.  I'll add reporting of runtime parameters in the next version.  At a minimum I'd like to show velocity along the orbit, current X and current Y, and distance to the center of the Earth.

(th)

Offline

Like button can go here

#17 2023-09-17 17:36:19

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

This evening I persuaded ChatGPT(4) to move the input and reporting section to side-by-side mode.

The previous version turned out to not fit on the computer screens where I ran it.  The new landscape style may work better for most folks who use computers.  The portrait style may be better suited for phones, but if you rotate the phone the landscape style should work.  I added some text to try to help folks who are running the program for the first time.

Here is a link to Version 38:
https://www.dropbox.com/scl/fi/njdo6ofc … 1wxd0&dl=0

Feedback would be welcome and is appreciated.

As a reminder, setup instructions are published earlier in this topic.  If anyone still has a question, please post an inquiry.

The goal of this project is to set up a simultaneous run of a ballistic launched projectile, to find the launch solution that results in the least expenditure of energy to match orbit with an on-orbit fuel depot.  This problem would be a few minutes work for someone who knows calculus, but I do not have that skill, so a digital solution will have to find the answer.

(th)

Offline

Like button can go here

#18 2023-10-27 20:46:10

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

As a reminder for anyone who might be following this topic...

As an explanation for anyone reading this post without looking at the topic...

I'm working on a Python program to demonstrate docking of a payload launched from a ballistic launcher, with a space station in circular orbit.

In earlier posts in this topic, I have shown or provided links to a Python program that simulates a satellite orbiting a central body.  My goal is to add a ballistic launcher to the existing program.  As a first step in that direction, I asked Google if anyone had written a program with animation to show the path of a projectile launched from an artillery piece.  It turns out that a great number of such programs are available, but Google went ahead and wrote one itself.  Here is the link to that program:

https://docs.google.com/document/d/10Ir … sp=sharing

Anyone ** should ** be able to download the code and run the animation, because Python runs on every OS ahd hardware ** except ** the original Chromebook.  The current Chromebook has a option to turn on Linux, so I expect Python to run there as well.

Update 2023/10/28 ... the code at the link above required some adjustments (by ChatGPT(4)) before it would run. The run produced a parabola as might be expected.  The graph appeared in the form shown by the link below.  I tried to capture the parabola, but only got the frame.

Z7QJnSm.png

(th)

Offline

Like button can go here

#19 2023-10-28 18:53:13

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Here is the revised Python code for an artillery demo, as provided by ChatGPT4.

# 2023/10/28 (th) This is a corrected version of a simple artillery demo program
# Corrections were provided by ChatGPT(4)

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation  # <--- Correct import here

def init():
    line.set_data([], [])
    return line,

def animate(i):
    t = np.linspace(0, i*dt, 2*i)
    x = v0*np.cos(alpha)*t
    y = v0*np.sin(alpha)*t - 0.5*g*t**2
    line.set_data(x, y)
    ax.set_xlim(0, x.max())  # Adjust x-axis limit
    ax.set_ylim(0, y.max())  # Adjust y-axis limit
    return line,

dt = 0.1
v0 = 100
alpha = np.pi/4
g = 9.81

fig, ax = plt.subplots()
ax.set_xlabel('x (m)')
ax.set_ylabel('y (m)')
line, = ax.plot([], [], color='red')  # Change how you create the line

anim = FuncAnimation(fig, animate, frames=200, interval=10, init_func=init, blit=True)  # Adjusted number of frames
plt.show()

(th)

Offline

Like button can go here

#20 2023-11-21 15:44:42

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

In recent times I've enlisted ChatGPT to help me with study of the Methane production concept reported in another topic.  The little Python program pasted below, if the Apache Internal Server Error gods are willing, is a GUI interface for code to take in parameters and deliver results as they can be either calculated or estimated. I'm, planning to show the Python code to the local Linux group this evening.

Too bad. Apache Internal Server Error objected ...

# Main loop
root.mainloop()

So here's the Dropbox link:
https://www.dropbox.com/scl/fi/712zzv9w … nf75z&dl=0

This code should download and run on any computer or operating system except for Chromebook. The latest Chromebooks can be equipped with Linux.

(th)

Offline

Like button can go here

#21 2023-11-26 21:05:48

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Here is the output of a long series of sessions with ChatGPT(4) to create an operator control program for a Methane Production system:

FZYsA96.png

The program was developed separately from the business development series, where equations and various facts are assembled in support of the business case.  I just offered the program to ChatGPT(4) in the business track, and it not only remembered what we'd been working on, but confirmed that the program can be filled out to fulfill the business objectives.

Here is a link to the source code: https://www.dropbox.com/scl/fi/r3sbyf0l … l9cq0&dl=0

Anyone should be able to download and run this program. Python runs on all OS and hardware, except for older Chromebooks.

Newer Chromebooks can install Linux, which supports Python.

The current version of the Operator Program for a Methane production facility is limited in capability. The focus until now was attempting to create a GUI interface that can be extended with the Real Universe facts and physics and chemistry needed.

Update: This program is going to need inputs from running equipment.  I am unsure of the best way to take in Real Universe data, but am considering using stand-alone microcontrollers to update files on shared hardware, and polling those files at the process update intervals which are currently set at one second.

The actual run time that will be required is unknown at this time. The program is set to a default of 30 seconds to exercise the progress bar. ChatGPT thinks the process of making methane could take as much as 30 minutes. 

A definite risk is that the reaction vessel may explode since the methane production reaction is exothermic. Temperatures and pressures required for the reaction are at the upper limits of material strength.

Here is a link to the transcript of sessions with ChatGPT(4) that led to development of the methane production process.

https://docs.google.com/document/d/1PLX … sp=sharing

The constants and equations are rendered in Python format.

(th)

Offline

Like button can go here

#22 2023-11-30 13:36:24

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Here is a screenshot of version 18 of the Methane Operator's control program ...

mLtk2BI.png

Changes include addition of display bars for temperature and pressure.

(th)

Offline

Like button can go here

#23 2024-02-09 21:04:52

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

This post is the first of what I hope will be a series to discover the feasibility of the Cycloid Payload Delivery concept for Mars.  ChatGPT4 has been improving steadily over the year I've been working with it.  I presented the problem to be solved in a series of exchanges in recent days, and CH4 has returned with an outline for a Python program that it seems to think can be expanded to find out if any existing cable that is commercially available can deliver a payload gently to the surface of Mars.  The method under consideration is to compute the load on the cable in metric tons, as the payload follows the Cycloid path from orbit to the surface. The strongest cable I have found so far can hold 10 tons. That cable is intended to hold gigantic broadcast towers against wind loads for decades at a time. Here is a link to a copy of the opening program, version 01.  Anyone in the forum readership can download this program and run it on any OS, including Chromebook, if the owner installs Linux as an application.

Apache Internal Server Error objected to the Python code so I'll put it on Dropbox

# Set the main application to run
root.mainloop()

https://www.dropbox.com/scl/fi/0y7o7qoy … 22dpd&dl=0

(th)

Offline

Like button can go here

#24 2024-02-29 09:17:04

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

Python is the computer language used by the Blender team.  The question I asked CH4 was about how to automate some of the repetitive data structure definition that is needed for even such as simple project as the Cycloid Payload Delivery system. In light of the fact that Blender is being used to make full length animations, it is not surprising that developers have created tools to assist the designer.

As usual, Apache Internal Server Error objected to the live Python code.

I can put it in Dropbox if anyone is interested.  An alternative is to ask ChatGPT to show you the Python code for a sliding cube in Blender.

At this point, having seen this code for the first time a few minutes ago, I have no idea how to use it, but hope to learn in the next few days.

If anyone is studying the Cycloid project, the current development phase is addition of text fields to show the status of various aspects of the simulation as it runs.   The automation need becomes apparent in consideration of the changes to the data that would occur every second, in a 30 second animation.  There are currently nine fields to be updated, and 30 update events. That would be 270 separate events (Keyframes) to be added to the timeline. It would be helpful to be able to run a script to generate all those Keyframes.

(th)

Offline

Like button can go here

#25 2024-05-02 06:43:06

tahanson43206
Moderator
Registered: 2018-04-27
Posts: 19,628

Re: Python Computer Language

For SpaceNut ... this post is ** really ** inside baseball...

import subprocess
import pyperclip

# Read the contents of the file into a variable
with open('file.txt', 'r') as f:
    text = f.read()

# Copy the text to the clipboard
pyperclip.copy(text)

The problem I am hoping to solve with the code snippet above is (probably) unique to the Azure environment we are using to test out changes to FluxBB 1.5.11 to allow us to upgrade the software to run with modern PHP and MySQL.

I am able to use the computer clipboard memory to pass data from local machine to the Azure machine without a problem.

The reverse trip does not appear to be possible using Nano as the text editor. Apparently Nano uses it's own buffer to hold copied data, and does NOT use the local computer memory.  The Python scripts above ** may ** be able to load data from an Azure file to the local computer clipboard.  I'll be testing the code later today.

The need for this arises from the fact I am doing debugging and editing on the local machine, but we are testing on Azure.  My goal is to insure that the software on the local machine and the Azure virtual machine is identical. 

In the case of search_idx.php, I found that there are more lines in the local version than in the Azure version.

This implies that I must have edited the Azure version to solve a problem, and did not go back to the local machine to duplicate the change.

Today's experiment will establish whether Python is indeed able to pass data from Azure to local via the clipboard.

(th)

Offline

Like button can go here

Board footer

Powered by FluxBB