Skip to content

Interface

Main

oqd_heisenberg_ion.interface.main

main

main entry point of the package when called from the command line

Parameters:

  • argv (list[str], default: None ) –

    list of command line arguments. Defaults to None.

Returns:

  • int

    exit code, equals 0 if program executes successfully

Source code in src/oqd_heisenberg_ion/interface/main.py
def main(argv=None):
    """
    main entry point of the package when called from the command line

    Args:
        argv (list[str], optional): list of command line arguments. Defaults to None.

    Returns:
        (int): exit code, equals 0 if program executes successfully
    """

    parser = argparse.ArgumentParser()
    parser.add_argument("--input", "-i", required=True, help="Path to input file.")
    parser.add_argument(
        "--override",
        "-o",
        required=False,
        action="append",
        nargs=2,
        metavar=("KEY", "VALUE"),
        help="Override key word arguments",
    )
    args = parser.parse_args(argv)

    override_dict = extract_override_arguments(args)

    sim_workflow = Orchestrator(input_file=args.input, **override_dict)
    sim_workflow.simulate()

    return 0

Orchestrator

oqd_heisenberg_ion.interface.orchestrator

Orchestrator

Responsible for managing the entire workflow of the package. Sequentially reads the inputs, calls the preprocessor, driver and simulator

Source code in src/oqd_heisenberg_ion/interface/orchestrator.py
class Orchestrator:
    """
    Responsible for managing the entire workflow of the package. Sequentially reads the inputs, calls the preprocessor, driver and simulator
    """

    def __init__(self, **kwargs):
        """
        constructor for the Orchestrator class. Determines whether inputs should be read from file or are provided as key word arguments

        Args:
            **kwargs (dict): key word arguments. An input file is expected if one of the keys is 'input_file'
        """

        if "input_file" in kwargs:
            self.build_from_file(**kwargs)
        else:
            self.build_from_parameters(**kwargs)

    def build_from_file(self, input_file, **kwargs):
        """
        used to call the preprocessor if input file needs to be read for the simulation.

        Args:
            input_file (str): path to the input file
        """

        file_inputs = InputReader(input_file_path=input_file)
        file_inputs.read_inputs_from_file(**kwargs)
        simulator = file_inputs.simulator

        preprocessor = PreprocessorFactory.create(simulator, file_inputs.parameter_set_list)
        driver_inputs = preprocessor.preprocess()

        self.driver = DriverFactory.create(simulator, preprocessor.simulation_folder, driver_inputs)

    def build_from_parameters(self, **kwargs):
        """
        used to call the preprocessor if the simulation inputs are provided as key word arguments
        """

        simulator = kwargs["simulator"]

        inputs = InputReader()
        inputs.read_kwarg_inputs(**kwargs)

        parameter_set_list = inputs.parameter_set_list

        self.preprocessor = PreprocessorFactory.create(simulator, parameter_set_list)
        driver_inputs = self.preprocessor.preprocess()

        self.driver = DriverFactory.create(simulator, self.preprocessor.simulation_folder, driver_inputs)

    def simulate(self):
        """
        simulates the entire workflow

        Returns:
            (int): the exit code, 0 when the program executes to completion
        """

        self.driver.simulate()

        return 0

__init__

constructor for the Orchestrator class. Determines whether inputs should be read from file or are provided as key word arguments

Parameters:

  • **kwargs (dict, default: {} ) –

    key word arguments. An input file is expected if one of the keys is 'input_file'

Source code in src/oqd_heisenberg_ion/interface/orchestrator.py
def __init__(self, **kwargs):
    """
    constructor for the Orchestrator class. Determines whether inputs should be read from file or are provided as key word arguments

    Args:
        **kwargs (dict): key word arguments. An input file is expected if one of the keys is 'input_file'
    """

    if "input_file" in kwargs:
        self.build_from_file(**kwargs)
    else:
        self.build_from_parameters(**kwargs)

build_from_file

used to call the preprocessor if input file needs to be read for the simulation.

Parameters:

  • input_file (str) –

    path to the input file

Source code in src/oqd_heisenberg_ion/interface/orchestrator.py
def build_from_file(self, input_file, **kwargs):
    """
    used to call the preprocessor if input file needs to be read for the simulation.

    Args:
        input_file (str): path to the input file
    """

    file_inputs = InputReader(input_file_path=input_file)
    file_inputs.read_inputs_from_file(**kwargs)
    simulator = file_inputs.simulator

    preprocessor = PreprocessorFactory.create(simulator, file_inputs.parameter_set_list)
    driver_inputs = preprocessor.preprocess()

    self.driver = DriverFactory.create(simulator, preprocessor.simulation_folder, driver_inputs)

build_from_parameters

used to call the preprocessor if the simulation inputs are provided as key word arguments

