Contents

カレコ料金グラフ

https://www.careco.jp/plan/ をプロットした。

料金表: careco_fee_table.txt

ベーシック

/ja/careco-fee/2021-10-16-20-26-24.png
ベーシック 料金グラフ

ミドル

/ja/careco-fee/2021-10-16-20-27-11.png
ミドル 料金グラフ

プレミアム

/ja/careco-fee/2021-10-16-20-27-27.png
プレミアム 料金グラフ

プレミアムプラス

/ja/careco-fee/2021-10-16-20-27-38.png
プレミアムプラス 料金グラフ

おまけ カラーマップ

一応描いてみたがあまり有用じゃなかった。 プレミアムプラスにはナイトパックが無いため、その特徴を表すサンドイッチ (⊿) 型のフラットな領域が無い。

/ja/careco-fee/2021-10-17-15-38-51.png
ベーシック 料金カラーマップ
/ja/careco-fee/2021-10-17-15-39-01.png
ミドル 料金カラーマップ
/ja/careco-fee/2021-10-17-15-39-09.png
プレミアム 料金カラーマップ
/ja/careco-fee/2021-10-17-15-39-20.png
プレミアムプラス 料金カラーマップ

おまけ Pythonスクリプト

  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
# SPDX-License-Identifier: Apache-2.0

"""
# time(MM:hh) time
# 00:00          0
# 00:50         50
# 09:00        540
# 18:00       1080
# 23:50       1430
# 24:00       1440
# 48:00       2880
"""

import itertools
import logging
import math
import sys
import typing as t

import matplotlib
import matplotlib.collections
import matplotlib.figure
import matplotlib.pyplot as plt
import matplotlib.ticker
import numpy as np

# -----------------------------------------------------------------------------
# parameters

CACHE_PATH = 'careco_fees.txt'
SAVE_CACHE = False
LOAD_CACHE = False

Type = t.Literal['basic', 'middle', 'premium', 'premium+']

M10 = 10  # 10min
M60 = 60  # 1h
M360 = 360  # 6h
M720 = 720  # 12h
M1440 = 1440  # 24h
M60i = M60 // M10
M1440i = M1440 // M10

# 10min
FEES10: dict[Type, int] = {
    'basic': 140,
    'middle': 160,
    'premium': 270,
    'premium+': 500,
}
# 6h
FEES360: dict[Type, int] = {
    'basic': 4080,
    'middle': 4080,
    'premium': 7600,
    'premium+': 10900,
}
# 12h
FEES720: dict[Type, int] = {
    'basic': 5700,
    'middle': 6700,
    'premium': 9000,
    'premium+': 12900,
}
# 24h
FEES1440: dict[Type, int] = {
    'basic': 7300,
    'middle': 8300,
    'premium': 11000,
    'premium+': 15800,
}
# 18:00-09:00
FEES_NIGHT: dict[Type, t.Optional[int]] = {
    'basic': 2700,
    'middle': 3100,
    'premium': 5100,
    'premium+': None,
}

# -----------------------------------------------------------------------------
# utils

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)


def minutes_to_str(minutes: int) -> str:
    return f'{minutes // M60:02}:{minutes % M60:02}'


def str_to_minutes(s: str) -> int:
    # datetime.datetime.strptime(s, '%H:%M')
    h, m = map(int, s.split(':'))
    return h * M60 + m


def times_concat(pairs_time_begin_end: list[tuple[int, int]]) -> list[tuple[int, int]]:
    """
    >>> times_concat([])
    []
    >>> times_concat([(0, 540)])
    [(0, 540)]
    >>> times_concat([(0, 540), (540, 1080), (1980, 2520), (2520, 2530)])
    [(0, 1080), (1980, 2530)]
    """
    if not pairs_time_begin_end:
        return []
    ret = []
    prev_begin = pairs_time_begin_end[0][0]
    prev_end = pairs_time_begin_end[0][1]
    for begin, end in pairs_time_begin_end[1:]:
        if begin == prev_end:
            prev_end = end
            continue
        ret.append((prev_begin, prev_end))
        prev_begin = begin
        prev_end = end
    ret.append((prev_begin, prev_end))
    return ret


