def _set_trials_level(tmap, scripts, order, children, actual_graph):
    """Adjust levels of trials according to their script and branchs


    Arguments:
    tmap -- map of trial.id to trial
    scripts -- group trials by scripts
    order -- ordered dict with desired script order
    children -- dict with list of trials that have key trial as target
    actual_graph -- edge dict by trial id
    """
    level = 0
    for script in order:
        last = level
        for trial in scripts[script]:
            if trial.id not in actual_graph:
                trial.level = level
                level += 1
                last += 1
                continue
            parent_id = actual_graph[trial.id]
            if children[parent_id].index(trial.id) > 0:
                trial.level = last
                last += 1
            else:
                parent = tmap[parent_id]
                trial.level = parent.level
            level = max(level, trial.level + 1)
