Yaml input files

YAML is a nice input file format that can be useful for using a file to set variables for a code.

  • It is common to have a program that has lots of parameters that the user needs to set.
  • These can be put in a text input file and the Python can read the values from that file.
    • This is preferable to having the user have to change your code itself.
  • A YAML input file has data in a format that is much easier to read from than if you had to write the code to parse the file yourself.
  • Click this link for more information on the file format.
  • Library needed: import yaml

Example

  • Below is a sample yaml input file called input.yaml.
  • This is a separate file, it is not in the jupyter notebook.
    • We are just showing the contents of the file here.
  • We have variable names with values and comments that describe the variables.
    • For example, there is a variable "seed" that has value 23 followed by a description.
  • Note, there can be different indentation levels, that are useful for grouping variables.
  • You can also load arrays of data values.

Basics

  • Keywords (variables) end in ":"
  • Put the value after the keyword
  • Blank lines are fine
  • Comments start with "#"
  • Use aligned indentation to indicate nesting.
    • This is good for grouping variables.
  • You can read variables in any order, and any number of times.
  • You can include arrays of data. Use "- " to begin the data.
  • See below for examples of getting data from the input file
In [2]:
from IPython.display import IFrame    
IFrame('http://ignite.byu.edu/che263/lectureNotes/input.yaml', width=600, height=820)
Out[2]:

Now open and get data from the file

In [11]:
import yaml

yfile = yaml.load(open("input.yaml"))

#--------- Read some nested vars: 

seed = yfile["params"]["seed"]              # seed is a variable in the params "nest"
tEnd = yfile["params"]["tEnd"]              # grab tEnd, also in the params "nest"
print("seed = ", seed)
print("tEnd = ", tEnd)

y_O2 = yfile["streamProps"]["comp0"]["O2"]  # grab O2 concentration (note the nesting)
print("O2 concentration = ",y_O2)

#---------- Load an array of data:

dumpTimes = yfile["dumpTimes"]              # load the 1-D array (this is too easy!)
xydata    = yfile["initParams"]["vprof"]

print("dumpTimes = ", dumpTimes)
print("xydata = ", xydata)
seed =  23
tEnd =  0.3682
O2 concentration =  0.21
dumpTimes =  [1e-05, 0.01, 0.02, 0.021]
xydata =  [[-0.02104, 9.25], [-0.019988, 9.25], [-0.016832, 9.15], [-0.01315, 9.0]]
In [ ]: