コード例 #1
0
def loadMultiFrequencyFiles(currentPatient, freqAxis, isExample):

    #load mat files for multi frequency recon
    matFileBase = currentPatient.mfr
    if isExample:
        matFileBase = 'exampleData/freqReconstructions/' + matFileBase
    else:
        matFileBase = 'matFilesIntermediate/' + matFileBase

    sampleFile = matFileBase + '_f' + str(1) + '.mat'
    array = loadmat(sampleFile)['bb']
    array = np.squeeze(np.cdouble(array))
    arrayShape = array.shape
    nx = arrayShape[0]
    ny = arrayShape[1]
    ntime = arrayShape[2]
    nmet = arrayShape[3]
    nf = len(freqAxis)

    #for storing abs images
    mfr = np.zeros((nx, ny, ntime, nmet, nf), dtype=np.cdouble)

    #for storing complex images
    if currentPatient.multichannel:
        ncoils = arrayShape[4]
        mfrc = np.zeros((nx, ny, ntime, nmet, ncoils, nf), dtype=np.cdouble)
    else:
        mfrc = np.zeros((nx, ny, ntime, nmet, nf), dtype=np.cdouble)

    print("image array shape")
    print(mfr.shape)

    for f in range(len(freqAxis)):

        #print('on frequency '+str(f+1)+' of ' + str(len(freqAxis)))
        currentFile = matFileBase + '_f' + str(f + 1) + '.mat'
        if currentPatient.multichannel:
            pixelArrayComplex = loadmat(currentFile)['bb']
            pixelArrayComplex = np.squeeze(np.cdouble(pixelArrayComplex))
            mfrc[:, :, :, :, :, f] = pixelArrayComplex

            # do the SOS here in the magnitude channel
            for coil in range(ncoils):
                if coil in channelList:
                    mfr[:, :, :, :, f] = mfr[:, :, :, :, f] + np.abs(
                        pixelArrayComplex[:, :, :, :, coil])
            mfr[:, :, :, :, f] = np.sqrt(mfr[:, :, :, :, f] / len(channelList))

        else:
            #pixelArray = loadmat(currentFile)['bbabs']
            pixelArrayComplex = loadmat(currentFile)['bb']
            #mfr[:,:,:,:,f] = pixelArray
            mfr[:, :, :, :, f] = pixelArrayComplex
            mfrc[:, :, :, :, f] = pixelArrayComplex
    return mfr, mfrc
コード例 #2
0
ファイル: test_umath.py プロジェクト: jarrodmillman/numpy
 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)
コード例 #3
0
 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)
コード例 #4
0
def ExpectationValue(fsoperarray_, fockspace_, mat_idx_, evec_):
    ans = np.cdouble(0.e0 + 0.e0j)
    for fsoper in fsoperarray_:
        for isnum in fockspace_:
            ifsstate = copy.deepcopy(fockspace_[isnum])
            i = mat_idx_[isnum]
            factor = fsoper.act_on(ifsstate)
            if not ifsstate.isZero:
                jsnum = ifsstate.fock_state_number()
                j = mat_idx_[jsnum]
                mat_elem = factor * fsoper.coeff * np.conj(evec_[j]) * evec_[i]
                if fsoper.hermitian:
                    mat_elem += np.conj(mat_elem)
                ans += mat_elem
            del ifsstate
    return ans
コード例 #5
0
 def __init__(self, M, d=np.sqrt(2)):
     """
     @parameters:
     - M: integer, number of constellations. Should be a power of 2
     - d: coordinate distance between adjacent constellations
     """
     assert (M != 0) and (M & (M - 1) == 0)  # M must be a power of 2
     self.M = M
     self.name = 'QAM'
     n = int(np.sqrt(M))
     self.n = n
     self.constellations = np.zeros((n, n), dtype=np.cdouble)
     self.symbols = []
     for p, q in itertools.product(np.arange(n), np.arange(n)):
         self.constellations[p][q] = np.cdouble(
             complex((-n / 2 + 0.5) + p, (-n / 2 + 0.5) + q))
         self.constellations[p][q] *= d
     self.symbols = np.reshape(self.constellations, -1)
コード例 #6
0
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
コード例 #7
0
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}
コード例 #8
0
ファイル: scalars.py プロジェクト: nanbo99/numpy
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()

np.bool_().tolist()
コード例 #9
0
ファイル: scalars.py プロジェクト: wuye0109/numpy
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._
コード例 #10
0
ファイル: conftest.py プロジェクト: BQSKit/bqskit
 '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': [],
 'seq-int_2': [0],
コード例 #11
0
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
コード例 #12
0
ファイル: test_dtypes.py プロジェクト: ayulockin/client
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]]]]))
コード例 #13
0
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)
np.float64(valor) 			# Flotante de precisión doble (signo de 1 bit, exponente de 11 bits, mantisa de 52 bits)
コード例 #14
0
ファイル: main.py プロジェクト: AMC-dyn/PyMCE

qin, pin = Wigner_dist.WignerSampling()

# As I am doing everything mass-weighted, also applied to the widths

dt = dyn.dt
tr = Traj.traj()

# tr.n = 1
tr.iprop = 0

tr.q = qin
tr.p = pin
tr.d = np.zeros(dyn.nstates, dtype=np.cdouble)
tr.d[dyn.inipes - 1] = np.cdouble(1)
tr.s = np.zeros(dyn.nstates)
tr.a = tr.d * np.exp(1j * tr.s)

