Skip to content

Instantly share code, notes, and snippets.

@k-sriram
Created January 11, 2019 14:54
Show Gist options
  • Save k-sriram/2f4ffadf8642b0a49826a123ce8466e0 to your computer and use it in GitHub Desktop.
Save k-sriram/2f4ffadf8642b0a49826a123ce8466e0 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# intdistribute.py
# Created by K. Sriram on 2018-10-29
#
# MIT License
#
# Copyright (c) 2018 Sriram Krishna
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import numpy as np
EPSILON = 1e-4
def intdistribute(total, distribution, epsilon=EPSILON):
"""
Function to distribute a given integer into several bins so that they roughly follow a given ratio.
Parameters
----------
total : int
The number to be divided into bins.
distribution : array_like
The ratios into which the number is to be divided. This should add up to 1.
epsilon : float, optional
Threshold used by the algorithm to differentiate between ints and non-ints.
Returns
-------
ndarray(dtype=int)
The integers which add up to total and are roughly in the ratio given by distribution.
Notes
-----
The algorithm tries to minimize the sum of deviations from the real numbers in the requisite ratios.
Examples
--------
>>> intdistribute(5,[0.25,0.75])
array([1, 4])
"""
if not isinstance(distribution, np.ndarray):
distribution = np.array(distribution)
if np.absolute(np.around(total) - total) > epsilon:
raise TypeError('Total not integer: {:.2f}'.format(total))
if np.absolute(distribution.sum() - 1) > epsilon:
raise TypeError('Distribution not proper. Sum = {:.2f}'.format(np.absolute(distribution.sum() - 1)))
if len(distribution.shape) != 1:
raise ValueError('Multi-dimensional arrays are not (yet) supported as distribution.')
total = int(total+0.5)
rem,base = np.modf(total*distribution)
base = base.astype(int)
extraneed = int(round((base.sum() - total)))
for i in rem.argsort()[-extraneed:]:
base[i] += 1
assert base.sum() == total, ('intdistribute didn\'t function as expected. mismatch between final sum and initial '
'value. {} != {}').format(base.sum(),total)
return base
if __name__ == '__main__':
assert np.all(intdistribute(5,[0.25,0.75]) == np.array([1, 4]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment