bubble-economy / trader_stats.py

  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
#!/usr/bin/env python
# encoding: utf-8
"""
trader_stats.py

functions that estimate various statistical features of various data, and
suporting functions for said primary ones.

Created by dan mackinlay on 2010-10-27.
Copyright (c) 2010 __MyCompanyName__. All rights reserved.
"""
import numpy as np
import scipy as sp
from scipy.spatial.distance import squareform
import nearness
import math
from utils import eps, Bunch, addict, make_iterable, minify, d
from mi import bin_vels, bin_naive, bin_angle_naive, choose_n_bins, ince_mi_dist_cont, ince_mi_dist_disc, angle, squish, plugin_mi_dist_cont, plugin_mi_dist_disc, stereographic_projection
from spanning_tree import spanning_weight

"""
In the general case, the interface for a traderset stat is

func(traderset, **kwargs).

All of the stats are slicewise, ATM, so their specific calling interface is,
for now, func(traderset, n_slices=None, n_steps=None skip=None, n_agents=None,
**kwargs) They must return a dict, which will be used to aggregate their
multiple values
"""

############################################
### data extraction/massaging - private
############################################

def _extract_loc_vel(traderset):
    return [traderset.raw_output_locs, traderset.raw_output_vels]

def _extract_loc_vel_angle(traderset):
    """2D velocity special, taking the arctangent of the velocity
    to get the correct number of degrees of freedom with no information
    loss."""
    locs, vels = _extract_loc_vel(traderset)
    outshape = list(vels.shape)
    outshape[2] = 1
    vel_angles = getattr(traderset, '_raw_output_vel_angles', None)
    if vel_angles is None:
        vel_angles = angle(
            vels[:,:,0],
            vels[:,:,1]).reshape(outshape)
        traderset._raw_output_vel_angles = vel_angles
    return [locs, vels, vel_angles]

def _extract_loc_vel_angle_acc_angle(traderset):
    """2D velocity special, discarding one timestep and providing a succesive
    differences series."""
    locs, vels, vel_angles = _extract_loc_vel_angle(traderset)
    keep_steps = vels.shape[0] - 1
    acc_angles = getattr(traderset, '_raw_output_acc_angles', None)
    if acc_angles is None:
        #successive differences, wrapped to be in [-pi, pi) so that small
        # accelerations are close to 0
        acc_angles = ((vel_angles[1:,:,:] - vel_angles[:-1,:,:]
            + 2* np.pi)
          % (2*np.pi)
        ) - np.pi
        traderset._raw_output_acc_angles = acc_angles
    return [locs[1:,:,:], vels[1:,:,:], vel_angles[1:,:,:], acc_angles]

def _extract_loc_vel_projection(traderset):
    """Throw out one dimension to get one axis per degree of freedom, without
    information loss in arbitrary dimensions>1"""
    locs, vels = _extract_loc_vel(traderset)
    outshape = list(vels.shape)
    indimensions = outshape[2]
    outshape[2] -= 1

    vel_projections = getattr(traderset, '_raw_output_vel_projections', None)
    if vel_projections is None:
        vel_projections = stereographic_projection(
            vels.reshape(-1,indimensions)
        ).reshape(outshape)
        traderset._raw_output_vel_projections = vel_projections
    return [locs, vels, vel_projections]

def _extract_loc_vel_acc_projection(traderset):
    """As above, but then calculate acceleration from it by successive
    differences. I suspect this is rubbish because of the nonlinearity of the
    stereographic projection."""
    locs, vels, vel_projections = _extract_loc_vel_projection(traderset)
    keep_steps = vels.shape[0] - 1
    acc_projections = getattr(traderset, '_raw_output_acc_projections', None)
    if acc_projections is None:
        acc_projections = vel_projections[1:,:,:] - vel_projections[:-1,:,:]
        traderset._raw_output_acc_projections = acc_projections
    return [locs[1:,:,:], vels[1:,:,:], vel_projections[1:,:,:], acc_projections]

def _extract_loc_vel_projection_acc(traderset):
    """project angles down one dimension, but preserve acceleration as a
    linear quantity"""
    locs, vels, vel_projection = _extract_loc_vel_projection(traderset)
    keep_steps = vels.shape[0] - 1
    acc = getattr(traderset, '_raw_output_acc', None)
    if acc is None:
        acc = vels[1:,:,:] - vels[:-1,:,:]
        traderset._raw_output_acc = acc
    return [locs[1:,:,:], vels[1:,:,:], vel_projection[1:,:,:], acc]
    
