forked from ActivitySim/sharrow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflows.py
More file actions
3037 lines (2838 loc) · 114 KB
/
flows.py
File metadata and controls
3037 lines (2838 loc) · 114 KB
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import ast
import base64
import hashlib
import importlib
import inspect
import io
import logging
import os
import re
import sys
import textwrap
import time
import warnings
import numba as nb
import numpy as np
import pandas as pd
import xarray as xr
from ._infer_version import __version__
from .aster import expression_for_numba, extract_all_name_tokens, extract_names_2
from .filewrite import blacken, rewrite
from .relationships import DataTree
from .table import Table
logger = logging.getLogger("sharrow")
class CacheMissWarning(UserWarning):
pass
well_known_names = {
"nb",
"np",
"pd",
"xr",
"pa",
"log",
"exp",
"log1p",
"expm1",
"max",
"min",
"piece",
"hard_sigmoid",
"transpose_leading",
"clip",
"get",
}
def one_based(n):
return pd.RangeIndex(1, n + 1)
def zero_based(n):
return pd.RangeIndex(0, n)
def clean(s):
"""
Convert any string into a similar python identifier.
If any modification of the string is made, or if the string
is longer than 120 characters, it is truncated and a hash of the
original string is added to the end, to ensure every
string maps to a unique cleaned name.
Parameters
----------
s : str
Returns
-------
cleaned : str
"""
if not isinstance(s, str):
s = f"{type(s)}-{s}"
cleaned = re.sub(r"\W|^(?=\d)", "_", s)
if cleaned != s or len(cleaned) > 120:
# digest size 15 creates a 24 character base32 string
h = base64.b32encode(
hashlib.blake2b(s.encode(), digest_size=15).digest()
).decode()
cleaned = f"{cleaned[:90]}_{h}"
return cleaned
def presorted(sortable, presort=None, exclude=None):
"""
Sort a collection, with certain items appearing first.
Parameters
----------
sortable : Collection
Elements to sort.
presort : Iterable, optional
Pre-sorted elements, which are yielded first, in this order,
if they appear in `sortable`.
Yields
------
Any
The elements of sortable.
"""
queue = set(sortable)
if presort is not None:
for j in presort:
if j in queue:
if exclude is None or j not in exclude:
yield j
queue.remove(j)
for i in sorted(queue):
if exclude is None or i not in exclude:
yield i
def _flip_flop_def(v):
if isinstance(v, str) and "# sharrow:" in v:
return v.split("# sharrow:", 1)[1].strip()
else:
return v
well_known_names |= {
"_args",
"_inputs",
"_outputs",
}
ARG_NAMES = {f"_arg{n:02}" for n in range(100)}
well_known_names |= ARG_NAMES
def filter_name_tokens(expr, matchable_names=None):
name_tokens = extract_all_name_tokens(expr)
arg_tokens = name_tokens & ARG_NAMES
name_tokens -= well_known_names
if matchable_names:
name_tokens &= matchable_names
return name_tokens, arg_tokens
class ExtractOptionalGetTokens(ast.NodeVisitor):
def __init__(self, from_names):
self.optional_get_tokens = set()
self.required_get_tokens = set()
self.from_names = from_names
def visit_Call(self, node):
if isinstance(node.func, ast.Attribute):
if node.func.attr == "get":
if isinstance(node.func.value, ast.Name):
if node.func.value.id in self.from_names:
if len(node.args) == 1:
if isinstance(node.args[0], ast.Constant):
if len(node.keywords) == 0:
self.required_get_tokens.add(
(node.func.value.id, node.args[0].value)
)
elif (
len(node.keywords) == 1
and node.keywords[0].arg == "default"
):
self.optional_get_tokens.add(
(node.func.value.id, node.args[0].value)
)
else:
raise ValueError(
f"{node.func.value.id}.get with unexpected keyword arguments"
)
if len(node.args) == 2:
if isinstance(node.args[0], ast.Constant):
self.optional_get_tokens.add(
(node.func.value.id, node.args[0].value)
)
if len(node.args) > 2:
raise ValueError(
f"{node.func.value.id}.get with more than 2 positional arguments"
)
self.generic_visit(node)
def check(self, node):
if isinstance(node, str):
node = ast.parse(node)
if isinstance(node, ast.AST):
self.visit(node)
else:
try:
node_iter = iter(node)
except TypeError:
pass
else:
for i in node_iter:
self.check(i)
return self.optional_get_tokens
def coerce_to_range_index(idx):
if isinstance(idx, pd.RangeIndex):
return idx
if isinstance(idx, (pd.Int64Index, pd.Float64Index, pd.UInt64Index)):
if idx.is_monotonic_increasing and idx[-1] - idx[0] == idx.size - 1:
return pd.RangeIndex(idx[0], idx[0] + idx.size)
return idx
FUNCTION_TEMPLATE = """
# {init_expr}
@nb.jit(
cache=False,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def {fname}(
{argtokens}
_outputs,
{nametokens}
):
return {expr}
"""
COLUMN_FILLER_TEMPLATE = """
@nb.jit(
cache=True,
parallel=False,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def {fname}_dim2_filler(
result,
col_num,
{nametokens}
):
for j0 in nb.prange(result.shape[0]):
result[j0, col_num] = {fname}({f_args_j} result[j0, :], {nametokens})
@nb.jit(
cache=True,
parallel=False,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def {fname}_dim3_filler(
result,
col_num,
{nametokens}
):
for j0 in nb.prange(result.shape[0]):
for j1 in range(result.shape[1]):
result[j0, j1, col_num] = {fname}({f_args_j} result[j0, j1, :], {nametokens})
"""
IRUNNER_1D_TEMPLATE = """
@nb.jit(
cache=True,
parallel={parallel_irunner},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def irunner(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
mask=None,
):
result = np.empty((argshape[0], {len_self_raw_functions}), dtype=dtype)
if mask is not None:
assert mask.ndim == 1
assert mask.shape[0] == argshape[0]
for j0 in nb.prange(argshape[0]):
if mask is not None:
if not mask[j0]:
result[j0, :] = np.nan
continue
linemaker(result[j0], j0, {joined_namespace_names})
return result
"""
IRUNNER_2D_TEMPLATE = """
@nb.jit(
cache=True,
parallel={parallel_irunner},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def irunner(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
mask=None,
):
result = np.empty((argshape[0], argshape[1], {len_self_raw_functions}), dtype=dtype)
if mask is not None:
assert mask.ndim == 2
assert mask.shape[0] == argshape[0]
assert mask.shape[1] == argshape[1]
for j0 in nb.prange(argshape[0]):
for j1 in range(argshape[1]):
if mask is not None:
if not mask[j0, j1]:
result[j0, j1, :] = np.nan
linemaker(result[j0, j1], j0, j1, {joined_namespace_names})
return result
"""
ARRAY_MAKER_1D_TEMPLATE = """
def array_maker(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
):
result = np.empty((argshape[0], {len_self_raw_functions}), dtype=dtype)
{meta_code_stack}
return result
"""
ARRAY_MAKER_2D_TEMPLATE = """
def array_maker(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
):
result = np.empty((argshape[0], argshape[1], {len_self_raw_functions}), dtype=dtype)
{meta_code_stack}
return result
"""
IDOTTER_1D_TEMPLATE = """
@nb.jit(
cache=True,
parallel={parallel_idotter},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def idotter(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
dotarray=None,
):
if dotarray is None:
raise ValueError("dotarray cannot be None")
assert dotarray.ndim == 2
result = np.empty((argshape[0], dotarray.shape[1]), dtype=dtype)
if argshape[0] > 1000:
for j0 in nb.prange(argshape[0]):
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
{meta_code_stack_dot}
np.dot(intermediate, dotarray, out=result[j0,:])
else:
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
for j0 in range(argshape[0]):
{meta_code_stack_dot}
np.dot(intermediate, dotarray, out=result[j0,:])
return result
"""
IDOTTER_2D_TEMPLATE = """
@nb.jit(
cache=True,
parallel={parallel_idotter},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def idotter(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
dotarray=None,
):
if dotarray is None:
raise ValueError("dotarray cannot be None")
assert dotarray.ndim == 2
result = np.empty((argshape[0], argshape[1], dotarray.shape[1]), dtype=dtype)
if argshape[0] > 1000:
for j0 in nb.prange(argshape[0]):
for j1 in range(argshape[1]):
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
{meta_code_stack_dot}
np.dot(intermediate, dotarray, out=result[j0,j1,:])
else:
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
for j0 in range(argshape[0]):
for j1 in range(argshape[1]):
{meta_code_stack_dot}
np.dot(intermediate, dotarray, out=result[j0,j1,:])
return result
"""
ILINER_1D_TEMPLATE = """
@nb.jit(
cache=False,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def linemaker(
intermediate, j0,
{joined_namespace_names}
):
{meta_code_stack_dot}
"""
ILINER_2D_TEMPLATE = """
@nb.jit(
cache=False,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def linemaker(
intermediate, j0, j1,
{joined_namespace_names}
):
{meta_code_stack_dot}
"""
MNL_GENERIC_TEMPLATE = """
@nb.jit(
cache=True,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def _sample_choices_maker(
prob_array,
random_array,
out_choices,
out_choice_probs,
):
'''
Random sample of alternatives.
Parameters
----------
prob_array : array of float, shape (n_alts)
random_array : array of float, shape (n_samples)
out_choices : array of int, shape (n_samples) output
out_choice_probs : array of float, shape (n_samples) output
'''
sample_size = random_array.size
n_alts = prob_array.size
random_points = np.sort(random_array)
a = 0
s = 0
unique_s = 0
z = 0.0
for a in range(n_alts):
z += prob_array[a]
while s < sample_size and z > random_points[s]:
out_choices[s] = a
out_choice_probs[s] = prob_array[a]
s += 1
if s >= sample_size:
break
if s < sample_size:
# rare condition, only if a random point is greater than 1 (a bug)
# or if the sum of probabilities is less than 1 and a random point
# is greater than that sum, which due to the limits of numerical
# precision can technically happen
a = n_alts-1
while prob_array[a] < 1e-30 and a > 0:
# slip back to the last choice with non-trivial prob
a -= 1
while s < sample_size:
out_choices[s] = a
out_choice_probs[s] = prob_array[a]
s += 1
@nb.jit(
cache=True,
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def _sample_choices_maker_counted(
prob_array,
random_array,
out_choices,
out_choice_probs,
out_pick_count,
):
'''
Random sample of alternatives.
Parameters
----------
prob_array : array of float, shape (n_alts)
random_array : array of float, shape (n_samples)
out_choices : array of int, shape (n_samples) output
out_choice_probs : array of float, shape (n_samples) output
out_pick_count : array of int, shape (n_samples) output
'''
sample_size = random_array.size
n_alts = prob_array.size
random_points = np.sort(random_array)
a = 0
s = 0
unique_s = -1
z = 0.0
out_pick_count[:] = 0
for a in range(n_alts):
z += prob_array[a]
if s < sample_size and z > random_points[s]:
unique_s += 1
while s < sample_size and z > random_points[s]:
out_choices[unique_s] = a
out_choice_probs[unique_s] = prob_array[a]
out_pick_count[unique_s] += 1
s += 1
if s >= sample_size:
break
if s < sample_size:
# rare condition, only if a random point is greater than 1 (a bug)
# or if the sum of probabilities is less than 1 and a random point
# is greater than that sum, which due to the limits of numerical
# precision can technically happen
a = n_alts-1
while prob_array[a] < 1e-30 and a > 0:
# slip back to the last choice with non-trivial prob
a -= 1
if out_choices[unique_s] != a:
unique_s += 1
while s < sample_size:
out_choices[unique_s] = a
out_choice_probs[unique_s] = prob_array[a]
out_pick_count[unique_s] += 1
s += 1
"""
MNL_1D_TEMPLATE = (
MNL_GENERIC_TEMPLATE
+ """
logit_ndims = 1
@nb.jit(
cache=True,
parallel={parallel},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def mnl_transform_plus1d(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
dotarray=None,
random_draws=None,
pick_counted=False,
logsums=False,
choice_dtype=np.int32,
pick_count_dtype=np.int32,
mask=None,
):
if dotarray is None:
raise ValueError("dotarray cannot be None")
assert dotarray.ndim == 2
if mask is not None:
assert mask.ndim == 1
assert mask.shape[0] == argshape[0]
result = np.full((argshape[0], random_draws.shape[1]), -1, dtype=choice_dtype)
result_p = np.zeros((argshape[0], random_draws.shape[1]), dtype=dtype)
if pick_counted:
pick_count = np.zeros((argshape[0], random_draws.shape[1]), dtype=pick_count_dtype)
else:
pick_count = np.zeros((argshape[0], 0), dtype=pick_count_dtype)
if logsums:
_logsums = np.zeros((argshape[0], ), dtype=dtype)
else:
_logsums = np.zeros((0, ), dtype=dtype)
for j0 in nb.prange(argshape[0]):
if mask is not None:
if not mask[j0]:
continue
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
{meta_code_stack_dot}
dotprod = np.dot(intermediate, dotarray)
shifter = np.max(dotprod)
partial = np.exp(dotprod - shifter)
local_sum = np.sum(partial)
partial /= local_sum
if logsums:
_logsums[j0] = np.log(local_sum) + shifter
if pick_counted:
_sample_choices_maker_counted(partial, random_draws[j0], result[j0], result_p[j0], pick_count[j0])
else:
_sample_choices_maker(partial, random_draws[j0], result[j0], result_p[j0])
return result, result_p, pick_count, _logsums
"""
)
# @nb.jit(
# cache=True,
# parallel=True,
# error_model='{error_model}',
# boundscheck={boundscheck},
# nopython={nopython},
# fastmath={fastmath})
# def mnl_transform_plus1d(
# argshape,
# {joined_namespace_names}
# dtype=np.{dtype},
# dotarray=None,
# random_draws=None,
# pick_counted=False,
# logsums=False,
# choice_dtype=np.int32,
# pick_count_dtype=np.int32,
# ):
# if dotarray is None:
# raise ValueError("dotarray cannot be None")
# assert dotarray.ndim == 2
# result = np.full((argshape[0], argshape[1], random_draws.shape[1]), -1, dtype=choice_dtype)
# result_p = np.zeros((argshape[0], argshape[1], random_draws.shape[1]), dtype=dtype)
# if pick_counted:
# pick_count = np.zeros((argshape[0], argshape[1], random_draws.shape[1]), dtype=pick_count_dtype)
# else:
# pick_count = np.zeros((argshape[0], argshape[1], 0), dtype=pick_count_dtype)
# if logsums:
# _logsums = np.zeros((argshape[0], argshape[1], ), dtype=dtype)
# else:
# _logsums = np.zeros((0, 0), dtype=dtype)
# for j0 in nb.prange(argshape[0]):
# for k0 in range(argshape[1]):
# intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
# {meta_code_stack_dot}
# dotprod = np.dot(intermediate, dotarray)
# shifter = np.max(dotprod)
# partial = np.exp(dotprod - shifter)
# local_sum = np.sum(partial)
# partial /= local_sum
# if logsums:
# _logsums[j0,k0] = np.log(local_sum) + shifter
# if pick_counted:
# _sample_choices_maker_counted(
# partial, random_draws[j0,k0], result[j0,k0], result_p[j0,k0], pick_count[j0,k0]
# )
# else:
# _sample_choices_maker(partial, random_draws[j0,k0], result[j0,k0], result_p[j0,k0])
# return result, result_p, pick_count, _logsums
MNL_2D_TEMPLATE = (
MNL_GENERIC_TEMPLATE
+ """
logit_ndims = 2
@nb.jit(
cache=True,
parallel={parallel},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def mnl_transform(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
dotarray=None,
random_draws=None,
pick_counted=False,
logsums=False,
choice_dtype=np.int32,
pick_count_dtype=np.int32,
mask=None,
):
if dotarray is None:
raise ValueError("dotarray cannot be None")
assert dotarray.ndim == 2
assert dotarray.shape[1] == 1
dotarray = dotarray.reshape(-1)
if random_draws is None:
raise ValueError("random_draws cannot be None")
assert random_draws.ndim == 2
assert random_draws.shape[0] == argshape[0]
if mask is not None:
assert mask.ndim == 1
assert mask.shape[0] == argshape[0]
result = np.full((argshape[0], random_draws.shape[1]), -1, dtype=choice_dtype)
result_p = np.zeros((argshape[0], random_draws.shape[1]), dtype=dtype)
if pick_counted:
pick_count = np.zeros((argshape[0], random_draws.shape[1]), dtype=pick_count_dtype)
else:
pick_count = np.zeros((argshape[0], 0), dtype=pick_count_dtype)
if logsums:
_logsums = np.zeros((argshape[0], ), dtype=dtype)
else:
_logsums = np.zeros((0, ), dtype=dtype)
for j0 in nb.prange(argshape[0]):
if mask is not None:
if not mask[j0]:
continue
partial = np.zeros(argshape[1], dtype=dtype)
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
shifter = -99999
for j1 in range(argshape[1]):
intermediate[:] = 0
{meta_code_stack_dot}
v = partial[j1] = np.dot(intermediate, dotarray)
if v > shifter:
shifter = v
for j1 in range(argshape[1]):
partial[j1] = np.exp(partial[j1] - shifter)
local_sum = np.sum(partial)
if logsums:
_logsums[j0] = np.log(local_sum) + shifter
if logsums == 1:
continue
partial /= local_sum
if pick_counted:
_sample_choices_maker_counted(partial, random_draws[j0], result[j0], result_p[j0], pick_count[j0])
else:
_sample_choices_maker(partial, random_draws[j0], result[j0], result_p[j0])
return result, result_p, pick_count, _logsums
@nb.jit(
cache=True,
parallel={parallel},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def mnl_transform_plus1d(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
dotarray=None,
random_draws=None,
pick_counted=False,
logsums=False,
choice_dtype=np.int32,
pick_count_dtype=np.int32,
mask=None,
):
if dotarray is None:
raise ValueError("dotarray cannot be None")
assert dotarray.ndim == 2
assert dotarray.shape[1] >= 1
if random_draws is None:
raise ValueError("random_draws cannot be None")
assert random_draws.ndim == 3
assert random_draws.shape[0] == argshape[0]
assert random_draws.shape[1] == argshape[1]
if mask is not None:
assert mask.ndim == 2
assert mask.shape[0] == argshape[0]
assert mask.shape[1] == argshape[1]
result = np.full((argshape[0], argshape[1], random_draws.shape[2]), -1, dtype=choice_dtype)
result_p = np.zeros((argshape[0], argshape[1], random_draws.shape[2]), dtype=dtype)
if pick_counted:
pick_count = np.zeros((argshape[0], argshape[1], random_draws.shape[2]), dtype=pick_count_dtype)
else:
pick_count = np.zeros((argshape[0], argshape[1], 0), dtype=pick_count_dtype)
if logsums:
_logsums = np.zeros((argshape[0], argshape[1], ), dtype=dtype)
else:
_logsums = np.zeros((0, 0), dtype=dtype)
for j0 in nb.prange(argshape[0]):
partial = np.zeros(dotarray.shape[1], dtype=dtype)
for j1 in range(argshape[1]):
if mask is not None:
if not mask[j0,j1]:
continue
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
{meta_code_stack_dot}
partial = np.dot(intermediate, dotarray, out=partial)
shifter = np.max(partial)
partial = np.exp(partial - shifter)
local_sum = np.sum(partial)
if logsums:
_logsums[j0,j1] = np.log(local_sum) + shifter
if logsums == 1:
continue
partial /= local_sum
if pick_counted:
_sample_choices_maker_counted(
partial, random_draws[j0,j1], result[j0,j1], result_p[j0,j1], pick_count[j0,j1]
)
else:
_sample_choices_maker(partial, random_draws[j0,j1], result[j0,j1], result_p[j0,j1])
return result, result_p, pick_count, _logsums
"""
)
NL_1D_TEMPLATE = """
from sharrow.nested_logit import _utility_to_probability
@nb.jit(
cache=True,
parallel={parallel},
error_model='{error_model}',
boundscheck={boundscheck},
nopython={nopython},
fastmath={fastmath},
nogil={nopython})
def nl_transform(
argshape,
{joined_namespace_names}
dtype=np.{dtype},
dotarray=None,
random_draws=None,
pick_counted=False,
logsums=False,
n_nodes=0,
n_alts=0,
edges_up=None, # int input shape=[edges]
edges_dn=None, # int input shape=[edges]
mu_params=None, # float input shape=[nests]
start_slots=None, # int input shape=[nests]
len_slots=None, # int input shape=[nests]
choice_dtype=np.int32,
pick_count_dtype=np.int32,
mask=None,
):
if dotarray is None:
raise ValueError("dotarray cannot be None")
assert dotarray.ndim == 2
if mask is not None:
assert mask.ndim == 1
assert mask.shape[0] == argshape[0]
if logsums == 1:
result = np.full((0, random_draws.shape[1]), -1, dtype=choice_dtype)
result_p = np.zeros((0, random_draws.shape[1]), dtype=dtype)
else:
result = np.full((argshape[0], random_draws.shape[1]), -1, dtype=choice_dtype)
result_p = np.zeros((argshape[0], random_draws.shape[1]), dtype=dtype)
if pick_counted:
pick_count = np.zeros((argshape[0], random_draws.shape[1]), dtype=pick_count_dtype)
else:
pick_count = np.zeros((argshape[0], 0), dtype=pick_count_dtype)
if logsums:
_logsums = np.zeros((argshape[0], ), dtype=dtype)
else:
_logsums = np.zeros((0, ), dtype=dtype)
for j0 in nb.prange(argshape[0]):
if mask is not None:
if not mask[j0]:
continue
intermediate = np.zeros({len_self_raw_functions}, dtype=dtype)
{meta_code_stack_dot}
utility = np.zeros(n_nodes, dtype=dtype)
utility[:n_alts] = np.dot(intermediate, dotarray)
if logsums == 1:
logprob = np.zeros(0, dtype=dtype)
probability = np.zeros(0, dtype=dtype)
else:
logprob = np.zeros(n_nodes, dtype=dtype)
probability = np.zeros(n_nodes, dtype=dtype)
_utility_to_probability(
n_alts,
edges_up, # int input shape=[edges]
edges_dn, # int input shape=[edges]
mu_params, # float input shape=[nests]
start_slots, # int input shape=[nests]
len_slots, # int input shape=[nests]
(logsums==1),
utility, # float output shape=[nodes]
logprob, # float output shape=[nodes]
probability, # float output shape=[nodes]
)
if logsums:
_logsums[j0] = utility[-1]
if logsums != 1:
if pick_counted:
_sample_choices_maker_counted(
probability[:n_alts], random_draws[j0], result[j0], result_p[j0], pick_count[j0]
)
else:
_sample_choices_maker(probability[:n_alts], random_draws[j0], result[j0], result_p[j0])
return result, result_p, pick_count, _logsums
"""
def zero_size_to_None(x):
if x is not None and x.size == 0:
return None
return x
def squeeze(x, *args):
x = zero_size_to_None(x)
if x is None:
return None
try:
return np.squeeze(x, *args)
except Exception:
if hasattr(x, "shape"):
logger.error(f"failed to squeeze {args!r} from array of shape {x.shape}")
else:
logger.error(f"failed to squeeze {args!r} from array of unknown shape")
raise
class Flow:
"""
A prepared data flow.
Parameters
----------
tree : DataTree
The tree from whence the output will be constructed.
defs : Mapping[str,str]
Gives the names and definitions for the variables to create in the
generated output.
error_model : {'numpy', 'python'}, default 'numpy'
The error_model option controls the divide-by-zero behavior. Setting
it to ‘python’ causes divide-by-zero to raise exception like
CPython. Setting it to ‘numpy’ causes divide-by-zero to set the
result to +/-inf or nan.
cache_dir : Path-like, optional
A location to write out generated python and numba code. If not
provided, a unique temporary directory is created.
name : str, optional
The name of this Flow used for writing out cached files. If not
provided, a unique name is generated. If `cache_dir` is given,
be sure to avoid name conflicts with other flow's in the same
directory.
dtype : str, default "float32"
The name of the numpy dtype that will be used for the output.
boundscheck : bool, default False
If True, boundscheck enables bounds checking for array indices, and
out of bounds accesses will raise IndexError. The default is to not
do bounds checking, which is faster but can produce garbage results
or segfaults if there are problems, so try turning this on for
debugging if you are getting unexplained errors or crashes.
nopython : bool, default True
Compile using numba's `nopython` mode. Provided for debugging only,
as there's little point in turning this off for production code, as
all the speed benefits of sharrow will be lost.
fastmath : bool, default True
If true, fastmath enables the use of "fast" floating point transforms,
which can improve performance but can result in tiny distortions in
results. See numba docs for details.
parallel : bool, default True
Enable or disable parallel computation for MNL and NL functions.
readme : str, optional
A string to inject as a comment at the top of the flow Python file.
flow_library : Mapping[str,Flow], optional
An in-memory cache of precompiled Flow objects. Using this can result
in performance improvements when repeatedly using the same definitions.
extra_hash_data : Tuple[Hashable], optional
Additional data used for generating the flow hash. Useful to prevent
conflicts when using a flow_library with multiple similar flows.
write_hash_audit : bool, default True
Writes a hash audit log into a comment in the flow Python file, for
debugging purposes.
hashing_level : int, default 1
Level of detail to write into flow hashes. Increase detail to avoid
hash conflicts for similar flows.
"""
def __new__(
cls,
tree,