Esempio n. 1
0
def run(envmass, mass):
    """Run vplanet and collect the output."""
    write_in(envmass, mass)
    subprocess.call(['vplanet', 'vpl.in'])
    output = vpl.GetOutput()
    envmassfinal = np.zeros(len(output.bodies) - 1)
    for i, body in enumerate(output.bodies[1:]):
        envmassfinal[i] = body.EnvelopeMass[-1]
    return (envmass - envmassfinal) / envmass
Esempio n. 2
0
def run(mass, semi):
    """Run vplanet and collect the output."""
    write_in(mass, semi)
    subprocess.call(['vplanet', 'vpl.in'])
    output = vpl.GetOutput()
    water = np.zeros(len(output.bodies) - 1)
    o2 = np.zeros(len(output.bodies) - 1)
    for i, body in enumerate(output.bodies[1:]):
        water[i] = 10 - body.SurfWaterMass[-1]
        o2[i] = body.OxygenMass[-1]
    return water, o2
Esempio n. 3
0
def run(masses):
    """Run vplanet and collect the output."""
    #write_in(masses)
    #subprocess.call(['vplanet', 'vpl.in'])
    output = vpl.GetOutput()
    age = output.bodies[0].Age
    radius = [output.bodies[n].Radius for n in range(len(masses))]
    temp = [output.bodies[n].Temperature for n in range(len(masses))]
    lum = [output.bodies[n].Luminosity for n in range(len(masses))]
    lxuv = [output.bodies[n].LXUVStellar for n in range(len(masses))]
    prot = [output.bodies[n].RotPer for n in range(len(masses))]
    return age, radius, lum, lxuv, temp, prot
Esempio n. 4
0
def run(masses):
    """Run vplanet and collect the output."""
    write_in(masses)
    subprocess.call(['vplanet', 'vpl.in'])
    output = vpl.GetOutput()
    time = output.bodies[0].Time
    radius = [output.bodies[n].Radius for n in range(len(masses))]
    temp = [output.bodies[n].Temperature for n in range(len(masses))]
    lum = [output.bodies[n].Luminosity for n in range(len(masses))]
    lxuv = [output.bodies[n].LXUVTot for n in range(len(masses))]
    prot = [output.bodies[n].RotPer for n in range(len(masses))]
    rg = [output.bodies[n].RadGyra for n in range(len(masses))]
    return time, radius, lum, lxuv, temp, prot, rg
Esempio n. 5
0
def HZLims(M):
    """Get the four HZ lims in AU for a star of mass `M`."""
    # Write the vpl.in file
    with open("vpl.in", "w") as file:
        print(system % "", file=file)

    # Write the star file
    with open("star.in", "w") as file:
        print(star % M, file=file)

    # Run
    subprocess.call(['vplanet', 'vpl.in'])
    output = vpl.GetOutput()
    return output.bodies[0].HZLimRecVenus[-1], \
        output.bodies[0].HZLimRunaway[-1], \
        output.bodies[0].HZLimMaxGreenhouse[-1], \
        output.bodies[0].HZLimEarlyMars[-1],
Esempio n. 6
0
def clim_evol(plname, dir='.', xrange=False, orbit=False, show=True):
    """
  Creates plots of insolation, temperature, albedo, ice mass,
  and bed rock height over the length of the simulation

  Parameters
  ----------
  plname : string
    The name of the planet with .Climate data

  Keyword Arguments
  -----------------
  dir : string
    Directory of vplanet simulation (default = '.')
  xrange : float tuple, list, or numpy array
    Range of x-values (time) to restrict plot
    (default = False (no restriction))
  orbit : bool
    Plot orbital data (obliquity, eccentricity, COPP)
    (default = False)
  show : bool
    Show plot in Python (default = True)

  Output
  ------
  PDF format plot with name 'evol_<dir>.pdf'

  """
    if not isinstance(dir, (list, tuple)):
        dir = [dir]

    nfiles = len(dir)

    if nfiles > 1 and orbit == True:
        raise Exception("Error: cannot plot multiple files when orbit = True")

    if orbit == True:
        fig = plt.figure(figsize=(16, 13))
    else:
        fig = plt.figure(figsize=(10 * nfiles, 15))

    fig.subplots_adjust(wspace=0.3, top=0.9)

    for ii in np.arange(nfiles):
        out = vpl.GetOutput(dir[ii])

        ctmp = 0
        for p in range(len(out.bodies)):
            if out.bodies[p].name == plname:
                body = out.bodies[p]
                ctmp = 1
            else:
                if p == len(out.bodies) - 1 and ctmp == 0:
                    raise Exception("Planet %s not found in folder %s" %
                                    (plname, dir[ii]))

        try:
            ecc = body.Eccentricity
        except:
            ecc = np.zeros_like(body.Time) + getattr(out.log.initial,
                                                     plname).Eccentricity

        try:
            inc = body.Inc
        except:
            inc = np.zeros_like(body.Time)

        try:
            obl = body.Obliquity
        except:
            obltmp = getattr(out.log.initial, plname).Obliquity
            if obltmp.unit == 'rad':
                obltmp *= 180 / np.pi
            obl = np.zeros_like(body.Time) + obltmp

        f = open(dir[ii] + '/' + plname + '.in', 'r')
        lines = f.readlines()
        f.close()
        pco2 = 0
        #pdb.set_trace()
        for i in range(len(lines)):
            if lines[i].split() != []:
                if lines[i].split()[0] == 'dRotPeriod':
                    P = -1 * np.float(lines[i].split()[1])
                if lines[i].split()[0] == 'dSemi':
                    semi = np.float(lines[i].split()[1])
                    if semi < 0:
                        semi *= -1
                if lines[i].split()[0] == 'dpCO2':
                    pco2 = np.float(lines[i].split()[1])

        try:
            longp = (body.ArgP + body.LongA + body.PrecA) * np.pi / 180.0
        except:
            longp = body.PrecA * np.pi / 180.0

        esinv = ecc * np.sin(longp) * np.sin(obl * np.pi / 180.)

        #titlestr = []
        #titlestr.append(r'$a = %f, pCO_2 = %f$'%(semi,pco2))
        #titlestr.append(r'$e_0 = %f, i_0 = %f^{\circ}, \psi_0 = %f^{\circ}, P_{rot} = %f$ d'%(ecc[0],inc[0],obl[0],P))
        fig.subplots_adjust(wspace=0.3)

        lats = np.unique(body.Latitude)
        nlats = len(lats)
        ntimes = len(body.Time)

        # plot temperature
        temp = np.reshape(body.TempLat, (ntimes, nlats))
        if orbit == True:
            ax1 = plt.subplot(4, 2, 1)
        else:
            ax1 = plt.subplot(5, nfiles, ii + 1)
        pos = ax1.figbox.get_points()
        #norm = mplcol.Normalize(vmin = -44,vmax = 15)
        c = plt.contourf(body.Time, lats, temp.T, cmap='plasma')
        plt.ylabel('Latitude')
        plt.title(r'Surface Temp [$^{\circ}$C]')
        plt.ylim(-90, 90)
        plt.yticks([-60, -30, 0, 30, 60])
        if xrange == False:
            left = 0
        else:
            left = xrange[0]
        #plt.text(left,140,'\n'.join(titlestr),fontsize=20)
        if xrange:
            plt.xlim(xrange)
        plt.colorbar(c,
                     cax=plt.axes([
                         pos[1, 0] + 0.01, pos[0, 1], 0.01,
                         pos[1, 1] - pos[0, 1]
                     ]))

        # plot albedo
        alb = np.reshape(body.AlbedoLat, (ntimes, nlats))
        if orbit == True:
            ax2 = plt.subplot(4, 2, 3)
        else:
            ax2 = plt.subplot(5, nfiles, ii + 2 * nfiles + 1)
        pos = ax2.figbox.get_points()
        # norm = mplcol.Normalize(vmin = 0.312,vmax = 0.6 )
        c = plt.contourf(body.Time, lats, alb.T, cmap='Blues_r')
        plt.ylabel('Latitude')
        plt.title('Albedo (TOA)')
        plt.ylim(-90, 90)
        plt.yticks([-60, -30, 0, 30, 60])
        if xrange:
            plt.xlim(xrange)
        plt.colorbar(c,
                     cax=plt.axes([
                         pos[1, 0] + 0.01, pos[0, 1], 0.01,
                         pos[1, 1] - pos[0, 1]
                     ]))

        # plot ice height
        ice = np.reshape(body.IceHeight, (ntimes, nlats))
        if orbit == True:
            ax3 = plt.subplot(4, 2, 5)
        else:
            ax3 = plt.subplot(5, nfiles, ii + 3 * nfiles + 1)
        pos = ax3.figbox.get_points()
        c = plt.contourf(body.Time, lats, ice.T, cmap='Blues_r')
        plt.ylabel('Latitude')
        plt.title('Ice sheet height [m]')
        plt.ylim(-90, 90)
        #   plt.xlim(0,2e6)
        plt.yticks([-60, -30, 0, 30, 60])
        if xrange:
            plt.xlim(xrange)
        plt.colorbar(c,
                     cax=plt.axes([
                         pos[1, 0] + 0.01, pos[0, 1], 0.01,
                         pos[1, 1] - pos[0, 1]
                     ]))
        # ax3p = ax3.twinx()
        #   plt.plot(body.Time,esinv,linestyle = 'solid',marker='None',color='salmon',linewidth=2)

        # plot bedrock
        brock = np.reshape(body.BedrockH, (ntimes, nlats))
        if orbit == True:
            ax4 = plt.subplot(4, 2, 7)
        else:
            ax4 = plt.subplot(5, nfiles, ii + 4 * nfiles + 1)
        pos = ax4.figbox.get_points()
        c = plt.contourf(body.Time, lats, brock.T, cmap='Reds_r')
        plt.ylabel('Latitude')
        plt.title('Bedrock height [m]')
        plt.ylim(-90, 90)
        plt.yticks([-60, -30, 0, 30, 60])
        plt.xlabel('Time [years]', fontsize=20)
        if xrange:
            plt.xlim(xrange)
        plt.colorbar(c,
                     cax=plt.axes([
                         pos[1, 0] + 0.01, pos[0, 1], 0.01,
                         pos[1, 1] - pos[0, 1]
                     ]))

        # plot insolation
        insol = np.reshape(body.AnnInsol, (ntimes, nlats))
        if orbit == True:
            ax5 = plt.subplot(4, 2, 2)
        else:
            ax5 = plt.subplot(5, nfiles, ii + nfiles + 1)
        pos = ax5.figbox.get_points()
        c = plt.contourf(body.Time, lats, insol.T, cmap='plasma')
        plt.ylabel('Latitude')
        plt.title(r'Annual average insolation [W/m$^2$]')
        plt.ylim(-90, 90)
        plt.yticks([-60, -30, 0, 30, 60])
        if xrange:
            plt.xlim(xrange)
        plt.colorbar(c,
                     cax=plt.axes([
                         pos[1, 0] + 0.01, pos[0, 1], 0.01,
                         pos[1, 1] - pos[0, 1]
                     ]))

        if orbit == True:
            #obliquity
            plt.subplot(4, 2, 4)
            plt.plot(body.Time,
                     obl,
                     linestyle='solid',
                     marker='None',
                     color='darkblue',
                     linewidth=2)
            plt.ylabel('Obliquity')
            if xrange:
                plt.xlim(xrange)

            #eccentricity
            plt.subplot(4, 2, 6)
            plt.plot(body.Time,
                     ecc,
                     linestyle='solid',
                     marker='None',
                     color='darkorchid',
                     linewidth=2)
            plt.ylabel('Eccentricity')
            if xrange:
                plt.xlim(xrange)

            #e sin(obl) sin varpi
            plt.subplot(4, 2, 8)
            plt.plot(body.Time,
                     esinv,
                     linestyle='solid',
                     marker='None',
                     color='salmon',
                     linewidth=2)
            plt.ylabel('COPP')
            plt.xlabel('Time [years]')
            if xrange:
                plt.xlim(xrange)

        if dir[ii] == '.':
            dir[ii] = 'cwd'

    #fig.suptitle('\n'.join(titlestr),fontsize=20)

        if (sys.argv[1] == 'pdf'):
            plt.savefig('IceBeltClimateEvol.pdf', dpi=300)
        if (sys.argv[1] == 'png'):
            plt.savefig('IceBeltClimateEvol.png', dpi=300)
        if show:
            plt.show()
        else:
            plt.close()
Esempio n. 7
0
def comp2huybers(plname,dir='.',xrange=False,show=True):
  """
  Creates plots of insolation, temperature, albedo, ice mass,
  and bed rock height over the length of the simulation

  Parameters
  ----------
  plname : string
    The name of the planet with .Climate data

  Keyword Arguments
  -----------------
  dir : string
    Directory of vplanet simulation (default = '.')
  xrange : float tuple, list, or numpy array
    Range of x-values (time) to restrict plot
    (default = False (no restriction))
  orbit : bool
    Plot orbital data (obliquity, eccentricity, COPP)
    (default = False)
  show : bool
    Show plot in Python (default = True)

  Output
  ------
  PDF format plot with name 'evol_<dir>.pdf'

  """
  if not isinstance(dir,(list,tuple)):
    dir = [dir]

  nfiles = len(dir)

  if nfiles > 1 and orbit == True:
    raise Exception("Error: cannot plot multiple files when orbit = True")


  fig = plt.figure(figsize=(8,12))

  fig.subplots_adjust(wspace=0.3,top=0.9,hspace=0.2)

  for ii in np.arange(nfiles):
    out = vplot.GetOutput(dir[ii])

    #pdb.set_trace()

    ctmp = 0
    for p in range(len(out.bodies)):
      if out.bodies[p].name == plname:
        body = out.bodies[p]
        ctmp = 1
      else:
        if p == len(out.bodies)-1 and ctmp == 0:
          raise Exception("Planet %s not found in folder %s"%(plname,dir[ii]))

    try:
      ecc = body.Eccentricity
    except:
      ecc = np.zeros_like(body.Time)+getattr(out.log.initial,plname).Eccentricity

    try:
      inc = body.Inc
    except:
      inc = np.zeros_like(body.Time)

    try:
      obl = body.Obliquity
    except:
      obltmp = getattr(out.log.initial,plname).Obliquity
      if obltmp.unit == 'rad':
        obltmp *= 180/np.pi
      obl = np.zeros_like(body.Time)+obltmp

    f = open(dir[ii]+'/'+plname+'.in','r')
    lines = f.readlines()
    f.close()
    pco2 = 0
    #pdb.set_trace()
    for i in range(len(lines)):
      if lines[i].split() != []:
        if lines[i].split()[0] == 'dRotPeriod':
          P = -1*np.float(lines[i].split()[1])
        if lines[i].split()[0] == 'dSemi':
          semi = np.float(lines[i].split()[1])
          if semi < 0:
            semi *= -1
        if lines[i].split()[0] == 'dpCO2':
          pco2 = np.float(lines[i].split()[1])

    try:
      longp = (body.ArgP + body.LongA + body.PrecA)*np.pi/180.0
    except:
      longp = body.PrecA*np.pi/180.0

    esinv = ecc*np.sin(longp)

    lats = np.unique(body.Latitude)
    nlats = len(lats)
    ntimes = len(body.Time)

    # plot temperature
    temp = np.reshape(body.TempLandLat,(ntimes,nlats))

    ax1 = plt.subplot(7,1,5)
    pos = ax1.figbox.get_points()
    c = plt.contourf(body.Time/1e6,lats[lats>58],temp.T[lats>58],20)
    plt.ylabel('Latitude')

    plt.ylim(60,83)
    plt.yticks([60,70,80])
    if xrange == False:
      left = 0
    else:
      left = xrange[0]
#     plt.text(left,140,'\n'.join(titlestr),fontsize=20)
    if xrange:
      plt.xlim(xrange)
    # plt.contour(body.Time/1e6,lats[lats>60],temp.T[lats>60],levels=[0],colors='w')
    plt.xticks(visible=False)
    clb=plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    clb.set_label('Surface Temp.\n($^{\circ}$C)',fontsize=12)

    # plot ice height
    ice = np.reshape(body.IceHeight+body.BedrockH,(ntimes,nlats))

    ax3 = plt.subplot(7,1,4)
    pos = ax3.figbox.get_points()
#     pdb.set_trace()
    c = plt.contourf(body.Time/1e6,lats[lats>58],ice.T[lats>58,:],20)
    plt.ylabel('Latitude')
    plt.ylim(60,83)
  #   plt.xlim(0,2e6)
    plt.yticks([60,70,80])
    if xrange:
      plt.xlim(xrange)
    # plt.contour(body.Time,lats[lats>60],ice.T[lats>60],levels=[0],colors='w')
    plt.xticks(visible=False)
    clb=plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    #clb.set_label('Ice height (m)')
    clb.set_label('Ice sheet\nheight (m)',fontsize=12)

    # ax3p = ax3.twinx()
  #   plt.plot(body.Time,esinv,linestyle = 'solid',marker='None',color='salmon',linewidth=2)


    ax4 = plt.subplot(7,1,6)
    pos = ax4.figbox.get_points()
    acc = body.IceAccum
    c = plt.contourf(body.Time/1e6,lats[lats>58],acc.T[lats>58],20)
    plt.ylabel('Latitude')
    plt.ylim(60,83)
    plt.yticks([60,70,80])
    plt.xticks(visible=False)
    if xrange == False:
      left = 0
    else:
      left = xrange[0]
#     plt.text(left,140,'\n'.join(titlestr),fontsize=20)
    if xrange:
      plt.xlim(xrange)
    clb=plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    tloc = ticker.MaxNLocator(nbins=5)
    clb.locator=tloc
    clb.update_ticks()
    clb.set_label('Ice Accum.\n(m year$^{-1}$)',fontsize=12)

    ax5 = plt.subplot(7,1,7)
    pos = ax5.figbox.get_points()
    abl = body.IceAblate
    c = plt.contourf(body.Time/1e6,lats[lats>58],-abl.T[lats>58],20)
    plt.ylabel('Latitude')
    # plt.title(r'Ice Ablation (m year$^{-1}$)',fontsize=12)
    plt.ylim(60,83)
    plt.yticks([60,70,80])
    plt.xlabel('Time (Myr)')
    if xrange == False:
      left = 0
    else:
      left = xrange[0]
