We're sorry but this page doesn't work properly without JavaScript enabled. Please enable it to continue.
Feedback

Per Python ad Astra

00:00

Formal Metadata

Title
Per Python ad Astra
Title of Series
Part Number
48
Number of Parts
169
Author
License
CC Attribution - NonCommercial - ShareAlike 3.0 Unported:
You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal and non-commercial purpose as long as the work is attributed to the author in the manner specified by the author or licensor and the work or content is shared also in adapted form only under the conditions of this
Identifiers
Publisher
Release Date
Language

Content Metadata

Subject Area
Genre
Abstract
Juan Luis Cano - Per Python ad Astra In the intersection of mechanics, mathematics and "cool stuff that travels through space" lies Astrodynamics, a beautiful branch of physics that studies the motion of spacecraft. In this talk we will describe poliastro, a pure Python library we can use to compute orbital maneuvers, plot trajectories and much more. The role of JIT compiling (using numba) to drop the previously used FORTRAN algorithms will also be discussed, as well as the importance of open source in scientific discoveries. ----- In the intersection of mechanics, mathematics and "cool stuff that travels through space" lies Astrodynamics, a beautiful branch of physics that studies the motion of spacecraft. Rocket launches have never been so popular thanks to companies like Space X, more and more investors pay attention to aerospace startups and amazing missions explore our planet and our Solar System every day. In this talk we will describe poliastro, a pure Python library we can use to compute orbital maneuvers, plot trajectories and much more. The role of JIT compiling (using numba) to drop the previously used FORTRAN algorithms will also be discussed, as well as the importance of open source in scientific discoveries.
Software developerUniverse (mathematics)Library (computing)Computer programMultiplication signSurfaceTerm (mathematics)Lecture/Conference
Programmer (hardware)Software developerAlgorithmOpen sourcePower (physics)NumberEndliche ModelltheorieOpen setBitCovering spaceEvent horizonSystem callLecture/ConferenceComputer animation
VideoconferencingDemosceneMultiplication signSpacetimeField (computer science)Instance (computer science)InfinityCASE <Informatik>Lecture/Conference
Inheritance (object-oriented programming)RandomizationCoefficient of determinationFinite-state machineRight angleDistanceRoundness (object)DialectVideo gameComputer animation
VelocityLatin squareCurveArithmetic meanOrbitTrailBranch (computer science)Point (geometry)Multiplication signAnalogyFocus (optics)Roundness (object)AreaSpeciesLecture/Conference
Object (grammar)Auto mechanicPhysicsBranch (computer science)Classical electromagnetismObservational studySpacetimeDifferent (Kate Ryan album)Object (grammar)SpacetimeObservational studyPerturbation theorySatelliteComputer animation
VelocityBitLecture/Conference
Kepler conjecturePhase transitionConic sectionGravitationPoint (geometry)Two-body problemKepler conjectureNichtlineares GleichungssystemArithmetic progressionMathematicianInitial value problemCASE <Informatik>Point (geometry)TrajectorySpacetimePosition operatorMultiplication signGeometryState of matterOrbitSound effectMassDifferent (Kate Ryan album)BitRadiusMathematicsPropagatorMoment (mathematics)GravitationData structureCellular automaton1 (number)Theory of relativitySatelliteMonster groupLecture/ConferenceComputer animation
ArmLibrary (computing)Fluid staticsData conversionVector graphicsMultiplication signCoroutineLibrary (computing)Software developerFrequencyType theoryInstance (computer science)Arithmetic meanPhysical systemMetreMaß <Mathematik>Multiplication signFluid staticsBuildingBlock (periodic table)Position operatorProjective planeCASE <Informatik>Time zoneData compressionLecture/ConferenceComputer animation
Binary fileFile formatKernel (computing)Library (computing)Sound effectObservational studyMereologyBinary fileRange (statistics)Software developerBookmark (World Wide Web)Arithmetic meanPosition operatorVelocityLecture/ConferenceComputer animation
CodeNeuroinformatikState of matterProjective planeComputer fileDifferential equationAlgorithmNumeral (linguistics)Software testingInternetworkingBitMultiplication signLevel (video gaming)Endliche ModelltheorieNumberLecture/Conference
SubsetFormal languagePower (physics)CompilerArray data structureBefehlsprozessorNumerical analysisCodeSet (mathematics)AlgorithmLine (geometry)CompilerSubsetArray data structureFormal languageNumberNumeral (linguistics)Graphics processing unitNumerical analysisComputer animation
Revision controlMaxima and minimaIntelTable (information)Line (geometry)ResultantRevision controlTheoryOrder of magnitudeCodeCompilerMeasurementBitBinary fileNumberConfidence intervalWave packetLecture/ConferenceComputer animation
CASE <Informatik>CodeLine (geometry)WeightLecture/Conference
Distribution (mathematics)Forcing (mathematics)Library (computing)CodeCASE <Informatik>WindowLink (knot theory)Food energyCompilerSource codeLecture/Conference
OrbitPoint (geometry)Cue sportsTrajectoryVideoconferencingPosition operatorGravitationPlanningNetwork topologyMetropolitan area networkComputer animation
Radio-frequency identificationState of matterPlot (narrative)View (database)Cellular automatonLink (knot theory)Open sourceConditional-access moduleWikiMaxima and minimaAddressing modePersonal identification numberFrequencyInclusion mapTangentLine (geometry)Kernel (computing)Lie groupFlip-flop (electronics)3 (number)Cone penetration testVector graphicsCode12 (number)Insertion lossOrbitOrbitBitInternetworkingPlotterPropagatorVelocityPosition operatorNeuroinformatikMaterialization (paranormal)MultilaterationFunctional (mathematics)Instance (computer science)Computer fileModule (mathematics)Maß <Mathematik>Machine visionPoint (geometry)Multiplication signImpulse responseVariable (mathematics)Order (biology)Vector spaceState of matterLevel (video gaming)AstrophysicsObject (grammar)Limit (category theory)Arc (geometry)FrequencyNoise (electronics)1 (number)InferenceCategory of beingPhysicalismMereologyExecution unitAreaWordRight angleMetreFiber (mathematics)Lecture/ConferenceComputer animation
Power (physics)Different (Kate Ryan album)Library (computing)Projective planeCollaborationismOpen sourceBit ratePresentation of a groupPhysical systemFormal languageAreaRight angleLecture/Conference
SpacetimeEndliche ModelltheorieMultiplication signSpacetimeOpen sourceSource codeUniverse (mathematics)CircleDecimalDependent and independent variablesDifferent (Kate Ryan album)Mathematical analysisFlow separationCollaborationismComputer animationLecture/Conference
Phase transitionApproximationGravitationPoint (geometry)Point (geometry)Goodness of fitGravitationMixture modelStandard deviationConservation lawTrailNumberMereologyMultiplication signTrajectoryComputer animationLecture/Conference
Phase transitionReal-time operating systemMultiplication signLaptopDiagram
AlgorithmPoint (geometry)AreaTerm (mathematics)OrbitPropagatorElectronic mailing listSatelliteCalculationNeuroinformatikEndliche ModelltheorieLibrary (computing)Goodness of fitCASE <Informatik>Combinational logicWeightInstance (computer science)Key (cryptography)RandomizationTrajectoryObject (grammar)Multiplication signPressureVideo gamePerspective (visual)MereologyOpen sourceSphereProjective planeCue sportsDrag (physics)Complete metric spaceReal numberLecture/Conference
Transcript: English(auto-generated)
The title is Per-Python Ad Astra. And please welcome Juan Luis Cano. Well, as the previous speaker said, there's a Python library for everything in life, even for rocket science.
Well, let me introduce myself first. My name is Juan Luis Cano. I'm an almost aerospace engineer studying in Madrid, and right now working in finance as a Python developer for BBBA. I'm mostly a self-taught programmer because in university they used to let us forge a little bit of Matlab,
and we run all of our algorithms in Excel, so it was not a great background to start with. And I'm a passionate individual about open source, open hardware, open science, and its relevance in the world that we live in now. I'm also the chair of the Python Spain Nonprofit, and organizing many events like the Python Spain Conference,
the Python Madrid Meetup, and I remind you that the Python Spain call for purpose is still open, in case I didn't make it clear yesterday in my quick lightning talk. And, well, space, fascinating, isn't it?
Well, I found something very amusing about space, and it's that almost nobody knows how it works and what's going on up there, and yet it's like the only field adults are willing to accept their ignorance and ask all kind of questions. And I say adults here because children have this amazing superpower of asking almost everything
and this infinite curiosity that adults start losing with time. Well, so, wait a minute. Before explaining what is exactly this astrodynamics thing and give you any Wikipedia definitions, let us start with a little video.
You might recognize here, Clark Kent from the Super Mario and he's watching live through his alien eyes and this ridiculous haircut and wondering, what if I use my super strength to put this baseball in orbit? And so it goes, bye-bye, then the dogs quickly runs to catch the ball
but realizes the situation and turns his back to Clark like seriously, and then, well, the bat hits some random guy in New Zealand or something. So what's happening here? Like, well, Superman is super, super strong, so if he's launching the baseball very, very quick,
then he's going to reach a very long distance and as the earth is round, well, there are no flat earthers in this room, right? Because I'm going to disappoint you a lot. You might leave now. Okay, as the earth is round, then the ground is starting to curve under your feet, so the ball is hitting some point
to the other side of the world. Eventually, it's going to reach like New Zealand, the other side, and if you launch the baseball even quicker, then at some point, the ground is curving so fast that you never touch it and this is what we call orbital velocity
or orbital motion and free fall because you don't actually need any propulsion or any means to increase your velocity and you are just falling all the time. This example is not mine. It was devised by Newton in his masterpiece of the 17th century, Principia Mathematica,
and it's one of the earliest examples of a thought experiment, but obviously, he didn't use Superman for the analogy. The title of the track of the piece is in Latin and we will talk more about Latin at the end of the talk. Keep this in mind. Well, so with this in mind, what is astrodynamics exactly?
Well, it's a branch of celestial mechanics that studies the motion of human-made objects through space and there is a very essential, a couple of essential differences between studying the motion of the planets and the motion of human-made objects because the satellites, rockets, and stuff are so small that we have to take into account all the perturbations that might act to them
and also they have propulsion means so they can act on their own trajectory and correct their velocity and this complicates everything. Well, and this is where the introduction stops. I'm going to put a little bit of math,
but I'm going to try to keep it very simple. I don't need everybody in the audience to understand everything, but I just want you to keep in mind the ideas that are behind these kind of problems. I'm going to talk about the basic problems that we solve in astrodynamics and later on, I'm going to say how do I solve them in Python? Well, the first one is the two-body problem
which is just one body orbiting around another one. Okay, in the limiting case, we are considering that these masses have no radius. Okay, so they're just like geometric points in space and as we are usually considering like the motion of a spacecraft around a planet or a moon or something,
then we can assume that the second body is very, very small and doesn't have any effect on the orbit of the first one and that is the equation that controls everything. And the second one is the Kepler problem which is like the initial value problem of the thing that I said before.
I have some state and some moment in time, I have a position and a velocity and after some time, I want to know where my satellite, my spacecraft, whatever is going to be. This is called also propagation and these are the equations for the elliptical case that govern everything. And I want to put this here
because that equation over there, the first one, if you remember your secondary school mathematics, you cannot solve that equation for E, for capital E. And that is the, for some people, they say that this equation is so difficult to solve
that it motivated 200 years of mathematicians to develop many different and innovative techniques to solve it and we made huge progress in mathematics thanks to the structure of this equation. And the last one is the Lambert problem which is a little bit different
but it's still based on the same thing. I have one position and I want to reach another position in a given time so I want to know what is exactly the trajectory they have to develop. In the early, like when we are designing a trajectory around the solar system because I have some mission as I will say after this,
we can assume that all the planets are like points and only consider the gravity of the sun. So to solve all these kind of problems, I created Polyastro which is an astrodynamics library written in Python. It is released under a permissive license and you have physical units handling.
It solves all the problems that I said before. It included some basic 2D plotting as we will say after this. And it would be impossible without the work of many, many people. I'm going to talk about a couple of the dependencies. The first one, in case you don't know it, is Astropy which is like a basic astronomy library
written in Python. It's a joint effort of many, many developers around the world and it's meant to have the very building blocks of any astronomy project that you might have. For instance, it has physical units which is like static typing for engineers because if you mix meters with miles
or something like that, then very bad things start to happen. It has also handling of dates and times. If you think that handling some time zones is a pain, then you better don't enter the astronomical times. It's a real mess.
And it also changes the compression between reference systems so I can express one position with respect to the sun, with respect to the product, et cetera. The second one is JPL-IFM which is a library by Brandon Rhodes which is one of my favorite Python developers.
And the thing is that the NASA and the Jet Propulsion Laboratory, they provide some planetary positions and velocity in very broad range that go between hundreds or thousands of years. And they provide them in binary format which is called SPK. And with this library, I can take that data and know exactly where a planet is going to be
in the year 3000. Okay, so what happens with the very basic algorithms because this involves integrating differential equations and stuff like that. And when I started working on this, I said, okay, let's see what have other people done on this before me.
And I found a lot of Fortran, Matlab, Jiva algorithms that were okay because they worked and they had a very good performance. But the code was a bit poorly written. There were no tests whatsoever. They were very difficult to distribute because they were in a works on my computer state
released to the internet in a zip file. And wrapping those algorithms written in Fortran or C++ or whatever from Python is possible but it might be a challenge. So I ended up with a thing that only was known to work on my computer. And then some years after that, I discovered Numba
which is a project by Continuum Analytics that is also free. And it's meant to accelerate the code, the numerical Python code that uses a lot of number crunching, numerical computations, NumPy arrays. And it supports a subset of the language
and compiles to LLVM which is the compiler tool set that is getting very famous now. And also it supports GPUs. So I tried to rewrite all the algorithms that were included in thousands of lines of Fortran only in Python and let's see how it goes.
And these are the results of a paper that I presented to the European Space Agency seven months ago. And if you can see here, the top line was the previous version compiled with the Intel Fortran compiler which in theory is one of the best ones. There is the reference for all the performance measures.
And with GFortran it was a bit slower like I lost 30% of the performance. And then you can see the bottom line is the Python code which is like two orders of magnitude is lower than Fortran which is the expected result. And then you have here this Python plus Numba result
that is visibly slower than Fortran but it's still more or less within the same order of magnitude. So I said well I'm going to throw to the trash bin thousands of lines of Fortran, a lot of pain and in return I'm going to lose 70% of performance
that in any case I can optimize later or wait for the technology to develop. So this is more or less what I did with this Fortran code. Yeah, I was very happy to throw all this away because now the people that know Python which are much more than the people that know Fortran
can easily contribute to my library. I can understand the code 10 months later after writing it and the distribution is much easier because I don't need to force everybody in Windows to have a Fortran compiler and in any case who knows what's that, yeah, anyway. So to give a practical example of this
as this talk was presented in the hot topics call for papers I wanted to bring something really, really hot which is the arrival of the Juno mission to Jupiter the other day. If I can press this link, thank you.
Okay, wait a minute. The Juno spacecraft was a mission that NASA launched in 2011, okay, as you can see here and it arrived to Jupiter two weeks ago. So it's been quite a long trip and the trajectory was pretty involved as you can see. There you have the orbit of the Earth in August 2011
and the first thing is launching this Juno spacecraft in a very wide orbit that even crosses the orbit of Mars and you waste no fuel in all this arc here. And what it's going to do next is going to perform a maneuver over here
in the point that is most far away from the sun to correct the trajectory and try to encounter the Earth in a different point. So exactly at that point without losing any fuel it's using the gravity of the Earth to change the trajectory and go to the orbit of Jupiter.
Well, the video goes blah, blah, blah and when we arrive to the end I remind you that it was launched in 2011 and in July 2016 this arrived to Jupiter. And this is like cosmic billiards because the planning of this trajectory
involves a lot of main hours and you have to take into account the positions of all the planets and for me it's so beautiful. And so what we can do now is reproduce exactly this orbit with polyester.
So if I go this to this wonderful IPython notebook, let's do this a bit quickly. Okay, so here I'm importing a lot of modules from polyester which include like the vision of the planets of the solar system, the sun, some objects to provide an API and here for instance what I'm doing is downloading these files from NASA
that I told you before to compute all the positions of the planets. I already have them in my computer. And here are some data that I got from the internet like the date of launch, the velocity of the initial maneuver, the date of the flyby of the Earth and the date of arrival. So the first thing that I'm going to do is to recover the position and the velocity of the Earth
in the date of the launch. And I can have here a couple of vectors. And as you can see, this is handling physical units using Astro Pi. So if I use these high level functions that I'm providing with polyester, there is no risk of mixing physical units. If I provide a vector in kilometers
and another one in meters, then everything is going to be in order. And if I provide some incorrect unit, then it's going to warn me. So I create some state which is going to hold some variables that we need later. And I do the same thing, computing the position and the velocity of the Earth the day of the flyby, okay?
So then I'm going to use these maneuver objects to say, okay, now I'm on the Earth the day of the launch and I'm going to do the first impulse to get into the first orbit. So if I apply the maneuver and I see the period of the orbit, this means the time that it takes to one complete orbit to complete,
then we see that it's above two years. So the period of the orbit of the Earth is obviously one year. So now I'm spending two. If I plug this thing, then I have the position, the orbit of the Earth and the first orbit of the spacecraft. If I go on doing this,
propagating and computing some more velocities and data that I need, then I have not only the position of the Earth and the first orbit, but also the point where I'm correcting the orbit to encounter the Earth one year later. If I go on using these functions that you can check,
I'm going to upload all the materials and plot this, as you can see, the API is pretty simple. Then I have this complete plot of all the segments of the orbit. You can see here, the orbit of the Earth,
the first segment, then the correction. This is the point of the flyby and then this is the last arc until I go to Jupiter. I wanted to stop here because there are some limitations in the API of polyester because for instance, I'm plotting all the segments that I don't travel through,
for instance, like this one. So there is a little bit of noise in this plot and also the three-dimensional API is not existing yet. So I won't go many pull requests. So going back to my presentation,
well, the conclusion of this is that Python not only works as a language, but it can be fast enough using some tricks for some purposes and we can optimize it later and improve the readability and everything. The ecosystem of libraries that we have for solving this kind of problems is amazing and people is pouring a lot of work into this
and it powers a lot of different projects. There are several things missing in polyester as I told you before and the good thing is that open development, developing everything on GitHub, pouring good documentation, writing tutorials is key for encouraging collaboration
and making this as easy to develop as possible. Before finishing my talk, I wanted to explain the title because it's a Latin catchphrase that used as a motto of the Royal Air Force which was per ardo adastra,
through struggle to space. This open source thing, it's many times a struggle. Maybe you have felt it in the past, especially pushing it to businesses and companies. So I wanted to tell you that per Python adastra to reflect that fact and also I wanted to put again the picture of the International Space Station
which is a collaboration between the United States, Russia, China, Europe and many other countries which for me means that even through political differences and historical differences, we can collaborate to build great things. So thank you very much. Keep dreaming. Don't lose your curiosity and thank you.
Thank you for a very nice talk. Do you have any question? Yes, we have. This was awesome, thank you. And now I want to say, I have a question. I read once that when we went to the moon,
they were using it that if you looked into the source code they were using six decimal places for pi. Which was funny because usually we try to use like a lot and no, you don't need that many and you can put people there. So could we use this thing to send people to the moon? No, and I'm going to explain why.
Well, the first is that contrary to popular belief, you don't need that many decimal places for pi and if you use like 10, then you can approximate the circle of the universe to the size of the human hair or something like that. It's ridiculous. The thing is that with polyester, I'm taking into account only this problem that is like only assuming that my body is very small
and also with the lumber problem that is calculated directly from point A to point B. And you see, I'm only taking into account one body of gravitational attraction. And when you're going from the Earth to the moon, you cannot do that because the moon is very big, it's very close to the Earth and in all the trajectory,
you have to take into account both bodies. So for now, we cannot use it to go to the moon but we can go to Mars. The moon is very boring, there's nothing there. Very well, do we have other questions?
Yes? You recreated Juno's trajectory, which is great. Sorry, can you repeat again? You recreated Juno's trajectory.
About Juno's trajectory, yes. I don't think I have a picture here. Yes. This, here, this one. I was wondering how much time did it take to recreate it? Sorry, I didn't understand.
How much time did it take to recreate it? To recreate it? Yes, to do this. I did it in real time right now. Like I just did it, I didn't have anything, well, I calculated the notebook an hour before but I restarted it so I'm computing everything on the fly.
Like all the algorithms, like going from point A to point B, they are extremely fast now. And the complete trajectory, like in real life, is taking like five years or something, or six years. Other questions? Yes?
Hi, good talk. My question is if from point A to point B is super fast, what would be a challenge on computing or whatever for this library? Yeah, the thing is that, well, I didn't say it, I think, but for many practical problems, you have to compute these solutions thousands of times.
For instance, when you want to optimize an orbit and say, okay, I'm going to try this billiards thing. For instance, there was a contest some months ago and there were solutions like, I don't know, go one flyby on the Earth, then Venus, then Mars, and then Jupiter, or there are many combinations as, well, you can imagine that there are many,
many combinations, and you have to compute these solutions thousands of times. So even if this is very fast to do it once, then if you start adding up and computing this a lot of times, then it's critical to have a good performance. Other questions?
I have a question myself, because I didn't exactly know what you were presenting, but I tested polyester because I'm doing calculation with orbital dynamics, but with satellites, low Earth satellites. Are you going to add the J2 term someday?
No, no, and I tell you why. Because this is going to be optimized for interplanetary trajectories. So for low Earth orbits, you have to take many things into account, like the thing that the Earth is not a sphere, but it's something like a pier, very strange, and also the pressure of the sun, because the sun pushes you when you are in orbit,
and you can actually feel the light displacing you. So I don't think I'm going to add those, but we have a parallel project with which hopefully we will try to be more suitable for near-Earth objects. So do you know any Python library
that can be used for low Earth orbit? Well, you have, for example, the library from Brandon Rhodes. Yes, thank you. At least you can compute the SDP-4 propagation model, which takes into account the orbital drag and stuff like that, so it's pretty accurate for most things, like for calculating
when some piece of space debris is going to hit us in our heads. Other questions? Okay, if this is not the case, please. Okay, thanks again, our speaker.