############################################
### slice-related support function - private
############################################

def _n_slices(length, n_slices=None, skip_chunk=1):
    """Return slice objects to divide this into so many chunks.
    """
    if n_slices is None:
        n_slices = length
    partition = np.around(
        np.linspace(0, length, num=n_slices+1)
    ).astype(int)
    for i in xrange(0, n_slices, skip_chunk):
        yield np.s_[partition[i]:partition[i+1]]

def _n_steps(length, n_steps, skip_chunk=1):
    """Return slice objects to divide this into chunks of so many steps,
    discarding any leftovers."""
    n_chunks = int(math.floor(length/n_steps))
    for i in xrange(0, n_chunks, skip_chunk):
        yield np.s_[n_steps*i:n_steps*(i+1)]

def _traderset_slices(traderset, n_slices=None, n_steps=None,
        skip=None, n_agents=None, extractor=_extract_loc_vel):
    """given a traderset, return an iterator over chunks of its execution
    history and, optionally, subsets of its agents. take a "skip" argument
    in the form of the string 'first' or 'last'."""
    state_arrays = extractor(traderset)
    keep_steps = state_arrays[0].shape[0]
    if n_agents is not None:
        #choose some reduced set of agents
        subset = np.random.permutation(traderset.num_agents)[:n_agents]
        print "subsetting to ", subset
        for i, state_array in enumerate(state_arrays):
            state_arrays[i] = state_array[:,subset,:]
    if n_slices is not None and n_steps is not None:
        raise ValueError(
            'cannot give values for both n_slices (%s) and n_steps(%s)' % (
                str(n_slices),
                str(n_steps)
            )
        )
    skip_chunk = None
    if isinstance(skip, (int, float)):
        skip_chunk = int(skip)
    else:
        skip_chunk = 1
    if n_steps:
        slice_iter = _n_steps(keep_steps, n_steps, skip_chunk)
    else:
        slice_iter = _n_slices(keep_steps, n_slices, skip_chunk)
    if skip=='last':
        slice_iter = [list(slice_iter)[-1]]
    elif skip=='first':
        slice_iter = [list(slice_iter)[0]]
        
    for sl in slice_iter:
        #yield the data, sliced according to those slices.
        yield [state_array[sl] for state_array in state_arrays]

def _do_slicewise_stat(stat,
        traderset,
        n_slices=None,
        n_steps=None,
        n_agents=None,
        skip=None,
        extractor=_extract_loc_vel,
        *args, **kwargs):
    return addict([stat(traderset, *slices, **kwargs)
      for slices in _traderset_slices(
        traderset,
        n_slices=n_slices,
        n_steps=n_steps,
        skip=skip,
        n_agents=n_agents,
        extractor=extractor
      )
    ])
    
##########################################
#variable-window-stats
##########################################

def susceptibility(*args, **kwargs):
    return _do_slicewise_stat(_susceptibility, *args, **kwargs)
    
def _susceptibility(traderset, loc_slice, vel_slice):
    """take mean of velocity over time per agent, then return plug-in estimate
    of variance across agents for this parameter (which means it still works
    when looking at a single timestep, as opp with transposed axes)"""
    #return d(est=vel_slice.var(1).mean())
    #i THINK the following one is right:
    return d(est=(vel_slice.mean(0)**2).sum(1).var())

def order(*args, **kwargs):
    return _do_slicewise_stat(_order, *args, **kwargs)

def _order(traderset, loc_slice, vel_slice):
    """magnitude of mean velocity over all timesteps"""
    return d(est=(vel_slice.mean(1).mean(0)**2).sum()**0.5)

def vel_loc_self_mi_adaptive(*args, **kwargs):
    return _do_slicewise_stat(_vel_loc_self_mi_adaptive, *args, **kwargs)

