def p_to_q(p_values):
    """
    Uses the Benjamini-Hochberg procedure to convert p_values to q_values

    :param p_values:  numpy.ndarray of p_values
    :return q_values: numpy.ndarray of q_values, same shape as p_values
    """
    original_shape = p_values.shape
    p_vals_flat = p_values.flatten()
    rank = p_vals_flat.argsort().argsort() + 1
    num_tests = p_values.size
    q_vals = p_vals_flat * num_tests / rank
    q_vals.shape = original_shape
    q_vals[q_vals > 1.0] = 1.0
    return q_vals
