Skip to content

skais_mapper.utils

All utility functions can be imported from here.

Modules:

Name Description
colors

Color module for more beautiful plots.

config

Configuration and runtime utility functions.

helper

Generic helper functions and other stuff.

primes

Functions for checking and computing prime numbers.

Classes:

Name Description
SkaisColorMaps

An assortment of linearly interpolated colormaps based on 4+ colors each.

SkaisColors

An assortment of colors and palettes.

Functions:

Name Description
alias_kw

Decorator for aliasing a keyword argument in a function.

compress_encode

Compress and encode a string for shorter representations.

current_time

Get current time as string.

extract_decode

Decompress and decode a short representation string.

get_run_id

Fetch a run-specific identifier.

next_prime

Next prime strictly larger than n.

set_run_id

Set the run-specific identifier.

SkaisColorMaps

An assortment of linearly interpolated colormaps based on 4+ colors each.

Methods:

Name Description
gen

Generate colormaps.

palette

Return a palette of a colormap with N linearly interpolated color points.

plot_gradients

Plot all color-map gradients.

random

Choose a random color map.

register_all

Register colormaps with matplotlib.

reverse

Reverse the specified colormap.

gen classmethod

gen()

Generate colormaps.

Returns:

Type Description
mpl.colors.LinearSegmentedColormap object

colormap generated from custom list

Source code in skais_mapper/utils/colors.py
271
272
273
274
275
276
277
278
@classmethod
def gen(cls):
    """Generate colormaps.

    Returns:
        (mpl.colors.LinearSegmentedColormap object): colormap generated from custom list
    """
    yield from cls.aslist

palette classmethod

palette(cmap_name: str, N: int)

Return a palette of a colormap with N linearly interpolated color points.

Parameters:

Name Type Description Default
cmap_name str

name of the colormap

required
N int

number of colors in the palette

required
Source code in skais_mapper/utils/colors.py
318
319
320
321
322
323
324
325
326
327
328
329
@classmethod
def palette(cls, cmap_name: str, N: int):
    """Return a palette of a colormap with N linearly interpolated color points.

    Args:
        cmap_name: name of the colormap
        N: number of colors in the palette
    """
    vals = np.linspace(0, 1, N)
    cmap = cls.__dict__[cmap_name]
    rgbas = cmap(vals)
    return [to_hex(rgba, keep_alpha=False) for rgba in rgbas]

plot_gradients classmethod

plot_gradients(savefig: bool = False)

Plot all color-map gradients.

Parameters:

Name Type Description Default
savefig bool

save figure as palettes.png

False
Source code in skais_mapper/utils/colors.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
@classmethod
def plot_gradients(cls, savefig: bool = False):
    """Plot all color-map gradients.

    Args:
        savefig (bool): save figure as palettes.png
    """
    gradient = np.linspace(0, 1, 256)
    gradient = np.vstack((gradient, gradient))
    fig, axes = plt.subplots(nrows=SkaisColorMaps.N)
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
    for ax, cmap in zip(axes, cls.aslist):
        ax.imshow(gradient, aspect="auto", cmap=cmap)
        pos = list(ax.get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3] / 2.0
        fig.text(x_text, y_text, cmap.name, va="center", ha="right", fontsize=10)
    for ax in axes:
        ax.set_axis_off()
    if savefig:
        plt.savefig("palette.png")

random classmethod

random() -> LinearSegmentedColormap

Choose a random color map.

Returns:

Name Type Description
cmap LinearSegmentedColormap

random colormap from custom list

Source code in skais_mapper/utils/colors.py
262
263
264
265
266
267
268
269
@classmethod
def random(cls) -> LinearSegmentedColormap:
    """Choose a random color map.

    Returns:
        cmap: random colormap from custom list
    """
    return random.choice(cls.aslist)

register_all staticmethod

register_all(verbose: bool = False)

Register colormaps with matplotlib.

Parameters:

Name Type Description Default
verbose bool

If True, print information to command line

False
Source code in skais_mapper/utils/colors.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
@staticmethod
def register_all(verbose: bool = False):
    """Register colormaps with matplotlib.

    Args:
        verbose (bool): If True, print information to command line
    """
    for g in SkaisColorMaps.aslist:
        if verbose:
            print(g.name)
        if g.name not in mpl.colormaps:
            mpl.colormaps.register(name=g.name, cmap=g)
        if f"skais_{g.name}" not in mpl.colormaps:
            mpl.colormaps.register(name=f"skais_{g.name}", cmap=g)

reverse classmethod

reverse(
    cmap: Colormap,
    set_bad: str = None,
    set_under: str = None,
    set_over: str = None,
) -> LinearSegmentedColormap

Reverse the specified colormap.

Parameters:

Name Type Description Default
cmap mpl.colors.LinearSegmentedColormap object

colormap to be reversed

required
set_bad str

set colormaps bad values to a different color

None
set_under str

set colormaps under values to a different color

None
set_over str

set colormaps over values to a different color

None

Returns:

Type Description
mpl.colors.LinearSegmentedColormap object

reversed colormap

Source code in skais_mapper/utils/colors.py
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
@classmethod
def reverse(
    cls, cmap: Colormap, set_bad: str = None, set_under: str = None, set_over: str = None
) -> LinearSegmentedColormap:
    """Reverse the specified colormap.

    Args:
        cmap (mpl.colors.LinearSegmentedColormap object): colormap to be reversed
        set_bad (str): set colormaps bad values to a different color
        set_under (str): set colormaps under values to a different color
        set_over (str): set colormaps over values to a different color

    Returns:
        (mpl.colors.LinearSegmentedColormap object): reversed colormap
    """
    reverse = []
    k = []

    for key in cmap._segmentdata:
        k.append(key)

        channel = cmap._segmentdata[key]
        data = []

        for t in channel:
            data.append((1 - t[0], t[2], t[1]))
        reverse.append(sorted(data))

    linear_l = dict(zip(k, reverse))
    rcmap = LinearSegmentedColormap(f"{cmap.name}_r", linear_l)
    if set_bad is not None:
        rcmap.set_bad(set_bad)
    if set_under is not None:
        rcmap.set_over(set_under)
    if set_over is not None:
        rcmap.set_over(set_over)
    return rcmap

SkaisColors

An assortment of colors and palettes.

Methods:

Name Description
cmap_from_color

Create a colormap from a single color.

cmap_from_color classmethod

cmap_from_color(
    color_str: str, secondary_color: str | None = None
) -> LinearSegmentedColormap

Create a colormap from a single color.

Parameters:

Name Type Description Default
color_str str

color string of the class color

required
secondary_color str | None

color into which the color changes in the colormap

None

Returns:

Type Description
mpl.colors.LinearSegmentedColormap object

reversed colormap

Source code in skais_mapper/utils/colors.py
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
@classmethod
def cmap_from_color(
    cls,
    color_str: str,
    secondary_color: str | None = None,
) -> LinearSegmentedColormap:
    """Create a colormap from a single color.

    Args:
        color_str: color string of the class color
        secondary_color: color into which the color changes in the colormap

    Returns:
        (mpl.colors.LinearSegmentedColormap object): reversed colormap
    """
    if color_str in cls.__dict__:
        color = cls.__dict__[color_str]
    else:
        color = color_str
    if secondary_color in cls.__dict__:
        secondary_color = cls.__dict__[secondary_color]
    elif secondary_color is None:
        secondary_color = color_variant(color, shift=125)
    cmap = LinearSegmentedColormap.from_list("Skais" + color_str, [secondary_color, color])
    return cmap

alias_kw

alias_kw(key: str, alias: str) -> Callable

Decorator for aliasing a keyword argument in a function.

Parameters:

Name Type Description Default
key str

Name of keyword argument in function to alias

required
alias str

Alias that can be used for this keyword argument

required
Source code in skais_mapper/utils/helper.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def alias_kw(key: str, alias: str) -> Callable:
    """Decorator for aliasing a keyword argument in a function.

    Args:
        key: Name of keyword argument in function to alias
        alias: Alias that can be used for this keyword argument
    """
    def decorator(func: Callable):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            alias_value = kwargs.get(alias)
            if alias_value:
                kwargs[key] = alias_value
            if alias in kwargs:
                del kwargs[alias]
            result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

compress_encode

compress_encode(string: str) -> str

Compress and encode a string for shorter representations.

Parameters:

Name Type Description Default
string str

String to be encoded.

required
Source code in skais_mapper/utils/helper.py
33
34
35
36
37
38
39
40
41
def compress_encode(string: str) -> str:
    """Compress and encode a string for shorter representations.

    Args:
        string: String to be encoded.
    """
    compressed_data = lzma.compress(string.encode("utf-8"))
    encoded_data = base64.b64encode(compressed_data)
    return encoded_data.decode("utf-8")

current_time

current_time(
    date_only: bool = True,
    as_str: bool = True,
    no_delim: bool = True,
) -> datetime.datetime | str

Get current time as string.

Parameters:

Name Type Description Default
date_only bool

If True, only the date is returned.

True
as_str bool

If True, a string is returned instead of a datetime object.

True
no_delim bool

If a string is returned, remove the standard delimiters.

True
Source code in skais_mapper/utils/helper.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def current_time(
    date_only: bool = True, as_str: bool = True, no_delim: bool = True
) -> datetime.datetime | str:
    """Get current time as string.

    Args:
        date_only: If True, only the date is returned.
        as_str: If True, a string is returned instead of a datetime object.
        no_delim: If a string is returned, remove the standard delimiters.
    """
    t = datetime.datetime.now()
    if date_only:
        t = t.date()
    if as_str:
        t = str(t)
        if no_delim:
            t = t.replace("-", "")
    return t

extract_decode

extract_decode(string: str) -> str

Decompress and decode a short representation string.

Parameters:

Name Type Description Default
string str

Compressed base64 string to be decoded.

required
Source code in skais_mapper/utils/helper.py
44
45
46
47
48
49
50
51
52
def extract_decode(string: str) -> str:
    """Decompress and decode a short representation string.

    Args:
        string: Compressed base64 string to be decoded.
    """
    compressed_data = base64.b64decode(string)
    original_data = lzma.decompress(compressed_data)
    return original_data.decode("utf-8")

get_run_id

get_run_id(length: int = 8) -> str

Fetch a run-specific identifier.

Source code in skais_mapper/utils/config.py
13
14
15
16
17
def get_run_id(
    length: int = 8,
) -> str:
    """Fetch a run-specific identifier."""
    return str(skais_mapper.RUN_UID).replace("-", "")[:length]

next_prime

next_prime(n: int) -> int

Next prime strictly larger than n.

Source code in skais_mapper/utils/primes.py
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
def next_prime(n: int) -> int:
    """Next prime strictly larger than n."""
    if n < 2:
        return 2
    # first odd larger than n
    n = (n + 1) | 1
    if n < 212:
        while True:
            if n in SMALL_PRIMES:
                return n
            n += 2

    # find our position in the sieve rotation via binary search
    x = int(n % 210)
    s = 0
    e = 47
    m = 24
    while m != e:
        if SIEVE_INDICES[m] < x:
            s = m
            m = (s + e + 1) >> 1
        else:
            e = m
            m = (s + e) >> 1

    i = int(n + (SIEVE_INDICES[m] - x))
    # adjust offsets
    offs = SIEVE_OFFSETS[m:] + SIEVE_OFFSETS[:m]
    while True:
        for o in offs:
            if is_prime(i):
                return i
            i += o

set_run_id

set_run_id(run_id: uuid.UUID | str | None = None)

Set the run-specific identifier.

Source code in skais_mapper/utils/config.py
20
21
22
23
24
25
26
def set_run_id(run_id: uuid.UUID | str | None = None):
    """Set the run-specific identifier."""
    if run_id is None:
        run_id = uuid.uuid4()
    if not isinstance(run_id, uuid.UUID):
        run_id = uuid.UUID(run_id)
    skais_mapper.RUN_UID = run_id