def time_night_split(time_begin: int, time_end: int) -> list[tuple[int, int, bool]]:
    """
    split at 09:00 and 18:00

    >>> time_night_split(str_to_minutes('08:30'), str_to_minutes('24:00') + str_to_minutes('21:00'))
    [(510, 540, True), (540, 1080, False), (1080, 1980, True), (1980, 2520, False), (2520, 2700, True)]

    >>> time_night_split(str_to_minutes('23:00'), str_to_minutes('24:00') + str_to_minutes('09:10'))
    [(1380, 1980, True), (1980, 1990, False)]

    :return: [(begin, end, is night)]
    """
    i = 0
    ret = []
    prev_begin = time_begin
    while True:
        if time_end < M1440 * i:
            break

        time = M1440 * i + str_to_minutes('09:00')
        if time_begin < time < time_end:
            ret.append((prev_begin, time, True))
            prev_begin = time

        time = M1440 * i + str_to_minutes('18:00')
        if time_begin < time < time_end:
            ret.append((prev_begin, time, False))
            prev_begin = time

        i += 1

    if str_to_minutes('09:00') <= prev_begin % M1440 < str_to_minutes('18:00'):
        ret.append((prev_begin, time_end, False))
    else:
        ret.append((prev_begin, time_end, True))

    return ret


# -----------------------------------------------------------------------------
# FeeCalculator