def _vel_loc_self_mi_adaptive(traderset,
        loc_slice,
        vel_slice,
        methods=("mean_mi",),
        estimator="ince",
        **mi_kwargs):
    """test all combinations of velocity and location for informativeness.
    
    This an expensive operation.
    
    We regard all traders as sample points and additionally regard each time
    step for each trader as an additional sample point. This is probably only
    valid if the time section is long enough to be ergodic.
    
    Distributions, and hence information values, are calculated for *each*
    dimension.
    
    Returns three estimates of the multi-information value 
      * the maximal spanning tree of the adjacency matrix, as per Chow and Liu
        (1968), and,
      * same, but not adjusted for dimensionality of data, and, 
      * a mean value. 
    
    Which is more valid is an open question, and possibly contingent on
    the order of interaction dependencies. We have no reason to suppose this
    is anything like a second-order dependency tree, but other estimators are
    even more CPU intensive."""
    
    # Not just vel_slice, as there is one less degree of freedom than
    # dimensions, and we do not wish to discover spurious order.
    # Note that this discards one bit of information by ignoring multi-valued
    # nature of the velocity. A better projection for 2d is atan, and for
    # arbitrary dimensions, the stereographic projection.
    all_params = np.dstack((vel_slice[:,:,:-1], loc_slice)) 
    
    #each degree of freedom is an input or output
    dimensions = all_params.shape[2]
    
    #aggregate t'other axes
    stacked_trials = all_params.reshape(-1, dimensions).T
        
    if estimator=="ince":
        estimator = ince_mi_dist_cont
    else:
        estimator = plugin_mi_dist_cont
    
    def mi_comparifier(*args):
        return estimator(*args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals
        
def vel_loc_self_mi_apriori(*args, **kwargs):
    return _do_slicewise_stat(_vel_loc_self_mi_apriori, *args, **kwargs)

def _vel_loc_self_mi_apriori(traderset,
        loc_slice,
        vel_slice,
        methods=("mean_mi",),
        n_bins="wicks",
        **mi_kwargs):
    """test all combinations of velocity and location for informativeness, but
    use a binning based on known characteristics of the isotropic case.
    see _vel_loc_self_mi_adaptive for more info"""
    if n_bins == "wicks":
        # bin using either Wick's criterion (radius) or, if that has
        # too many bins, Cochrane's.
        n_bins = int(min(
            2.0/traderset.radius+0.5,
            choose_n_bins(vel_slice.shape[0]*vel_slice.shape[1], test=False)
        ))
    elif n_bins == "cochrane":
        # bin using the cochrane criterion, which has as many bins as possible
        n_bins = int(np.floor(np.sqrt(choose_n_bins(vel_slice.shape[0]*vel_slice.shape[1]))))
    print "using %d bins" % n_bins
    vel_slice = bin_vels(vel_slice, n_bins=n_bins, dimensions=traderset.dimensions) 
    loc_slice = bin_naive(loc_slice, n_bins=n_bins, range=(0.,1.))
    all_params = np.dstack((vel_slice[:,:,:-1], loc_slice))#not just vel_slice, as there is one less degree of freedom than dimensions
    dimensions = all_params.shape[2] #each degree of freedom is an input or output
    stacked_trials = all_params.reshape(-1, dimensions).T #aggregate t'other axes
    def mi_comparifier(*args):
        return ince_mi_dist_disc(*args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals

def mi_wicks_2d(*args, **kwargs):
    return _do_slicewise_stat(_mi_wicks_2d,
      extractor=_extract_loc_vel_angle, *args, **kwargs)

def _mi_wicks_2d(traderset,
        loc_slice,
        vel_slice,
        vel_angle_slice,
        loc_binner=bin_naive,
        vel_binner=bin_angle_naive,
        estimator="ince",
        binning='disc',
        squish_bins=True,
        **mi_kwargs):
    """does loc determine angle? We work this out in the special 2D case using
    Wick's actual method, which involves the use of trignometric 2d angles,
    and idiosyncratic bin numbers and placement.
    """
    #from IPython.core.debugger import Tracer
    #Tracer()()
    n_bins = int(min(
        2.0/traderset.radius+0.5,
        math.sqrt(choose_n_bins(vel_slice.shape[0]*vel_slice.shape[1], test=False))
    ))
    
    n_bins = int(np.floor(2./(traderset.radius)))
    n_loc_bins = n_bins
    n_vel_bins = n_bins

    if binning =='disc':
        locs = loc_binner(loc_slice[:,:,0:1], n_bins)
        vels = vel_binner(vel_angle_slice, n_bins)
        if squish_bins:
            locs, n_loc_bins = squish(locs)
            vels, n_vel_bins = squish(vels)
        if estimator=="ince":
            estimator = lambda x,y,**kwargs: ince_mi_dist_disc(x,y,n_loc_bins, n_vel_bins,**kwargs)
        else:
            estimator = lambda x,y,**kwargs: plugin_mi_dist_disc(x,y,n_loc_bins, n_vel_bins,**kwargs)
    else:
        locs = loc_slice[:,:,0:1]
        vels = vel_angle_slice
        if estimator=="ince":
            estimator = lambda x,y,**kwargs: ince_mi_dist_cont(x,y, n_bins=n_bins, **kwargs)
        else:
            estimator = lambda x,y,**kwargs: plugin_mi_dist_cont(x,y, n_bins=n_bins, **kwargs)
    
    est = estimator(
        locs, vels,
        **mi_kwargs
    )
    return d(est=est, n_bins=(n_loc_bins, n_vel_bins))
    
def mi_wicks_hi_d(*args, **kwargs):
    return _do_slicewise_stat(_mi_wicks_hi_d,
      extractor=_extract_loc_vel_projection, *args, **kwargs)

def _mi_wicks_hi_d(
        traderset,
        loc_slice,
        vel_slice,
        vel_projection_slice,
        methods=("mean_mi",),
        estimator="ince",
        **mi_kwargs
    ):
    """does loc determine angle? We work this out using a high-dimensional
    analogue to Wick's actual method, based on stereographic projection and
    idiosyncratic bin numbers. (We don't use his uniform bin boundaries yet as
    it is tedious to work out for stereographic projection.)
    """
    n_bins = int(np.floor(2./(traderset.radius)))
    
    if estimator=="ince":
        estimator = ince_mi_dist_disc
    else:
        estimator = plugin_mi_dist_disc
    
    def mi_comparifier(X, Y, *args):
        return estimator(X, Y, n_bins=n_bins,  **mi_kwargs)
        
    all_params = np.dstack((vel_projection_slice, loc_slice)) 
    
    #each column is an input or output
    dimensions = all_params.shape[2]

    #aggregate t'other axes
    stacked_trials = all_params.reshape(-1, dimensions).T
    
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals

def acc_acc_particlewise_mi_adaptive_2d(*args, **kwargs):
    return _do_slicewise_stat(_acc_acc_particlewise_mi_adaptive_2d,
      extractor=_extract_loc_vel_angle_acc_angle, *args, **kwargs)

#define a convenience alias to the deprecated older function name
acc_acc_mi_adaptive = acc_acc_particlewise_mi_adaptive_2d

def _acc_acc_particlewise_mi_adaptive_2d(traderset,
        loc_slice,
        vel_slice,
        vel_angle_slice,
        acc_slice,
        methods=("mean_mi",),
        **mi_kwargs):
    """Whiten velocity into acceleration by difference. Then calculate MI
    between the observations. For this one we take every particle to have its
    own distribution and every timestep to be an independent observation, and
    presume 2d simulation and hence 1d acceleration.
    
    This is a very expensive calculation, scaling as O(n^2) for n particles.
    
    Additionally I'd like to verify that it actually doesn't mess up the
    particle ordering, of which I am currently unsure.
    """    
    trial_shape = acc_slice.shape[:2]
    #each particle has a distribution
    dimensions = trial_shape[1]
    
    stacked_trials = acc_slice.reshape(-1, dimensions).T
    
    def mi_comparifier(*args):
        return ince_mi_dist_cont(*args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals

def mi_angular_vel_particlewise(traderset, oversample=1, *args, **kwargs):
    """I treat this one differently since it uses a subset of agents per
    default. Gah, more special casing."""
    res = {}
    for i in xrange(oversample):
        res[str(i)] = _do_slicewise_stat(
          _mi_angular_vel_particlewise,
          traderset,
          extractor=_extract_loc_vel_angle,
          *args, **kwargs)
    return res

def _mi_angular_vel_particlewise(traderset,
        loc_slice,
        vel_slice,
        vel_angle_slice,
        methods=("mean_mi",),
        estimator="ince",
        **mi_kwargs):
    """Does one particle's angle reflect another's? We work this out in the
    special 2D case.
    
    Still not totally sure I got the transpose right for higher-d data.
    """
    #each particle has a distribution
    sample_length = vel_angle_slice.shape[0]

    stacked_trials = np.transpose(
        vel_angle_slice,
        (1,0,2)).reshape(-1, sample_length)
        
    if estimator=="ince":
        estimator = ince_mi_dist_cont
    else:
        estimator = plugin_mi_dist_cont
            
    def mi_comparifier(*args):
        return estimator(*args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals

def mi_angular_vel_apriori_particlewise(traderset, oversample=1, *args, **kwargs):
    """I treat this one differently since it uses a subset of agents per
    default. Gah, more special casing."""
    res = {}
    for i in xrange(oversample):
        res[str(i)] = _do_slicewise_stat(
          _mi_angular_vel_apriori_particlewise,
          traderset,
          extractor=_extract_loc_vel_angle,
          *args, **kwargs)
    return res

def _mi_angular_vel_apriori_particlewise(traderset,
        loc_slice,
        vel_slice,
        vel_angle_slice,
        loc_binner=bin_naive,
        vel_binner=bin_angle_naive,
        methods=("mean_mi",),
        estimator="ince",
        squish_bins=True,
        **mi_kwargs):
    """Does one particle's angle reflect another's? We work this out in the
    special 2D case.
    
    Still not totally sure I got the transpose right for higher-d data.
    """
    n_vel_bins = int(np.floor(2./(traderset.radius)))
    
    # loc_slice = loc_binner(loc_slice[:,:,0:1], n_bins)
    vels = vel_binner(vel_angle_slice, n_vel_bins)

    if squish_bins:
        # locs, n_loc_bins = squish(locs)
        vels, n_vel_bins = squish(vels)
    
    #each particle has a distribution
    sample_length = vels.shape[0]

    stacked_trials = np.transpose(
        vels,
        (1,0,2)).reshape(-1, sample_length)
        
    if estimator=="ince":
        estimator = ince_mi_dist_disc
    else:
        estimator = plugin_mi_dist_disc
        
    def mi_comparifier(X,Y, *args):
        return estimator(X, Y,
            x_bins=n_vel_bins, y_bins=n_vel_bins,
            *args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals

def mi_distance_angular_vel_apriori_particlewise(traderset, oversample=1, n_agents=2, *args, **kwargs):
    """I treat this one differently since it uses a subset of agents per
    default. Gah, more special casing."""
    res = {}
    for i in xrange(oversample):
        res[str(i)] = _do_slicewise_stat(
          _mi_distance_angular_vel_apriori_particlewise,
          traderset,
          n_agents=n_agents,
          extractor=_extract_loc_vel_angle,
          *args, **kwargs)
    return res

def _mi_distance_angular_vel_apriori_particlewise(traderset,
        loc_slice,
        vel_slice,
        vel_angle_slice,
        loc_binner=bin_naive,
        vel_binner=bin_angle_naive,
        estimator="ince",
        squish_bins=True,
        **mi_kwargs):
    """Does ones particle's distance from another say anything about their relative angle?
    This could be done via random samples
    """
    n_bins = int(np.floor(2./(traderset.radius)))
    #from IPython.core.debugger import Tracer; Tracer()()
    rel_loc_slice = loc_slice[:,1,:] - loc_slice[:,0,:] + 0.5
    rel_loc_slice = rel_loc_slice - np.floor(rel_loc_slice) - 0.5
    dist_slice = ((rel_loc_slice ** 2).sum(1) ** 0.5).flatten()
    rel_vel_angle_slice = np.modf((vel_angle_slice[:,1,:]-vel_angle_slice[:,0,:])/np.pi)[0].flatten()
    
    #this first one should actually be binned a little differently, but I am disinclined to work out how atm
    locs = bin_naive(dist_slice, n_bins=n_bins, range=(0.,np.sqrt(0.5)))
    vels = bin_naive(rel_vel_angle_slice, n_bins=n_bins, range=(-1.0, 1.0))
    
    n_vel_bins = n_bins
    n_loc_bins = n_bins
    
    if squish_bins:
        locs, n_loc_bins = squish(locs)
        vels, n_vel_bins = squish(vels)
        
    if estimator=="ince":
        estimator = ince_mi_dist_disc
    else:
        estimator = plugin_mi_dist_disc
    
    est = estimator(
        locs, vels,
        n_loc_bins, n_vel_bins, **mi_kwargs
    )
    return d(est=est)

def mi_distance_angular_vel_particlewise_macerated(traderset, oversample=100, n_agents=2, *args, **kwargs):
    """I treat this one different than the other particlewise things for long and tedious reasons.
    Note we clobber the n_agents param."""
    return _do_slicewise_stat(
          _mi_distance_angular_vel_particlewise_macerated,
          traderset,
          extractor=_extract_loc_vel_angle,
          oversample=oversample,
          *args, **kwargs)

def _mi_distance_angular_vel_particlewise_macerated(traderset,
        loc_slice,
        vel_slice,
        vel_angle_slice,
        binning='disc',
        n_bins="cochrane",
        loc_binner=bin_naive,
        vel_binner=bin_angle_naive,
        estimator="ince",
        oversample=100,
        squish_bins=True,
        **mi_kwargs):
    """Does ones particle's distance from another say anything about their relative angle?
    This could be done via random samples.
    """
    #(time, agent, dimension)
    time_len = loc_slice.shape[0]
    particle_len = loc_slice.shape[1]
    dim_len = loc_slice.shape[2]
    if n_bins == "wicks":
        # bin using either Wick's criterion (radius) 
        n_bins = int(np.floor(2./(traderset.radius)))
    elif n_bins == "cochrane":
        # bin using the cochrane criterion, which has as many bins as possible
        n_bins = int(np.floor(math.sqrt(choose_n_bins(time_len*oversample*time_len*oversample))))
    if binning =='disc':
        if estimator=="ince":
            estimator = ince_mi_dist_disc
        else:
            estimator = plugin_mi_dist_disc
    else:        
        if estimator=="ince":
            estimator = lambda x,y,**kwargs: ince_mi_dist_cont(x,y, n_bins=n_bins, **kwargs)
        else:
            estimator = lambda x,y,**kwargs: plugin_mi_dist_cont(x,y, n_bins=n_bins, **kwargs)
    # from IPython.core.debugger import Tracer; Tracer()()
    locs = np.zeros((oversample, time_len), dtype=loc_slice.dtype)
    vels = np.zeros((oversample, time_len), dtype=vel_slice.dtype)
    time_lut = np.arange(time_len)
    dim_lut = np.arange(dim_len)
    for i in xrange(oversample):
        particle_lut1 = np.random.randint(particle_len, size=time_len)
        particle_lut2 = np.random.randint(particle_len, size=time_len)
        rel_loc_slice = loc_slice[time_lut,particle_lut1,:] - loc_slice[time_lut,particle_lut2,:] + 0.5
        rel_loc_slice = rel_loc_slice - np.floor(rel_loc_slice) - 0.5
        locs[i] = ((rel_loc_slice ** 2).sum(1) ** 0.5).ravel()
        vels[i] = np.modf((vel_angle_slice[time_lut,particle_lut1,:]-vel_angle_slice[time_lut,particle_lut2,:])/np.pi)[0].ravel()
    
    n_vel_bins = n_bins
    n_loc_bins = n_bins

    if binning =='disc':
        #this first one should actually be binned a little differently, but I am disinclined to work out how atm
        locs = bin_naive(locs, n_bins=n_bins, range=(0.,np.sqrt(0.5)))
        vels = bin_naive(vels, n_bins=n_bins, range=(-1.0, 1.0))
        if squish_bins:
            locs, n_loc_bins = squish(locs)
            vels, n_vel_bins = squish(vels)
    
    est = estimator(
        locs.ravel(), vels.ravel(),
        x_bins=n_loc_bins, y_bins=n_vel_bins, **mi_kwargs
    )
    return d(est=est)

def acc_acc_particlewise_mi_adaptive_hi_d(*args, **kwargs):
    return _do_slicewise_stat(_acc_acc_particlewise_mi_adaptive_hi_d,
      extractor=_extract_loc_vel_projection_acc, *args, **kwargs)

def _acc_acc_particlewise_mi_adaptive_hi_d(traderset,
        loc_slice,
        vel_slice,
        vel_projection_slice,
        acc_slice,
        methods=("mean_mi",),
        **mi_kwargs):
    """Whiten velocity into acceleration by difference. Then calculate MI
    between the observations. For this one we take every particle to have its
    own distribution and every timestep to be an independent observation.

    This currently fucks up particle ordering, so I don't support it.
    """
    raise NotImplementedError("Particlewise acc-acc MI is broken")
    trial_shape = acc_slice.shape[:2]
    
    #each particle has a distribution
    dimensions = trial_shape[1]

    stacked_trials = acc_slice.reshape(-1, dimensions).T
    
    def mi_comparifier(*args):
        return ince_mi_dist_cont(*args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals

def acc_acc_axiswise_mi_adaptive_hi_d(*args, **kwargs):
    return _do_slicewise_stat(_acc_acc_axiswise_mi_adaptive_hi_d,
      extractor=_extract_loc_vel_projection_acc, *args, **kwargs)

def _acc_acc_axiswise_mi_adaptive_hi_d(traderset,
        loc_slice,
        vel_slice,
        vel_projection_slice,
        acc_slice,
        methods=("mean_mi",),
        **mi_kwargs):
    """Whiten velocity into acceleration by difference. Then calculate MI
    between the observations. For this one we take every axis to have its
    own distribution and every particle at every timestep to be an independent
    observation. (This is a cheaper measure than the particlewise version)
    
    TODO: better verification of correctness here.
    """
    trial_shape = acc_slice.shape[:]
    
    #each axis has a distribution
    dimensions = trial_shape[2]
    
    stacked_trials = acc_slice.reshape(-1, dimensions).T
    
    def mi_comparifier(*args):
        return ince_mi_dist_cont(*args, **mi_kwargs)
        
    #get condensed-form MI-distance matrix
    dists = sp.spatial.distance.pdist(
        stacked_trials,
        mi_comparifier
    )
    vals = {}
    if 'mean_mi' in methods:
        vals['mean_mi'] = dists.mean()
    raw_tree_mi, node_count = spanning_weight(dists)
    if 'tree_mi_raw' in methods:
        vals['tree_mi_raw'] = raw_tree_mi
    if 'tree_mi_w' in methods:
        vals['tree_mi_w'] = raw_tree_mi/float(node_count)
    return vals


def _swept_stat(traderset, stat, extractor, *args, **kwargs):
    """Bit of a hack; this guy extracts an estimate of some viable step
    lengths from the traderset and then sweeps through those step lengths"""
    #be conservative about chunk length
    max_step_exp = int(math.floor(math.log(traderset.keep_steps-1)/math.log(2)))
    results = {}
    stat_name = stat.func_name
    for step_exp in xrange(max_step_exp+1):
        n_steps = int(2**step_exp)
        print "sweeping", stat_name, n_steps
        results[n_steps] = _do_slicewise_stat(stat,
            traderset,
            n_steps=n_steps,
            extractor=extractor,
            *args, **kwargs)
    return results

def acc_acc_axiswise_mi_adaptive_hi_d_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_acc_acc_axiswise_mi_adaptive_hi_d,
        extractor=_extract_loc_vel_projection_acc,
        *args, **kwargs
    )
    
def acc_acc_axiswise_mi_adaptive_hi_d_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_acc_acc_axiswise_mi_adaptive_hi_d,
        extractor=_extract_loc_vel_projection_acc,
        *args, **kwargs
    )
    
def mi_wicks_2d_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_mi_wicks_2d,
        extractor=_extract_loc_vel_angle,
        *args, **kwargs
    )

def mi_wicks_hi_d_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_mi_wicks_hi_d,
        extractor=_extract_loc_vel_projection,
        *args, **kwargs
    )
    
def susceptibility_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_susceptibility,
        extractor=_extract_loc_vel,
        *args, **kwargs
    )

def order_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_order,
        extractor=_extract_loc_vel,
        *args, **kwargs
    )

def mi_angular_vel_particlewise_swept(
        traderset,
        *args, **kwargs):
    return _swept_stat(
        traderset,
        stat=_mi_angular_vel_particlewise,
        extractor=_extract_loc_vel_angle,
        *args, **kwargs
    )
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.