planet hunting with python richard p. nelson, guillem anglada …€¦ · richard p. nelson,...

36
1 Planet Hunting with Python Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University of London Abstract NASA’s Kepler spacecraft was launched in 2009 and spent approximately 4 years staring at 150,000 stars, searching for planets orbiting around them using the transit detection method. The mission resulted in the discovery of 4717 exoplanet candidates, of which 2303 have been confirmed as bona fide planets, and a number of which are found to reside in multi-planet systems. More recently, NASA’s TESS planet hunting mission was launched and is now taking data. During your research, you will learn to write computer programmes in the Python programming language, and you will use your newly developed skills to write routines to analyse data from the Kepler and TESS missions using simplified algorithms. You will analyse light curves that have been downloaded from the Kepler and TESS spacecraft, and determine the key physical parameters of the planetary systems including orbital periods, orbital inclinations to the line of sight, orbital semi-major axes (i.e. the distance between the star and the planet), and the physical radii of the planets. You will learn about fitting models to data, and techniques for optimising the accuracy of these models. Based on your analysis, you will be able to draw conclusions about the observed population of exoplanets, including whether or not they look like the planets in our Solar Systems, and explore how dynamical interactions between planets in multi-planet systems can be detected in the data. Introduction The first extrasolar planet discovered orbiting a Sun-like star was 51 Pegasi b (Mayor & Queloz 1995), and this discovery led to Michel Mayor and Didier Queloz being awarded the Nobel Prize for Physics in 2019. During the 24 years since this ground-breaking discovery, the total number of confirmed extrasolar planets has increased to 4,073 1 with new discoveries being made on an almost daily basis. We now know that the population of exoplanets in our Galaxy is very diverse, and that our Solar System does not provide an example of the most typical architecture. The launch of the Kepler spacecraft in March 2009 heralded a dramatic improvement in our knowledge about exoplanets (Borucki et al 2010). Kepler was launched into an Earth-trailing heliocentric orbit, which allowed it to stare 1 Number taken from exoplanetarchive.ipac.caltech.edu in October 2019.

Upload: others

Post on 13-Oct-2020

15 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

1

PlanetHuntingwithPython

RichardP.Nelson,GuillemAnglada-Escudé&GavinColemanSchoolofPhysics&Astronomy,QueenMaryUniversityofLondon

AbstractNASA’sKeplerspacecraftwaslaunchedin2009andspentapproximately4yearsstaringat150,000stars,searchingforplanetsorbitingaroundthemusingthetransitdetectionmethod.Themissionresultedinthediscoveryof4717exoplanetcandidates,ofwhich2303havebeenconfirmedasbonafideplanets,andanumberofwhicharefoundtoresideinmulti-planetsystems.Morerecently,NASA’sTESSplanethuntingmissionwaslaunchedandisnowtakingdata.Duringyourresearch,youwilllearntowritecomputerprogrammesinthePythonprogramminglanguage,andyouwilluseyournewlydevelopedskillstowriteroutinestoanalysedatafromtheKeplerandTESSmissionsusingsimplifiedalgorithms.YouwillanalyselightcurvesthathavebeendownloadedfromtheKeplerandTESSspacecraft,anddeterminethekeyphysicalparametersoftheplanetarysystemsincludingorbitalperiods,orbitalinclinationstothelineofsight,orbitalsemi-majoraxes(i.e.thedistancebetweenthestarandtheplanet),andthephysicalradiioftheplanets.Youwilllearnaboutfittingmodelstodata,andtechniquesforoptimisingtheaccuracyofthesemodels.Basedonyouranalysis,youwillbeabletodrawconclusionsabouttheobservedpopulationofexoplanets,includingwhetherornottheylookliketheplanetsinourSolarSystems,andexplorehowdynamicalinteractionsbetweenplanetsinmulti-planetsystemscanbedetectedinthedata.IntroductionThefirstextrasolarplanetdiscoveredorbitingaSun-likestarwas51Pegasib(Mayor&Queloz1995),andthisdiscoveryledtoMichelMayorandDidierQuelozbeingawardedtheNobelPrizeforPhysicsin2019.Duringthe24yearssincethisground-breakingdiscovery,thetotalnumberofconfirmedextrasolarplanetshasincreasedto4,0731withnewdiscoveriesbeingmadeonanalmostdailybasis.WenowknowthatthepopulationofexoplanetsinourGalaxyisverydiverse,andthatourSolarSystemdoesnotprovideanexampleofthemosttypicalarchitecture.ThelaunchoftheKeplerspacecraftinMarch2009heraldedadramaticimprovementinourknowledgeaboutexoplanets(Boruckietal2010).KeplerwaslaunchedintoanEarth-trailingheliocentricorbit,whichallowedittostare

1Numbertakenfromexoplanetarchive.ipac.caltech.eduinOctober2019.

Page 2: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

2

continuouslyatoneregionoftheskyforaperiodofapproximately4years2.Themissionusedthetransitdetectiontechniquetofindplanets.Thismethodlooksfortheperiodicdimmingofthelightfromastarasseenbyanobserverwhenaplanetpassesinfrontofthestarduringitsorbit(seeFig.1).

Figure1:Thisdiagramillustratesthephysicalprinciplesbehindthetransitdetectionmethod.Whenanorbitingplanetpassesinfrontofitshoststar,someofthelightfromthestarisblockedoutandthestarappearstodimslightly.Detectingtheperiodicdimmingofadistantstarmaythereforeindicatethepresenceofaplanet.

Forgeometricalreasons,mostplanetaryorbitsarounddistantstarsdonotcausetheplanettopassinfrontofthestarwhenobservedbytheKeplerspacecraft.Forarandomlyorientatedorbittheprobabilityofobservingatransitistypicallyabout1%,soforthisreasontheKeplerspacecraftmonitoredthebrightnessofapproximately150,000starsforthedurationofthemission,resultinginthediscoveryof4717planetcandidates,ofwhich2303havebeenconfirmedtobegenuineexoplanets.Notethattherearenumerouswaysinwhichdifferentastrophysicalphenomenacanmimicatransitingplanet,hencetheneedforadditionalobservationsthatareabletoconfirmtheplanetarynatureoftheKeplerplanetcandidatesystems.TheKeplerspacecraftproduceddataintheformoflightcurvesforeachoftheobservedstars–datafilesthatlistthetimeofobservationandthebrightnessofthestaroveranextendedperiodoftime.Theselightcurveswerethenprocessedtoremoveartefactsandotherunwantedfeaturesfromthedata(aprocessknownasdetrending)priortothedatabeingmadeavailableforscientiststoanalyse.SeeFig.2foranexampleofadetrendedlightcurve.Youwillusethesedetrendedlightcurvesinyouranalysis,andoneofthethingsthatyouwilllearnishowtodownloadthedatafilesforindividualsystemsfromtheKeplerdataarchivesothatyoucanchoosewhichsystemstoanalyse.2MoreinformationabouttheKeplermissioncanbefoundatkepler.nasa.gov

Page 3: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

3