#     plt.text(left,140,'\n'.join(titlestr),fontsize=20)
    if xrange:
      plt.xlim(xrange)
    clb = plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    clb.set_label('Ice Ablation\n(m year$^{-1}$)',fontsize=12)

    plt.subplot(7,1,1)
    plt.plot(body.Time/1e6,obl,linestyle = 'solid',marker='None',color=vplot.colors.dark_blue,linewidth =2)
    plt.ylabel('Obliquity')
    plt.xticks(visible=False)
    if xrange:
      plt.xlim(xrange)

    plt.subplot(7,1,2)
    plt.plot(body.Time/1e6,ecc,linestyle = 'solid',marker='None',color=vplot.colors.purple,linewidth =2)
    plt.ylabel('Eccenticity')
    plt.xticks(visible=False)
    if xrange:
      plt.xlim(xrange)

    plt.subplot(7,1,3)
    plt.plot(body.Time/1e6,esinv,linestyle = 'solid',marker='None',color=vplot.colors.red,linewidth=2)
    plt.ylabel('CPP')
    plt.xticks(visible=False)
    if xrange:
      plt.xlim(xrange)

    if dir[ii] == '.':
      dir[ii] = 'cwd'

  plt.savefig('milankovitch.pdf')

  if show:
    plt.show()
  else:
    plt.close()
Esempio n. 8
0
import numpy as np
import matplotlib.pyplot as plt
import vplot

out = vplot.GetOutput()
out2 = vplot.GetOutput('tides_only')

plt.figure(figsize=(8.5, 6))
q = out.comp.SemiMajorAxis * (1 - out.comp.Eccentricity)
plt.semilogy(out.comp.Time / 1e9,
             out.comp.SemiMajorAxis,
             'k--',
             zorder=100,
             label='Semi-major axis (with encounters)')
plt.plot(out.comp.Time / 1e9,
         q,
         'k-',
         zorder=100,
         label='Perihelion (with encounters)')

q = out2.comp.SemiMajorAxis * (1 - out2.comp.Eccentricity)
plt.semilogy(out2.comp.Time / 1e9,
             out2.comp.SemiMajorAxis,
             '--',
             c=vplot.colors.pale_blue,
             label='Semi-major axis (tide only)')
plt.plot(out2.comp.Time / 1e9,
         q,
         '-',
         c=vplot.colors.pale_blue,
         label='Perihelion (tide only)')
Esempio n. 9
0
# Plot
fig, axes = plt.subplots(ncols=1, nrows=3, sharex=True, figsize=(8, 18))

labels = [
    r"CPL, Dynamic $r_g$", r"CPL, Static $r_g$", r"CTL, Dynamic $r_g$",
    r"CTL, Static $r_g$"
]

colors = [
    vpl.colors.red, vpl.colors.purple, vpl.colors.orange, vpl.colors.pale_blue
]

#Extracting and plotting the data from each folder
for ii in range(len(dataDirs)):
    # Load data
    output = vpl.GetOutput(os.path.join(dirPath, dataDirs[ii]))

    # Extract data
    time = output.secondary.Time
    a_crit = output.secondary.CriticalSemiMajorAxis
    orbP = output.secondary.OrbPeriod
    ecc = output.secondary.Eccentricity

    # Top: Critical semi-major axis
    axes[0].plot(time, a_crit, lw=4, label=labels[ii], color=colors[ii])

    # Format
    axes[0].set_ylabel("Critical Semi-Major Axis [au]", fontsize=20)
    axes[0].set_ylim(ymin=0.145, ymax=0.36)
    axes[0].set_yticks([0.05 * i + 0.15 for i in range(5)])
    axes[0].yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
Esempio n. 10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
example1.py
-----------

