def test_precisions_consistent(self): z = 1 + 1j for f in self.funcs: fcf = f(np.csingle(z)) fcd = f(np.cdouble(z)) fcl = f(np.clongdouble(z)) assert_almost_equal(fcf, fcd, decimal=6, err_msg="fch-fcd %s" % f) assert_almost_equal(fcl, fcd, decimal=15, err_msg="fch-fcl %s" % f)
def test_precisions_consistent(self): z = 1 + 1j for f in self.funcs: fcf = f(np.csingle(z)) fcd = f(np.cdouble(z)) fcl = f(np.clongdouble(z)) assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s' % f) assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s' % f)
def estimate(in_data, pilots=0): """ Estimate channel effects by some cool properties. Since the effects of the channel medium is a convolution of the transmitted signal, we can abuse this for some easy math. We take the time domain input signal and turn that into a frequency domain signal. If we had a perfect channel, this frequency domain signal would exactly equal the signal transmitted. But it doesn't. However, we are in the frequency domain, which means convolution turns into multiplication, and to find the effect of the channel on each subcarrier, we can simply use division. Unfortunately, we don't know what the original data was, so we use "pilot" subchannels, which transmit known information. We can use this to get estimates for each of the pilot carriers, and finally, we can interpolate these values to get an estimate for everything. There are a few issues with this method: 1: It is very estimate-ey. We have to interpolate from a subset of the carriers. 2: It is quite inefficient. We are sending useless information on every symbol. I think a better solution is to send a known symbol (or a set of known symbols) at the beginnning of each transmission instead. This means we get a full channel estimate every time. This also has the advantage of being able to synchronise the symbols. Since I will be implementing some sort of protocol anyways, I think this will be a good idea. As well, we move slow enough that the channel will not likely change significantly over a single packet. Actually maybe not? Looked at a paper, check the drive. """ carrier_symbol = in_data[0] H_est = 0 H = np.ndarray((len(carrier_symbol)), dtype=np.csingle) # Obtain estimate for each sub carrier for i in range(len(carrier_symbol)): H[i] = carrier_symbol[i] / np.csingle(1 + 1j) print(H) # Exact channel response H_exact = np.fft.fft(channel_response, 64) plt.plot(range(64), np.real(H), "b-") plt.plot(range(64), np.real(H_exact), "r") plt.show(block=True) plt.plot(range(64), np.imag(H), "b-") plt.plot(range(64), np.imag(H_exact), "r") plt.show(block=True) return H
def test_GerchbergSaxton(self): n = 10 lamda = 0.1 A, x_numpy, y = self.Ax_y_setup(n, lamda) y = np.expand_dims(np.csingle(y), 1) x_numpy = np.expand_dims(x_numpy, 1) A = np.csingle(A) A = linop.MatMul(y.shape, A) x0 = np.zeros(A.ishape, dtype=np.complex) alg_method = alg.GerchbergSaxton(A, y, x0, max_iter=100, tol=10E-9, lamb=lamda) while (not alg_method.done()): alg_method.update() phs = np.conj(x_numpy * alg_method.x / abs(x_numpy * alg_method.x)) npt.assert_allclose(alg_method.x * phs, x_numpy, rtol=1e-6)
def function(X, A): D = X * A #11. Create a complex number Z with absolute and real parts != 0 Z = np.csingle(73 + 142.14132j) #12. Show its real and imaginary parts as well as it’s absolute value print(Z.real) print(Z.imag) print(np.absolute(Z)) #13. Muliply result D with the absolute value of Z and record it to C C = D * np.absolute(Z)
def test_np_sanitization(): class CustomParamsLogger(CustomLogger): def __init__(self): super().__init__() self.logged_params = None @rank_zero_only def log_hyperparams(self, params): params = self._convert_params(params) params = self._sanitize_params(params) self.logged_params = params logger = CustomParamsLogger() np_params = { "np.bool_": np.bool_(1), "np.byte": np.byte(2), "np.intc": np.intc(3), "np.int_": np.int_(4), "np.longlong": np.longlong(5), "np.single": np.single(6.0), "np.double": np.double(8.9), "np.csingle": np.csingle(7 + 2j), "np.cdouble": np.cdouble(9 + 4j), } sanitized_params = { "np.bool_": True, "np.byte": 2, "np.intc": 3, "np.int_": 4, "np.longlong": 5, "np.single": 6.0, "np.double": 8.9, "np.csingle": "(7+2j)", "np.cdouble": "(9+4j)", } logger.log_hyperparams(Namespace(**np_params)) assert logger.logged_params == sanitized_params
def __init__(self): NT = namedtuple('NT', tuple('abc')) self.values = [ np.longlong(-1), np.int_(-1), np.intc(-1), np.short(-1), np.byte(-1), np.ubyte(1), np.ushort(1), np.uintc(1), np.uint(1), np.ulonglong(1), np.half(1.0), np.single(1.0), np.float_(1.0), np.longfloat(1.0), np.csingle(1.0j), np.complex_(1.0j), np.clongfloat(1.0j), np.bool_(0), np.str_('1'), np.unicode_('1'), np.void(1), np.object(), np.datetime64('NaT'), np.timedelta64('NaT'), np.nan, 12, 12.0, True, None, float('NaN'), object(), (1, 2, 3), NT(1, 2, 3), datetime.date(2020, 12, 31), datetime.timedelta(14), ] # Datetime & Timedelta for precision in ['ns', 'us', 'ms', 's', 'm', 'h', 'D', 'M', 'Y']: for kind, ctor in (('m', np.timedelta64), ('M', np.datetime64)): self.values.append(ctor(12, precision)) for size in (1, 8, 16, 32, 64, 128, 256, 512): self.values.append(bytes(size)) self.values.append('x' * size)
def sort_mode_shapes(u_unsorted, grids, grids_order): # this function sorts a displacement field according # to a user-specified grid order # this function can be also used to extract a set of # ids from the total imported displacement field # allocation u_sorted = np.csingle([np.zeros([3,len(grids_order)],dtype=np.complex) \ for i in range(len(u_unsorted))]) # loop over the number of fields (e.g. mode shapes) for j in range(len(u_unsorted)): # loop over the grid ids in the desired order for i, grid in enumerate(grids_order): # finding position of current grid index = int(np.where(grids == int(grid))[0]) # saving displacements u_sorted[j][:, i] = u_unsorted[j][:, index] return u_sorted
np.ubyte() np.ushort() np.uintc() np.uintp() np.uint0() np.uint() np.ulonglong() np.half() np.single() np.double() np.float_() np.longdouble() np.longfloat() np.csingle() np.singlecomplex() np.cdouble() np.complex_() np.cfloat() np.clongdouble() np.clongfloat() np.longcomplex() np.bool_().item() np.int_().item() np.uint64().item() np.float32().item() np.complex128().item() np.str_().item() np.bytes_().item()
reveal_type(np.short()) # E: numpy.signedinteger[numpy.typing._ reveal_type(np.intc()) # E: numpy.signedinteger[numpy.typing._ reveal_type(np.intp()) # E: numpy.signedinteger[numpy.typing._ reveal_type(np.int0()) # E: numpy.signedinteger[numpy.typing._ reveal_type(np.int_()) # E: numpy.signedinteger[numpy.typing._ reveal_type(np.longlong()) # E: numpy.signedinteger[numpy.typing._ reveal_type(np.ubyte()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.ushort()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.uintc()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.uintp()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.uint0()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.uint()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.ulonglong()) # E: numpy.unsignedinteger[numpy.typing._ reveal_type(np.half()) # E: numpy.floating[numpy.typing._ reveal_type(np.single()) # E: numpy.floating[numpy.typing._ reveal_type(np.double()) # E: numpy.floating[numpy.typing._ reveal_type(np.float_()) # E: numpy.floating[numpy.typing._ reveal_type(np.longdouble()) # E: numpy.floating[numpy.typing._ reveal_type(np.longfloat()) # E: numpy.floating[numpy.typing._ reveal_type(np.csingle()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.singlecomplex()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.cdouble()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.complex_()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.cfloat()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.clongdouble()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.clongfloat()) # E: numpy.complexfloating[numpy.typing._ reveal_type(np.longcomplex()) # E: numpy.complexfloating[numpy.typing._
'float_4': 1.26738e14, 'float_5': 1.23, 'float_6': np.half(1234.0), 'float_7': np.single(1234.0), 'float_8': np.double(1234.0), 'float_9': np.longdouble(1234.0), 'float_10': np.float32(1234.0), 'float_11': np.float64(1234.0), # Needs typeshed sync 'complex_1': complex(0.0j), # type: ignore # Needs typeshed sync 'complex_2': complex(0.0 + 0.0j), # type: ignore 'complex_3': 1.0j, 'complex_4': 1.0 + 1.0j, 'complex_5': 1.0 - 1.0j, 'complex_7': np.csingle(1234 + 1234j), 'complex_8': np.cdouble(1234 + 1234j), 'complex_9': np.clongdouble(1234 + 1234j), # needs newer numpy 'complex_10': np.complex64(1234 + 1234j), # type: ignore # needs newer numpy 'complex_11': np.complex128(1234 + 1234j), # type: ignore 'bool_1': False, 'bool_2': True, 'bool_3': np.bool_(False), 'bool_4': np.bool_(True), 'seq-str_1': [], 'seq-str_2': ['0'], 'seq-str_3': ['0, 1', 'abc', '@#!$^%&(#'], 'seq-str_4': ['A'] * 10, 'seq-int_1': [],
def test_table_typing_numpy(): # Pulled from https://numpy.org/devdocs/user/basics.types.html # Numerics table = wandb.Table(columns=["A"], dtype=[NumberType]) table.add_data(None) table.add_data(42) table.add_data(np.byte(1)) table.add_data(np.short(42)) table.add_data(np.ushort(42)) table.add_data(np.intc(42)) table.add_data(np.uintc(42)) table.add_data(np.int_(42)) table.add_data(np.uint(42)) table.add_data(np.longlong(42)) table.add_data(np.ulonglong(42)) table.add_data(np.half(42)) table.add_data(np.float16(42)) table.add_data(np.single(42)) table.add_data(np.double(42)) table.add_data(np.longdouble(42)) table.add_data(np.csingle(42)) table.add_data(np.cdouble(42)) table.add_data(np.clongdouble(42)) table.add_data(np.int8(42)) table.add_data(np.int16(42)) table.add_data(np.int32(42)) table.add_data(np.int64(42)) table.add_data(np.uint8(42)) table.add_data(np.uint16(42)) table.add_data(np.uint32(42)) table.add_data(np.uint64(42)) table.add_data(np.intp(42)) table.add_data(np.uintp(42)) table.add_data(np.float32(42)) table.add_data(np.float64(42)) table.add_data(np.float_(42)) table.add_data(np.complex64(42)) table.add_data(np.complex128(42)) table.add_data(np.complex_(42)) # Booleans table = wandb.Table(columns=["A"], dtype=[BooleanType]) table.add_data(None) table.add_data(True) table.add_data(False) table.add_data(np.bool_(True)) # Array of Numerics table = wandb.Table(columns=["A"], dtype=[[NumberType]]) table.add_data(None) table.add_data([42]) table.add_data(np.array([1, 0], dtype=np.byte)) table.add_data(np.array([42, 42], dtype=np.short)) table.add_data(np.array([42, 42], dtype=np.ushort)) table.add_data(np.array([42, 42], dtype=np.intc)) table.add_data(np.array([42, 42], dtype=np.uintc)) table.add_data(np.array([42, 42], dtype=np.int_)) table.add_data(np.array([42, 42], dtype=np.uint)) table.add_data(np.array([42, 42], dtype=np.longlong)) table.add_data(np.array([42, 42], dtype=np.ulonglong)) table.add_data(np.array([42, 42], dtype=np.half)) table.add_data(np.array([42, 42], dtype=np.float16)) table.add_data(np.array([42, 42], dtype=np.single)) table.add_data(np.array([42, 42], dtype=np.double)) table.add_data(np.array([42, 42], dtype=np.longdouble)) table.add_data(np.array([42, 42], dtype=np.csingle)) table.add_data(np.array([42, 42], dtype=np.cdouble)) table.add_data(np.array([42, 42], dtype=np.clongdouble)) table.add_data(np.array([42, 42], dtype=np.int8)) table.add_data(np.array([42, 42], dtype=np.int16)) table.add_data(np.array([42, 42], dtype=np.int32)) table.add_data(np.array([42, 42], dtype=np.int64)) table.add_data(np.array([42, 42], dtype=np.uint8)) table.add_data(np.array([42, 42], dtype=np.uint16)) table.add_data(np.array([42, 42], dtype=np.uint32)) table.add_data(np.array([42, 42], dtype=np.uint64)) table.add_data(np.array([42, 42], dtype=np.intp)) table.add_data(np.array([42, 42], dtype=np.uintp)) table.add_data(np.array([42, 42], dtype=np.float32)) table.add_data(np.array([42, 42], dtype=np.float64)) table.add_data(np.array([42, 42], dtype=np.float_)) table.add_data(np.array([42, 42], dtype=np.complex64)) table.add_data(np.array([42, 42], dtype=np.complex128)) table.add_data(np.array([42, 42], dtype=np.complex_)) # Array of Booleans table = wandb.Table(columns=["A"], dtype=[[BooleanType]]) table.add_data(None) table.add_data([True]) table.add_data([False]) table.add_data(np.array([True, False], dtype=np.bool_)) # Nested arrays table = wandb.Table(columns=["A"]) table.add_data([[[[1, 2, 3]]]]) table.add_data(np.array([[[[1, 2, 3]]]]))
mode_number.append(int(re.findall("\d+", split_str[0])[0])) freq_gvt.append(float(re.findall("\d+\.\d+", split_str[1])[0])) damp_gvt.append(float(re.findall("\d+\.\d+", split_str[2])[0])) mode_shapes.append([sub['r1'], sub['r2'], sub['r3']]) node_number_eigenvector = sub['node_nums'] # check if the number of sensors providing data is fewer than the number # of sensors defined in geometry; a la some of the sensors were turned off # during the test if len(node_number) != len(node_number_eigenvector): cut_off = range(len(node_number_eigenvector)) else: cut_off = range(len(node_number)) # normalize eigenvector mode_shapes_normalized = np.csingle(mode_shapes) for i in range(len(mode_shapes_normalized)): mode_shapes_normalized[:][:][i] = np.divide(mode_shapes_normalized[:][:][i]\ ,np.max(np.max(np.abs(mode_shapes_normalized[:][:][i])))) # # function to sort node displacements in eigenvector to the same order as # coordinates (or accelerometers) definition def sort_mode_shapes(u_unsorted, grids, grids_order): # this function sorts a displacement field according # to a user-specified grid order # this function can be also used to extract a set of # ids from the total imported displacement field
np.byte(valor) # entero con signo almacenado como un byte (definido por la plataforma) np.ubyte(valor) # entero sin signo almacenado como un byte (definido por la plataforma) np.short(valor) # entero corto con signo (definido por la plataforma) np.ushort(valor) # entero corto sin signo (definido por la plataforma) np.intc(valor) # entero medio con signo (definido por la plataforma) np.uintc(valor) # entero medio sin signo (definido por la plataforma) np.int_(valor) # entero largo con signo (definido por la plataforma) np.uint(valor) # entero largo sin signo (definido por la plataforma) np.longlong(valor) # entero largo largo con signo (definido por la plataforma) np.ulonglong(valor) # entero largo largo sin signo (definido por la plataforma) np.half(valor) # Flotante de precisión media (signo de 1 bit, exponente de 5 bits, mantisa de 10 bits) np.float16(valor) # Flotante de precisión media (signo de 1 bit, exponente de 5 bits, mantisa de 10 bits) np.single(valor) # Flotante de precisión simple (signo de 1 bit, exponente de 8 bits, mantisa de 23 bits) np.double(valor) # Flotante de precisión doble (signo de 1 bit, exponente de 11 bits, mantisa de 52 bits) np.longdouble(valor) # Flotante de precisión extendida (definido por la plataforma) np.csingle(valor) # Número complejo representado por dos flotantes de precisión simple (componente real e imaginario) np.cdouble(valor) # Número complejo representado por dos flotantes de precisión doble (componente real e imaginario) np.clongdouble(valor) # Número complejo representado por dos flotantes de precisión extendida (componente real e imaginario) # Tipos de datos con Alias de tamaño (se convierte el valor al tipo especificado) np.int8(valor) # entero de 1 byte con signo (-128 a 127) np.uint8(valor) # entero de 1 byte sin signo (0 a 255) np.int16(valor) # entero de 2 bytes con signo (-32768 a 32767) np.uint16(valor) # entero de 2 bytes sin signo (0 a 65535) np.int32(valor) # entero de 4 bytes con signo (-2147483648 a 2147483647) np.uint32(valor) # entero de 4 bytes sin signo (0 a 4294967295) np.int64(valor) # entero de 8 bytes con signo (-9223372036854775808 a 9223372036854775807) np.uint64(valor) # entero de 8 bytes sin signo (0 a 18446744073709551615) np.intp(valor) intptr_t # entero utilizado para indexar np.uintp(valor) uintptr_t # entero lo suficientemente grande como para contener un puntero np.float32(valor) # Flotante de precisión simple (signo de 1 bit, exponente de 8 bits, mantisa de 23 bits)
reveal_type(np.short()) # E: {short} reveal_type(np.intc()) # E: {intc} reveal_type(np.intp()) # E: {intp} reveal_type(np.int0()) # E: {intp} reveal_type(np.int_()) # E: {int_} reveal_type(np.longlong()) # E: {longlong} reveal_type(np.ubyte()) # E: {ubyte} reveal_type(np.ushort()) # E: {ushort} reveal_type(np.uintc()) # E: {uintc} reveal_type(np.uintp()) # E: {uintp} reveal_type(np.uint0()) # E: {uintp} reveal_type(np.uint()) # E: {uint} reveal_type(np.ulonglong()) # E: {ulonglong} reveal_type(np.half()) # E: {half} reveal_type(np.single()) # E: {single} reveal_type(np.double()) # E: {double} reveal_type(np.float_()) # E: {double} reveal_type(np.longdouble()) # E: {longdouble} reveal_type(np.longfloat()) # E: {longdouble} reveal_type(np.csingle()) # E: {csingle} reveal_type(np.singlecomplex()) # E: {csingle} reveal_type(np.cdouble()) # E: {cdouble} reveal_type(np.complex_()) # E: {cdouble} reveal_type(np.cfloat()) # E: {cdouble} reveal_type(np.clongdouble()) # E: {clongdouble} reveal_type(np.clongfloat()) # E: {clongdouble} reveal_type(np.longcomplex()) # E: {clongdouble}
class TestNumpy: @staticmethod def test_get_numpy() -> None: """ Test get_numpy when module is present """ # Arrange # Act result = Numpy.get_numpy() # Assert assert result is np @staticmethod def test_get_numpy_missing(mocker: MockFixture) -> None: """ Test get_numpy when module is missing """ # Arrange mocker.patch.dict("sys.modules", {"numpy": None}) # Act result = Numpy.get_numpy() # Assert assert result is None @staticmethod def test_get_numpy_missing_error(mocker: MockFixture) -> None: """ Test get_numpy when module is missing raises error """ # Arrange mocker.patch.dict("sys.modules", {"numpy": None}) # Act / assert with pytest.raises(ImportError, match="foo"): Numpy.get_numpy(raise_error=True, custom_error_message="foo") @staticmethod @pytest.mark.parametrize("value, expected", [(np.array([1, 2, 3]), True), ([1, 2, 3], False)]) def test_is_numpy_object(value, expected) -> None: """ Test is_numpy_object """ # Arrange # Act result = Numpy.is_numpy_object(value) # Assert assert result == expected @staticmethod def test_get_numpy_primatives() -> None: """ Test _get_numpy_primatives """ # Arrange # Act result = Numpy._get_numpy_primatives(np) # Assert assert len(result) == 33 # Expected number of types for thing in result: assert "numpy" in getattr(thing, "__module__", "").split( ".") # Check that type is from numpy assert type(thing) is type # Check that each type is a type @staticmethod def test_encode_numpy_error(): """ Test that the encode_numpy raises an error if no encoding is defined. """ # Arrange value = "not a numpy" # Act & Assert with pytest.raises(NotImplementedError): Numpy.encode_numpy(value) @staticmethod @pytest.mark.parametrize( "value, expected", [ # fmt: off (np.array([['balloons'], ['are'], ['awesome'] ]), [['balloons'], ['are'], ['awesome']]), (np.bool_(1), True), (np.byte(4), 4), (np.ubyte(4), 4), (np.short(4), 4), (np.ushort(4), 4), (np.intc(4), 4), (np.uintc(4), 4), (np.int_(4), 4), (np.uint(4), 4), (np.longlong(4), 4), (np.ulonglong(4), 4), (np.float16(4), 4), (np.single(4), 4), (np.double(4), 4), (np.longdouble(4), 4), (np.csingle(4), 4), (np.cdouble(4), 4), (np.clongdouble(4), 4), (np.int8(4), 4), (np.int16(4), 4), (np.int32(4), 4), (np.int64(4), 4), (np.uint8(4), 4), (np.uint16(4), 4), (np.uint32(4), 4), (np.uint64(4), 4), (np.intp(4), 4), (np.uintp(4), 4), (np.float32(4), 4), (np.float64(4), 4), (np.complex64(4), 4 + 0j), (np.complex128(4), 4 + 0j), (np.complex_(4), 4 + 0j), # fmt: on ], ) def test_encode_numpy(value, expected) -> None: """ Test encode_numpy """ # Arrange # Act result = Numpy.encode_numpy(value) # Assert assert result == expected
while i != regions: E = Earray[i] * Eo U = Uarray[i] * Uo # our Alpha and Beta Values A = (W * np.sqrt(U * E) / np.sqrt(2)) * (np.sqrt(1 + (sigma / (W * E)**2)) - 1)**(1 / 2) B = (W * np.sqrt(U * E) / np.sqrt(2)) * (np.sqrt(1 + (sigma / (W * E)**2)) + 1)**(1 / 2) gamma = np.complex(A, B) #saving each value in an array Barray[i] = B Aarray[i] = A GammaArray[i] = gamma # Our values for N N = np.csingle( ((np.sqrt(U / E) * np.exp(1j * (1 / 2) * np.arctan(sigma / (W * E)))) / (1 + (sigma / (W * E))**(2))**(1 / 4))) print("N ", i, " is equal to =", N) Narray[i] = N i = i + 1 print("Now, let calculate the impedance and reflections") # removing from the top of our incrementor i = i - 1 while i != 0: if i == regions: ZoArray[i] = Narray[i] ZoArray[i - 1] = ZoArray[i] elif i != regions: Loarray[i] = (ZoArray[i] - Narray[i]) / (ZoArray[i] + Narray[i])