Figure2.ThetoppanelshowsadetrendedlightcurveforthesystemKepler7b.They-axisshowsthefluxoflightfromthestarinarbitraryunitsandthex-axisshowsthetime(inunitscalledJuliandays).Theperiodicdipsinthelightcurvecorrespondtowhentheplanetispassinginfrontofthestar.Thelowerpanelshowswhatiscalledthephase-foldedlightcurve(blackcrosses)withamodelfittedtoit(redcurve).Thephase–foldedcurvecontainsallthedatainthetoppanel,butplottedsothatthemid-pointofeachtransitoccursattimet=0.

Aprimaryaimofthisprojectistoprovidehands-onexperienceofprogramminginPythonwithinthecontextofastronomicaldataanalysis.Pythonisbecomingacommonlyusedprogramminglanguageinmanyareasoflife,includinginthescientificworldwhereitisusedfordataanalysisandmathematicalmodelling,andinschoolsanduniversitieswhereitisbecomingthelanguageofchoicewhenteachingcomputerprogramming.Python’sincreasingpopularityarisesforanumberofreasons:itisfreetouse;itrunsunderalloperatingsystems(Windows,MacOSX,Linux);itsbasicstructureandsyntaxissimilartomanyotherlanguages;itcontainstheabilitytoperformmathematicalcalculationsandtoplotdataingraphicalformwithinaself-containedprogrammingpackage.Laterinthisdocumentyouwillbeprovidedwithasequenceofprogrammingtasksofincreasingcomplexitytohelpyoudevelopyourprogrammingskillsinincrementalstages.

Page 4: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

4

ObtainingphysicalinformationfromtransitdataFromFig.1wecanseethatareasonablemodelforaplanetarytransitistoassumethatanopaquecirculardiscofradiusRpmovesacrossauniformlyluminouscirculardiscofradiusRs,blockingsomefractionofthelightdetectedbyanobserver.Here,RpandRsaretheradiioftheplanetandstar,respectively.ObtainingtheplanetradiusfromthelightcurveExercise:Usingthesimplemodeldescribedabove,andshowninFig.1,foraplanetarytransit,obtainanexpressionforthechangeintheobservedluminosityofastarofradiusRswhenaplanetofradiusRptransitsinfrontofit.Inparticular,obtainanexpressionforΔL/LsintermsofRsandRp,whereΔL=Ls-LTandLsdenotesthestellarluminositywhentheplanetisnottransiting,andLTdenotestheobservedluminositywhentheplanetisatthemid-transitpoint.[Hint.Thinkaboutwhatfractionoftheemittedlightfromthestarisblockedoutbytheopaquedisc(i.e.theplanet)passinginfrontofit.ThesurfaceareaofthestarisπRs2andtheareaoftheplanetisπRp2.Theluminosityorbrightnessofauniformlyemittingdisc(i.e.thestar)canbewrittenasthefluxofradiationbeingemittedfromthesurfacemultipliedbythesurfaceareaofthedisc.Thefluxisdefinedtobetheamountofradiationemittedbythediscperunitareaperunittime.]Solution:Yourteacherhasthesolution.Trytoworkitoutforyourselfbeforeseekingassistance.Planet’sorbitalperiodObtainingtheplanet’sorbitalperiodfromatransitlightcurveiseasywhenthereisasingleplanettransitingastar.Itissimplythetimethatelapsesbetweensuccessivedipsinthelightcurve.WhenyoustarttoworkwiththeKeplerdata,youwillnoticethatthetimeslistedinthelightcurvedatafiles,andonthewebsitethathoststhedataarchive,areinstrangeunits–“BarycentricJulianDayminusaconstantoffset”(abbreviatedtoeitherBJDor[BJD–2454833]).Forcomplicatedhistoricalreasons,astronomersmeasuretimefromnoononthe1stJanuary4714BC.ThisdayisknownasJulianDayzero,andallsubsequentdaysareknownasJulianDay1,2,3,4,5,…Thenumber2,454,833mentionedabovecorrespondstonoonon1stJanuary2009andissubtractedfromtheJuliandateinordertomakethenumbersmoremanageable.HencethetimeslistedinKeplerlightcurvesarethenumberofdayssincenoonon1stJanuary2009.

Page 5: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

5

Orbitalsemi-majoraxisIfweassumethatthetransitingplanetsareincircularorbitaroundtheirstars,thenwecanobtainanexpressionforthesemi-majoraxisoftheorbit(thedistancebetweenthestarandplanetduringitsorbit)intermsofthemassofthestar(whichcanbeobtainedfromtheKeplerdataarchive)andtheorbitalperiod(whichcanbeobtainedfromthetransitlightcurve).Thisisgivenasanexercisebelowwithstepbystephints.Exercise:Whenaplanetisincircularorbitaroundastar,wecansaythereisaforcebalancebetweengravityandthecentrifugalforce.Hence,westartbyequatingthegravitationalforceactingbetweenthestarandplanettothecentrifugalforceassociatedwiththecircularorbitalmotionoftheplanet

𝐺𝑀$𝑀%

𝑎' = 𝑀%𝑣'

𝑎 wherevdenotesthevelocityofthecircularorbitandaisthesemi-majoraxis.MsisthemassofthestarandMpisthemassoftheplanet,andGisNewton’sgravitationalconstant.Manipulatethisequationsothatthesemi-majoraxis,𝑎,isexpressedintermsofeverythingelse.Yourteacherhasthesolutionsoaskifyouneedassistance.Thevelocity,𝑣,atwhichtheplanetmovesarounditscircularorbitisgivenbythedistancearoundthecircle(oritscircumference),C,dividedbythetimetaken,P,whereinourcasePistheorbitalperiod.(Remember:Velocityisdistancetravelleddividedbythetimetaken).Obtainanexpressionforvintermsofthesemi-majoraxis,𝑎,andtheorbitalperiodP.Yourteacherhasthesolutionsoaskifyouneedassistance.Nowcombineyourexpressionsforthesemi-majoraxis,𝑎,andthevelocity,v,togetanexpressionfor𝑎intermsof𝑀$ ,P,Gandπ.Yourteacherhasthesolutionsoaskifyouneedassistance.Toworkoutthevaluesofthesemi-majoraxis,𝑎,foreachexoplanetyouwillstudyinthisproject,youwillneedthemassofthestar,Ms.Wehaveprovidedthisinapdffile(Stellar_Mass_Radius.pdf)onyourmemorystickforeachofthesystemsyouwillanalyse.Thisfilealsocontainstheradiusofthestar.PleasenotethatthevaluesofMsandRsareexpressedinunitsoftheSolarmassandSolarradius,wheretheseareMSun=1.989x1030kgandRSun=7x108m.NotethatG=6.67x10-11m3kg-1s-2intheseunits,andthesemi-majoraxisyouwillobtainwillbeinmetres.YoumaywanttoconvertthisintoAstronomicalUnits(themeandistancebetweentheEarthandSun),where1AU=1.5x1011m.

Page 6: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

6