Source code in src/oqd_heisenberg_ion/interface/orchestrator.py
def build_from_parameters(self, **kwargs):
    """
    used to call the preprocessor if the simulation inputs are provided as key word arguments
    """

    simulator = kwargs["simulator"]

    inputs = InputReader()
    inputs.read_kwarg_inputs(**kwargs)

    parameter_set_list = inputs.parameter_set_list

    self.preprocessor = PreprocessorFactory.create(simulator, parameter_set_list)
    driver_inputs = self.preprocessor.preprocess()

    self.driver = DriverFactory.create(simulator, self.preprocessor.simulation_folder, driver_inputs)

simulate

simulates the entire workflow

Returns:

  • int

    the exit code, 0 when the program executes to completion

Source code in src/oqd_heisenberg_ion/interface/orchestrator.py
def simulate(self):
    """
    simulates the entire workflow

    Returns:
        (int): the exit code, 0 when the program executes to completion
    """

    self.driver.simulate()

    return 0

Input File Reader

oqd_heisenberg_ion.common.inputs.input_reader

InputReader

Extracts provided inputs and generates a list of parameter sets, with each parameter set represented as a dict. Inputs need to be provided either in a tab-delimited file or as key word arguments

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
class InputReader:
    """
    Extracts provided inputs and generates a list of parameter sets, with each parameter set represented as a dict.
    Inputs need to be provided either in a tab-delimited file or as key word arguments
    """

    def __init__(self, simulator=None, input_file_path=None):
        """
        initializes the InputReader

        Args:
            input_file_path (str, optional): path to input file. Defaults to None.
        """
        if input_file_path is not None:
            self.input_file = os.path.abspath(input_file_path)
        if simulator is not None:
            self.simulator = convert_to_snake_case(simulator)

        self.num_parameter_sets = 1

        self.is_param_iterable = {}

        self.parameter_set_list = []

    def read_kwarg_inputs(self, **kwargs):
        """
        Extracts inputs from key word arguments and builds list of parameter sets

        Args:
            **kwargs (dict): input key word arguments provided by user
        """

        input_config = self.extract_kwarg_inputs(**kwargs)

        self.extract_parameter_set_list(input_config)

    def read_inputs_from_file(self, **overrides):
        """
        Extracts inputs from file and builds list of parameter sets

        Args:
            **overrides (dict): input key word arguments provided by user as overrides
        """

        input_config = self.extract_file_key_value_inputs()

        input_config = self.override_file_inputs(input_config, **overrides)

        self.extract_parameter_set_list(input_config)

        self.simulator = convert_to_snake_case(self.parameter_set_list[0]["simulator"])

    def extract_file_key_value_inputs(self):
        """
        Reads input file to generate a dict of key value pairs specifying parameters. Each value is a list of parameters

        Returns:
            (dict): containing the key value pairs from the tab delimited input file
        """

        input_config = {}

        with open(self.input_file) as f:
            line_count = 0

            for line in f.readlines():
                line_count += 1

                if line.startswith("#") or line.strip() == "":
                    continue

                line_data = line.strip().split("\t")

                key = line_data[0]
                data = line_data[1].strip().split(",")

                input_config = self.record_input(input_config, key, data)

        return input_config

    def extract_kwarg_inputs(self, **kwargs):
        """
        Uses key word arguments to generate a dict of key value pairs specifying parameters. Each value is a list of parameters

        Returns:
            (dict): containing the key value pairs from the tab delimited input file
        """

        input_config = {}

        for key, val in kwargs.items():
            if isinstance(val, Sequence) and not isinstance(val, str):
                input_config = self.record_input(input_config, key, val)
            else:
                input_config = self.record_input(input_config, key, [val])

        return input_config

    def record_input(self, input_config, key, data):
        """
        counts the parameter sets for a given key and records the key and the value in the input_config dictionary

        Args:
            input_config (dict): key value pairs container for input parameters
            key (str): parameter key
            data (str): parameter value

        Returns:
            (dict): containing the key value pairs from the tab delimited input file
        """

        count_entries = len(data)
        self.count_parameter_sets(count_entries, key)

        input_config[key] = data
        self.is_param_iterable[key] = count_entries != 1

        return input_config

    def override_file_inputs(self, input_config, **kwargs):
        """
        overrides file parameter specification with given parameter values

        Args:
            input_config (dict): key value pairs container for input parameters
            **kwargs (dict): key word arguments containing the overriding keys and values

        Returns:
            (dict): key value pairs container for input parameters
        """

        for key, val in kwargs.items():
            data = val.strip().split(",")
            self.record_input(input_config, key, data)

        return input_config

    def count_parameter_sets(self, count_entries, key):
        """
        updates the number of parameter sets if more than one parameter set is specified for given key

        Args:
            count_entries (int): number of entries for given key
            key (str): parameter key

        Raises:
            Exception: if number of values provided for key and number of parameter sets > 1 are inconsistent
        """

        if count_entries != 1:
            if self.num_parameter_sets == 1:
                self.num_parameter_sets = count_entries
                self.key_num_parameters_set = key

            # Can't have n>1 parameter sets in one field and m>1 parameter sets in another
            elif self.num_parameter_sets != count_entries:
                raise Exception(f"Inconistent number of entries for fields: {key} and {self.key_num_parameters_set}\n")

    def extract_parameter_set_list(self, input_config):
        """
        populates the list of parameter sets (class member) from the dictionary of input key value pairs

        Args:
            input_config (dict): contains the key value pairs specifying the parameter set
        """
        if not self.parameter_set_list:
            for i in range(self.num_parameter_sets):
                self.parameter_set_list.append({})
        elif len(self.parameter_set_list) == 1:
            for i in range(len(self.parameter_set_list), self.num_parameter_sets):
                self.parameter_set_list.append(copy.deepcopy(self.parameter_set_list[0]))
        elif len(self.parameter_set_list) != self.num_parameter_sets:
            raise Exception("Inconsistent numbers of parameter sets encountered")

        for key, val in input_config.items():
            if len(val) == 1:
                for i in range(self.num_parameter_sets):
                    self.parameter_set_list[i][key] = val[0]
            else:
                for i in range(self.num_parameter_sets):
                    self.parameter_set_list[i][key] = val[i]

    def write_parameter_sets_to_file(self, file_path):
        """
        writes the list of parameter sets to a tab delimited file

        Args:
            file_path (str): path to the file
        """

        with open(file_path, "w") as f:

            line = "simulator\t" + self.simulator + "\n"
            f.write(line)

            for key in self.parameter_set_list[0].keys():
                line = key + "\t"
                line += ",".join([str(parameter_set[key]) for parameter_set in self.parameter_set_list])
                line += "\n"

                f.write(line)

