Last active
November 14, 2019 22:20
-
-
Save chinghwayu/f61b3ef72b4504b84980d3f07791ed5d to your computer and use it in GitHub Desktop.
Generating data from INI configuration files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from configparser import ConfigParser | |
def generate_data(filename, name): | |
"""This function read parameters from an ini file and generates data depending on the 'dtype' option.""" | |
config = ConfigParser() | |
config.read(filename) | |
mode = config.get(name, "mode", fallback="discrete") | |
dtype = config.get(name, "dtype", fallback="string") | |
if mode == "discrete": | |
if dtype == "int": | |
values = map(int, config.get(name, "values").split(",")) | |
elif dtype == "float": | |
values = map(float, config.get(name, "values").split(",")) | |
else: | |
values = map(str, config.get(name, "values").split(",")) | |
elif mode == "step": | |
if dtype == "int": | |
start = config.getint(name, "start") | |
stop = config.getint(name, "stop") | |
step = config.getint(name, "step") | |
elif dtype == "float": | |
start = config.getfloat(name, "start") | |
stop = config.getfloat(name, "stop") | |
step = config.getfloat(name, "step") | |
else: | |
raise ValueError("dtype key of either 'int' or 'float' must exist.") | |
stop = round(stop + step, 14) # increment stop for inclusive range and round off floating point error | |
values = frange(start, stop, step) | |
return values | |
def frange(start, stop=None, step=None): | |
"""This provides a floating point range function is both positive and negative directions""" | |
if stop is None: | |
stop = start | |
start = 0 | |
if step is None: | |
step = 1 | |
i = start | |
while True: | |
if step > 0 and i >= stop: | |
break | |
elif step < 0 and i <= stop: | |
break | |
yield i | |
i = round(i + step, 14) # round off floating point rounding error |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[discrete_float] | |
mode = discrete | |
dtype = float | |
values = 1.04,1.1,1.16 | |
[step_integer] | |
mode = step | |
dtype = int | |
start = 10 | |
stop = 100 | |
step = 10 | |
[step_float] | |
mode = step | |
dtype = float | |
start = 0 | |
stop = -0.1 | |
step = -0.02 | |
[character] | |
values = A,B,C |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment