def _balance_grid_shape(total_temporal_bins, num_rows, num_cols):
    while True:
        if abs(num_rows - num_cols) <= 1:
            # We might be able to reduce both.
            if total_temporal_bins < (num_rows - 1) * (num_cols - 1):
                num_rows -= 1
                num_cols -= 1
            # If not, then we're nearly done.
            else:
                # We might end up with a grid that is slightly too large. We
                # tend to favor larger column numbers rather than rows, so we'll
                # try to drop another column to get a tighter grid.
                if total_temporal_bins <= num_rows * (num_cols - 1):
                    num_cols -= 1

                # Favor more columns or more rows in the final layout.
                if num_rows > num_cols:
                    num_rows, num_cols = num_cols, num_rows

                break
        else:
            if num_rows > num_cols:
                # When we have a delta >= 2, first we try to drop just one of the values.
                if total_temporal_bins < (num_rows - 1) * num_cols:
                        num_rows -= 1
                # In certain cases we can't just drop a value yet we still have a delta
                # that is >= 2. In that situation we need to trade a value between them.
                elif total_temporal_bins < (num_rows - 1) * (num_cols + 1):
                    num_rows -= 1
                    num_cols += 1
            else:
                if total_temporal_bins < num_rows * (num_cols - 1):
                        num_cols -= 1
                elif total_temporal_bins < (num_rows + 1) * (num_cols - 1):
                    num_rows += 1
                    num_cols -= 1

    return (int(num_rows), int(num_cols))
Balance grid shape values to prevent large row/col discrepancies.
dataset/ETHPy150Open apache/climate/ocw-ui/backend/processing.py/_balance_grid_shape