# struct vs ctypes:
# Ha az egyes mezőket mindig külön-külön változóként akarom kezelni, akkor a struct célszerű, ha
# együtt egy objektumként, akkor a ctypes. Ha a három számomra fontos adat különböző offszetekkel
# helyezkedhet el, akkor a struct célszerűbb, mert a ctypes-nál mindegyikhez külön egy-egy osztályt
# kell definiálni, amelyekben ráadásul esetleg sok számomra szükségtelen attribútum van.
# id_, = struct.unpack_from('<I', buffer, 0)
# temperature, = struct.unpack_from('<d', buffer, 100)
# active, = struct.unpack_from('<?', buffer, 1000)
# A ctypes nemcsak objektumorientáltabb elérést ad, hanem lehetőséget a buffer közvetlen, másolás
# nélküli kezelésére is.

# numpy: big endian tömb, átmásolni gyorsításhoz?
# pandas: inhomogén táblázatok kezelője.
# mix_3.py: TM-be
# Általános szabály: mikor nem vektorizálható több lépésben sem egy numpy művelet? (-> numba)
# set_dict_comp_1 dict comp

# listcomp_2 mérés gyenge
# search_index: find

exit()
import numpy as np

a = np.arange(12, dtype=np.uint8)
print(a.strides)
print(a)
b = a

a = a.reshape(3, 4)
print(a.strides)
print(a)
#a[0, 0] = 77
#print(b[0])

a = a.T #reshape(4, 3)
#a[0, 0] = 88
#print(b[0])

print(a.strides)
print(a)

exit()

from joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
import time
import atexit

def func(i):
    atexit.register(lambda: print('worker atexit', flush=True))
    print('***', i)
    time.sleep(1)
    if i == 4:
        x = 1 / 0

    time.sleep(4)

try:
    g = Parallel(n_jobs=-1,
                 backend='loky',
                 return_as='generator_unordered')(delayed(func)(i)
                                                  for i in range(5)
                                                 )
    for x in g:
        print('lefutott')
except Exception as e:
    print('KIVÉTEL:', repr(e))
    #get_reusable_executor().shutdown(wait=False, kill_workers=False)

# *** 0
# *** 1
# *** 2
# *** 3
# *** 4
# KIVÉTEL: ZeroDivisionError('division by zero')

# *** 0
# *** 1
# *** 2
# *** 3
# *** 4

# -- 5 mp várakozás, kill_workers=True esetében is
# worker atexit
# worker atexit
# worker atexit
# worker atexit
# worker atexit
# C:\Users\NMI\AppData\Local\Programs\Python\Python311\Lib\site-packages\joblib\parallel.py:1886:
# UserWarning: 5 tasks which were still being processed by the workers have been cancelled.
# You could benefit from adjusting the input task iterator to limit unnecessary computation time.

exit(0)
start = time.perf_counter()
g = Parallel(n_jobs=-1,
             backend='loky',
             return_as='generator')(delayed(func)(p)
                                    for p in params
                                   )
end = time.perf_counter()
t = round(end - start, 3)
print(t)

start = time.perf_counter()
for p in params:
    x = next(g)
end = time.perf_counter()
t = round(end - start, 3)
print(t)

print('------')
start = time.perf_counter()
g = Parallel(n_jobs=-1,
             backend='loky',
             return_as='generator')(delayed(func)(p)
                                    for p in params
                                   )
end = time.perf_counter()
t = round(end - start, 3)
print(t)

start = time.perf_counter()
for p in params:
    x = next(g)
end = time.perf_counter()
t = round(end - start, 3)
print(t)

print('------')

start = time.perf_counter()
g = Parallel(n_jobs=-1,
             backend='loky',
             return_as='generator')(delayed(func)(p)
                                    for p in params
                                   )

lst = list(g)
end = time.perf_counter()
t = round(end - start, 3)
print(t)
exit()
def func_1(param):
    time.sleep(param)

    return param

def func_2(param):
    time.sleep(1)

    return 2 * param

params = (1, 1, 4, 1, 1)

start = time.perf_counter()
g_1 = Parallel(n_jobs=-1, backend='threading', return_as='generator')(delayed(func_1)(p) for p in params)
print(type(g_1))
lst_2 = [func_2(p) for p in g_1]
end = time.perf_counter()
t_2 = round(end - start, 3)
print(lst_2) # [2, 2, 2, 2, 8]
print(t_2)   # 6.018

exit()
from joblib import Parallel, delayed
from joblib.externals.loky import get_reusable_executor
import time

def func(num):
    if num == 4:
        print('INDULOK', num, flush=True)
        time.sleep(1)
        print('DOBOK', num, flush=True)
        raise ValueError('jaj 4')

    print('indulok', num, flush=True)
    time.sleep(3)
    if num == 0:
        raise IndexError('jaj 0')
    time.sleep(2)
    print('vége', num, flush=True)