DeterminingthetransitimpactparameterFigure33showsthatthetransitimpactparameter,denotedbyb,isameasureofhowclosetothecentreofthestellardisctheplanetpassesatthemidpointofthetransit.bismeasuredinunitsofthestellarradius,R*.Notethatwerefertotheangleiastheinclinationoftheorbit,suchthatananglei=90ocorrespondstoaplanetthatpassesacrossthecentreofthestellardisc.Figure3showsthattheimpactparameter,b,thesemi-majoraxis,a,andtheinclinationoftheorbit,i,arerelatedbysimpletrigonometry.Figure3:Theobserverislocatedontheleftofthediagramandislookingrighttowardsthestar.Theplanetisassumedtobeatthemidpointofthetransit,anditsprojecteddistanceabovethecentreofthestarisgivenbybxR*.

Figure4showsafaceonviewofthepaththattheplanettakesacrossthestellardiscduringatransit,anddemonstratesthetrigonometricrelationdescribedabove.ThelengthofthechordthatcorrespondstothepathtakenbytheplanetacrossthestellardisccanbedeterminedfromPythagoras’theorem.

Figure4:Face-onviewofthepathtakenbyaplanetasitcrossesthestellardiscduringatransit.

Theequationforthelengthofthechordis

2𝑙 = 2,-𝑅∗ + 𝑅%1'−(𝑏𝑅∗)'

3ThediagramsusedinFigures3,4,and5wereobtainedfromhttps://www.paulanthonywilson.com/exoplanets/exoplanet-detection-techniques/the-exoplanet-transit-method/

Page 7: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

7

Thediagrambelowgivesa3-dimensionalviewofthegeometryoftheorbitofatransitingplanet.

Figure5:3-dimensionalviewofthepathtakenbyatransitingplanetonitsorbit.

Fromthetriangledrawnintheorbitalplane,wecanseethatsin 9:'; = <

=(note

thatthediagramexaggerateshowclosetheorbitistothestar.Inalmostallcases,thedistancebetweenthecentreofthestarandthemidpointbetweenAandBiswellapproximatedbythesemi-majoraxisa).Assumingthattheplanetisonacircularorbit,thedurationofthetransitisgivenbytheexpression

𝑇?@A = 𝑃𝛼2𝜋

Whencombiningthiswiththeequationsabove,weobtaintheexpression

𝑇?@A = 𝑃𝜋 sin

EF

⎛,-𝑅∗ + 𝑅%1

'−(𝑏𝑅∗)'

𝑎⎠

Fromthisyoucanrearrangefor𝑏𝑅∗anddeterminethetransitimpactparameterbasedonmeasuringthedurationofthetransit,Tdur,fromthelightcurve.ExerciseObtainanexpressionfor𝑏𝑅∗fromtheaboveequationforTdur.UsingFigure4,obtainanexpressionfortheorbitalinclinationanglei.SolutionYourteacherhasthesolution.Trytoworkitoutforyourselfbeforeseekingassistance.

Page 8: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

8

Summary:Wenowhavesufficientinformationtobeabletoobtainthefollowinginformationfromthelightcurvesandstellarparameters(stellarmassandstellarradius)providedbytheKeplerdataarchiveforeachplanet-hostingstar:

• theplanet'sradius• theplanet’sorbitalperiod• theorbitalsemi-majoraxis• theimpactparameter• theorbitalinclination

Page 9: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

9

WritingprogrammesinPythonWenowprovideanintroductiontowritingcomputercodeinPython,withafocusonwhatyouwillneedtoanalyseKeplerdata.First,youwillbeintroducedtovariousprogrammingconceptsandPythoncommands,andthenyouwillbeprovidedwithasequenceofexercisesthatallowyoutoputthisnewinformationintopractice.Inadditiontofollowingwhatiswrittenbelow,youmayfinditusefultolookatsomeon-linePythontutorials.Ifyoutype“pythontutorial”intogoogle,thenyou’llfindliterallyhundredsofwebsitesthatofferinformationaboutprogramminginpython.Onethatwefoundusefulingettinganoverviewwhendevelopingthisprojectishttp://www.python-course.eu/course.phpAsitethatprovidesdocumentationonmanyaspectsofpythonishttp://scipy.orgIfyougetstuckandwanttoknowhowtodosomethinginPython,thengoogle“HowtodosomethinginPython”,wheresomethingcouldbe“plotagraph”,“readdataintoanarray”,oranyotherissueyou’rehavingproblemswith.TherearemanyversionsofPythonavailabletodownloadandinstallonyourcomputer.WestronglyrecommendusingAnaconda,whichmaybedownloadedfromthissite:https://www.anaconda.com/download/-windowsOnceyouhaveAnacondapythoninstalled,werecommendusingtheSpyderdeveloperenvironmentwhichwillappearasfollowswhenyoulaunchtheAnaconda-Navigator.ClickonthistolaunchSpyder.

PLEASENOTETHATPYTHONCOMESINTWODISTINCTFLAVOURS:PYTHON2andPYTHON3.WEWILLONLYUSETHEVERSIONPYTHON2.7.

Page 10: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

10

GettingstartedYouhavebeengivenaUSBmemorystickcontainingafolderPlanetHuntingWithPython2019.Beforegettingstartedwiththeprogrammingexamplesbelow,youareadvisedtocopythisPlanetHuntingWithPython2019folderandallofitscontentsontoyourcomputer.ThisfolderwillbewhereyoushouldsaveallofthePythonscriptsthatyoucreate.YouwillcreateandrunthepythonscriptsusingSpyder.Whenthishasbeenlaunchedyoushouldseethewindowshownbelow.

ThisiswhereyoutypeyourPythoncommands

ClickthegreenplaybuttontorunaPythonscript

ThisistheconsolewheretheoutputsfromyourPythonscriptsareprinted.Ifyourscriptrequiresinputfromtheuser,thenthisiswherethatinputshouldbetyped.

UsetheFilemenuatthetopofthescreentosaveyourscriptstothePlanetHuntingWithPython2019directory.ChooseSaveas…andnavigatetotherequireddirectory

Page 11: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

11

CreatingvariablesandarraysVariablesarenames(alwaysbeginningwithanupper-orlower-caseletter)thatyoucanassignavalueto.Youshouldthinkofavariableasalocationinthecomputer’smemorywhereavalueisstored(notethatthevaluecanbeanumber(realorinteger)orastring(i.e.aletteroraword)).Onceavariablehasbeenassignedaparticularvalue,itwillstorethatvalueuntilanothervalueisassignedtoit.Anexampleofassigningthevalue10toavariablesothatitisstoredasdecimalnumberisshownbelow(notethedecimalpoint):var=10.Arraysaredatastructuresthatstoreacollectionofvaluesthatarenormallyofthesametype(i.e.realnumbers,integersorstrings).Thiscollectionofnumberswilloftenhavesomerelationtoeachother.AnexamplerelevanttothisprojectisthatanarraycouldstoreallofthetimesassociatedwithaKeplerlightcurve,andanotherarraycouldstorethecorrespondingobservedluminosities/fluxesofthestar.Assigningvariablestoanarraycanbedoneasfollows:x=[1.,2.,3.,4.,5.]y=[1.,4.,9.,16.,25.]Thepreviousexampleswereofone-dimensionalarrays.Pythonalsoincludestwo-orthree-dimensionalarrays.Althoughwewon’tusethesehigher-dimensionalarraysinthisproject,anexampleofassignmenttoatwo-dimensionalarraywouldlooklikethis.z=[[1,2],[3,4]]Herethefirsttwoelementsofthearrayformthefirstcolumnandthesecondtwoelementsformthesecondcolumn,asshownbelow.Wecanthinkofarraysashavingsimilarstructurestomatricesinmathematics.Toaccessaspecificelementofaone-dimensionalarray,youwouldtypex[0]whichwouldreturnthevalue“1.”intheexampleabove,sincetheindexingofarraysinpythonstartsatzero.Similarly,accessinganelementofatwo-dimensionalarraycanbeachievedasfollows:z[0,0]whichwouldaccesstheelementinthefirstcolumnandfirstrow,givingavalueof1intheaboveexample.Aswewillseelater,arrayscanbecreatedautomaticallyinPythonbyreadingmultiplevaluesintoavariablenamefromadatafile,andyouwilldothisfrequentlyaspartofthisproject.

1324

Page 12: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

12

AddingcommentstoprogrammesIfyouwanttoaddacommenttoyourscriptssothatyouorotherpeoplecanunderstandthemlater,youcanusethe#symbol.Thisissomethingthatwewouldstronglyencourageyoutodoasyouwriteyourprogrammes.Pythonignoreseverythingonalinepastthe#symbol.ThecommentcanbeonthesamelineasaPythoncommand:var=10#ThisisacommentHere,Pythononlyexecutesthevar=10command,andignores‘Thisisacomment’.Alternatively,thecommentcanappearonaseparateline:#Thisisacommentvar=10PrintingtotheterminalInPythonyoucanprinttexttotheterminal.Thisisdoneusingtheprintcommandasfollows:print‘Hello’Theprintcommandcanalsoprintthevaluesofavariableoranarray.Ifwehaveavariablecalled‘var’whichisassignedthevalue10,thenthefollowingPythoncodecommandwillinitialisethevariableandprintitsvaluetotheterminal:var=10printvarNotethatforvariablesandarraysnoquotationmarksarerequired.Quotationmarksareonlyrequiredforprintingstrings.Ifwewanttoprintmultiplevariablesorpiecesofinformationonthesameline,weusethefollowingprintcommand:var=10print‘Thevariablevarisequalto:‘,varThe‘comma’allowsmultiplepiecesofinformationtobeprintedusingasingleprintcommandasshowninthefigurebelow

Pythoncommands

Outputprintedinconsole

Page 13: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

13

ForloopsForloopsareusefulforrunningthesameblockofcoderepeatedly.Theyhaveaspecificsyntax(writtenformat).Belowisanexampleofaforloop:count=0foriinrange(0,50):

count=count+1print‘count=‘,count

Notethattheindentation(eitheraspaceortab)isrequiredforPythontoknowwhichcommandsformpartoftheloop.Wecallthecommandsthatareexecutedrepeatedlythebodyoftheloop.Allcommandswithinthebodyoftheloopmusthavethesameindentation.Theaboveloopwoulditerate50times(Pythonstartswiththeloopcounter,i,havingthevaluezero,sothecodewilliterate50timesfromzero),adding1eachtimetothevariablecountandthenprintingthevalueofcounttotheterminal.ifstatementsforconditionalexecutionofcodeifstatementsareveryuseful.Theyuseconditionalstatementsthatevaluatetoeithertrueorfalsetodeterminewhichpiecesofcodetorun.Theyhaveaspecificsyntaxthatmustbefollowedforthecodetoexecuteproperly.Belowisanexampleofanifstatement:var=5ifvar==10: print‘true’else: print‘false’Since5doesnotequal10,pythonwillskiptheprint‘true’statementandexecutethecodeassociatedwiththeelsecondition,whichinthiscasewillcauseittoprint‘false’totheterminal.Itispossibletoinsert‘elseif’conditions,whichcausethescripttoonlyruntheblockofcodeassociatedwiththefirstconditionalstatementthatitdeterminestobetrue.Seetheexamplebelow:var=5ifvar==10: print‘varisequalto10’elifvar==5: #“elif”represents“elseif”here print‘varisequalto5’else: print‘varisnotequalto5or10’Withvarbeingequalto5,thecodewillnowprint‘varisequalto5’becausethesecondifconditionissatisfied.Withintheifstatement,youcanaddasmany‘elif’statementsasyoulike,andtheelsestatementshouldalwayscomeattheend.

Checkforthecolonhere

CHECK:Checkforthecolonhere

CHECK:Checkfortheindentationshere

Checktheindentationshere.Spyderwillnormallydotheindentationforyou

Page 14: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

14

NestedloopsNestedloopsareusedwhenrepeatedlyexecutingablockofPythoncodethatdependsonthevaluesoftwoindependentvariables(thesevariablescanbethevaluesoftheloopcountersthemselves,orothervariablesthataredefinedandmodifiedwithinthebodiesoftheloops).Notethatoneneedstotakecareoftheindentationswhenimplementingnestedforloops.Anexampleofmultipleforloopsisgivenbelow:foriinrange(0,3): forjinrange(0,3): print‘i=’,i,’j=’,jTheabovecodewillrunthroughthewholesequenceofthe‘j’loopduringasingleiterationofthe‘i'loop,printingthevaluesofiandjtotheterminal,asshowninthediagrambelow:

Pythoncodefrompreviousexample

Outputfrompreviousexample

Page 15: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

15

CombiningforloopsandifstatementsOneneedstobecarefulabouttheindentationwhencombiningloopsandifstatements.Anexampleisshownbelow:foriinrange(0,10): ifi==4: printi elifi==8: printiThecodeherewouldstartrunningtheforloopstartingati=0,beforecheckingtheconditionalifandelifstatementsandrunningtheappropriatepieceofcode.Itwouldthenreturntotheforloopandcontinuetothenextiterationofi,repeatingthissequence10times.AskingtheusertoinputinformationattheterminalItissometimesnecessaryforascripttoasktheusertosupplyinformationthatisrequiredforitscontinuedexecution.Forexample,hereisascriptfordeterminingifthereisenoughspaceinaroomforthenumberofpeoplerequired.space=30number_of_people=input(‘Howmanypeoplewillbeintheroom?’)ifnumber_of_people<=space: print‘Thereisenoughspace’else: print‘WARNING:Notenoughspace’HerePythonwillstopatthelinecontainingtheinputcommanduntiltheuserrespondsbytypingintherelevantvalueattheconsole,asshowninthescreenshotbelow.Thisvalueisthenstoredinthevariablenumber_of_people.

Thecodepromptstheusertoinputinformationhere.Clickontheconsole,typetherequiredinformationandpresstheenterkey

Page 16: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

16