'''

from __future__ import division, print_function, absolute_import, \
                       unicode_literals
import matplotlib.pyplot as plt
import vplot as vpl

# Grab the output from a run
output = vpl.GetOutput('gl581')

# Set up a matplotlib plot as usual
fig, ax = plt.subplots(2, 2, figsize=(12, 8))

# Make font size smaller
plt.rcParams.update({'font.size': 10})

# Now use ``vpl.plot`` instead of ``plt.plot`` to do the
# plotting to get customized VPLOT plots. You can specify
# keyword arguments in the same way you would for ``plt.plot``.
for planet in output.bodies[1:]:
    vpl.plot(ax[0, 0], output.star.Time, planet.Eccentricity, marker='None')
    vpl.plot(ax[0, 1], output.star.Time, planet.Obliquity)

vpl.plot(ax[1, 0],
         output.c.Eccentricity,
Esempio n. 11
0
def GetEvol(x, **kwargs):
    """
    Run a VPLanet simulation for this initial condition vector, x
    """

    # Get the current vector
    dMass, dSatXUVFrac, dSatXUVTime, dStopTime, dXUVBeta = x
    dSatXUVFrac = 10**dSatXUVFrac  # Unlog
    dStopTime *= 1.e9  # Convert from Gyr -> yr

    # Get the prior probability
    lnprior = kwargs["LnPrior"](x, **kwargs)
    if np.isinf(lnprior):
        return None

    # Get strings containing VPLanet input files (they must be provided!)
    try:
        star_in = kwargs.get("STARIN")
        vpl_in = kwargs.get("VPLIN")
    except KeyError as err:
        print("ERROR: Must supply STARIN and VPLIN.")
        raise

    # Get PATH
    try:
        PATH = kwargs.get("PATH")
    except KeyError as err:
        print("ERROR: Must supply PATH.")
        raise

    # Randomize file names
    sysName = 'vpl%012x' % random.randrange(16**12)
    starName = 'st%012x' % random.randrange(16**12)
    sysFile = sysName + '.in'
    starFile = starName + '.in'
    logfile = sysName + '.log'
    starFwFile = '%s.star.forward' % sysName

    # Populate the star input file
    star_in = re.sub("%s(.*?)#" % "dMass", "%s %.6e #" % ("dMass", dMass),
                     star_in)
    star_in = re.sub("%s(.*?)#" % "dSatXUVFrac",
                     "%s %.6e #" % ("dSatXUVFrac", dSatXUVFrac), star_in)
    star_in = re.sub("%s(.*?)#" % "dSatXUVTime",
                     "%s %.6e #" % ("dSatXUVTime", -dSatXUVTime), star_in)
    star_in = re.sub("%s(.*?)#" % "dXUVBeta",
                     "%s %.6e #" % ("dXUVBeta", -dXUVBeta), star_in)
    with open(os.path.join(PATH, "output", starFile), 'w') as f:
        print(star_in, file=f)

    # Populate the system input file

    # Populate list of planets
    saBodyFiles = str(starFile) + " #"
    saBodyFiles = saBodyFiles.strip()

    vpl_in = re.sub('%s(.*?)#' % "dStopTime",
                    '%s %.6e #' % ("dStopTime", dStopTime), vpl_in)
    vpl_in = re.sub('sSystemName(.*?)#', 'sSystemName %s #' % sysName, vpl_in)
    vpl_in = re.sub('saBodyFiles(.*?)#', 'saBodyFiles %s #' % saBodyFiles,
                    vpl_in)
    with open(os.path.join(PATH, "output", sysFile), 'w') as f:
        print(vpl_in, file=f)

    # Run VPLANET and get the output, then delete the output files
    subprocess.call(["vplanet", sysFile], cwd=os.path.join(PATH, "output"))
    output = vpl.GetOutput(os.path.join(PATH, "output"), logfile=logfile)

    try:
        os.remove(os.path.join(PATH, "output", starFile))
        os.remove(os.path.join(PATH, "output", sysFile))
        os.remove(os.path.join(PATH, "output", starFwFile))
        os.remove(os.path.join(PATH, "output", logfile))
    except FileNotFoundError:
        # Run failed!
        return None

    # Ensure we ran for as long as we set out to
    if not output.log.final.system.Age / utils.YEARSEC >= dStopTime:
        return None

    return output
Esempio n. 12
0
# Run the simulations
dir_path = os.path.dirname(os.path.realpath(__file__))
dirs = ["LehmerCatling17", "Dynamic"]

# Run simulations
for dir in dirs:
    print("Running " + dir + ".")
    os.chdir(os.path.join(dir_path, dir))

    # Run simulation
    subprocess.call(['vplanet', 'vpl.in'])
# Return to top-level directory
os.chdir(dir_path)

# Load data
lc17 = vpl.GetOutput("./LehmerCatling17")
dyn = vpl.GetOutput("./Dynamic")

### First figure: Comparative atmospheric escape ###

# Plot
fig, axes = plt.subplots(nrows=4, ncols=3, sharex=True, figsize=(16, 11))

time = lc17.star.Time

## Upper left: Envelope mass ##
axes[0, 0].plot(time, lc17.planet.EnvelopeMass, color='k')
axes[0, 0].plot(time, dyn.planet.EnvelopeMass, color=vpl.colors.dark_blue)

# Format
axes[0, 0].set_ylim(-0.01, 0.07)
Esempio n. 13
0
if (sys.argv[1] != 'pdf' and sys.argv[1] != 'png'):
    print('ERROR: Unknown file format: ' + sys.argv[1])
    print('Options are: pdf, png')
    exit(1)

#Typical plot parameters that make for pretty plot
mpl.rcParams['figure.figsize'] = (10, 8)
mpl.rcParams['font.size'] = 16.0

# Load data
#InputDirb = input("Input Directory b:")
#InputDirc = input("Input Directory c:")
#You can also hard code the addresses.
InputDirb = "./TGMCDrand_002b"
InputDirc = "./TGMCDrand_002c"
outputb = vpl.GetOutput(InputDirb)
outputc = vpl.GetOutput(InputDirc)
print("Directories Located")

# Extract data
time = outputb.TGb.Time / 1.0e6  # Scale to Myr
eccb = outputb.TGb.Eccentricity
eccc = outputc.TGc.Eccentricity
obbb = outputb.TGb.Obliquity
obbc = outputc.TGc.Obliquity
rotb = outputb.TGb.RotPer
rotc = outputc.TGc.RotPer
tidhb = outputb.TGb.SurfEnFluxEqtide
tidhc = outputc.TGc.SurfEnFluxEqtide
print("Files Found")
Esempio n. 14
0
mpl.rcParams['font.size'] = 10.0

### First figure: water photolysis escape ###

# Run simulations
os.chdir('WaterCPL')
print('Running WaterCPL.')
subprocess.call(['vplanet', 'vpl.in'])

os.chdir('../WaterCTL')
print('Running WaterCTL.')
subprocess.call(['vplanet', 'vpl.in'])
os.chdir('..')

# Load data
cpl = vpl.GetOutput("./WaterCPL")
ctl = vpl.GetOutput("./WaterCTL")

# Plot
fig, axes = plt.subplots(nrows=2, ncols=2)

time = cpl.b.Time / 1e9

## Upper left: Water Mass ##
axes[0, 0].plot(time, cpl.b.SurfWaterMass, color='k', label='CPL')
axes[0, 0].plot(time, ctl.b.SurfWaterMass, color=vpl.colors.red, label='CTL')
# Format
axes[0, 0].set_ylim(-0.02, 10)
axes[0, 0].set_ylabel("Water Mass (Earth Oceans)")
axes[0, 0].set_xlabel('Time (Gyr)')
axes[0, 0].set_xlim(0, 1)
Esempio n. 15
0
os.chdir('../Bondi')
print('Running Lopez12CPL-Bondi.')
subprocess.call(['vplanet', 'vpl.in'])

os.chdir('../ELim')
print('Running Lopez12CPL-ELim.')
subprocess.call(['vplanet', 'vpl.in'])

os.chdir('../RR')
print('Running Lopez12CPL-RR.')
subprocess.call(['vplanet', 'vpl.in'])

os.chdir('../..')

# Load data
cplauto = vpl.GetOutput("./Lopez12CPL/Auto")
cplbondi = vpl.GetOutput("./Lopez12CPL/Bondi")
cplelim = vpl.GetOutput("./Lopez12CPL/ELim")
cplrr = vpl.GetOutput("./Lopez12CPL/RR")

# Plot
fig, axes = plt.subplots(nrows=3, ncols=2)

timeauto = cplauto.auto.Time / 1e6
timebondi = cplbondi.bondi.Time / 1e6
timeelim = cplelim.el.Time / 1e6
timerr = cplrr.rr.Time / 1e6

## Upper left: Envelope Mass ##
axes[0, 0].plot(timeauto, cplauto.auto.EnvelopeMass, color='k')
axes[0, 0].plot(timebondi, cplbondi.bondi.EnvelopeMass, color=vpl.colors.red)
Esempio n. 16
0
from __future__ import division, print_function, absolute_import, unicode_literals
import matplotlib as mpl
import matplotlib.pyplot as plt
import vplot as vpl
import numpy as np

mpl.rcParams.update({'font.size': 24})

# Load in simulation results using vplot
ocean_path = "ocean/"
no_ocean_path = "no_ocean/"
cp_path = "cpl/"
env_path = "env_ocean/"

# Make object for each simulation set to hold data
ocean = vpl.GetOutput(ocean_path)
no_ocean = vpl.GetOutput(no_ocean_path)
cpl = vpl.GetOutput(cp_path)
env = vpl.GetOutput(env_path)

# Time grid same for all simulations
time = ocean.pandora.Time

# Define color preferences
ocean_color = vpl.colors.dark_blue
no_ocean_color = vpl.colors.red
cpl_color = vpl.colors.pale_blue
env_color = vpl.colors.orange

# Define Labels
ocean_label = "Ocean"
Esempio n. 17
0
# Check correct number of arguments
if (len(sys.argv) != 2):
    print('ERROR: Incorrect number of arguments.')
    print('Usage: ' + sys.argv[0] + ' <pdf | png>')
    exit(1)
if (sys.argv[1] != 'pdf' and sys.argv[1] != 'png'):
    print('ERROR: Unknown file format: ' + sys.argv[1])
    print('Options are: pdf, png')
    exit(1)

# Run simulation
subprocess.call(['vplanet', '-q', 'vpl.in'])

# Make object for each simulation set to hold data
prox = vpl.GetOutput()

# Time grid same for all simulations
time = prox.ProxCenELim.Time / 1e6

# Define color preferences
elim_color = vpl.colors.dark_blue
rrlim_color = vpl.colors.pale_blue
auto_color = vpl.colors.orange

# Define linestyles
prox_ls = '-'
lc17_ls = ':'

# Define Labels
prox_label = "ProxCenb"
Esempio n. 18
0
def clim_evol(plname,dir='.',xrange=False,orbit=False,show=True):
  """
  Creates plots of insolation, temperature, albedo, ice mass,
  and bed rock height over the length of the simulation

  Parameters
  ----------
  plname : string
    The name of the planet with .Climate data

  Keyword Arguments
  -----------------
  dir : string
    Directory of vplanet simulation (default = '.')
  xrange : float tuple, list, or numpy array
    Range of x-values (time) to restrict plot
    (default = False (no restriction))
  orbit : bool
    Plot orbital data (obliquity, eccentricity, COPP)
    (default = False)
  show : bool
    Show plot in Python (default = True)

  Output
  ------
  PDF format plot with name 'evol_<dir>.pdf'

  """
  if not isinstance(dir,(list,tuple)):
    dir = [dir]

  nfiles = len(dir)

  if nfiles > 1 and orbit == True:
    raise Exception("Error: cannot plot multiple files when orbit = True")


  fig = plt.figure(figsize=(9,8))
  fig.subplots_adjust(wspace=0.5,hspace = 0.5)

  for ii in np.arange(nfiles):
    out = vpl.GetOutput(dir[ii])

    ctmp = 0
    for p in range(len(out.bodies)):
      if out.bodies[p].name == plname:
        body = out.bodies[p]
        ctmp = 1
      else:
        if p == len(out.bodies)-1 and ctmp == 0:
          raise Exception("Planet %s not found in folder %s"%(plname,dir[ii]))

    try:
      ecc = body.Eccentricity
    except:
      ecc = np.zeros_like(body.Time)+getattr(out.log.initial,plname).Eccentricity

    try:
      inc = body.Inc
    except:
      inc = np.zeros_like(body.Time)

    try:
      obl = body.Obliquity
    except:
      obltmp = getattr(out.log.initial,plname).Obliquity
      if obltmp.unit == 'rad':
        obltmp *= 180/np.pi
      obl = np.zeros_like(body.Time)+obltmp

    f = open(dir[ii]+'/'+plname+'.in','r')
    lines = f.readlines()
    f.close()
    pco2 = 0
    #pdb.set_trace()
    for i in range(len(lines)):
      if lines[i].split() != []:
        if lines[i].split()[0] == 'dRotPeriod':
          P = -1*np.float(lines[i].split()[1])
        if lines[i].split()[0] == 'dSemi':
          semi = np.float(lines[i].split()[1])
          if semi < 0:
            semi *= -1
        if lines[i].split()[0] == 'dpCO2':
          pco2 = np.float(lines[i].split()[1])

    try:
      longp = (body.ArgP + body.LongA + body.PrecA)*np.pi/180.0
    except:
      longp = body.PrecA*np.pi/180.0

    esinv = ecc*np.sin(longp)*np.sin(obl*np.pi/180.)

    lats = np.unique(body.Latitude)
    nlats = len(lats)
    ntimes = len(body.Time)

    # plot temperature
    temp = np.reshape(body.TempLat,(ntimes,nlats))
    ax1 = plt.subplot(4,2,1)
    pos = ax1.figbox.get_points()
    c = plt.contourf(body.Time,lats,temp.T,cmap='plasma')
    plt.ylabel(r'Latitude [$^\circ$]', fontsize = 10)
    plt.title(r'Surface Temp [$^{\circ}$C]', fontsize = 12)
    plt.ylim(-85,85)
    plt.yticks([-60,-30,0,30,60], fontsize = 9)
    plt.xticks(fontsize = 9)
    if xrange:
      plt.xlim(xrange)
    cbar = plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    plt.setp(cbar.ax.yaxis.get_ticklabels(), fontsize = 9)

    # plot albedo
    alb = np.reshape(body.AlbedoLat,(ntimes,nlats))
    ax2 = plt.subplot(4,2,3)
    pos = ax2.figbox.get_points()
    c = plt.contourf(body.Time,lats,alb.T,cmap = 'Blues_r')
    plt.ylabel(r'Latitude [$^\circ$]', fontsize = 10)
    plt.title('Albedo [TOA]', fontsize = 12)
    plt.ylim(-85,85)
    plt.yticks([-60,-30,0,30,60], fontsize = 9)
    plt.xticks(fontsize = 9)
    if xrange:
      plt.xlim(xrange)
    cbar = plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    plt.setp(cbar.ax.yaxis.get_ticklabels(), fontsize = 9)


    # plot ice height
    ice = np.reshape(body.IceHeight,(ntimes,nlats))
    ax3 = plt.subplot(4,2,5)
    pos = ax3.figbox.get_points()
    c = plt.contourf(body.Time,lats,ice.T,cmap='Blues_r')
    plt.ylabel(r'Latitude [$^\circ$]', fontsize = 10)
    plt.title('Ice sheet height [m]', fontsize = 12)
    plt.ylim(-85,85)
    plt.yticks([-60,-30,0,30,60], fontsize = 9)
    plt.xticks(fontsize = 9)
    if xrange:
      plt.xlim(xrange)
    cbar = plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    plt.setp(cbar.ax.yaxis.get_ticklabels(), fontsize = 9)


    # plot bedrock
    brock = np.reshape(body.BedrockH,(ntimes,nlats))
    ax4 = plt.subplot(4,2,7)
    pos = ax4.figbox.get_points()
    c = plt.contourf(body.Time,lats,brock.T,cmap='Reds_r')
    plt.ylabel(r'Latitude [$^\circ$]', fontsize = 10)
    plt.title('Bedrock height [m]', fontsize = 12)
    plt.ylim(-85,85)
    plt.yticks([-60,-30,0,30,60], fontsize = 9)
    plt.xlabel('Time [years]',fontsize = 10)
    plt.xticks(fontsize = 9)
    if xrange:
      plt.xlim(xrange)
    cbar = plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    plt.setp(cbar.ax.yaxis.get_ticklabels(), fontsize = 9)

    # plot insolation
    insol = np.reshape(body.AnnInsol,(ntimes,nlats))
    ax5 = plt.subplot(4,2,2)
    pos = ax5.figbox.get_points()
    c = plt.contourf(body.Time,lats,insol.T,cmap='plasma')
    plt.ylabel(r'Latitude [$^\circ$]', fontsize = 10)
    plt.title(r'Annual average instellation [W/m$^2$]', fontsize = 12)
    plt.ylim(-85,85)
    plt.yticks([-60,-30,0,30,60], fontsize = 9)
    plt.xticks(fontsize = 9)
    if xrange:
      plt.xlim(xrange)
    cbar = plt.colorbar(c,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    plt.setp(cbar.ax.yaxis.get_ticklabels(), fontsize = 9)

    #obliquity
    plt.subplot(4,2,4)
    plt.plot(body.Time,obl,linestyle = 'solid',marker='None',color='darkblue',linewidth =2)
    plt.ylabel(r'Obliquity [$^\circ$]', fontsize = 10)
    plt.yticks(fontsize = 9)
    plt.xticks(fontsize = 9)

    if xrange:
        plt.xlim(xrange)

    #eccentricity
    plt.subplot(4,2,6)
    plt.plot(body.Time,ecc,linestyle = 'solid',marker='None',color='darkorchid',linewidth =2)
    plt.ylabel('Eccentricity', fontsize = 10)
    plt.xticks(fontsize = 9)
    plt.yticks(fontsize = 9)
    if xrange:
        plt.xlim(xrange)

    #e sin(obl) sin varpi
    plt.subplot(4,2,8)
    plt.plot(body.Time,esinv,linestyle = 'solid',marker='None',color='salmon',linewidth=2)
    plt.ylabel('COPP', fontsize = 10)
    plt.xlabel('Time [years]', fontsize = 10)
    plt.xticks(fontsize = 9)
    plt.yticks(fontsize = 9)
    if xrange:
        plt.xlim(xrange)

    if dir[ii] == '.':
      dir[ii] = 'cwd'

    if (sys.argv[1] == 'pdf'):
        plt.savefig('Evolve_Example.pdf')
    if (sys.argv[1] == 'png'):
        plt.savefig('Evolve_Example.png')
    if show:
        plt.show()
    else:
        plt.close()
Esempio n. 19
0
    lum0, obliq0, semi0, albedo_f, totice_m, snowball = np.loadtxt(listf,
                                                                   unpack=True)

#if the list files does not exist, create it
else:
    lum0 = np.zeros(len(folders))
    obliq0 = np.zeros(len(folders))
    semi0 = np.zeros(len(folders))
    albedo_f = np.zeros(len(folders))
    totice_m = np.zeros(len(folders))
    snowball = np.zeros(len(folders))

    crap = open(listf, "w")
    for i in np.arange(len(folders)):
        f = folders[i].decode("utf-8")
        out = vplot.GetOutput(f)
        lum0[i] = getattr(out.log.initial, 'sun').Luminosity
        obliq0[i] = getattr(out.log.initial, 'earth').Obliquity
        semi0[i] = getattr(out.log.initial, 'earth').SemiMajorAxis
        albedo_f[i] = out.earth.AlbedoGlobal[
            -1]  # -1 gives you the last entry in an array
        totice_m[i] = out.earth.TotIceMass[-1]
        snowball[i] = getattr(out.log.final, 'earth').Snowball
        crap.write("%f %f %f %f %f %f \n" %
                   (lum0[i], obliq0[i], semi0[i], albedo_f[i], totice_m[i],
                    snowball[i]))
    crap.close()

lum0 = np.reshape(lum0, (num, num))
obliq0 = np.reshape(obliq0, (num, num)) * 180 / np.pi
semi0 = np.reshape(semi0, (num, num)) / 1.49598e11
Esempio n. 20
0
def seasonal_maps(time, dir='.', show=True):
    """
  Creates plots of insolation, temperature, and ice balance
  over the course of an orbit (4 orbits for temp)

  Parameters
  ----------
  time : float
    The time of the data you want to plot (see SeasonalClimateFiles directory)

  Keyword Arguments
  -----------------
  dir : string
    Directory of vplanet simulation (default = '.')
  show : bool
    Show plot in Python (default = True)

  Output
  ------
  PDF format plot with name 'surf_seas_<time>.pdf'

  """
    dirf = dir + '/SeasonalClimateFiles'
    if not os.path.exists(dirf):
        raise StandardError('SeasonalClimateFiles directory does not exist')
    else:
        check = 0
        for f in subprocess.check_output('echo ' + dirf + '/*.DailyInsol.*',
                                         shell=True).split():
            f1 = re.split(
                '\.',
                re.split('/', f.decode('ascii'))[-1])  #split apart output file

            if len(f1) == 4:
                timestamp = f1[3]
            elif len(f1) == 5:
                timestamp = f1[3] + '.' + f1[4]

            time0 = np.float(timestamp)

            if time0 == time:
                #get system and planet names
                sysname = f1[0]
                plname = f1[1]
                insolf = dirf + '/' + sysname + '.' + plname + '.DailyInsol.' + timestamp
                tempf = dirf + '/' + sysname + '.' + plname + '.SeasonalTemp.' + timestamp
                icef = dirf + '/' + sysname + '.' + plname + '.SeasonalIceBalance.' + timestamp
                check = 1
        #print(insolf,tempf,icef)
        #exit()

        if check == 0:
            raise StandardError('Climate data not found for time %f' % time)

        insol = np.loadtxt(insolf, unpack=True)
        temp = np.loadtxt(tempf, unpack=True)
        ice = np.loadtxt(icef, unpack=True)
        output = vpl.GetOutput(dir)

        ctmp = 0
        for p in range(len(output.bodies)):
            if output.bodies[p].name == plname:
                body = output.bodies[p]
                ctmp = 1
            else:
                if p == len(output.bodies) - 1 and ctmp == 0:
                    raise Exception("Planet %s not found in folder %s" %
                                    (plname, folders[j]))

        lats = body.Latitude[0]
        try:
            obl = planet.Obliquity[np.where(body.Time == time)[0]]
        except:
            obl = getattr(output.log.initial, plname).Obliquity
            if obl.unit == 'rad':
                obl *= 180 / np.pi

        try:
            ecc = planet.Eccentricity[np.where(planet.Time == time)[0]]
        except:
            ecc = getattr(output.log.initial, plname).Eccentricity

        try:
            longp = (planet.LongP +
                     planet.PrecA)[np.where(planet.Time == time)[0]]
        except:
            try:
                longp = getattr(output.log.initial, plname).LongP
            except:
                try:
                    longp = (getattr(output.log.initial, plname).LongA +
                             getattr(out.log.initial, plname).ArgP)
                    if longp.unit == 'rad':
                        longp *= 180 / np.pi
                    longp = longp % 360
                except:
                    longp = 0

        fig = plt.figure(figsize=(16, 6))
        #fig.suptitle('Time = %f, Obl = %f, Ecc = %f, LongP = %f'%(time,obl,ecc,longp),fontsize=20)
        plt.subplot(1, 3, 1)
        fig.subplots_adjust(wspace=0.3)
        plt.title(r'Insolation [W/m$^2$]', fontsize=12)
        c1 = plt.contourf(np.arange(np.shape(insol)[1]),
                          lats,
                          insol,
                          cmap='plasma')
        plt.colorbar(c1)
        plt.ylim(lats[0], lats[-1])
        plt.xlabel('Time (days)')
        plt.ylabel('Latitude (degrees)')

        scale = 4 * np.shape(insol)[1] / np.shape(temp)[1]
        plt.subplot(1, 3, 2)
        c2 = plt.contourf(np.arange(np.shape(temp)[1]) * scale,
                          lats,
                          temp,
                          cmap='plasma')
        plt.title(r'Surface Temp [$^{\circ}$C]', fontsize=12)
        plt.colorbar(c2)
        plt.ylim(lats[0], lats[-1])
        plt.ylabel('Latitude (degrees)')
        plt.xlabel('Time (days)')
        plt.xlim(0, np.shape(temp)[1] * scale / 4.)

        scale = np.shape(insol)[1] / np.shape(ice)[1]
        plt.subplot(1, 3, 3)
        c3 = plt.contourf(np.arange(np.shape(ice)[1]) * scale,
                          lats,
                          ice,
                          cmap='Blues_r')
        plt.title(r'Ice balance [kg/m$^2$/s]', fontsize=12)
        plt.colorbar(c3)
        plt.ylim(lats[0], lats[-1])
        plt.xlabel('Time (days)')
        plt.ylabel('Latitude (degrees)')

        if (sys.argv[1] == 'pdf'):
            plt.savefig('IceBeltSeasonal.pdf', dpi=300)
        if (sys.argv[1] == 'png'):
            plt.savefig('IceBeltSeasonal.png', dpi=300)
        if show:
            plt.show()
        else:
            plt.close()
Esempio n. 21
0
def LnProb(x, **kwargs):
    """
    logprobability (lnlike + lnprior) function: runs VPLanet simulation
    """

    # Get the current vector
    dMass, dSatXUVFrac, dSatXUVTime, dStopTime, dXUVBeta = x
    dSatXUVFrac = 10**dSatXUVFrac  # Unlog
    dStopTime *= 1.e9  # Convert from Gyr -> yr
    dOutputTime = dStopTime  # Output only at the end of the simulation

    # Get the prior probability
    lnprior = kwargs["LnPrior"](x, **kwargs)
    if np.isinf(lnprior):
        blobs = np.array([np.nan, np.nan, np.nan])
        return -np.inf, blobs

    # Get strings containing VPLanet input files (they must be provided!)
    try:
        star_in = kwargs.get("STARIN")
        vpl_in = kwargs.get("VPLIN")
    except KeyError as err:
        print("ERROR: Must supply STARIN and VPLIN.")
        raise

    # Get PATH
    try:
        PATH = kwargs.get("PATH")
    except KeyError as err:
        print("ERROR: Must supply PATH.")
        raise

    # Randomize file names
    sysName = 'vpl%012x' % random.randrange(16**12)
    starName = 'st%012x' % random.randrange(16**12)
    sysFile = sysName + '.in'
    starFile = starName + '.in'
    logfile = sysName + '.log'
    starFwFile = '%s.star.forward' % sysName

    # Populate the star input file
    star_in = re.sub("%s(.*?)#" % "dMass", "%s %.6e #" % ("dMass", dMass),
                     star_in)
    star_in = re.sub("%s(.*?)#" % "dSatXUVFrac",
                     "%s %.6e #" % ("dSatXUVFrac", dSatXUVFrac), star_in)
    star_in = re.sub("%s(.*?)#" % "dSatXUVTime",
                     "%s %.6e #" % ("dSatXUVTime", -dSatXUVTime), star_in)
    star_in = re.sub("%s(.*?)#" % "dXUVBeta",
                     "%s %.6e #" % ("dXUVBeta", -dXUVBeta), star_in)
    with open(os.path.join(PATH, "output", starFile), 'w') as f:
        print(star_in, file=f)

    # Populate the system input file

    # Populate list of planets
    saBodyFiles = str(starFile) + " #"
    saBodyFiles = saBodyFiles.strip()

    vpl_in = re.sub('%s(.*?)#' % "dStopTime",
                    '%s %.6e #' % ("dStopTime", dStopTime), vpl_in)
    vpl_in = re.sub('%s(.*?)#' % "dOutputTime",
                    '%s %.6e #' % ("dOutputTime", dOutputTime), vpl_in)
    vpl_in = re.sub('sSystemName(.*?)#', 'sSystemName %s #' % sysName, vpl_in)
    vpl_in = re.sub('saBodyFiles(.*?)#', 'saBodyFiles %s #' % saBodyFiles,
                    vpl_in)
    with open(os.path.join(PATH, "output", sysFile), 'w') as f:
        print(vpl_in, file=f)

    # Run VPLANET and get the output, then delete the output files
    subprocess.call(["vplanet", sysFile], cwd=os.path.join(PATH, "output"))
    output = vpl.GetOutput(os.path.join(PATH, "output"), logfile=logfile)

    try:
        os.remove(os.path.join(PATH, "output", starFile))
        os.remove(os.path.join(PATH, "output", sysFile))
        os.remove(os.path.join(PATH, "output", starFwFile))
        os.remove(os.path.join(PATH, "output", logfile))
    except FileNotFoundError:
        # Run failed!
        blobs = np.array([np.nan, np.nan, np.nan])
        return -np.inf, blobs

    # Ensure we ran for as long as we set out to
    if not output.log.final.system.Age / utils.YEARSEC >= dStopTime:
        blobs = np.array([np.nan, np.nan, np.nan])
        return -np.inf, blobs

    # Get stellar properties
    dLum = float(output.log.final.star.Luminosity)
    dLumXUV = float(output.log.final.star.LXUVStellar)
    dRad = float(output.log.final.star.Radius)

    # Compute ratio of XUV to bolometric luminosity
    dLumXUVRatio = dLumXUV / dLum

    # Extract constraints
    # Must at least have luminosity, err for star
    lum = kwargs.get("LUM")
    lumSig = kwargs.get("LUMSIG")
    try:
        lumXUVRatio = kwargs.get("LUMXUVRATIO")
        lumXUVRatioSig = kwargs.get("LUMXUVRATIOSIG")
    except KeyError:
        lumXUVRatio = None
        lumXUVRatioSig = None

    # Compute the likelihood using provided constraints, assuming we have
    # luminosity constraints for host star
    lnlike = ((dLum - lum) / lumSig)**2
    if lumXUVRatio is not None:
        lnlike += ((dLumXUVRatio - lumXUVRatio) / lumXUVRatioSig)**2
    lnprob = -0.5 * lnlike + lnprior

    # Return likelihood and blobs
    blobs = np.array([dLum, dLumXUV, dRad])
    return lnprob, blobs
Esempio n. 22
0
            snowballS = float(line[2])
            northCapL = float(line[3])
            northCapS = float(line[4])
            southCapL = float(line[5])
            southCapS = float(line[6])
            icebeltL = float(line[7])
            icebeltS = float(line[8])
            iceFree = float(line[9])

            if (
                icebeltL == 1 and icebeltS == 0 and southCapS == 0 and
                southCapL == 0 and northCapS == 0 and northCapL == 0 and
                snowballL == 0 and snowballS == 0
            ):
                if icecount <= 70:
                    out = vpl.GetOutput(folders[number])
                    body = out.bodies[1]

                    lats = np.unique(body.Latitude)
                    nlats = len(lats)
                    ntimes = len(body.Time)

                    ice = np.reshape(body.IceHeight,(ntimes,nlats))
                    ice_last = ice[-1]

                    data += ((ice_last.T)/1000)
                    indi = axs[x].plot(lats,((ice_last.T)/1000), color = 'gray', alpha = 0.25)
                    icecount += 1

    for z in range(data.size):
        avg_count[z] = data[z]/icecount
Esempio n. 23
0
    exit(1)
if (sys.argv[1] != 'pdf' and sys.argv[1] != 'png'):
    print('ERROR: Unknown file format: ' + sys.argv[1])
    print('Options are: pdf, png')
    exit(1)
filepref = 'TidalEarth'

dir_path = os.path.dirname(os.path.realpath(__file__))
dirs = ["au0.01", "au0.02", "au0.05"]
# Run the simulations
for dir in dirs:
    print("Running simulation in %s directory...\n" % dir)
    os.chdir(os.path.join(dir_path, dir))
    subprocess.call(['vplanet', 'vpl.in'])
# load data
outputs = [vplot.GetOutput(str(os.path.join(dir_path, dir))) for dir in dirs]
#out0 = vplot.GetOutput(dirs[0])
out0 = outputs[0]
out1 = outputs[1]
out2 = outputs[2]

# Print final state
out = out0


def fig2x3(out, nfig, color='k', legendon=False):
    fig = plt.figure(nfig, figsize=(10, 15))
    panel = 1
    plt.subplot(rows, cols, panel)
    plt.plot(out.tidalearth.Time,
             out.tidalearth.TMan,
Esempio n. 24
0
def LnLike(daStateVector, **kwargs):
    """
    loglikelihood function: runs VPLanet simulation
    """

    # Get the current state vector
    dMass,dFSat,dTSat,dAge,dBeta,dFRock,dWaterMass,dEnvMass,dEscCoeffH,dEscCoeffH2O,dPressXUV,dAlbedo,dPlanetMass,dOrbPer = daStateVector

    # Convert to VPLanet input
    dFSat = 10 ** dFSat # Unlog
    dStopTime = dAge*1.e9 # Convert from Gyr -> yr
    dOutputTime = dStopTime # Output only at the end of the simulation

    # Initialize the output parameter vector
    daParams = np.zeros(iNumOutputPrms)

    # Get the prior probability to ignore unphysical state vectors
    # Do this to prevent errors stemming from VPLanet not finishing
    dLnPrior = kwargs["LnPrior"](daStateVector, **kwargs)
    if np.isinf(dLnPrior):
        for iPrm in range(iNumOutputPrms):
            daParams[iPrm] = np.nan
        return -np.inf, daParams

    # Get strings containing VPLanet input files (they must be provided!)
    try:
        sStarFileIn = kwargs.get("STARIN")
        sPrimaryFileIn = kwargs.get("VPLIN")
        sPlanetFileIn = kwargs.get("PLANETIN")
    except KeyError as err:
        print("ERROR: Must supply VPLIN, STARIN, and EIN in LnLike.")
        raise

    # Get PATH
    try:
        PATH = kwargs.get("PATH")
    except KeyError as err:
        print("ERROR: Must supply PATH.")
        raise

    # Randomize file names to prevent overwrites
    sVPLName = 'vpl%012x' % random.randrange(16**12)
    sStarName = 'st%012x' % random.randrange(16**12)
    sPlanetName = 'e%012x' % random.randrange(16**12)
    sPrimaryFile = sVPLName + '.in'
    sStarFile = sStarName + '.in'
    sPlanetFile = sPlanetName + '.in'
    sLogFile = sVPLName + '.log'
    sStarFwFile = '%s.star.forward' % sVPLName
    sPlanetFwFile = '%s.e.forward' % sPlanetName


# mkdir output!

    # Populate the input files
    sStarFileIn = re.sub("%s(.*?)#" % "dMass", "%s %.6e #" % ("dMass", dMass), sStarFileIn)
    sStarFileIn = re.sub("%s(.*?)#" % "dSatXUVFrac", "%s %.6e #" % ("dSatXUVFrac", dFSat), sStarFileIn)
    sStarFileIn = re.sub("%s(.*?)#" % "dSatXUVTime", "%s %.6e #" % ("dSatXUVTime", -dTSat), sStarFileIn)
    sStarFileIn = re.sub("%s(.*?)#" % "dXUVBeta", "%s %.6e #" % ("dXUVBeta", -dBeta), sStarFileIn)

    sPlanetFileIn = re.sub("%s(.*?)#" % "dFracRock", "%s %.6e #" % ("dFracRock", dFRock), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dSurfaceWaterMass", "%s %.6e #" % ("dSurfaceWaterMass", dWaterMass), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dEnvelopeMass", "%s %.6e #" % ("dEnvelopeMass", -dEnvMass), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dAtmXAbsEffH2O", "%s %.6e #" % ("dAtmXAbsEffH2O", dEscCoeffH2O), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dAtmXAbsEffH ", "%s %.6e #" % ("dAtmXAbsEffH", dEscCoeffH), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dPresXUV", "%s %.6e #" % ("dPresXUV", dPressXUV), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dAlbedoGlobal", "%s %.6e #" % ("dAlbedoGlobal", dAlbedo), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dMass", "%s %.6e #" % ("dMass", dPlanetMass), sPlanetFileIn)
    sPlanetFileIn = re.sub("%s(.*?)#" % "dOrbPeriod", "%s %.6e #" % ("dOrbPeriod", dOrbPer), sPlanetFileIn)

    with open(os.path.join(PATH, "output", sStarFile), 'w') as f:
        print(sStarFileIn, file = f)

    with open(os.path.join(PATH, "output", sPlanetFile), 'w') as f:
        print(sPlanetFileIn, file = f)

    # Populate the primary input file
    # Populate list of planets
    saBodyFiles = str(sStarFile) + " " + str(sPlanetFile) +" #"

    saBodyFiles = saBodyFiles.strip()

    sPrimaryFileIn = re.sub('%s(.*?)#' % "dStopTime", '%s %.6e #' % ("dStopTime", dStopTime), sPrimaryFileIn)
    sPrimaryFileIn = re.sub('%s(.*?)#' % "dOutputTime", '%s %.6e #' % ("dOutputTime", dOutputTime), sPrimaryFileIn)
    sPrimaryFileIn = re.sub('sSystemName(.*?)#', 'sSystemName %s #' % sVPLName, sPrimaryFileIn)
    sPrimaryFileIn = re.sub('saBodyFiles(.*?)#', 'saBodyFiles %s #' % saBodyFiles, sPrimaryFileIn)
    with open(os.path.join(PATH, "output", sPrimaryFile), 'w') as f:
        print(sPrimaryFileIn, file = f)

    #exit()

    # Run VPLANET and get the output, then delete the output files
    subprocess.call(["vplanet", '-q', sPrimaryFile], cwd = os.path.join(PATH, "output"))
    output = vpl.GetOutput(os.path.join(PATH, "output"), logfile = sLogFile)

    try:
        os.remove(os.path.join(PATH, "output", sStarFile))
        os.remove(os.path.join(PATH, "output", sPlanetFile))
        os.remove(os.path.join(PATH, "output", sPrimaryFile))
        os.remove(os.path.join(PATH, "output", sStarFwFile))
        os.remove(os.path.join(PATH, "output", sLogFile))
    except FileNotFoundError:
        # Run failed!
        for iPrm in range(iNumOutputPrms):
            daParams[iPrm] = np.nan
        return -np.inf, daParams

    # Ensure we ran for as long as we set out to
    # XXX Why not == pr < dEpsilon?
    if not output.log.final.system.Age / YEARSEC >= dStopTime:
        for iPrm in range(iNumOutputPrms):
            daParams[iPrm] = np.nan
        return -np.inf, daParams

    # Get final values of observed parameters
    dLumTrial = float(output.log.final.star.Luminosity)
    dLumXUVTrial = float(output.log.final.star.LXUVStellar)
    dTEffTrial = float(output.log.final.star.Temperature)
    dMassETrial = float(output.log.final.e.Mass)
    dRadETrial = float(output.log.final.e.Radius)

    # Compute ratio of XUV to bolometric luminosity
    dLumXUVRatioTrial = dLumXUVTrial / dLumTrial

    # Get extra parameters
    dStarRad = float(output.log.final.star.Radius)
    dEqTemp = float(output.log.final.e.ThermTemp)
    dSurfPress = float(output.log.final.e.PresSurf)
    dWaterMass = float(output.log.final.e.SurfWaterMass)
    dEnvMass = float(output.log.final.e.EnvelopeMass)
    dOxygenPress = float(output.log.final.e.OxygenMass)
    dSemi = float(output.log.final.e.SemiMajorAxis)

    # Extract constraints
    # Must at least have luminosity, err for star
    dLum = kwargs.get("LUM")
    dLumSig = kwargs.get("LUMSIG")

    dLumXUVRatio = kwargs.get("LUMXUVRATIO")
    dLumXUVRatioSig = kwargs.get("LUMXUVRATIOSIG")

    dTEff = kwargs.get("TEFF")
    dTEffSig = kwargs.get("TEFFSIG")

    dMassE = kwargs.get("MASSE")
    dMassESig = kwargs.get("MASSESIG")

    dRadE = kwargs.get("RADE")
    dRadESig = kwargs.get("RADESIG")

    # Compute the likelihood using provided constraints, assuming we have
    # luminosity constraints for host star
    dLnLike = 0

    dLnLike += ((dLum - dLumTrial) / dLumSig) ** 2
    dLnLike += ((dLumXUVRatio - dLumXUVRatioTrial) / dLumXUVRatioSig) ** 2
    dLnLike += ((dTEff - dTEffTrial) / dTEffSig) ** 2
    dLnLike += ((dMassE - dMassETrial) / dMassESig) ** 2
    dLnLike += ((dRadE - dRadETrial) / dRadESig) ** 2

    dLnLike = -0.5 * dLnLike

    print("dLnLike: ",dLnLike)
    # Return likelihood and diognostic parameters

    daParams = np.array([dLumTrial,
                         dLumXUVTrial,
                         dTEffTrial,
                         dMassETrial,
                         dRadETrial,
                         dStarRad,
                         dEqTemp,
                         dSurfPress,
                         dWaterMass,
                         dEnvMass,
                         dOxygenPress,
                         dSemi
                         ])
    return dLnLike, daParams
Esempio n. 25
0
import sys
import scipy.signal as sig
import subprocess

# Check correct number of arguments
if (len(sys.argv) != 2):
    print('ERROR: Incorrect number of arguments.')
    print('Usage: '+sys.argv[0]+' <pdf | png>')
    exit(1)
if (sys.argv[1] != 'pdf' and sys.argv[1] != 'png'):
    print('ERROR: Unknown file format: '+sys.argv[1])
    print('Options are: pdf, png')
    exit(1)

subprocess.call(['vplanet', 'vpl.in'])
out = vpl.GetOutput()

time = out.TGstar.Time/1e3

fig = plt.figure(figsize=(6.5,8))
plt.subplot(3,2,1)
plt.plot(time,out.TGb.Obliquity,color='k')
plt.plot(time,out.TGc.Obliquity,color=vpl.colors.red)
plt.ylabel(r'Obliquity ($^\circ$)')

plt.subplot(3,2,2)
plt.plot(time,out.TGb.Eccentricity,color='k')
plt.plot(time,out.TGc.Eccentricity,color=vpl.colors.red)
plt.ylabel('Eccentricity')

plt.subplot(3,2,3)
Esempio n. 26
0
# -*- coding: iso-8859-1 -*-
import numpy as np
import matplotlib.pyplot as plt
import vplot

plt.rcParams["text.usetex"] = True
plt.rcParams["text.latex.unicode"] = True

out = vplot.GetOutput()

fig = plt.figure(figsize=(8.5, 8))
fig.subplots_adjust(hspace=0.1)

t, a, e, inc, longa, argp, ma = np.loadtxt('hnbdata/1.dat', unpack=True)
ax = plt.subplot(4, 2, 1)
plt.plot(out.Mercury.Time / 1e6,
         out.Mercury.Eccentricity,
         'k-',
         label='DistOrb',
         zorder=100)
plt.plot(t / 1e6, e, '0.5', label='HNBody')
plt.xlim(0, 1)
plt.ylabel('$e$')
plt.xticks(visible=False)
plt.text(0.05, 0.85, 'Mercury', transform=ax.transAxes)

plt.subplot(4, 2, 2)
plt.plot(out.Mercury.Time / 1e6,
         out.Mercury.Inc,
         'k-',
         label='DistOrb',
    print('ERROR: Incorrect number of arguments.')
    print('Usage: ' + sys.argv[0] + ' <pdf | png>')
    exit(1)
if (sys.argv[1] != 'pdf' and sys.argv[1] != 'png'):
    print('ERROR: Unknown file format: ' + sys.argv[1])
    print('Options are: pdf, png')
    exit(1)

# Run the sims
subp.call('cd Kopparapu; vplanet vpl.in', shell=True)
print("Completed Kopparapu simulation.")
subp.call('cd DryLimits; vplanet vpl.in', shell=True)
print("Completed DryLimits simulation.")

# First plot traditional HZ
output = vpl.GetOutput('Kopparapu')

rc('axes', linewidth=2)
plt.rcParams['xtick.major.pad'] = '8'
plt.rcParams['ytick.major.pad'] = '5'
plt.rcParams['xtick.major.size'] = 10
plt.rcParams['xtick.major.width'] = 2
plt.rcParams['xtick.minor.size'] = 5
plt.rcParams['xtick.minor.width'] = 1
plt.rcParams['ytick.major.size'] = 10
plt.rcParams['ytick.major.width'] = 2
plt.rcParams['ytick.minor.size'] = 5
plt.rcParams['ytick.minor.width'] = 1

plt.figure(figsize=(7, 6), dpi=300)
Esempio n. 28
0
import numpy as np
import matplotlib.pyplot as plt
import vplot
import sys

# Check correct number of arguments
if (len(sys.argv) != 2):
    print('ERROR: Incorrect number of arguments.')
    print('Usage: ' + sys.argv[0] + ' <pdf | png>')
    exit(1)
if (sys.argv[1] != 'pdf' and sys.argv[1] != 'png'):
    print('ERROR: Unknown file format: ' + sys.argv[1])
    print('Options are: pdf, png')
    exit(1)

cpl = vplot.GetOutput('CPL')
ctl = vplot.GetOutput('CTL')

fig, ax = plt.subplots(1, 2, figsize=(12, 4))

ax[0].plot(cpl.d.Time,
           cpl.d.RotPer,
           color='k',
           linestyle='dashed',
           label='CPL')
ax[0].plot(ctl.d.Time, ctl.d.RotPer, color='k', linestyle='solid', label='CTL')
ax[0].set_xscale('log')
ax[0].set_xlabel('Time (Years)')
ax[0].set_ylabel('Rotation Period (d)')
ax[0].legend(loc='upper left', fontsize=10)
Esempio n. 29
0
def seasonal_maps(time, dir = '.', show = True):
  """
  Creates plots of insolation, temperature, and ice balance
  over the course of an orbit (4 orbits for temp)

  Parameters
  ----------
  time : float
    The time of the data you want to plot (see SeasonalClimateFiles directory)

  Keyword Arguments
  -----------------
  dir : string
    Directory of vplanet simulation (default = '.')
  show : bool
    Show plot in Python (default = True)

  Output
  ------
  PDF format plot with name 'surf_seas_<time>.pdf'

  """
  dirf = dir+'/SeasonalClimateFiles'
  if not os.path.exists(dirf):
    raise StandardError('SeasonalClimateFiles directory does not exist')
  else:
    check = 0
    for f in subprocess.check_output('echo '+dirf+'/*.DailyInsol.*',shell=True).split():
      f1 = re.split('\.',re.split('/',f.decode('ascii'))[-1])  #split apart output file

      if len(f1) == 4:
        timestamp = f1[3]
      elif len(f1) == 5:
        timestamp = f1[3]+'.'+f1[4]

      time0 = np.float(timestamp)

      if time0 == time:
        #get system and planet names
        sysname = f1[0]
        plname = f1[1]
        insolf = dirf+'/'+sysname+'.'+plname+'.DailyInsol.'+timestamp
        tempf = dirf+'/'+sysname+'.'+plname+'.SeasonalTemp.'+timestamp
        icef = dirf+'/'+sysname+'.'+plname+'.SeasonalIceBalance.'+timestamp
        planckbf = dirf+'/'+sysname+'.'+plname+'.SeasonalFOut.'+timestamp
        check = 1

    if check == 0:
      raise StandardError('Climate data not found for time %f'%time)

    insol = np.loadtxt(insolf,unpack=True)
    temp = np.loadtxt(tempf,unpack=True)
    ice = np.loadtxt(icef,unpack=True)
    fluxo = np.loadtxt(planckbf,unpack=True)
    output = vplot.GetOutput(dir)
    ctmp = 0
    for p in range(len(output.bodies)):
      if output.bodies[p].name == plname:
        body = output.bodies[p]
        ctmp = 1
      else:
        if p == len(output.bodies)-1 and ctmp == 0:
          raise Exception("Planet %s not found in folder %s"%(plname,dir))

    lats = body.Latitude[0]
    try:
      obl = body.Obliquity[np.where(body.Time==time)[0]]
    except:
      obl = getattr(output.log.initial,plname).Obliquity
      if obl.unit == 'rad':
        obl *= 180/np.pi

    try:
      ecc = body.Eccentricity[np.where(body.Time==time)[0]]
    except:
      ecc = getattr(output.log.initial,plname).Eccentricity

    try:
      longp = (body.LongP+body.PrecA)[np.where(body.Time==time)[0]]
    except:
      try:
        longp = getattr(output.log.initial,plname).LongP
      except:
        try:
          longp = (getattr(output.log.initial,plname).LongA+getattr(out.log.initial,plname).ArgP)
          if longp.unit == 'rad':
            longp *= 180/np.pi
          longp = longp%360
        except:
          longp = 0

    fig = plt.figure(figsize=(8.5,5))
    fig.subplots_adjust(wspace=0.3,hspace=0.2)
    # fig.suptitle('Time = %f, Obl = %f, Ecc = %f, LongP = %f'%(time,obl,ecc,longp),fontsize=20)
    ax = plt.subplot(2,2,1)
    ax.set_position(pos=[0.1,0.54,0.3,0.41])
    pos = ax.figbox.get_points()
    c1=plt.contourf(np.arange(np.shape(insol)[1]),lats,insol,cmap='plasma')
    plt.ylim(lats[0],lats[-1])
    plt.ylabel('Latitude ($^{\circ}$)')
    plt.yticks([-60,-30,0,30,60],['60S','30S','0','30N','60N'])
    # plt.xticks(visible=False)
    clb = plt.colorbar(c1,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    clb.set_label(r'Insolation (W/m$^2$)',fontsize=12)

    scale = 4*np.shape(insol)[1]/np.shape(temp)[1]
    ax = plt.subplot(2,2,2)
    ax.set_position(pos=[0.6,0.54,0.3,0.41])
    pos = ax.figbox.get_points()
    c2=plt.contourf(np.arange(np.shape(temp)[1])*scale,lats,temp,cmap='plasma')
    plt.ylim(lats[0],lats[-1])
    # plt.ylabel('Latitude ($^{\circ}$)')
    plt.xlim(0,np.shape(temp)[1]*scale/4.)
    plt.yticks([-60,-30,0,30,60],['60S','30S','0','30N','60N'])
    # plt.xticks(visible=False)
    clb=plt.colorbar(c2,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    clb.set_label(r'Surface Temp ($^{\circ}$C)',fontsize=12)

    scale = np.shape(insol)[1]/np.shape(ice)[1]
    ax = plt.subplot(2,2,3)
    ax.set_position(pos=[0.1,0.05,0.3,0.41])
    pos = ax.figbox.get_points()
    c3=plt.contourf(np.arange(np.shape(ice)[1])*scale,lats,ice*1e3,cmap='Blues_r')
    plt.ylim(lats[0],lats[-1])
    plt.ylabel('Latitude ($^{\circ}$)')
    plt.yticks([-60,-30,0,30,60],['60S','30S','0','30N','60N'])
    plt.xlabel('Day')
    clb =plt.colorbar(c3,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    clb.set_label(r'Ice balance (10$^{-3}$ kg/m$^2$/s)',fontsize=12)


    scale = 4*np.shape(insol)[1]/np.shape(temp)[1]
    ax = plt.subplot(2,2,4)
    ax.set_position(pos=[0.6,0.05,0.3,0.41])
    pos = ax.figbox.get_points()
    c2=plt.contourf(np.arange(np.shape(fluxo)[1])*scale,lats,fluxo,cmap='plasma')
    plt.ylim(lats[0],lats[-1])
    plt.xlim(0,np.shape(temp)[1]*scale/4.)
    # plt.ylabel('Latitude ($^{\circ}$)')
    plt.yticks([-60,-30,0,30,60],['60S','30S','0','30N','60N'])
    plt.xlabel('Day')
    clb=plt.colorbar(c2,cax=plt.axes([pos[1,0]+0.01,pos[0,1],0.01,pos[1,1]-pos[0,1]]))
    clb.set_label(r'OLR (W m$^{-2}$)',fontsize=12)

    plt.savefig('seasons.pdf')
    if show:
      plt.show()
    else:
      plt.close()
Esempio n. 30
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
example2.py
-----------

'''

from __future__ import division, print_function, absolute_import, \
    unicode_literals
import vplot as vpl
import matplotlib.pyplot as plt

# Grab the output from a run
output = vpl.GetOutput('solarsys')

# Set up a matplotlib plot as usual
fig, ax = plt.subplots(2, 2, figsize=(12, 8))

# Now use ``vpl.plot`` instead of ``plt.plot`` to do the
# plotting to get customized VPLOT plots. You can specify
# keyword arguments in the same way you would for ``plt.plot``.
for planet in [output.Earth, output.Jupiter]:
    vpl.plot(ax[0, 0], 100 * planet.Time, planet.Eccentricity)
    vpl.plot(ax[0, 1], 100 * planet.Time, planet.Inc)

vpl.plot(ax[1, 0], output.Earth.Latitude[0], output.Earth.TempLat[0])
vpl.plot(ax[1, 1], output.Earth.Time, output.Earth.IceHeight[:, 0])

# Add legends
ax[0, 0].legend()