start = time.perf_counter()
try:
    lst = Parallel(n_jobs=-1, backend='threading')(delayed(func)(i) for i in range(5))
except Exception as e:
    print('kivétel:', e)
    get_reusable_executor().shutdown(wait=True, kill_workers=False)

end = time.perf_counter()
print('eltelt idő:', round(end - start, 3))

# loky:

# indulok 0
# indulok 1
# indulok 2
# indulok 3
# INDULOK 4
# DOBOK 4
# kivétel: jaj 4
# eltelt idő: 1.953

# threading:

# indulok 0
# indulok 1
# indulok 2
# INDULOK 4
# indulok 3
# DOBOK 4
# kivétel: jaj 4
# eltelt idő: 1.015
# >>> vége 0
# vége 1
# vége 2
# vége 3

# indulok 0
# indulok 1
# indulok 3
# indulok 2
# INDULOK 4
# DOBOK 4
# kivétel: jaj 4
# eltelt idő: 1.019
# >>> vége 1
# vége 2
# vége 3

exit()

from multiprocessing import shared_memory
import numpy as np

dtype_ = np.dtype([
    ('id', '<u4'),           # Little Endian unsigned 4 bájtos int; ha előjelest akarunk: '<i4'
    ('dummy_1', 'S4'),       # 4 bájtos bájtsorozat (kitöltő)
    ('temperature', '<f8'),  # Little Endian 8 bájtos float
    ('active', 'u1'),        # 1 bájtos unsigned int
    ('dummy_2', 'S7')        # 2 bájtos bájtsorozat (kitöltő)
], align=False)

size_ = dtype_.itemsize
print(size_) # 24

shm = shared_memory.SharedMemory(create=True, size=size_)

shape = (1,)

buf_data = np.ndarray(shape, dtype=dtype_, buffer=shm.buf)

buf_data = np.frombuffer(
           shm.buf,
           dtype=dtype_,
           count=np.prod(shape)
).reshape(shape, copy=False)

buf_data[0]['id'] = 42
buf_data[0]['temperature'] = 36.5
buf_data[0]['active'] = True

def func(shm_name, shape, dtype):
    shm = shared_memory.SharedMemory(create=False, name=shm_name)

    # Így is lehetne:

    # buf_data = np.frombuffer(
    #            shm.buf,
    #            dtype=dtype,
    #            count=np.prod(shape)
    # ).reshape(shape, copy=False)

    buf_data = np.ndarray(shape, dtype=dtype, buffer=shm.buf)

    buf_data[0]['temperature'] += 1 # melegszik az idő

    del buf_data # ez most nem kötelező, de jó, ha van, ld. shared_memory_1.py...

    shm.close()  # ...mert ezután már nem fogunk véletlenül hozzányúlni a tömbünkhöz

func(shm.name, shape, dtype_)
print(buf_data[0]['temperature'])  # 37.5

del buf_data     # np.ndarray()-nél itt sem kötelező, de szokjunk rá
shm.close()
shm.unlink()

# a = np.ndarray(
#     shape=(100, 200),
#     dtype=np.float64,
#     buffer=shm.buf,
#     offset=128
# )

# a = np.frombuffer(
#     shm.buf,
#     dtype=np.float64,
#     count=100 * 200,
#     offset=128
# ).reshape(100, 200, copy=False)

# strides-t mikor használjuk?

# a = np.ndarray(
#     shape=shape,
#     dtype=dtype,
#     buffer=shm.buf,
#     offset=offset,
#     strides=strides,
#     order=order
# )

data = b'\x01\x00\x02\x00\x03\x00\x04\x00'
data = bytearray(b'\x01\x00\x02\x00\x03\x00\x04\x00')

a = np.frombuffer(data, dtype=np.uint16)

data = bytearray(range(10))
view = memoryview(data)
a = np.frombuffer(view, dtype=np.uint8)
print(a)

# Hol fordulhat elő?

# Tegyük fel, hogy egy bináris protokollból kaptunk 1 MB adatot:

# packet = receive_packet()
# a = np.frombuffer(packet, dtype=np.float32)

# Nem kell:

# list(packet)

# majd ebből numpy tömböt építeni.

# Ez különösen akkor érdekes, amikor:

# szenzoradat,
# képadat,
# audioadat,
# bináris hálózati protokoll,
# saját bináris fájlformátum

# van.


#---

# import mmap
# import numpy as np
#
# with open("data.bin", "r+b") as f:
#
#     mm = mmap.mmap(f.fileno(), 0)
#
#     a = np.ndarray(
#         shape=(1000, 1000),
#         dtype=np.float64,
#         buffer=mm
#     )
#
#     print(a[100, 200])
#
#     mm.close()

#---

# Egy teljes, hibakezeléses példa!
# Mi van, ha egy másik processzben száll el?
exit()

# raise from
# Mit nem lehet több lépésben sem vektorizálni?