Readingdataintoarraysfromatextfile–introducingnumpyTheKeplerdatathatyouwilluseinyourprojectwillbecontainedintextfiles,andyourprogrammeswillneedtoreadthisdatabeforeanalysingit.OnefeatureofPythonthatwehavenotyetdiscussedisthefactthatmanyofthefunctionsthatPythonoffersarecontainedinlibraries/packagesthatneedtobeloadedduringaPythonsessionbeforetheycanbeused.Whenwritingascript,itisagoodideatoloadtherequiredlibrariesatthebeginningofthescript.Onelibrarythatdealswithmathematicalfunctionsandnumericaldataiscallednumpy.Theusefulfeaturethatwewillintroducehereisitsloadtextcapability,butitalsoprovidesalargenumberofmathematicalfunctionssuchassine,cosine,sqrt,etc.Belowisascriptthatwillreadindatafromthefile‘xy.txt’locatedinthedirectoryDATAwhichisinthePlanetHuntingWithPython2019folder,andthenprintthedataouttotheterminal.importnumpyasnp #Wecouldjustuse‘importnumpy’,butassigningitasnp #allowsforeasiertypinglaterinthescript.x,y=np.loadtxt(‘DATA/xy.txt’,unpack=True)#Specifythatloadtxtispartof #thenumpylibrary->np.loadtxtforiinrange(0,len(x)):#weuselen(x)hereaswedonotknowthelengthofx.#Thecommandlen(x)determinesthenumberof#elementsinthearrayxwhichhasbeencreatedwhen#readinginthedatafromthefileDATA/xy.txt

printx[i],y[i]#Sincexandyarearrays,the[i]arerequiredtoaccessthe#specificelementsofthatarray.

Intheaboveexamplethedataisreadinandprintedoutlinebyline.Nowthatwehavethexandyarraysloadedin,let’sconsiderwhatwewoulddoifwewantedtocreateanewarrayzconsistingoftheelementsofthetwoexistingarraysmultipliedtogether(i.e.x[i]*y[i]forallvaluesofi).Anexampleisshownbelow:z=[] #initialisethearrayzwhichisemptyforiinrange(0,len(x)): #iterateforloopoverallelementsofx z.append(x[i]*y[i]) #Thiswillcalculatethevalueofx[i]*y[i]andappend#ittothelistofvaluesalreadycontainedinthe#arrayzprintz[i]

Page 17: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

17

PlottingdataItisalmostalwaysusefultoplotyourdata,andforthetaskofanalysingKeplerlightcurvesitisessential.InordertoplotdatainPythonweneedtoloadthelibrarymatplotlib.pyplot,whichprovidestheplottingfunctionsthatweneed.Belowisascriptthatwillloadinthedatafrom‘xy.txt’andthenplotit,asshownbythefigure.importnumpyasnpimportmatplotlib.pyplotasplt#Similartothenumpyexampleabove,#useplttomakethingseasierx,y=np.loadtxt(‘DATA/xy.txt’,unpack=True)plt.plot(x,y) #Thisplotsthedatatothecurrentfigure.Moreoptionscanbe#includedinthiscommandtodefinetheline-width,colour,#markersymbol,etc.Forexample,plt.plot(x,y,‘r.’)wouldplotthe#datausingreddotsasmarkers.plt.show()#Thisdrawsthefigureonthescreen,asshownbelow

Importantnote:WhengeneratingaplotinSpyder,bydefaultitwillembedtheplotinthesmallconsolewindow.Thisisnotwhatwewantbecauseweneedtobeabletomanipulatetheplotswegenerateinthisproject,andthatisnotpossiblewhentheplotisembeddedintheconsolewindow.ToallowSpydertogenerateaseparateplotwindowthatwecanmanipulatepleasedothefollowingsteps(noteitshouldonlybenecessarytodothisonceasSpyderwillrememberyou’vechangedthesettings):1).ClickonthespannersymbolthatopenstheSpyderpreferencesmenu2).ClickonIPythonconsole3).ClickontheGraphicstab4).UnderGraphicsbackendselectAutomatic,andthepressApplyandOK5).NowrestartSpyderandruntheplottingscript

Page 18: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

18

Otherusefulcommandsnp.sum(x)#givesthesumofallarrayelementsnp.mean(x)#givesthemeanofallarrayelementsifcount%10==0#the%symbolgivestheremainderwhencountisdividedby#10inthisexample.Sometimeswecallthisthemodulusof#dividing10intocount.Theremaindervalueisthen#comparedwith0todetermineiftheconditionintheif#statementistrueplt.xlabel(‘String’)#putsanaxislabelonthexaxis.Changexlabeltoylabelto#labeltheyaxislen(x)#givesthenumberofelementsinarrayxINT(x)#givesjusttheintegerpartofthenumberstoredinx.Couldalsoreplace#xwithanexpressionsuchasINT(x/y)wherexandyaretwonumbers.np.sin(x)#Calculatethesineofx(assumedtobeinradians).np.arcsin(x)#Calculatethearcsineofx.x**2#Calculatesxsquared.Notethatx**ycalculatesxtothepowerofy,where#yisanynumbernp.sqrt(x)#CalculatessquarerootofxPythonprogrammingexercisesBelowwehaveprovided11exercisesthatputintopracticetheprogrammingconceptsandcommandsdiscussedearlierinthisdocument.Yourteacherandvisitingprojectteachingassistant(ifpresent)havebeenprovidedwithsamplecodesthatsolveeachtask,sofeelfreetoaskforhintsifyougetstuck.

1. Writeaprogramthatoutputs‘HelloWorld’totheterminal

2. Writeaprogramthatoutputs‘HelloWorld’50timesusingaforloop

3. Writeaprogramwithaforloopthatiterates50timesandoutputs‘Hello

World’afterevery5iterations.

4. Writeaprogramwithaforloopwith50iterationsandoutputs‘Hello

World’everyoddvalueoftheloopcounterand,and‘GoodbyeWorld’

everyevenvalue.

5. Readinthetextfile‘xy.txt’andprintthedatatotheterminalin2columns

6. Plotthedatain‘xy.txt’withbluedots

7. Plotthedatain‘xy.txt’withreadcrosses

8. Plotthedatain‘xy.txt’asalineplot

9. Findtheindividualsumsofthe‘x’dataandthe‘y’dataandprintthemto

theterminal

10. Determinetheindividualmeansforthe‘x’and‘y’dataandprintthemto

theterminal

Page 19: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

19

11. Writeacodethatcreates3variablescalled‘day’,‘month’,‘year’.Getthe

codetoasktheusertoinputvaluesforeachvariable,andthenoutputthe

valuesistheform“Todaysdateis:”dd/mm/yyyy.Nowrunthecodeusing

todaysdateastheinput.

Page 20: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

20

Keplerdataanalysisexercises

LightcurvesfromtheKeplermissionarestoredinfileswhosenamesindicate

thereferencenumberofthestarintheKeplerInputCatalogue(KIC).This

cataloguewascreatedbeforethemissionlaunch,sothatastronomershada

sourceofinformationaboutthestarsthatKeplerwasgoingtosurvey.Thelight

curvesarepresentedinaforminwhichthechangeinfluxofthestar,relativeto

thefluxreceivedwhentheplanetisnottransiting,islistedagainsttime

measuredinJulianDaysminus2454833,suchthattimezerocorrespondsto12

noonon1stJanuary2009.Below,wehaveprovidedasequenceoftasksthatwill

allowyoutodeterminethekeyparametersofsometransitingplanets.

