Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
Are there any good up-to-date physics libraries for Python that are for Linux? I'm just getting into Python using PyGame, but PyGame's lack of a physics library isn't cool. I spent about two hours trying to find a good physics library but it's like trying to grab oil; I can't seem to do it.
I barely need a physics engine at all; all I want to do is program an object to 'jump' up and then fall back to the ground. There seems to be some simple collisions going on (which PyGame can handle, I think) but it's the actual jump calculation that's stumping me. If it turns out that there aren't any good ususable physics libraries, the problem seems simple enough that I might just try to find a basic acceleration equation and a gravity equation and try to apply those... I'd like to avoid having to do that, though.
Thanks for any help.
Pymunk is another promising one that you might want to take a look at.
Try pyODE, it is the python binding of open dynamic engine.
You can find more information here
The basic physics kinematic equations are all you need. Even though the questions was already answered, if I were you, I'd still do it by hand just because using a library seems like overkill. Start the equation for velocity:
velocity = initial velocity + (acceleration * time)
From there, we integrate to find position:
position = initial position + (initial velocity * time) + (acceleration * time^2)/2
Your jump is looking to calculate the y position of the character, so just use that equation to calculate y position and toy with initial velocity and acceleration. Standard acceleration due to gravity is -9.8 meters per second^2 (at least on the surface of the earth - it's different son different planets). Start with initial position whatever your character is at, or 0 if the ground is 0 to you.
So:
y = vt + (-4.9)t^2
Pick an initial velocity v value to provide the upward movement when the jump starts, and t should be the elapsed game time since he started jumping.
You only need one line of code to do this, no libraries necessary!
EDIT: dealing with what to do when you land.
So in the real world, acceleration is caused by unbalanced forces. Gravity is always acting on you, but when you're standing in the ground, it's being countered and canceled out by the "normal force" of the ground. As long as the ground you're standing on is strong enough to support your weight, the ground will push back up and counter gravity and you will not accelerate downward. So in your game, if you're not actually simulating forces, just change the acceleration from -9.8 to 0 when your character is touching the ground. If the ground is flat, your jump ends when position = initial position
According to the ODE website's installation instructions, the ODE package itself now contains Python bindings based on CPython; and the pyODE bindings are considered obsolete. Installation instructions are included in the above page.
By default this is for Python 2, but I was able to make this binding work with Python 3, too, with a minimum amount of work (Mac OS X). I could even run the tutorials.
This might be out of topic, but just for the record, here is what I had to change:
I had to change OpCode.h by uncommenting the #defines for sqrt, sin, cos, asin and acos (lines 33-37, file version: March 20, 2001). This is an ugly hack that I needed because without this ODE itself did not compile with double precision arithmetic, which one needs to use with the python bindings if we can trust the documentation on the ODE page.
I had to change setup.py by adding the following lines after line 18:
# bugfix: in Python3 read() returns bytes, which need to be converted
# to strings
try:
ode_cflags = [x.decode("utf-8") for x in ode_cflags]
ode_libs = [x.decode("utf-8") for x in ode_libs]
except:
# in Python2 we just continue
pass
To run the tutorials, in the demos directory I used
$ 2to3 -w *.py
That's it.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 11 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I was simulating the solar system (Sun, Earth and Moon). When I first started working on the project, I used the base units: meters for distance, seconds for time, and metres per second for velocity. Because I was dealing with the solar system, the numbers were pretty big, for example the distance between the Earth and Sun is 150·10⁹ m.
When I numerically integrated the system with scipy.solve_ivp, the results were completely wrong. Here is an example of Earth and Moon trajectories.
But then I got a suggestion from a friend that I should use standardised units: astronomical unit (AU) for distance and years for time. And the simulation started working flawlessly!
My question is: Why is this a generally valid advice for problems such as mine? (Mind that this is not about my specific problem which was already solved, but rather why the solution worked.)
Most, if not all integration modules work best out of the box if:
your dynamical variables have the same order of magnitude;
that order of magnitude is 1;
the smallest time scale of your dynamics also has the order of magnitude 1.
This typically fails for astronomical simulations where the orders of magnitude vary and values as well as time scales are often large in typical units.
The reason for the above behaviour of integrators is that they use step-size adaption, i.e., the integration step is adjusted to keep the estimated error at a defined level.
The step-size adaption in turn is governed by a lot of parameters like absolute tolerance, relative tolerance, minimum time step, etc.
You can usually tweak these parameters, but if you don’t, there need to be some default values and these default values are chosen with the above setup in mind.
Digression
You might ask yourself: Can these parameters not be chosen more dynamically? As a developer and maintainer of an integration module, I would roughly expect that introducing such automatisms has the following consequences:
About twenty in a thousand users will not run into problems like yours.
About fifty a thousand users (including the above) miss an opportunity to learn rudimentary knowledge about how integrators work and reading documentations.
About one in thousand users will run into a horrible problem with the automatisms that is much more difficult to solve than the above.
I need to introduce new parameters governing the automatisms that are even harder to grasp for the average user.
I spend a lot of time in devising and implementing the automatisms.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Ok so I am struggling in this computer programming class, as I am totally new to computer programming. let me post my actual assignment and then see if anyone could help get me started with it.
assignment:
This Lab is Part 1 of building a type of fractal called a Lindenmayer system.
In this first part, you will just be implementing symple set of draw commands.
Write a program that takes 3 inputs:
1) Draw String: This must be a string of draw commands (see the table below).
2) Length: This must be an integer equal greater than 0 and less than or equal to 100. It defines the length variable used in some of the draw commands.
3) Angle: This must be a floating point number equal greater than 0.0 and less than or equal to 360.0. It defines the angle variable used in some of the draw commands.
Character Draw Commands
h
Draw a straight line segment length pixels long in the current heading.
f
Same as h
g
Move, without drawing, a straight line segment length pixels long in the current heading.
+
Turn the heading clockwise by angle.
Turn the heading counter-clockwise by angle.
A
Each of these color commands must change the turtle color to color that is different form the background and different from the other 5 color commands. Pick colors that you think look good together.
B
C
D
E
F
any other character
Ignore
So, that is the assignment, sorry it's so long. I have been reading my textbook, and unfortunately it gives very little info on how to actually do this assignment. It also didn't help that our professor showed us all these cool things fractals could do, but didn't actually tell us anything about how to do the assignment (don't ask me why?)
I am really at a loss as to how to even begin to code this thing, if someone could help me or at least point me in the right direction, at starting to go about coding for this stuff, it would really help me out. I don't expect anyone to do it all for me, just maybe help show me where to begin.
PS. There is one other thin our professor wrote that is probably important.
Now that you have the "if" statement at your command, you do need to check for bad input. If the user inputs bad data, print an error message and exit the program.
Your assignment seems simple to me so make sure you don't overthink it just because the professor showed you some strange sorcery! Yes fractals can do a lot of cool ( and complicated ) things but your professor is not asking you to do any super complex stuff. The first thing you want to do is look at the Official Python Tutorial. For this turtle assignment, you do not need to read all of the tutorial. Simply read the first four sections (up to the end of More Control Flow Tools) to get a good grasp on all the tools you'll need to do this assignment. I assume the main things you will need are functions and basic control flow statements so pay close attention to those parts.
The next thing you want to do is look at the documentation for the turtle module. Learn the basic commands, specifically turtle.up(), turtle.down() and how to move and rotate the turtle around on your screen. Think of your turtle as a "pen" that has an orientation and you have to tell that "pen" exactly what to do with Python commands. That should be more than enough to get you started on this assignment. Good luck to you and welcome to the world of programming. :)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
So I've been thinking of creating a program similar to this in Python. The problem is that I know next to nothing about AI. Right now I'm reading up on genetic algorithms and neural networks and such, but there's a lot of things to absorb.
My largest problem now is I don't know how the entire thing is put together. So if anyone can tell me the general framework for a program like this, I'll be really grateful. For example, how the creatures can "see" things in their surroundings, the kind of "chromosomes" they have and how the environment is created.
Also, can anyone suggest suitable libraries for AIs, any engines, etc? I've been thinking of using neurolab, will that be a good idea?
Thanks!
Interestingly, I've created what you're describing, in Python.
Here's a pic:
The green dots are food, and the red ones are organisms that need to evolve and learn how to eat the food blocks.
The best source of inspiration and guidance for something like this is definitely Polyworld: youtube.com/watch?v=_m97_kL4ox0.
Another great example which helped me learn about backpropagation, which I suggest you should learn too, is here: arctrix.com/nas/python/bpnn.py.
Although this question is simply too vague to answer correctly, the general tip is that you first get a solid ground on how ANN's function, and then construct a program with this general algorithm:
Check for user input (should the camera move? should the program quit?)
For each organism:
Check if it is alive, etc.
Take input from the world
Evaluate its neural network
Apply the results to the physical body
Apply positive or negative feedback (as you'll see, it all comes down to this)
Update the world (you can use a physics engine)
Optionally, draw the world
For example, your input neurons could correspond with physical or visual stimulation. Is there something in front of me? Then set neuron X to 1, otherwise to 0.
And your output neurons could map into forces. Is neuron Y active? If so, apply an impulse to this organism's in this world cycle.
I also recommend that you don't use other people's libraries for your neural network computation, because this is a great way to actually learn how to implement them yourself. You could you Pygame for rendering, and PyBox2D for physics, though.
Now, about "seeing" other organisms... These problems are best solved when isolated. You need a good software design, that will enable you to divide the whole problem into many subproblems, which are easier to solve.
In general, seeing can be done by raycasting. Create a directional, normalized vector (where the length is 1 unit, that is, sqrt(x*x + y*y) == 1), and then scale it (x *= factor; y *= factor;). That way, you get a line that's stretching outwards. Before you scale it, you can then loop through all of the organisms in the world (you'll have to optimize this), and check if the vector is inside of them. If it is, calculate its length, and your organism has some information about its surroundings.
There are many simpler ways. For example, divide space around each organism into four quadrants, which four represent eyes (X - up, right, down, left of the organism). Then calculate the length from the organism to every other organism (optimize!). Find the closest organism. Find out in which quadrant it is. Voila, an active eye!
I hope I was helpful, but you'll have to be more precise and come back when you have an actual problem. Read the FAQ as well.
http://scikit-learn.org/ is a great resource (and framework) for you to learn about machine learning in python.
If you want to build a neural network, http://pybrain.org/ is a good framework.
full EDIT:
I will give some more information about the whole problem. The project is in early stage and my question is actually only about a narrow portion of the thing.
the final goal:
I am currently trying to simulate the flow of hot air around a rigid obstacle in Python. I have a steady inflow of air, the flow in the bulk is transient and turbulent. The aim of the whole exercise is to understand how
-the air flow behaves
-the obstacle heats up
-the air cools down and the air-pressure drops
done so far:
Not much, the thing is in early stage. I have a 2d rectangular domain and a circular obstacle. The mesh is getting finer at the boundary between bulk and obstacle, since that is where the interesting stuff is happening. Currently I only consider the airflow, no convection or heat transfer. I use the FEniCS software collection to solve the Navier-Stokes equation. Fenics comes with an example for an N-S solver using the Chorin projection method, I adapted this example to my setting. I model the rigid body as an area with no-slip boundary condition (i.e. I set the velocity of the air flow to zero). The solver still solves the N-S equation in that area, in particular the pressure inside the obstacle changes over time. Probably it is a better idea to avoid this and restrict the N-S solver to the bulk. But at the moment I don't think this affects the speed very much.
problem:
The thing runs quite slow. I do not mind if the final simulations takes a few days, but currently it is only 2d fluid flow around an obstacle and the mesh is not as fine as I want it to be in the end. I hoped this to be faster, as it will become a lot more complicated when the heat comes into play.
my question:
It boils down to one question:
What is a fast algorithm or method to solve the Navier-Stokes equation in Python?
I am perfectly fine with writing a solver from scratch, but this raises the same question. This morning it occured to me that the projection method is maybe not the worst idea, because it decouples the pressure and velocity upgrade, I could try to assign this to different CPU kernels.
Python would actually be a fine choice if you were writing it all from scratch. But you'll need a LOT of background to do it from scratch.
A coupled solution is a difficult problem.
It's been pointed out to me that you're using a package - FEniCS (thank you, Sven). My original answer needs some amendment. I'll start with a few questions about the physics, then turn to the package.
Incompressible Navier Stokes applies to a gas like air if the Mach number for air at that temperature is less than 0.1. Is that the case for your problem? It's probably true, but I thought I'd ask.
Navier Stokes does NOT apply to your solid obstacle. If you model the whole thing with one mesh, how are you describing the solid? Is it a high viscosity fluid? This could make the system of equations ill-conditioned and hard to solve. It would also affect the stable time step size if you're using explicit integration.
Is it a steady flow or a transient? (steady is easier) Is the flow laminar or turbulent? (laminar is easier)
It's conduction heat transfer in your solid obstacle and conduction/convection in your fluid. The fluid will have momentum and thermal boundary layers along the solid obstacle of the surface that your mesh will have to resolve. That's where the important heat transfer between the solid and fluid is happening. These will require a fine mesh local to the solid surface to resolve the transition from the boundary condition to the far field velocity and temperature. Have you taken that into account in your mesh?
It appears to me that FEniCS is using finite elements, but I don't see anything in the docs that tells me how you're supposed to couple the momentum and energy equations together.
You'll have to tell a great deal more to get decent advice here. Is there a numerical methods in physics Stackoverflow? You'll need it.
I'm working on an adventure game in Python using Pygame. My main problem is how I am going to define the boundaries of the room and make the main character walk aroud without hitting a boundary every time. Sadly, I have never studied algorithms so I have no clue on how to calculate a path. I know this question is quite general and hard to answer but a point in the right direction would be very appreciated. Thanks!
There are two easy ways of defining your boundaries which are appropriate for such a game.
The simpler method is to divide your area into a grid, and use a 2D array to keep track of which squares in the grid are passable. Usually, this array stores your map information too, so in each position, there is a number that indicates whether that square contains grass or wall or road or mountain etc. (and therefore what picture to display). To give you a rough picture:
######
#.# #
# ## #
# #
######
A more complex method which is necessary if you want a sort of "maze" look, with thin walls, is to use a 2D array that indicates whether there is a vertical wall in between grid squares, and also whether there is a horizontal wall between grid squares. A rough picture (it looks a stretched in ASCII but hopefully you'll get the point):
- - - -
| | |
- -
| |
- - - -
The next thing to decide is what directions your character may move in (up/down/left/right is easiest, but diagonals are not too much harder). Then the program basically has to "mentally" explore the area, starting from your current position, hoping to come across the destination.
A simple search that is easy to implement for up/down/left/right and will find you the shortest path, if there is one, is called Breadth-First search. Here is some pseudocode:
queue = new Queue #just a simple first-in-first-out
queue.push(startNode)
while not queue.empty():
exploreNode = queue.pop()
if isWalkable(exploreNode): #this doesn't work if you use
#"thin walls". The check must go
#where the pushes are instead
if isTarget(exploreNode):
#success!!!
else:
#push all neighbours
queue.push( exploreNode.up )
queue.push( exploreNode.down )
queue.push( exploreNode.left )
queue.push( exploreNode.right )
This algorithm is slow for large maps, but it will get you used to some graph-search and pathfinding concepts. Once you've verified that it works properly, you can try replacing it with A* or something similar, which should give the same results in less time!
A* and many other searching algorithms use a priority queue instead of a FIFO queue. This lets them consider "more likely" paths first, but get around to the roundabout paths if it turns out that the more direct paths are blocked.
I recommend you read up on the A* search algorithm as it is commonly used in games for pathing problems.
If this game is two dimensional (or 2.5) I suggest you use a tile system as checking for collisions will be easier. Theres lots of information online that can get you started with these.
Sadly, I have never studied algorithms so I have no clue on how to calculate a path.
Before you start writing games, you should educate yourself on those. This takes a little more effort at the beginning, but will save you much time later.
I am not familiar with pygame, but many applications commonly use bounding volumes to define the edge of some region. The idea is that as your character walks, you will check if the characters volume intersects with the volume of a wall. You can then either adjust the velocity or stop your character from moving. Use differing shapes to get a smooth wall so that your character doesn't get stuck on the pointy edges.
These concepts can be used for any application which requires quick edge and bounds detection.