~q3cpma/mus

ref: e99afe099fd0b6cf6a4cce58902c9612ecd9fca9 mus/fair_shuf -rwxr-xr-x 3.8 KiB
e99afe09q3cpma Finish build.sh and README, move TODO to root 1 year, 27 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#!/bin/sh
set -eu
rpath_share=$(dirname -- "$0")
. "$rpath_share"/mus_util.sh

usage()
{
	cat <<EOF | text_format
**NAME**
    $(basename -- "$0") - shuf(1) with adjustable fairness enforcement

**SYNOPSIS**
    $(basename -- "$0") [**-hd0**] [**-n** __NLINES__] [**-m** __MULT__] [**-e** __EXP__] __DB_PATH__

**DESCRIPTION**
    A simple shuf(1) alternative keeping count of the lines it already picked
    and favouring the less often picked ones. Unlike shuf(1), it default to
    outputting one line.

    For that purpose, it reads a database __DB_PATH__ consisting of lines
    prefixed by their pick counter followed by at least one whitespace, which
    will be updated after execution.

    Each line's probability of being picked will be weighted by its absolute
    deviation from the mean raised to the __EXP__th power then multiplied by
    __MULT__.  Both __EXP__ and __MULT__ defaults to 1.

**OPTIONS**
    **-h**
        Print this notice and exit.

    **-d**
        Debug mode: print the result of the weight computation and exit.

    **-0**
        Use '\0' instead of '\n' as database and output line separator.

    **-n** __NLINES__
        Output __NLINES__ lines instead of one.

    **-m** __MULT__
        Set the weight multiplier to __MULT__.

    **-e** __EXP__
        Set the weight exponent to __MULT__.

EOF
	exit $1
}

debug=0
rsep='\n'
nlines=1
wmult=1
wexp=1
while getopts "hd0n:m:e:" OPT
do
	case "$OPT" in
		h)
			usage 0
			;;
		d)
			debug=1
			;;
		0)
			rsep='\0'
			;;
		n)
			nlines=$OPTARG
			! match "$nlines" '[0-9]+' &&
				die "$nlines: not an unsigned integer"
			;;
		m)
			wmult=$OPTARG
			! match "$wmult" '[0-9]+' &&
				die "$wmult: not an unsigned integer"
			;;
		e)
			wexp=$OPTARG
			! match "$wexp" '[0-9]+' &&
				die "$wexp: not an unsigned integer"
			;;
		\?)
			usage 1
			;;
	esac
done
shift $((OPTIND - 1))
[ $# -ne 1 ] && usage 1
requirefile "$1"

awk -vRS="$rsep" -vORS="$rsep" -vdebug=$debug -vnlines=$nlines -vwmult=$wmult \
	-vwexp=$wexp \
'function max(a, b)
{
	return a > b ? a : b;
}

function ceil(x)
{
	_tmp = int(x)
	return (_tmp == x ? x : _tmp + 1)
}

function die(msg)
{
	print msg >"/dev/stderr"
	exit(exit_status = 1)
}

function rand_init()
{
	"od -An -N4 -tu4 /dev/urandom" | getline
	srand($1)
}

function compute_weights()
{
	if(!nb_unpicked)
	{
		for(i = 0; i < NR; ++i)
			picked[i] = 0
		nb_unpicked = NR
	}

	_avg = 0
	for(i = 0; i < NR; ++i)
	{
		if(!picked[i])
			_avg += counter[i]
	}
	_avg /= nb_unpicked
	if(_avg == 0) # Special case: all counters are zero
	{
		for(i = 0; i < NR; ++i)
			weight[i] = 1
		nonzero_weights = wsum = nb_unpicked
		return
	}
	for(i = 0; i < NR; ++i)
	{
		if(picked[i])
			continue

		if(counter[i] > _avg)
			weight[i] = max(0, int(_avg - wmult * (counter[i] - _avg) ^ wexp))
		else
			weight[i] = ceil(_avg + wmult * (_avg - counter[i]) ^ wexp)
		if(weight[i])
			++nonzero_weights
		wsum += weight[i]
	}
	if(debug)
	{
		print "avg="_avg, "wsum="wsum, "nonzero_weights="nonzero_weights
		for(i = 0; i < NR; ++i)
		{
			if(!picked[i])
				print "c="counter[i], "w="weight[i], "v="value[i]
		}
		exit(0)
	}
}

function write_db(db_path)
{
	printf "" >db_path
	for(i = 0; i < NR; ++i)
		print counter[i], value[i] >>db_path
}


BEGIN {rand_init()}

{
	picked[NR - 1] = 0
	counter[NR - 1] = $1
	if($1 !~ /^[0-9]+$/)
		die("Line " NR ", " $1 ": malformed counter")
	sub("[0-9]+[[:blank:]]+", "")
	value[NR - 1] = $0
}

END \
{
	if(exit_status)
		exit(exit_status)

	nb_unpicked = NR
	compute_weights()

	for(; nlines; --nlines)
	{
		if(!nonzero_weights)
			compute_weights()
		r = int(rand() * (wsum + 1))
		for(i = 0; i < NR; ++i)
		{
			if(picked[i] || !weight[i])
				continue
			if(r <= weight[i])
			{
				print value[i]
				picked[i] = 1
				--nb_unpicked
				wsum -= weight[i]
				++counter[i]
				break
			}
			r -= weight[i]
		}
		--nonzero_weights
	}
	write_db(FILENAME)
}' "$1"