1. Writeaprogrammetoplotthelightcurve(fluxagainsttime)forthe

systemKIC006922244.Notethatthedatasetisstoredinthefile

KIC006922244.tblthathasbeendownloadedfromtheKeplerdata

archive(storedintheDATAdirectorythatyouwillfindinthe

PlanetHuntingWithPython2019folder).Thiscontains3columnsofnumbers

thatmustallbereadinbyyourprogramme.Thefirstcolumncontains

non-usefuldataandshouldbeignoredafterithasbeenreadin.Lateryou

willlearnhowtodownloadyourowndatafilesfromtheKeplerarchive,

andthesewillhavethesameformatasKIC006922244.tbl.Notethatthe

first3linesofthisfilealsoneedtobeignored,soyouneedtousethe

skiprows=3optioninthenp.loadtxtcommandthatyouusetoreadthe

datafile.

Figure6:ThisfigureshowsthelightcurvecontainedinthedatafileKIC006922244.tbl

Usefulbuttons

Page 21: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

21

Figure7:Azoominonthefirst10transits

2. FindthetransitsignalforKIC006922244andestimateitsperiod.Note

thattheplottingwindowthatpopsupwhenperformingtask1abovehas

buttonstoallowyoutozoominondifferentregionsoftheplot(i.e.press

themagnifyingglass–andexpandtheplotbydraggingthecursoracross

therequiredarea).Furthermore,whenyoumovethecursorintheplot

windowthepositionofthecursorarrowshouldbeindicatedinthelower

partofthewindowframe,andthisisausefulfeaturefordeterminingthe

timeofatransitmid-pointandotherparameters.Itisworthexploring

whatthesebuttonsdoasyouwillusethemfrequentlyinthisproject.To

findtheperiod,weadvisefindingaregionofthelightcurvewithoutany

breakscontaining10transits(notethatwhenyouzoominonthelight

curveyouwillseemanysmallbreaksinthedatacorrespondingtotimes

whenthespacecraftwasdownloadingdataorwasfiringitsthrusters).

Findthetimeofmid-transitforthefirstandlastofthesetransits(make

sureyouzoominoneachoftheseandusethecursorvaluestogetan

accurateestimate),andthendividethetimeintervalbetweenthefirst

andtenthtransitbythenumberoftransitsminus1(i.e.9inthis

example).Youshouldnowhaveanestimateoftheorbitalperiod.

3. Writeaprogrammetophase-foldthelightcurvesothatalltransitsinthe

datalieontopofoneanother,andplotthefluxwithrespecttothephase

Page 22: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

22

(Note:Hintsaboutgeneratingaphasefoldedlightcurvearegivenin

theappendixattheendofthisdocument!Westronglyrecommend

thatyoureadthis.Ifyougetreallystuckthenyourteacherhasthe

Pythoncodeneededtodothephasefolding).Phasefolding

correspondstojustshiftingthetimecoordinateofthedatabythecorrect

amountsothatthetransitsalloccuratpreciselythesametime.You

shouldarrangeyourdatasothatthephase-foldedlightcurvehasthemid-

pointofthetransitsatphase0.0,withthelightcurvebeforeandduring

ingressoccurringwithanegativephase(withminimumvalue=-(orbital

period)/2)andegressoccurringwithpositivephase(wherethe

maximumtimeshownis+(orbitalperiod)/2-seethefigurebelow).The

phaseshouldberepresentedinunitsofJuliandayseithersideofzero.

Youcanaddthefollowinglinetoyourscripttosortthedatabefore

plottingit,wheret2isanarraythatcontainsthenewshiftedtime

coordinateforalloftheoriginalvaluesoftherelativeflux:

t2,flux=zip(*sorted(zip(t2,flux)))#Thisusesthet2arraytosortbotharrayst2andflux.i.e.#itsortsthemwithrespecttotimeNote:Thequalityofyourphase-foldedcurvewilldependverysensitively

onyourestimateoftheorbitalperiod.Youalsoneedtoknowthetimeof

thefirsttransitmid-pointtoperformthephasefolding.Intheexample

shownbelow,togetthephase-foldeddataintheleftpanelweestimated

theperiodtobe3.522XwheretheXrepresentsadigitthatyouwillneedto

determineforyourself.i.e.Youwillneedtohaveanestimateaccurateto

fourdecimaldigitstogetareasonablephasefoldedcurve.Therightpanel

showswhathappensiftheorbitalperiodestimatechangesbyjust-0.0005

JulianDays.

Figure8:Theleftpanelshowsthephase-foldedlightcurvewithanaccurateestimatefortheorbitalperiod.Therightpanelshowswhathappenswithaslightlyinaccurateestimateoftheperiod.

Page 23: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

23

4. Whensatisfiedthattheperiodisaccurate,obtainthefollowing

parametersfromthephasefoldedplot(usingthecursorandprinted

valuesintheplotwindowwillbeveryusefulhere!):

a. Maximumdepthofthetransit(notingthatthisshouldcontainan

approximateaverageofthenoiseinthedata).

b. Time(orphase)thatthetransitbegins,whentheplanetjust

beginstopassinfrontofthestar(ingressstarttime)

c. Timethatthetransitfirstreachesmaximumdepth,whenthe

wholeplanetisinfrontofthestar(ingressendtime)

d. Timethatthetransitreachesitsmidpoint.

5. Nowconstructapiece-wisefunctiontoactasamodelthatyouwillfitto

thedatausingtheparametersdeterminedintask4.Youcanassumethe

transitissymmetricaboutthemidpoint.Themodelshouldincludea

horizontalliney=0outsideofthetransit,sincethatisthemeanvalueof

thedatathere.Themodelfunctionbetweenthestartofingressandthe

endofingressshouldberepresentedasastraightlinewithan

appropriateslope.Thetimeintervalbetweentheendofingressandthe

beginningofegress,correspondingtomaximumtransitdepth,shouldbe

representedasahorizontallinewithy=minimumflux.Plotthephase-

foldedKeplerdataandthenthemodelonthesameplot(youneedtodo

theplottinginthisordersothatthedataplotdoesnotobscurethe

model).Plottingthemodelontopofthedataisachievedbyissuing

consecutiveplt.plotcommands.SeeFigure10onthenextpageforan

examplehowyourmodelanddatashouldlookwhenplotted.Asintask3,

youshouldaddthefollowinglinetoyourscripttosortthedata

time3,flux=zip(*sorted(zip(time3,flux)))#Thisusesthetime3arrayto

#sortbotharraystime3and

#flux.i.e.itsortsthemwith

#respecttotime

Page 24: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

24

Figure9:Plotshowingthemodel(redline)overplottedonthedata(bluedots)

6. Nowdetermineanerrorestimateforyourmodelusingthefollowing

equationfortheChi-squaredtest:

𝜒' =1𝑁N

(𝐹P − 𝐹Q)'

𝜎'

S

PTF

whereFiisthedata,Fmisthefluxpredictedbyyourpiece-wiselinear

function(themodel)correspondingtothetime/phaseassociatedwithFi,

andσ2isthevarianceofthedataaboutitsmean.Althoughnotcompletely