__init__

initializes the InputReader

Parameters:

  • input_file_path (str, default: None ) –

    path to input file. Defaults to None.

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def __init__(self, simulator=None, input_file_path=None):
    """
    initializes the InputReader

    Args:
        input_file_path (str, optional): path to input file. Defaults to None.
    """
    if input_file_path is not None:
        self.input_file = os.path.abspath(input_file_path)
    if simulator is not None:
        self.simulator = convert_to_snake_case(simulator)

    self.num_parameter_sets = 1

    self.is_param_iterable = {}

    self.parameter_set_list = []

read_kwarg_inputs

Extracts inputs from key word arguments and builds list of parameter sets

Parameters:

  • **kwargs (dict, default: {} ) –

    input key word arguments provided by user

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def read_kwarg_inputs(self, **kwargs):
    """
    Extracts inputs from key word arguments and builds list of parameter sets

    Args:
        **kwargs (dict): input key word arguments provided by user
    """

    input_config = self.extract_kwarg_inputs(**kwargs)

    self.extract_parameter_set_list(input_config)

read_inputs_from_file

Extracts inputs from file and builds list of parameter sets

Parameters:

  • **overrides (dict, default: {} ) –

    input key word arguments provided by user as overrides

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def read_inputs_from_file(self, **overrides):
    """
    Extracts inputs from file and builds list of parameter sets

    Args:
        **overrides (dict): input key word arguments provided by user as overrides
    """

    input_config = self.extract_file_key_value_inputs()

    input_config = self.override_file_inputs(input_config, **overrides)

    self.extract_parameter_set_list(input_config)

    self.simulator = convert_to_snake_case(self.parameter_set_list[0]["simulator"])

extract_file_key_value_inputs

Reads input file to generate a dict of key value pairs specifying parameters. Each value is a list of parameters

Returns:

  • dict

    containing the key value pairs from the tab delimited input file

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def extract_file_key_value_inputs(self):
    """
    Reads input file to generate a dict of key value pairs specifying parameters. Each value is a list of parameters

    Returns:
        (dict): containing the key value pairs from the tab delimited input file
    """

    input_config = {}

    with open(self.input_file) as f:
        line_count = 0

        for line in f.readlines():
            line_count += 1

            if line.startswith("#") or line.strip() == "":
                continue

            line_data = line.strip().split("\t")

            key = line_data[0]
            data = line_data[1].strip().split(",")

            input_config = self.record_input(input_config, key, data)

    return input_config

extract_kwarg_inputs

Uses key word arguments to generate a dict of key value pairs specifying parameters. Each value is a list of parameters

Returns:

  • dict

    containing the key value pairs from the tab delimited input file

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def extract_kwarg_inputs(self, **kwargs):
    """
    Uses key word arguments to generate a dict of key value pairs specifying parameters. Each value is a list of parameters

    Returns:
        (dict): containing the key value pairs from the tab delimited input file
    """

    input_config = {}

    for key, val in kwargs.items():
        if isinstance(val, Sequence) and not isinstance(val, str):
            input_config = self.record_input(input_config, key, val)
        else:
            input_config = self.record_input(input_config, key, [val])

    return input_config

record_input

counts the parameter sets for a given key and records the key and the value in the input_config dictionary

Parameters:

  • input_config (dict) –

    key value pairs container for input parameters

  • key (str) –

    parameter key

  • data (str) –

    parameter value

Returns:

  • dict

    containing the key value pairs from the tab delimited input file

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def record_input(self, input_config, key, data):
    """
    counts the parameter sets for a given key and records the key and the value in the input_config dictionary

    Args:
        input_config (dict): key value pairs container for input parameters
        key (str): parameter key
        data (str): parameter value

    Returns:
        (dict): containing the key value pairs from the tab delimited input file
    """

    count_entries = len(data)
    self.count_parameter_sets(count_entries, key)

    input_config[key] = data
    self.is_param_iterable[key] = count_entries != 1

    return input_config

override_file_inputs

overrides file parameter specification with given parameter values

Parameters:

  • input_config (dict) –

    key value pairs container for input parameters

  • **kwargs (dict, default: {} ) –

    key word arguments containing the overriding keys and values

Returns:

  • dict

    key value pairs container for input parameters

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def override_file_inputs(self, input_config, **kwargs):
    """
    overrides file parameter specification with given parameter values

    Args:
        input_config (dict): key value pairs container for input parameters
        **kwargs (dict): key word arguments containing the overriding keys and values

    Returns:
        (dict): key value pairs container for input parameters
    """

    for key, val in kwargs.items():
        data = val.strip().split(",")
        self.record_input(input_config, key, data)

    return input_config

count_parameter_sets

updates the number of parameter sets if more than one parameter set is specified for given key

Parameters:

  • count_entries (int) –

    number of entries for given key

  • key (str) –

    parameter key

Raises:

  • Exception

    if number of values provided for key and number of parameter sets > 1 are inconsistent

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def count_parameter_sets(self, count_entries, key):
    """
    updates the number of parameter sets if more than one parameter set is specified for given key

    Args:
        count_entries (int): number of entries for given key
        key (str): parameter key

    Raises:
        Exception: if number of values provided for key and number of parameter sets > 1 are inconsistent
    """

    if count_entries != 1:
        if self.num_parameter_sets == 1:
            self.num_parameter_sets = count_entries
            self.key_num_parameters_set = key

        # Can't have n>1 parameter sets in one field and m>1 parameter sets in another
        elif self.num_parameter_sets != count_entries:
            raise Exception(f"Inconistent number of entries for fields: {key} and {self.key_num_parameters_set}\n")

extract_parameter_set_list

populates the list of parameter sets (class member) from the dictionary of input key value pairs

Parameters:

  • input_config (dict) –

    contains the key value pairs specifying the parameter set

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def extract_parameter_set_list(self, input_config):
    """
    populates the list of parameter sets (class member) from the dictionary of input key value pairs

    Args:
        input_config (dict): contains the key value pairs specifying the parameter set
    """
    if not self.parameter_set_list:
        for i in range(self.num_parameter_sets):
            self.parameter_set_list.append({})
    elif len(self.parameter_set_list) == 1:
        for i in range(len(self.parameter_set_list), self.num_parameter_sets):
            self.parameter_set_list.append(copy.deepcopy(self.parameter_set_list[0]))
    elif len(self.parameter_set_list) != self.num_parameter_sets:
        raise Exception("Inconsistent numbers of parameter sets encountered")

    for key, val in input_config.items():
        if len(val) == 1:
            for i in range(self.num_parameter_sets):
                self.parameter_set_list[i][key] = val[0]
        else:
            for i in range(self.num_parameter_sets):
                self.parameter_set_list[i][key] = val[i]

write_parameter_sets_to_file

writes the list of parameter sets to a tab delimited file

Parameters:

  • file_path (str) –

    path to the file

Source code in src/oqd_heisenberg_ion/common/inputs/input_reader.py
def write_parameter_sets_to_file(self, file_path):
    """
    writes the list of parameter sets to a tab delimited file

    Args:
        file_path (str): path to the file
    """

    with open(file_path, "w") as f:

        line = "simulator\t" + self.simulator + "\n"
        f.write(line)

        for key in self.parameter_set_list[0].keys():
            line = key + "\t"
            line += ",".join([str(parameter_set[key]) for parameter_set in self.parameter_set_list])
            line += "\n"

            f.write(line)