import torch


def get_optimizer(optim, model, lr, wd, verbose=True):
    """Sets the requested optimizer if available.

    :param optim: str, name of optimizer to use.
    :param model: object, model to optimize.
    :param lr: float, learning rate to use for training.
    :param wd: float, weight decay to use for training.
    :param verbose: bool, flag to print statements.

    :return optimizer: object, torch.optim object.
    """

    if optim.lower() == "adam":
        optimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=wd)
    elif optim.lower() == "sgd":
        optimizer = torch.optim.SGD(model.parameters(), lr=lr, weight_decay=wd)
    else:
        raise NotImplementedError(
            f"The optimizer {optim} is not implemented.\n"
            f"Valid options are: 'adam', 'sgd'."
        )
    if verbose:
        print(f"Initialized optimizer:\n{optimizer}\n")

    return optimizer