accurate,whencalculatingthemeanandσ2foryourdatayoushoulduse

alldatapoints,includingthosecorrespondingtothetransits,sincein

practicethismakesonlymodestdifferencecomparedwithremovingthe

contributionforthetransits.Rememberthatthevarianceisreallyjust

estimatingthenoiseinyourdata,orthelevelofscatteraboutzero.A

modelfitthatisconsistentwithbeingwithinthenoiseofthedatashould

haveaχ2valuelessthan1.

7. Repeatsteps4-6foramaximumof10timestoobtainanimprovedmodel

forthedata,wherethebestfitisobtainedwhenχ2hasitsminimumvalue.

8. Usingtheyourbestfitparameters,writeaprogramme(orextendyour

existingprogramme)todeterminethefollowingplanetparameters(you

Page 25: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

25

canusethestellarparameterslocatedinthefileStellar_Mass_Radius.pdf

whichmaybefoundintheDATAfolder):

a. Planetradius(inunitsofR_Earth)

b. OrbitalPeriod(days)

c. Semi-majoraxis(AU)

d. Transitimpactparameter

e. Planetorbitalinclination

Thevaluesyouobtainshouldbesimilartothese:

Planetradius=15.038Earthradii(Earth’sradiusisapproximately6.37x106m)

Period=3.5224

Semi-majoraxis=0.04712AU

Impactparameterb=0.66256

Inclination=84.5677degrees

9. NowperformthesameanalysisfortheotherKeplerandTESSsystemsfor

whichdatafilesarepresentinthedirectoryDATA:KICXXXXXX.tbl(whereXXXXXXrepresents8359498,11853905,6922244,2571238,10418224,

9631995,7950644,5881688)andTICXXXXXXXX.dat(whereXXXXXXXXX

represents100100827,271893367,266980320)

Page 26: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

26

Suggestionsforfurtherindependentresearch

Wehavetriedtoprovideastructuredsetofexercisestoguideyouthroughthe

processofobtainingphysicalinformationaboutplanetarysystemsfromKepler

lightcurves.Herearesomesuggestionsforhowyoumightextendyourwork.

1.DownloaddatafromtheKeplerarchiveandanalyseamuchlargernumberof

systems(seebelowfordetailedinstructionsonhowtodownloaddatafromthe

Keplerarchive).Usetheplanetparametersthatyouobtaintodetermine

informationabouttheplanetpopulationthatisorbitingtheKeplertargetstars.

Forexample,determinethefrequencydistributionofplanetswithdifferentradii.

Howmanygiantplanetsarethere(e.g.Jupiters)versussmallerNeptune-sized

bodies?Whicharemorecommon–largerorsmallerplanets?Howarethe

planetsdistributedasafunctionoftheirorbitalperiods?

2.Foreachsystemyouhaveexamined,implementanautomatedsearchthrough

thedifferentmodel-fitparametervaluesinordertoobtainabest-fitsolution(we

suggestthatyouuseasinglevaluefortheorbitalperiodandvarytheother

modelparametersduetothesensitivitytochangingtheperiod).Here,youwill

needtoimplementasequenceofnestedforloopsthatscanthrougharangeof

parametervalues.Foreachindependentsetofparametervaluesyoushould

applytheChi-squaredtestdescribedearlier,andselectthemodelwiththe

lowestChi-squaredvalue.

3.Downloadlightcurvesforsomesystemsknowntohavetwoplanets.Useyour

previouslydevelopedcodestofindtheperiodandparametersofthemost

obvioustransitsignal.Writearoutinetomanipulatethelightcurvedataand

removethisdominanttransitsignal(youcandothisbysimplyaddingthe

negativeofthemodel-fittothedatawhichthenremovesthetransitsignal,or

youcanremovethedominanttransitsbyreplacingthedataduringeachtransit

withdatacopiedfromthetimebetweentransits),andnowapplyyour

programmestofindtheorbitalperiodandsystemparametersofthe2ndplanet.

Page 27: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

27

4.Forasingleplanetorbitingastar,theorbitalperiodshouldnotchange.Write

aprogrammetoexaminewhetherornottheorbitalperiodischangingforthe

systemsthatyouhaveexamined(ifchangesareoccurringthentheseareknown

asTransitTimingVariations–orTTVsforshort).Onewayofdoingthisisto

createaplotoftheoriginaldetrendedlightcurvedataandtosuperimposeonita

plotofthemodelfitappliedtothiswholetimeseriesratherthantothephase-

foldedlightcurve.Byeyeinspectionshouldthentellyouiftheperiodremains

constantsincethemodelshouldfitalltransits.Seeifyoucanfindawayof

automatingthesearchforTTVs,andplottheTTVsversustimetoseeifthereis

anystatisticallysignificantevidenceforrealTTVs.Choosesome2-planet

systemswheretheremaybegravitationalinteractionsbetweentheplanetsthat

couldperturbtheirorbitsandinduceTTVs.Canyoufindevidenceofplanet-

planetdynamicalinteractionswhicharesystematicallychangingtheorbital

periods?

Page 28: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

28

TodownloadlightcurvedatafromtheNASAexoplanetarchivegoto

http://exoplanetarchive.ipac.caltech.edu

Undertakethefollowingstepstoselectthesystemsthatyouwishtodownload

datafor.Ouradviceistoonlydownloadsystemsforwhichthereareconfirmed

planets,andforwhichtheplanettransitsignalismuchbiggerthanthenoise.

Thisnormallymeansthatyouwillselectplanetswithfairlylargeradiisothatthe

transitscaneasilybeseenbyeyeinplotsofthelightcurves.

ThefirststepistocreatealistofKeplersystemsthatyouwishtodownloadthe

datafor.ClickonthebuttonindicatedonthepreviousfigureshowingtheNASA

archivewebpage.Thiswillloadaninteractivetable:

Clickhere

Page 29: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

29

Youwillnoticethatthetablecontainsinformationonmanysystems,andalso

containsinformationthatisnotrelevantwhenselectingalistofplanets(it

scrollsrightwardsalongway!).Theredboxescontainingwhitecrossesatthe

topofeachcolumncanbeusedtoremovethosecolumns.Wesuggestcullingthe

databyremovingthefollowingcolumns(movingfromlefttoright):Disposition

UsingKeplerData;DispositionScore;NotTransit-LikeFalsePositiveFlag;Stellar

EclipseFalsePositiveFlag;CentroidOffsetFalsePositiveFlag;Ephemeris

Match…;TransitEpoch;ImpactParameter;TransitDuration;TransitDepth;

EquilibriumTemperature;InsolationFlux;TCEPlanetNumber;TCEDelivery;

StellarEffectiveTemperature;RA;Dec;Kepler-band.

NowweneedtoaddtwocolumnsbyclickingontheSelectColumnsbuttonatthe

topleft(seepreviousfigure).ScrolldownandselecttheNumberofPlanets

optionandtheStellarMassoptionandclickontheUpdateSelectionbuttonin

thedropdownmenu(seefigurebelow).

Clicktoremovecolumn

Clicktoaddcolumn

Page 30: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

30

You should now have a table that looks like this

