/
beatmap.py
2547 lines (2205 loc) · 75.1 KB
/
beatmap.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
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
from datetime import timedelta
from enum import unique, IntEnum
from functools import partial
import inspect
from itertools import chain, islice, cycle
import operator as op
import re
from zipfile import ZipFile
import numpy as np
from .game_mode import GameMode
from .mod import ar_to_ms, ms_to_ar, circle_radius, od_to_ms_300, ms_300_to_od
from .position import Position, Point
from .utils import (
accuracy as calculate_accuracy,
lazyval,
memoize,
no_default,
orange,
)
from .curve import Curve
def _get(cs, ix, default=no_default):
try:
return cs[ix]
except IndexError:
if default is no_default:
raise
return default
class TimingPoint:
"""A timing point assigns properties to an offset into a beatmap.
Parameters
----------
offset : timedelta
When this ``TimingPoint`` takes effect.
ms_per_beat : float
The milliseconds per beat, this is another representation of BPM.
meter : int
The number of beats per measure.
sample_type : int
The type of hit sound samples that are used.
sample_set : int
The set of hit sound samples that are used.
volume : int
The volume of hit sounds in the range [0, 100]. This value will be
clipped if outside the range.
parent : TimingPoint or None
The parent of an inherited timing point. An inherited timing point
differs from a normal timing point in that the ``ms_per_beat`` value is
negative, and defines a new ``ms_per_beat`` based on the parent
timing point. This can be used to change volume without affecting
offset timing, or changing slider speeds. If this is not an inherited
timing point the parent should be ``None``.
kiai_mode : bool
Wheter or not kiai time effects are active.
"""
def __init__(self,
offset,
ms_per_beat,
meter,
sample_type,
sample_set,
volume,
parent,
kiai_mode):
self.offset = offset
self.ms_per_beat = ms_per_beat
self.meter = meter
self.sample_type = sample_type
self.sample_set = sample_set
self.volume = np.clip(volume, 0, 100)
self.parent = parent
self.kiai_mode = kiai_mode
@lazyval
def half_time(self):
"""The ``TimingPoint`` as it would appear with
:data:`~slider.mod.Mod.half_time` enabled.
"""
return type(self)(
4 * self.offset / 3,
self.ms_per_beat if self.inherited else (4 * self.ms_per_beat / 3),
self.meter,
self.sample_type,
self.sample_set,
self.volume,
getattr(self.parent, 'half_time', None),
self.kiai_mode,
)
def double_time(self):
"""The ``TimingPoint`` as it would appear with
:data:`~slider.mod.Mod.double_time` enabled.
"""
return type(self)(
2 * self.offset / 3,
self.ms_per_beat if self.inherited else (2 * self.ms_per_beat / 3),
self.meter,
self.sample_type,
self.sample_set,
self.volume,
getattr(self.parent, 'double_time', None),
self.kiai_mode,
)
@lazyval
def bpm(self):
"""The bpm of this timing point.
If this is an inherited timing point this value will be None.
"""
ms_per_beat = self.ms_per_beat
if ms_per_beat < 0:
return None
return round(60000 / ms_per_beat)
def __repr__(self):
if self.parent is None:
inherited = 'inherited '
else:
inherited = ''
return (
f'<{type(self).__qualname__}:'
f' {inherited}{self.offset.total_seconds() * 1000:g}ms>'
)
@classmethod
def parse(cls, data, parent):
"""Parse a TimingPoint object from a line in a ``.osu`` file.
Parameters
----------
data : str
The line to parse.
parent : TimingPoint
The last non-inherited timing point.
Returns
-------
timing_point : TimingPoint
The parsed timing point.
Raises
------
ValueError
Raised when ``data`` does not describe a ``TimingPoint`` object.
"""
try:
offset, ms_per_beat, *rest = data.split(',')
except ValueError:
raise ValueError(
f'failed to parse {cls.__qualname__} from {data!r}',
)
try:
offset_float = float(offset)
except ValueError:
raise ValueError(f'offset should be a float, got {offset!r}')
offset = timedelta(milliseconds=offset_float)
try:
ms_per_beat = float(ms_per_beat)
except ValueError:
raise ValueError(
f'ms_per_beat should be a float, got {ms_per_beat!r}',
)
try:
meter = int(_get(rest, 0, '4'))
except ValueError:
raise ValueError(f'meter should be an int, got {meter!r}')
try:
sample_type = int(_get(rest, 1, '0'))
except ValueError:
raise ValueError(
f'sample_type should be an int, got {sample_type!r}',
)
try:
sample_set = int(_get(rest, 2, '0'))
except ValueError:
raise ValueError(
f'sample_set should be an int, got {sample_set!r}',
)
try:
volume = int(_get(rest, 3, '1'))
except ValueError:
raise ValueError(f'volume should be an int, got {volume!r}')
try:
inherited = not bool(int(_get(rest, 4, '1')))
except ValueError:
raise ValueError(f'inherited should be a bool, got {inherited!r}')
try:
kiai_mode = bool(int(_get(rest, 5, '0')))
except ValueError:
raise ValueError(f'kiai_mode should be a bool, got {kiai_mode!r}')
return cls(
offset=offset,
ms_per_beat=ms_per_beat,
meter=meter,
sample_type=sample_type,
sample_set=sample_set,
volume=volume,
parent=parent if inherited else None,
kiai_mode=kiai_mode,
)
class HitObject:
"""An abstract hit element for osu! standard.
Parameters
----------
position : Position
Where this element appears on the screen.
time : timedelta
When this element appears in the map.
hitsound : int
The hitsound to play when this object is hit.
addition : str, optional
Unknown currently.
"""
time_related_attributes = frozenset({'time'})
def __init__(self, position, time, hitsound, addition='0:0:0:0'):
self.position = position
self.time = time
self.hitsound = hitsound
self.addition = addition
def __repr__(self):
return (
f'<{type(self).__qualname__}: {self.position},'
f' {self.time.total_seconds() * 1000:g}ms>'
)
def _time_modify(self, coefficient):
"""Modify this ``HitObject`` by multiplying time related attributes
by the ``coefficient``.
Parameters
----------
coefficient : float
The coefficient to multiply the ``time_related`` values by.
Returns
-------
modified : HitObject
The modified hit object.
"""
time_related_attributes = self.time_related_attributes
kwargs = {}
for name in inspect.signature(type(self)).parameters:
value = getattr(self, name)
if name in time_related_attributes:
value *= coefficient
kwargs[name] = value
return type(self)(**kwargs)
@lazyval
def half_time(self):
"""The ``HitObject`` as it would appear with
:data:`~slider.mod.Mod.half_time` enabled.
"""
return self._time_modify(4 / 3)
@lazyval
def double_time(self):
"""The ``HitObject`` as it would appear with
:data:`~slider.mod.Mod.double_time` enabled.
"""
return self._time_modify(2 / 3)
@lazyval
def hard_rock(self):
"""The ``HitObject`` as it would appear with
:data:`~slider.mod.Mod.hard_rock` enabled.
"""
kwargs = {}
for name in inspect.signature(type(self)).parameters:
value = getattr(self, name)
if name == 'position':
value = Position(value.x, 384 - value.y)
kwargs[name] = value
return type(self)(**kwargs)
@classmethod
def parse(cls, data, timing_points, slider_multiplier, slider_tick_rate):
"""Parse a HitObject object from a line in a ``.osu`` file.
Parameters
----------
data : str
The line to parse.
timing_points : list[TimingPoint]
The timing points in the map.
slider_multiplier : float
The slider multiplier for computing slider end_time and ticks.
slider_tick_rate : float
The slider tick rate for computing slider end_time and ticks.
Returns
-------
hit_objects : HitObject
The parsed hit object. This will be the concrete subclass given
the type.
Raises
------
ValueError
Raised when ``data`` does not describe a ``HitObject`` object.
"""
try:
x, y, time, type_, hitsound, *rest = data.split(',')
except ValueError:
raise ValueError(f'not enough elements in line, got {data!r}')
try:
x = int(x)
except ValueError:
raise ValueError(f'x should be an int, got {x!r}')
try:
y = int(y)
except ValueError:
raise ValueError(f'y should be an int, got {y!r}')
try:
time = timedelta(milliseconds=int(time))
except ValueError:
raise ValueError(f'type should be an int, got {time!r}')
try:
type_ = int(type_)
except ValueError:
raise ValueError(f'type should be an int, got {type_!r}')
try:
hitsound = int(hitsound)
except ValueError:
raise ValueError(f'hitsound should be an int, got {hitsound!r}')
if type_ & Circle.type_code:
parse = Circle._parse
elif type_ & Slider.type_code:
parse = partial(
Slider._parse,
timing_points=timing_points,
slider_multiplier=slider_multiplier,
slider_tick_rate=slider_tick_rate,
)
elif type_ & Spinner.type_code:
parse = Spinner._parse
elif type_ & HoldNote.type_code:
parse = HoldNote._parse
else:
raise ValueError(f'unknown type code {type_!r}')
return parse(Position(x, y), time, hitsound, rest)
class Circle(HitObject):
"""A circle hit element.
Parameters
----------
position : Position
Where this circle appears on the screen.
time : timedelta
When this circle appears in the map.
"""
type_code = 1
@classmethod
def _parse(cls, position, time, hitsound, rest):
if len(rest) > 1:
raise ValueError('extra data: {rest!r}')
return cls(position, time, hitsound, *rest)
class Spinner(HitObject):
"""A spinner hit element
Parameters
----------
position : Position
Where this spinner appears on the screen.
time : timedelta
When this spinner appears in the map.
end_time : timedelta
When this spinner ends in the map.
addition : str
Hitsound additions.
"""
type_code = 8
time_related_attributes = frozenset({'time', 'end_time'})
def __init__(self,
position,
time,
hitsound,
end_time,
addition='0:0:0:0:'):
super().__init__(position, time, hitsound, addition)
self.end_time = end_time
@classmethod
def _parse(cls, position, time, hitsound, rest):
try:
end_time, *rest = rest
except ValueError:
raise ValueError('missing end_time')
try:
end_time = timedelta(milliseconds=int(end_time))
except ValueError:
raise ValueError(f'end_time should be an int, got {end_time!r}')
if len(rest) > 1:
raise ValueError(f'extra data: {rest!r}')
return cls(position, time, hitsound, end_time, *rest)
class Slider(HitObject):
"""A slider hit element.
Parameters
----------
position : Position
Where this slider appears on the screen.
time : datetime.timedelta
When this slider appears in the map.
end_time : datetime.timedelta
When this slider ends in the map
hitsound : int
The sound played on the ticks of the slider.
curve : Curve
The slider's curve function.
length : int
The length of this slider in osu! pixels.
ticks : int
The number of slider ticks including the head and tail of the slider.
num_beats : int
The number of beats that this slider spans.
tick_rate : float
The rate at which ticks appear along sliders.
ms_per_beat : int
The milliseconds per beat during the segment of the beatmap that this
slider appears in.
edge_sounds : list[int]
A list of hitsounds for each edge.
edge_additions : list[str]
A list of additions for each edge.
addition : str
Hitsound additions.
"""
type_code = 2
time_related_attributes = frozenset({'time', 'end_time', 'ms_per_beat'})
def __init__(self,
position,
time,
end_time,
hitsound,
curve,
repeat,
length,
ticks,
num_beats,
tick_rate,
ms_per_beat,
edge_sounds,
edge_additions,
addition='0:0:0:0'):
super().__init__(position, time, hitsound, addition)
self.end_time = end_time
self.curve = curve
self.repeat = repeat
self.length = length
self.ticks = ticks
self.num_beats = num_beats
self.tick_rate = tick_rate
self.ms_per_beat = ms_per_beat
self.edge_sounds = edge_sounds
self.edge_additions = edge_additions
@lazyval
def tick_points(self):
"""The position and time of each slider tick.
"""
repeat = self.repeat
time = self.time
repeat_duration = (self.end_time - time) / repeat
curve = self.curve
pre_repeat_ticks = []
append_tick = pre_repeat_ticks.append
beats_per_repeat = self.num_beats / repeat
for t in orange(self.tick_rate, beats_per_repeat, self.tick_rate):
pos = curve(t / beats_per_repeat)
timediff = timedelta(milliseconds=t * self.ms_per_beat)
append_tick(Point(pos.x, pos.y, time + timediff))
pos = curve(1)
timediff = repeat_duration
append_tick(Point(pos.x, pos.y, time + timediff))
repeat_ticks = [
Point(p.x, p.y, pre_repeat_tick.offset)
for pre_repeat_tick, p in zip(
pre_repeat_ticks,
chain(pre_repeat_ticks[-2::-1], [self.position])
)
]
tick_sequences = islice(
cycle([pre_repeat_ticks, repeat_ticks]),
repeat,
)
return list(
chain.from_iterable(
(
Point(p.x, p.y, p.offset + n * repeat_duration)
for p in tick_sequence
)
for n, tick_sequence in enumerate(tick_sequences)
),
)
@lazyval
def hard_rock(self):
"""The ``HitObject`` as it would appear with
:data:`~slider.mod.Mod.hard_rock` enabled.
"""
kwargs = {}
for name in inspect.signature(type(self)).parameters:
value = getattr(self, name)
if name == 'position':
value = Position(value.x, 384 - value.y)
elif name == 'curve':
value = value.hard_rock
kwargs[name] = value
return type(self)(**kwargs)
@classmethod
def _parse(cls,
position,
time,
hitsound,
rest,
timing_points,
slider_multiplier,
slider_tick_rate):
try:
group_1, *rest = rest
except ValueError:
raise ValueError(f'missing required slider data in {rest!r}')
try:
slider_type, *raw_points = group_1.split('|')
except ValueError:
raise ValueError(
'expected slider type and points in the first'
f' element of rest, {rest!r}',
)
points = [position]
for point in raw_points:
try:
x, y = point.split(':')
except ValueError:
raise ValueError(
f'expected points in the form x:y, got {point!r}',
)
try:
x = int(x)
except ValueError:
raise ValueError('x should be an int, got {x!r}')
try:
y = int(y)
except ValueError:
raise ValueError('y should be an int, got {y!r}')
points.append(Position(x, y))
try:
repeat, *rest = rest
except ValueError:
raise ValueError(f'missing repeat in {rest!r}')
try:
repeat = int(repeat)
except ValueError:
raise ValueError(f'repeat should be an int, got {repeat!r}')
try:
pixel_length, *rest = rest
except ValueError:
raise ValueError(f'missing pixel_length in {rest!r}')
try:
pixel_length = float(pixel_length)
except ValueError:
raise ValueError(
f'pixel_length should be a float, got {pixel_length!r}',
)
try:
raw_edge_sounds_grouped, *rest = rest
except ValueError:
raw_edge_sounds_grouped = ''
raw_edge_sounds = raw_edge_sounds_grouped.split('|')
edge_sounds = []
if raw_edge_sounds != ['']:
for edge_sound in raw_edge_sounds:
try:
edge_sound = int(edge_sound)
except ValueError:
raise ValueError(
f'edge_sound should be an int, got {edge_sound!r}',
)
edge_sounds.append(edge_sound)
try:
edge_additions_grouped, *rest = rest
except ValueError:
edge_additions_grouped = ''
if edge_additions_grouped:
edge_additions = edge_additions_grouped.split('|')
else:
edge_additions = []
if len(rest) > 1:
raise ValueError(f'extra data: {rest!r}')
for tp in reversed(timing_points):
if tp.offset <= time:
break
else:
tp = timing_points[0]
if tp.parent is not None:
velocity_multiplier = -100 / tp.ms_per_beat
ms_per_beat = tp.parent.ms_per_beat
else:
velocity_multiplier = 1
ms_per_beat = tp.ms_per_beat
pixels_per_beat = slider_multiplier * 100 * velocity_multiplier
num_beats = (
np.round(((pixel_length * repeat) / pixels_per_beat) * 16) / 16
)
duration = timedelta(milliseconds=np.ceil(num_beats * ms_per_beat))
ticks = int(
(
(np.ceil((num_beats - 0.1) / repeat * slider_tick_rate) - 1)
) *
repeat +
repeat +
1
)
return cls(
position,
time,
time + duration,
hitsound,
Curve.from_kind_and_points(slider_type, points, pixel_length),
repeat,
pixel_length,
ticks,
num_beats,
slider_tick_rate,
ms_per_beat,
edge_sounds,
edge_additions,
*rest,
)
class HoldNote(HitObject):
"""A HoldNote hit element.
Parameters
----------
position : Position
Where this HoldNote appears on the screen.
time : timedelta
When this HoldNote appears in the map.
Notes
-----
A ``HoldNote`` can only appear in an osu!mania map.
"""
type_code = 128
@classmethod
def _parse(cls, position, time, hitsound, rest):
if len(rest) > 1:
raise ValueError('extra data: {rest!r}')
return cls(position, time, hitsound, *rest)
def _get_as_str(groups, section, field, default=no_default):
"""Lookup a field from a given section.
Parameters
----------
groups : dict[str, dict[str, str]]
The grouped osu! file.
section : str
The section to read from.
field : str
The field to read.
default : int, optional
A value to return if ``field`` is not in ``groups[section]``.
Returns
-------
cs : str
``groups[section][field]`` or default if ``field` is not in
``groups[section]``.
"""
try:
mapping = groups[section]
except KeyError:
if default is no_default:
raise ValueError(f'missing section {section!r}')
return default
try:
return mapping[field]
except KeyError:
if default is no_default:
raise ValueError(f'missing field {field!r} in section {section!r}')
return default
def _get_as_int(groups, section, field, default=no_default):
"""Lookup a field from a given section and parse it as an integer.
Parameters
----------
groups : dict[str, dict[str, str]]
The grouped osu! file.
section : str
The section to read from.
field : str
The field to read and parse.
default : int, optional
A value to return if ``field`` is not in ``groups[section]``.
Returns
-------
integer : int
``int(groups[section][field])`` or default if ``field` is not in
``groups[section]``.
"""
v = _get_as_str(groups, section, field, default)
if v is default:
return v
try:
return int(v)
except ValueError:
raise ValueError(
f'field {field!r} in section {section!r} should be an int,'
f' got {v!r}',
)
def _get_as_int_list(groups, section, field, default=no_default):
"""Lookup a field from a given section and parse it as an integer list.
Parameters
----------
groups : dict[str, dict[str, str]]
The grouped osu! file.
section : str
The section to read from.
field : str
The field to read and parse.
default : int, optional
A value to return if ``field`` is not in ``groups[section]``.
Returns
-------
ints : list[int]
``int(groups[section][field])`` or default if ``field` is not in
``groups[section]``.
"""
v = _get_as_str(groups, section, field, default)
if v is default:
return v
try:
return [int(e.strip()) for e in v.split(',')]
except ValueError:
raise ValueError(
f'field {field!r} in section {section!r} should be an int list,'
f' got {v!r}',
)
def _get_as_float(groups, section, field, default=no_default):
"""Lookup a field from a given section and parse it as an float
Parameters
----------
groups : dict[str, dict[str, str]]
The grouped osu! file.
section : str
The section to read from.
field : str
The field to read and parse.
default : float, optional
A value to return if ``field`` is not in ``groups[section]``.
Returns
-------
f : float
``float(groups[section][field])`` or default if ``field` is not in
``groups[section]``.
"""
v = _get_as_str(groups, section, field, default)
if v is default:
return v
try:
return float(v)
except ValueError:
raise ValueError(
f'field {field!r} in section {section!r} should be a float,'
f' got {v!r}',
)
def _get_as_bool(groups, section, field, default=no_default):
"""Lookup a field from a given section and parse it as an float
Parameters
----------
groups : dict[str, dict[str, str]]
The grouped osu! file.
section : str
The section to read from.
field : str
The field to read and parse.
default : float, optional
A value to return if ``field`` is not in ``groups[section]``.
Returns
-------
f : float
``float(groups[section][field])`` or default if ``field` is not in
``groups[section]``.
"""
v = _get_as_str(groups, section, field, default)
if v is default:
return v
try:
# cast to int then to bool because '0' is still True; bools are written
# to the file as '0' and '1' so this is safe.
return bool(int(v))
except ValueError:
raise ValueError(
f'field {field!r} in section {section!r} should be a bool,'
f' got {v!r}',
)
def _moving_average_by_time(times, data, delta, num):
"""Take the moving average of some values and sample it at regular
frequencies.
Parameters
----------
times : np.ndarray
The array of times to use in the average.
data : np.ndarray
The array of values to take the average of. Each column is averaged
independently.
delta : int or float
The length of the leading and trailing window in seconds
num : int
The number of samples to take.
Returns
-------
times : np.ndarray
A column vector of the times sampled at.
averages : np.ndarray
A column array of the averages. 1 column per column in the input
"""
# take an even sample from 0 to the end time
out_times = np.linspace(
times[0].item(),
times[-1].item(),
num,
dtype='timedelta64[ns]',
)
delta = np.timedelta64(int(delta * 1e9), 'ns')
# compute the start and stop indices for each sampled window
window_start_ixs = np.searchsorted(times[:, 0], out_times - delta)
window_stop_ixs = np.searchsorted(times[:, 0], out_times + delta)
# a 2d array of shape ``(num, 2)`` where each row holds the start and stop
# index for the window
window_ixs = np.stack([window_start_ixs, window_stop_ixs], axis=1)
# append a nan to the end of the values so that we can do many slices all
# the way to the end in reduceat
values = np.vstack([data, [np.nan] * data.shape[1]])
# sum the values in the ranges ``[window_start_ixs, window_stop_ixs)``
window_sums = np.add.reduceat(values, window_ixs.ravel())[::2]
window_sizes = np.diff(window_ixs, axis=1).ravel()
# convert window_sizes of 0 to 1 (inplace) to prevent division by zero
np.clip(window_sizes, 1, None, out=window_sizes)
out_values = np.stack(window_sums / window_sizes.reshape((-1, 1)))
return out_times.reshape((-1, 1)), out_values
class _DifficultyHitObject:
"""An object used to accumulate the strain information for calculating
stars.
Parameters
----------
hit_object : HitObject
The hit object to wrap.
radius : int
The circle radius
previous : _DifficultyHitObject, optional
The previous difficulty hit object.
"""
decay_base = 0.3, 0.15
almost_diameter = 90
stream_spacing = 110
single_spacing = 125
weight_scaling = 1400, 26.25
circle_size_buffer_threshold = 30
@unique
class Strain(IntEnum):
"""Indices for the strain specific values.
"""
speed = 0
aim = 1
def __init__(self, hit_object, radius, previous=None):
self.hit_object = hit_object
scaling_factor = 52 / radius
if radius < self.circle_size_buffer_threshold:
scaling_factor *= 1 + min(
self.circle_size_buffer_threshold - radius,
5,
) / 50
# this currently ignores slider length
self.normalized_start = self.normalized_end = Position(