with open('initialqp.dat', 'r') as f:
    f.readline()
    for i in range(geo.ndf):
        N, M = f.readline().strip().split()
        tr.q[i] = np.double(float(N.replace('D', 'E')))
        tr.p[i] = np.double(float(M.replace('D', 'E')))
#     f.readline()
#     f.readline()
#     idf=0
#     for i in range(geo.natoms):
#         for j in range(3):
#             N = f.readline().strip().split()
コード例 #15
0
    def __init__(self, file_name, wls=None, nk=None, eps=None):
        r"""
        Parameters:

        file_name:
            1. complex value, written in numpy format or as string;
            2. one of the predefined strings (air, water, glass);
            3. filename with optical constants.

            File header should state `lambda`, `n` and `k` columns
            If either `nk= n + 1j*k` or `eps = re + 1j*im` arrays are
            specified, then the data from one of them will be used
            and filename content will be ignored.

        wls: float array
            array of wavelengths (in nm) used for data interpolation.
            If None then ``np.linspace(300, 800, 500)`` will be used.

        """
        if isinstance(file_name, str):
            self.__name__ = 'Mat_%s' % os.path.basename(file_name)
        else:
            self.__name__ = 'Mat_%.3f' % file_name

        if wls is None:
            wl_min = 200  # 149.9
            wl_max = 1200  # 950.1
            wls = np.array([wl_min, wl_max])
        k = np.array([0.0, 0.0])
        if nk is not None:
            n = np.real(nk)
            k = np.imag(nk)
        elif eps is not None:
            mod = np.absolute(eps)
            n = np.sqrt((mod + np.real(eps)) / 2)
            k = np.sqrt((mod - np.real(eps)) / 2)
        else:
            try:
                np.cdouble(file_name)
                is_complex = True
            except ValueError:
                is_complex = False
            if is_complex:
                nk = np.cdouble(file_name)
                n = np.array([np.real(nk), np.real(nk)])
                k = np.array([np.imag(nk), np.imag(nk)])
            else:
                if file_name.lower() == 'air':
                    n = np.array([1.0, 1.0])
                elif file_name.lower() == 'water':
                    n = np.array([1.33, 1.33])
                elif file_name.lower() == 'glass':
                    n = np.array([1.66, 1.66])
                else:
                    optical_constants = np.genfromtxt(file_name, names=True)
                    wls = optical_constants['lambda']
                    if np.max(wls) < 100:  # wavelengths are in micrometers
                        wls = wls * 1000  # convert to nm
                    n = optical_constants['n']
                    k = optical_constants['k']
                    if wls[0] > wls[1]:  # form bigger to smaller
                        wls = np.flipud(wls)  # reverse order
                        n = np.flipud(n)
                        k = np.flipud(k)
                    n = n[wls > wl_min]
                    k = k[wls > wl_min]
                    wls = wls[wls > wl_min]
                    n = n[wls < wl_max]
                    k = k[wls < wl_max]
                    wls = wls[wls < wl_max]
        wl_step = np.abs(wls[1] - wls[0])
        if (wl_step > 1.1) and (wl_step < 500):
            interp_kind = 'cubic'  # cubic interpolation
        else:  # too dense or too sparse mesh, linear interpolation is needed
            interp_kind = 'linear'
        # print('Interpolation kind : %s'%interp_kind)
        self._get_n_interp = interpolate.interp1d(wls, n, kind=interp_kind)
        self._get_k_interp = interpolate.interp1d(wls, k, kind=interp_kind)
コード例 #16
0
print("Create tensor operations for actual tensor construction")
create_tensor0 = op_factory.createTensorOpShared(exatn.TensorOpCode.CREATE)
create_tensor0.setTensorOperand(tensor0)

create_tensor1 = op_factory.createTensorOpShared(exatn.TensorOpCode.CREATE)
create_tensor1.setTensorOperand(tensor1)

create_tensor2 = op_factory.createTensorOpShared(exatn.TensorOpCode.CREATE)
create_tensor2.setTensorOperand(tensor2)

print("Create tensor operation for contracting tensors")
contract_tensors = op_factory.createTensorOpShared(exatn.TensorOpCode.CONTRACT)
contract_tensors.setTensorOperand(tensor0)
contract_tensors.setTensorOperand(tensor1)
contract_tensors.setTensorOperand(tensor2)
contract_tensors.setScalar(0, np.cdouble(0.5j + 0))
contract_tensors.setIndexPattern("D(a,b,c,d)+=L(c,a,k,l)*R(d,l,k,b)")

destroy_tensor2 = op_factory.createTensorOpShared(exatn.TensorOpCode.DESTROY)
destroy_tensor2.setTensorOperand(tensor2)

destroy_tensor1 = op_factory.createTensorOpShared(exatn.TensorOpCode.DESTROY)
destroy_tensor1.setTensorOperand(tensor1)

destroy_tensor0 = op_factory.createTensorOpShared(exatn.TensorOpCode.DESTROY)
destroy_tensor0.setTensorOperand(tensor0)

numserver = exatn.getNumServer()
numserver.submit(create_tensor0)
numserver.submit(create_tensor1)
numserver.submit(create_tensor2)