Nowweneedtocullthedatafurthertoobtainasetofplanetsforwhichyour

searchandparameterfittingalgorithmswillwork.Systemsforwhichthetransit

signalisnotmuchlargerthanthenoiseneedmuchmoresophisticatedroutines

thantheoneswehavediscussedalready.Textboxesareprovidedatthetopof

Typeinheretoselectdata

Page 31: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

31

eachcolumntoselectdataaccordingtouserdefinedcriteria.Firsttype“>100”

intotheTransitSignal-to-Noisetextbox,asshowninthefigureabove.Thetable

willautomaticallyupdate.Nowmakethefollowingselections(afterwhichyour

tableshouldhaveabout97systemslistedasshowninthefigurebelow).

NumberofPlanets:1

ExoplanetArchiveDisposition:CONFIRMED

OrbitalPeriod:>3.5

PlanetaryRadius:>3

StellarRadius:<2

Nowchoosewhichsystemyouwanttodownloadthedatafor.Makeanoteofthe

StellarRadiusandtheStellarMassasthesewillberequiredwhendetermining

planetparametersfromthelightcurves.

Hoveryourcursoroverthe“i”symbolnexttotheKepIDnumberthatyouwanttodownloaddatafor.Apop-upmenushouldappearwhenyouhoveroverthe“i”symbol.Scrolldownandclickontheoption“KeplerDVTimeSeriesandPeriodogram”.Aplotshouldnowappear(asshownbelow).TheexamplebelowisforKepID11250587.

Hovercursorhere

Page 32: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

32

Nowwewanttoplotthedetrendedlightcurve(thisisacleaned-upversionofthelightcurveprovidedbytheKeplermission)whichcanbeobtainedbyclickingontheYAxisColumnoption,asshownabove,choosingLC_DETRENDfromthemenu,andthenpressingtheredrawbutton,givingthefollowingplot.

Todownloadthedetrendedlightcurveintheformofadatafile,withthesameformatthatwasusedintheKeplerprogrammingexercisesprovidedearlierinthisdocument,clickonthebuttonindicatedintheabovediagram.Thiswilldownloadafilecalledplot.tblthatcontainsthelightcurveinatextfilewiththree

Clickheretoredraw

Clickhere

Clickheretodown-loaddata

Page 33: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

33

columnsandathree-lineheader.Younowhaveadatafiletoanalyseusingyourpreviouslydevelopedalgorithmsandprogrammes.ChangeitsnametomatchtheKICnumberandyou’rereadytogo.Todownloaddataonsystemscontainingmorethanoneplanet,repeattheabovesteps,exceptchooseNumberofPlanets=2toextractdataon2-planetsystems.Arecommended2-planetsystemtodownloadisKepler117.ToobtainmoreTESSdatacontactRichardNelsonatQMULwhocansupplydataformoresystems.ReferencesMayor,M.,Queloz,D.,AJupiter-masscompaniontoasolar-typestar,1995,Nature,378,355-359Borucki,W.J.etal,KeperPlanet-DetectionMission:IntroductionandFirstResults,2010,Science,327,977InformationabouttheKeplermission:https://kepler.nasa.gov/index.cfmNASAExoplanetArchive:http://exoplanetarchive.ipac.caltech.eduExoplanetDataExplorer(usefulforgeneratingplotsofexoplanetpropertiesandexploringthestatisticsoftheexoplanetpopulation):http://exoplanets.orgExtrasolarPlanetEncyclopedia(similartotheExoplanetDataExplorer):http://exoplanet.euAreferencesitefordocumentationonpythoncommandsandlibraries:http://scipy.org(Clickonthedocumentationbuttonattopofthepage)

Page 34: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

34

Appendix–HintsonhowtophasefoldthelightcurvesBelowweprovideasequenceofstepsforphasefoldingtheKeplerlightcurvessothatweobtaindatainthesameformatasthatplottedintheleftpanelofFig.9.Figure12showsazoom-inofthelightcurveforKIC006922244,theexampleusedearlierinthisdocument.Itshowsthetimeofthefirsttransit,indicatedbytheblackarrow.

Figure10ThisimageshowsazoominoftheKIC006922244datashowingthetimeofthefirsttransit

Step1:Determinethetimeofthefirsttransit.Letusrefertothisast_transit1.Alsodeterminetheperiodwithwhichthetransitsoccur.WeusethesymbolPtodenotetheperiod.Step2:Wenowwanttoshiftthelightcurvedatatotheleftinsuchawaythatthefirsttransitoccursatatimet=P/2.i.eThetimeofthefirsttransitshouldnowoccuratatimethatcorrespondstohalftheorbitalperiod.Thisstepcanbeimplementedinpythonbysimplysubtractingtheappropriatenumberfromallofthetimevaluescontainedinthelightcurve.TheresultofdoingthisisshowninFigure13.

Figure11ThisfigureshowstheKIC006922244dataafterthetimecoordinatehasbeenshiftedsothatthefirsttransitoccursatt=P/2,wherePistheperiodassociatedwiththetransits.Theblackarrowsindicatethatsuccessivetransitsoccuratt=P/2,3P/2,5P/2,etc…Theredverticallinesindicatethepositionsintimethatcorrespondtooneperiod,twoperiods,threeperiodsetc.

Page 35: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

35

Step3:Wenowneedtousemodulararithmetictoshiftsectionsofthelightcurvesothattheyaresuperimposedononeanother.Thisistheessenceofphasefoldingthelightcurve.Considertwodecimalnumbers,AandB.InmanycomputinglanguagesthecommandMOD(A,B)willgivetheremainderofdividingAbyB.Inotherwords,ifwewriteA=NxB+R,whereNisaninteger,thenMOD(A,B)=R.ItshouldbeclearfromlookingatFigure13thatift[i]containsthetimesassociatedwitheachofthepointsontheshiftedlightcurve,thenapplyingMOD(t[i],P)toallpointswillcreateaphasefoldedlightcurvewiththemid-pointofthetransitoccurringatatimet=P/2.TheresultofimplementingthisinpythonisshowninFigure14.Importantnote:Inpython,wetype(A%B)andnotMOD(A,B)toobtaintheremainderofdividingAbyB.

Figure12ThisimageshowstheKIC006922244dataafterithasbeenphasefolded,withthetransitsoccurringattimet=P/2,wherePistheperiod

Step4:NowwesimplyneedtoshiftthelightcurvebyanamountP/2tocentrethetransitattimet=0.WedothisbysubtractingP/2fromallofthetimevaluesinthedata.TheresultofdoingthisisshowninFigure15.Rememberthatphasefoldingonlyworksifyouhaveanaccuratefigurefortheperiod!

Figure13ThisfigureshowsthedataforKIC006922244afterphasefoldingandshiftingsothatthemidpointsofallthetransitsoccurattimet=0.

Page 36: Planet Hunting with Python Richard P. Nelson, Guillem Anglada …€¦ · Richard P. Nelson, Guillem Anglada-Escudé & Gavin Coleman School of Physics & Astronomy, Queen Mary University

36

PythoncodeforphasefoldingYourteacherhasthesolution.Trytoworkitoutforyourselfbeforeseekingassistance.