class FeeCalculator:
    def __init__(self, time_end_max: int):
        self.time_end_max = time_end_max
        self.time_end_max_i = time_end_max // M10
        self._fees_no_night_pack = self._fees_no_night_pack_init()
        self._fees = self._fees_init()

    def fee(self, type_: Type, time_begin: int, time_end: int) -> int:
        return self._fees[(type_, time_begin, time_end)]

    def fee_i(self, type_: Type, time_begin_i: int, time_end_i: int) -> int:
        return self.fee(type_, time_begin_i * M10, time_end_i * M10)

    @staticmethod
    def load_cache(cache_path: str) -> 'FeeCalculator':
        ret = FeeCalculator(0)
        with open(cache_path) as f:
            assert f.readline() == 'type time_begin time_end fee\n'
            for line in f.readlines():
                type_, time_begin, time_end, fee = line.removesuffix('\n').split()
                time_begin, time_end = map(str_to_minutes, (time_begin, time_end))
                fee = int(fee)
                ret._fees[(type_, time_begin, time_end)] = fee
                ret.time_end_max = max(ret.time_end_max, time_end)
        ret.time_end_max_i = ret.time_end_max // M10
        return ret

    def save_cache(self):
        with open(CACHE_PATH, 'w') as f:
            f.write('type time_begin time_end fee\n')
            for type_ in Type.__args__:
                for time_begin, time_end in itertools.product(range(0, TIME_END_MAX + M10, M10), repeat=2):
                    if time_end < time_begin:
                        continue
                    f.write(f'{type_} {minutes_to_str(time_begin)} {minutes_to_str(time_end)} {self.fee(type_, time_begin, time_end)}\n')

    @staticmethod
    def _fees_no_night_pack_init() -> dict[tuple[Type, int], int]:
        ret = {}
        for type_ in Type.__args__:
            type_: Type
            for min_ in range(M1440, 0 - M10, -M10):
                if min_ == M1440:
                    ret[(type_, min_)] = FEES1440[type_]
                    continue
                min_rest = min_
                fee_ = 0
                if min_rest >= M720:
                    fee_ += FEES720[type_]
                    min_rest -= M720
                if min_rest >= M360:
                    fee_ += FEES360[type_]
                    min_rest -= M360
                fee_ += FEES10[type_] * (min_rest // M10)
                ret[(type_, min_)] = min(fee_, ret[(type_, min_ + M10)])
        return ret

    def _fees_init(self) -> dict[tuple[Type, int, int], int]:
        ret = {}
        for type_ in Type.__args__:
            logger.debug(f'initializing {type_}...')
            type: Type
            for time_begin, time_end in itertools.product(range(0, self.time_end_max + M10, M10), repeat=2):
                if time_end < time_begin:
                    continue
                ret[type_, time_begin, time_end] = self._fee_with_night_pack(type_, time_begin, time_end)
        return ret

    def _fee_with_night_pack(self, type_: Type, time_begin: int, time_end: int) -> int:
        fee_per_night = FEES_NIGHT[type_]
        if fee_per_night is None:
            return self._fee_no_night_pack(type_, time_end - time_begin)

        ret = math.inf

        tuples_begin_end_is_night: list[tuple[int, int, bool]] = time_night_split(time_begin, time_end)
        night_tuples_begin_end: list[tuple[int, int]] = [(x[0], x[1]) for x in tuples_begin_end_is_night if x[2]]

        list_tuples_night_apply: list[tuple[tuple[int, int]], ...] = []  # TODO: list[list[tuple[int, int]]]
        for n_apply in range(len(night_tuples_begin_end) + 1):
            list_tuples_night_apply += itertools.combinations(night_tuples_begin_end, n_apply)

        for tuples_night_apply in list_tuples_night_apply:
            fee_ = fee_per_night * len(tuples_night_apply)
            if fee_ > ret:
                continue
            tuples_begin_end_no_night = [(x[0], x[1]) for x in tuples_begin_end_is_night if (x[0], x[1]) not in tuples_night_apply]
            fee_ += sum(self._fee_no_night_pack(type_, x[1] - x[0]) for x in times_concat(tuples_begin_end_no_night))
            ret = min(ret, fee_)

        return ret

    def _fee_no_night_pack(self, type_: Type, min_: int) -> int:
        return self._fees_no_night_pack[(type_, M1440)] * (min_ // M1440) + self._fees_no_night_pack[(type_, min_ % M1440)]


# -----------------------------------------------------------------------------
# plot

plt.rcParams['font.size'] = 18


def minutes_to_tick_label(minutes: int) -> str:
    if minutes <= M1440:
        return f'{minutes // M60:02}:{minutes % M60:02}'
    minutes -= M1440
    assert minutes <= M1440
    return f'next {minutes // M60:02}:{minutes % M60:02}'


def plot_lines(fc: FeeCalculator, type_: Type):
    cmap = plt.get_cmap("tab10")

    fig, ax1 = plt.subplots(1, 1, figsize=[12, 10])
    fig: matplotlib.figure.Figure
    ax1: t.Union[plt.Axes, plt.Subplot]  # type(ax1): matplotlib.axes._subplots.AxesSubplot

    ax1.set_title(f'careco {type_}')
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Fee (yen)')
    ax1.grid(True, which='major', axis='both')
    ax1.grid(True, which='minor', axis='both', color='lightgray', linestyle='--', linewidth=0.5)
    ax1.tick_params(axis='both', which='both', direction='in')

    # https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
    # line_styles = ['-', '--', '-.', ':', (0, (3, 1, 1, 1)), (0, (3, 1, 1, 1, 1))]
    line_styles = ['-', '--', ':']
    plot_interval_i = 1 * M60 // M10  # 1h
    for time_begin_i in range(M1440i):
        if time_begin_i % plot_interval_i != 0:
            continue
        times = [x * M10 for x in range(time_begin_i, fc.time_end_max_i + 1)]
        fees = [fc.fee(type_, time_begin_i * M10, x) for x in times]

        i_color, i_linestyle = divmod(time_begin_i // plot_interval_i, len(line_styles))
        i_color %= cmap.N

        # n_colors = 6  # cmap.N: 10 is too much
        # i_linestyle, i_color = divmod(i, n_colors)
        # i_linestyle %= len(line_styles)

        ax1.plot(times, fees, linestyle=line_styles[i_linestyle], color=cmap(i_color))  # '.-', label='09:00-'

    major_tick_interval_i = 3 * M60 // M10  # 3h
    minor_tick_interval_i = 1 * M60 // M10  # 1h

    ax1.set_xlim(0, fc.time_end_max)
    x_ticks_major = [x * M10 for x in range(fc.time_end_max_i + 1) if x % major_tick_interval_i == 0]
    x_ticks_minor = [x * M10 for x in range(fc.time_end_max_i + 1) if x % minor_tick_interval_i == 0]
    x_tick_labels = [minutes_to_tick_label(x * M10) for x in range(fc.time_end_max_i + 1) if x % major_tick_interval_i == 0]
    ax1.set_xticks(x_ticks_major)
    ax1.set_xticks(x_ticks_minor, minor=True)
    ax1.set_xticklabels(x_tick_labels, rotation=60)

    ax1ty = ax1.twiny()
    ax1ty.tick_params(axis='x', which='both', direction='in')
    ax1ty.set_xlim(0, fc.time_end_max)
    ax1ty.set_xticks(x_ticks_major)
    ax1ty.set_xticks(x_ticks_minor, minor=True)
    ax1ty.set_xticklabels(x_tick_labels, rotation=-60)

    major_tick_interval_yen = 5000
    minor_tick_interval_yen = 1000

    y_max = ((fc.fee(type_, 0, fc.time_end_max) // major_tick_interval_yen) + 1) * major_tick_interval_yen  # 14600 -> 15000
    ax1.set_ylim(0, y_max)
    y_ticks_major = [x for x in range(0, y_max + major_tick_interval_yen, major_tick_interval_yen)]
    y_ticks_minor = [x for x in range(0, y_max + minor_tick_interval_yen, minor_tick_interval_yen)]
    ax1.set_yticks(y_ticks_major)
    ax1.set_yticks(y_ticks_minor, minor=True)

    ax1tx = ax1.twinx()
    ax1tx.tick_params(axis='y', which='both', direction='in')
    ax1tx.set_ylim(0, y_max)
    ax1tx.set_yticks(y_ticks_major)
    ax1tx.set_yticks(y_ticks_minor, minor=True)

    fig.tight_layout()
    fig.show()


def plot_pcolor(fc: FeeCalculator, type_: Type):
    fig, ax1 = plt.subplots(1, 1, figsize=[14, 10])
    fig: matplotlib.figure.Figure
    ax1: t.Union[plt.Axes, plt.Subplot]  # type(ax1): matplotlib.axes._subplots.AxesSubplot

    ax1.set_title(f'careco {type_}')
    ax1.set_xlabel('End time')
    ax1.set_ylabel('Start time')
    ax1.grid(True, which='major', axis='x')
    ax1.grid(True, which='major', axis='y', color='k')
    ax1.grid(True, which='minor', axis='both', color='lightgray', linestyle='--', linewidth=0.5)
    ax1.tick_params(axis='both', which='both', direction='in')

    fees = np.empty((M1440i + 1, fc.time_end_max_i + 1))  # dtype=int: ValueError: cannot convert float NaN to integer
    for time_begin_i in range(M1440i + 1):
        for time_end_i in range(fc.time_end_max_i + 1):
            if time_end_i < time_begin_i:
                fees[time_begin_i, time_end_i] = np.nan
                continue
            fees[time_begin_i, time_end_i] = fc.fee_i(type_, time_begin_i, time_end_i)

    # qcs = ax1.contourf(fees)
    # qcs: matplotlib.contour.QuadContourSet
    # qm = ax1.pcolormesh(fees)
    # qm: matplotlib.collections.QuadMesh
    # pc = ax1.pcolor(fees)
    pc = ax1.pcolorfast(fees)
    pc: matplotlib.collections.PolyCollection
    # pc.set_clim(0, 50000)
    # without pad=0.1 (i.e. using default pad=0.05): overlaps with twinx
    fig.colorbar(pc, ax=ax1, pad=0.1)

    major_tick_interval_i = 3 * M60 // M10  # 3h
    minor_tick_interval_i = 1 * M60 // M10  # 1h

    ax1.set_xlim(0, fc.time_end_max_i)
    x_ticks_major = [x for x in range(fc.time_end_max_i + 1) if x % major_tick_interval_i == 0]
    x_ticks_minor = [x for x in range(fc.time_end_max_i + 1) if x % minor_tick_interval_i == 0]
    x_tick_labels = [minutes_to_tick_label(x * M10) for x in range(fc.time_end_max_i + 1) if x % major_tick_interval_i == 0]
    ax1.set_xticks(x_ticks_major)
    ax1.set_xticks(x_ticks_minor, minor=True)
    ax1.set_xticklabels(x_tick_labels, rotation=60)

    ax1ty = ax1.twiny()
    ax1ty.tick_params(axis='x', which='both', direction='in')
    ax1ty.set_xticks(x_ticks_major)
    ax1ty.set_xticks(x_ticks_minor, minor=True)
    ax1ty.set_xticklabels(x_tick_labels, rotation=-60)

    ax1.set_ylim(0, M1440i)
    y_ticks_major = [x for x in range(M1440i + 1) if x % major_tick_interval_i == 0]
    y_ticks_minor = [x for x in range(M1440i + 1) if x % minor_tick_interval_i == 0]
    y_tick_labels = [minutes_to_tick_label(x * M10) for x in range(M1440i + 1) if x % major_tick_interval_i == 0]
    ax1.set_yticks(y_ticks_major)
    ax1.set_yticks(y_ticks_minor, minor=True)
    ax1.set_yticklabels(y_tick_labels, rotation=0)

    ax1tx = ax1.twinx()
    ax1tx.tick_params(axis='y', which='both', direction='in')
    ax1tx.set_yticks(y_ticks_major)
    ax1tx.set_yticks(y_ticks_minor, minor=True)
    ax1tx.set_yticklabels(y_tick_labels, rotation=0)

    fig.tight_layout()
    fig.show()

    return

    # imshow: y軸が逆になる

    fig, ax1 = plt.subplots(1, 1, figsize=[14, 10])
    fig: matplotlib.figure.Figure
    ax1: t.Union[plt.Axes, plt.Subplot]  # type(ax1): matplotlib.axes._subplots.AxesSubplot

    fees = np.empty((M1440i + 1, fc.time_end_max_i + 1))  # dtype=int: ValueError: cannot convert float NaN to integer
    for time_begin_i in range(M1440i + 1):
        for time_end_i in range(fc.time_end_max_i + 1):
            if time_end_i < time_begin_i:
                fees[time_begin_i, time_end_i] = np.nan
                continue
            fees[time_begin_i, time_end_i] = fc.fee_i(type_, time_begin_i, time_end_i)
    ai = ax1.imshow(fees)
    ai: matplotlib.image.AxesImage


# -----------------------------------------------------------------------------
# main

def print_fee_table(fc: FeeCalculator, type_: Type):
    # too long...
    return

    print('\n\n\n')
    end_interval = M60  # 1h

    n_ends = M1440 // M60
    end_times = [f'返却:{minutes_to_tick_label(x * end_interval)}' for x in range(n_ends)]
    print(f'|利用開始時間|{"|".join(end_times)}|')
    print('|---' + '|---' * n_ends + '|')
    for time_begin_i in range(M1440i):
        print(f'|{minutes_to_tick_label(time_begin_i * M10)}', end='')
        for time_end_i in range(M1440i):
            if time_end_i * M10 % end_interval != 0:
                continue
            if time_end_i <= time_begin_i:
                print(f'|', end='')
                continue
            print(f'|{fc.fee_i(type_, time_begin_i, time_end_i)}', end='')
        print('|')

    print('\n\n')

    n_ends = ((fc.time_end_max - M1440) // end_interval) + 1  # XXX: + 1 is unsafe if fc.time_end_max % M60 != 0
    end_times = [f'返却:翌{minutes_to_tick_label(x * end_interval)}' for x in range(n_ends)]
    print(f'|利用開始時間|{"|".join(end_times)}|')
    print('|---' + '|---' * n_ends + '|')
    for time_begin_i in range(M1440i):
        print(f'|{minutes_to_tick_label(time_begin_i * M10)}', end='')
        for time_end_i in range(M1440i, fc.time_end_max_i + 1):
            if time_end_i * M10 % end_interval != 0:
                continue
            if time_end_i <= time_begin_i:
                print(f'|', end='')
                continue
            print(f'|{fc.fee_i(type_, time_begin_i, time_end_i)}', end='')
        print('|')

    breakp = 1


if __name__ == '__main__':
    TIME_END_MAX = M1440 * 2  # 48:00

    if LOAD_CACHE:
        fc = FeeCalculator.load_cache(CACHE_PATH)
    else:
        fc = FeeCalculator(time_end_max=TIME_END_MAX)

    # test
    for type_, time_begin, time_end, fee_ in [
        ('middle', '09:00', '09:00', 0),
        ('middle', '09:00', '09:10', 160),
        ('middle', '09:00', '13:10', 4000),
        ('middle', '09:00', '13:20', 4080),
        ('middle', '09:00', '15:00', 4080),
        ('middle', '09:00', '17:40', 6640),
        ('middle', '09:00', '17:50', 6700),
        ('middle', '09:00', '21:00', 6700),
        ('middle', '09:00', '21:10', 6860),
    ]:
        assert fc.fee(type_, str_to_minutes(time_begin), str_to_minutes(time_end)) == fee_
        del type_, time_begin, time_end, fee_

    if SAVE_CACHE:
        fc.save_cache()

    for type_ in Type.__args__:
        print_fee_table(fc, type_)

    for type_ in Type.__args__:
        plot_lines(fc, type_)
    for type_ in Type.__args__:
        plot_pcolor(fc, type_)

    sys.exit(0)