Exemple #1
0
def run(autoTester):

    # Real

    r = num.array([[2.12, -2.11, -1.23], [2.31, 1.14, 3.15],
                   [1.13, 1.98, 2.81]])

    autoTester.check('Matrix r', num.round(r, 2).tolist(), '<br>')

    ri = linalg.inv(r)

    autoTester.check('Matrix ri', num.round(ri, 2).tolist(), '<br>')

    __pragma__('opov')
    rid = r @ ri
    __pragma__('noopov')

    autoTester.check('r @ ri', [[int(round(elem)) for elem in row]
                                for row in rid.tolist()], '<br>')

    __pragma__('opov')
    delta = 0.001
    autoTester.check('r * r', num.round(r * r + delta, 3).tolist(), '<br>')
    autoTester.check('r / r', num.round(r / r + delta, 3).tolist(), '<br>')
    autoTester.check('r + r', num.round(r + r + delta, 3).tolist(), '<br>')
    autoTester.check('r - r', num.round(r - r + delta, 3).tolist(), '<br>')
    __pragma__('noopov')

    # Complex

    __pragma__('opov')
    c = num.array([[2.12 - 3.15j, -2.11, -1.23], [2.31, 1.14, 3.15 + 2.75j],
                   [1.13, 1.98 - 4.33j, 2.81]], 'complex128')
    __pragma__('noopov')

    autoTester.check('Matrix c', num.round(c, 2).tolist(), '<br>')

    ci = linalg.inv(c)

    autoTester.check('Matrix ci', num.round(ci, 2).tolist(), '<br>')

    __pragma__('opov')
    cid = c @ ci
    __pragma__('noopov')

    # autoTester.check ('c @ ci', [['{} + j{}'.format (int (round (elem.real)), int (round (elem.imag))) for elem in row] for row in cid.tolist ()], '<br>')

    __pragma__('opov')
    delta = 0.001 + 0.001j
    autoTester.check('c * c', num.round(c * c + delta, 3).tolist(), '<br>')
    autoTester.check('c / c', num.round(c / c + delta, 3).tolist(), '<br>')
    autoTester.check('c + c', num.round(c + c + delta, 3).tolist(), '<br>')
    autoTester.check('c - c', num.round(c - c + delta, 3).tolist(), '<br>')
    __pragma__('noopov')
Exemple #2
0
    def zoom (self, zoomFactor = 40):
        ''' Zoom by shifting image plane
        '''
    
        self.zoomFactor = zoomFactor
        self.zoomShift = 40 / zoomFactor
		self.supVecPlane = ns.array ((0, 0, -zoomShift / 6))
Exemple #3
0
 def func(self, formula,
          x_vec):  # x=linspace(0,10,0.1) -> y=func(2*x+sin(x),x)
     x_vec = x_vec.tolist()
     result = []
     for i in range(len(x_vec)):
         tmp = formula.replace('x', str(x_vec[i]))
         result[i] = eval(tmp)
     return num.array(result, dtype=float)
Exemple #4
0
 def convert_format(self, input_str):
     # interpret as nd Matrix array!
     print(input_str)
     if "[" in input_str:
         input_str = input_str.split("],[")
         for i in range(len(input_str)):
             input_str[i] = input_str[i].replace("[", "")
             input_str[i] = input_str[i].replace("]", "")
             input_str[i] = input_str[i].split(",")
         return (num.array(input_str, dtype=float))
     if input_str.isdigit():
         return float(input_str)
     if "'" in input_str:
         input_str = input_str.replace("'", "")
     return str(input_str)
Exemple #5
0
def run (autoTester):
	a = num.array ([
		[0, -2, -1], 
		[2, 1, 3], 
		[1, 1, 2]
	])
	
	autoTester.check ('Matrix a', a.astype ('int32') .tolist (), '<br>')
	
	ai = linalg.inv (a)
	
	autoTester.check ('Matrix ai', ai.astype ('int32') .tolist (), '<br>')
	
	__pragma__ ('opov')
	id = a @ ai
	__pragma__ ('noopov')
	
	autoTester.check ('a @ ai', id.astype ('int32') .tolist (), '<br>')
Exemple #6
0
 def print_local_storage(self):
     output_text = self.fixed_length_string(
         "Variable", 12) + self.fixed_length_string("Content",
                                                    18) + "\t" + "Dim"
     for key, value in self.local_storage.items(self):
         dim = "1"
         try:
             dim = ((num.array(value).shape))
         except:
             print("Could not get shape of " + key)
         out_str = str(value)
         out_str = out_str.replace("\n", " ")
         out_str = out_str.replace(" ", "")
         out_str = out_str.replace("\t", "")
         out_str = out_str.replace("][", "],[")
         output_text = output_text + "\n" + self.fixed_length_string(
             str(key), 12) + self.fixed_length_string(out_str,
                                                      18) + "\t" + dim
     document.getElementById('local_storage').value = (output_text)
Exemple #7
0
def eig(a):  # Everything presumed complex for now
    evals, evecs = eigen.eig(a)

    nrows, ncols = evecs.shape
    real = evecs.realbuf
    imag = evecs.imagbuf

    for icol in range(ncols):
        sum = 0

        for irow in range(nrows):
            iterm = irow * ncols + icol
            sum += (real[iterm] * real[iterm] + imag[iterm] * imag[iterm])

        norm = Math.sqrt(sum)

        for irow in range(nrows):
            iterm = irow * ncols + icol
            real[iterm] /= norm
            imag[iterm] /= norm

    return ns.array(evals, 'complex64'), evecs
Exemple #8
0
def eig (a):    # Everything presumed complex for now
    evals, evecs = eigen.eig (a)
    
    nrows, ncols = evecs.shape
    real = evecs.realbuf
    imag = evecs.imagbuf
    
    for icol in range (ncols):
        sum = 0
        
        for irow in range (nrows):
            iterm = irow * ncols + icol
            sum += (real [iterm] * real [iterm] + imag [iterm] * imag [iterm])
            
        norm = Math.sqrt (sum)
            
        for irow in range (nrows):
            iterm = irow * ncols + icol
            real [iterm] /= norm
            imag [iterm] /= norm
            
    return ns.array (evals, 'complex64'), evecs
    
Exemple #9
0
def run(autoTester):
    __pragma__('opov')
    delta = 0.001 + 0.001j
    __pragma__('noopov')

    autoTester.check('<br>------ 1D ------<br>')

    cut = 102

    autoTester.check('Samples computed: {}<br>'.format(tTotal * fSample))
    autoTester.check('Samples shown: {}<br>'.format(cut))

    orig = num.array([
        complex(0.3 + sin(2 * pi * fSin * t) + 0.5 * cos(2 * pi * fCos * t), 0)
        for t in [iSample / fSample for iSample in range(tTotal * fSample)]
    ], 'complex128')

    __pragma__('opov')

    autoTester.check('Original samples',
                     num.round(orig + delta, 3).tolist()[:cut], '<br>')

    if transpiled:
        timeStartFft = getNow()
    freqs = fft.fft(orig)
    if transpiled:
        timeStopFft = getNow()

    autoTester.check('Frequencies',
                     num.round(freqs + delta, 3).tolist()[:cut], '<br>')

    if transpiled:
        timeStartIfft = getNow()
    reconstr = fft.ifft(freqs)
    if transpiled:
        timeStopIfft = getNow()

    autoTester.check('Reconstructed samples',
                     num.round(reconstr + delta, 3).tolist()[:cut], '<br>')

    __pragma__('noopov')

    if transpiled:
        print('FFT for {} samples took {} ms'.format(
            tTotal * fSample, timeStopFft - timeStartFft))
        print('IFFT for {} samples took {} ms'.format(
            tTotal * fSample, timeStopIfft - timeStartIfft))

    autoTester.check('<br>------ 2D ------<br>')

    __pragma__('opov')

    orig2 = num.zeros((128, 128), 'complex128')
    orig2[32:96, 32:96] = num.ones((64, 64), 'complex128')

    autoTester.check('Original samples',
                     num.round(orig2 + delta, 3)[64:68, 16:112].tolist(),
                     '<br>')

    if transpiled:
        timeStartFft = getNow()

    freqs2 = fft.fft2(orig2)
    if transpiled:
        timeStopFft = getNow()

    autoTester.check('Frequencies',
                     num.round(freqs2 + delta, 3)[64:68, 16:112].tolist(),
                     '<br>')

    if transpiled:
        timeStartIfft = getNow()
    reconstr2 = fft.ifft2(freqs2)
    if transpiled:
        timeStopIfft = getNow()

    if transpiled:
        print('FFT2 for {} samples took {} ms'.format(
            orig2.size, timeStopFft - timeStartFft))
        print('IFFT2 for {} samples took {} ms'.format(
            orig2.size, timeStopIfft - timeStartIfft))

    autoTester.check('Reconstructed samples',
                     num.round(reconstr2 + delta, 3)[64:68, 16:112].tolist(),
                     '<br>')

    __pragma__('noopov')
Exemple #10
0
 def __init__ (self):
     '''Initialize constants
     '''
 
     dirVec0Plane = ns.array ((1, 0, 0))
     dirVec1Plane = ns.array ((0, 1, 0))
Exemple #11
0
    def project (self, celestialBodyVec, rField, rScreen):
        '''Project a celestial body onto the screen
        
                             y                    * celestial body
                             |            *
                           \ |  *
                      *     \|
        eye *        z - - - + - - -
        (origin)             |\
                             | \
                             |  x
                        image plane
                        
        Let vs be the vector from the origin to the celestial body.
        Let vl be any vector that ends on the line through the origin and the celestial body.
        Then vl = a vs
        
        Let vp be any vector that ends on the image plane
        Let d the distance from the origin to the center of the image plane
        Let ux, uy and uz be the unitvectors in directions x, y and z respectively
        Then vp = b ux + c uy - d uz
        
        The star is shown on the image plane at the intersection with the line between eye and star.
        At his intersection:
        
        a vs = b ux + c uy - d uz ==>
        
        d uz = a vs - b ux + - uy ==>
        
                 (vsx)     (-1)     ( 0)
        d uz = a (vsy) + b ( 0) + c (-1)
                 (vsz)     ( 0)     ( 0)
        
               (vsx, -1,  0) (a)
        d uz = (vsy,  0, -1) (b) ==>
               (vsz,  0,  0) (c)
               
                 (a)                           (vsx, -1,  0)
        d uz = D (b) with direction matrix D = (vsy,  0, -1) ==>
                 (c)                           (vsz,  0,  0)
                 
        (a)    -1
        (b) = D  d uz
        (c)
        
        The screen coordinates of the projected star are (a, b)
        
        '''
        
        # Bail out if object in front of image plane
        
        if projectableVec3D [2] < supVecPlane [2]:
            return None   

        # Compute inverse of direction matrix D
        
        invDirMat = (dirVecLine * ns.array ((1, 0, 0)) .T + dirVec0Plane * ns.array ((-1, 0, 0)) .T  + dirVec1Plane * ns.array ((0, -1, 0)) .T) .I
        
        # Compute projected 3D vector
        
        projectedCelestialBodyVec = invDirMat @ projectableVec
                
        # rField in pixels / rScreen in m will map object with size of rScreen m exactly to rField pixels
        projectedVec2D = (
            (rField / (rScreen / 6d)) * projectedVec3D [1],
            (rField / (rScreen / 6d)) * projectedVec3D [2]
        )
        
        return true
            
        boolean map (double [] mappedVec2D, double [] mappableVec3D, double rField, double rScreen) {	
            double [] rotAngVec = new double [] {Math.PI / 180d * tilt, Math.PI/180d * course, 0d};
            
            double s, c;

            s = Math.sin (rotAngVec [1]);
            c = Math.cos (rotAngVec [1]);
                    
            double rotZCourseMat [][] = new double [][] {
                { c, -s, 0d},
                { s,  c, 0d},
                {0d, 0d, 1d}
            };

            s = Math.sin (rotAngVec [0]);
            c = Math.cos (rotAngVec [0]);
            
            double rotYTiltMat [][] = new double [][] {
                { c, 0d,  s},
                {0d, 1d, 0d},
                {-s, 0d,  c}
            };

            double rotationMat [][] = new double [3][3];
            double [] zoomedVec3D = new double [3];
            double [] rotatedVec = new double [3];
            
            LinAlg.mul (rotationMat, rotYTiltMat, rotZCourseMat);
            LinAlg.mul (zoomedVec3D, zoomFactor / 30d, mappableVec3D);
            LinAlg.mul (rotatedVec, rotationMat, zoomedVec3D);
            return project (mappedVec2D, rotatedVec, rField, rScreen);
        }
Exemple #12
0
def run (autoTester):
    autoTester.check ('====== inverse ======')

    # Real

    r = num.array ([
        [2.12, -2.11, -1.23], 
        [2.31, 1.14, 3.15], 
        [1.13, 1.98, 2.81]
    ])
    
    autoTester.check ('Matrix r', num.round (r, 2) .tolist (), '<br>')
    
    ri = linalg.inv (r)
    
    autoTester.check ('Matrix ri', num.round (ri, 2) .tolist (), '<br>')
    
    __pragma__ ('opov')
    rid = r @ ri
    __pragma__ ('noopov')
    
    autoTester.check ('r @ ri', [[int (round (elem)) for elem in row] for row in rid.tolist ()], '<br>')
    
    __pragma__ ('opov')
    delta = 0.001
    autoTester.check ('r * r', num.round (r * r + delta, 3) .tolist (), '<br>')
    autoTester.check ('r / r', num.round (r / r + delta, 3) .tolist (), '<br>')
    autoTester.check ('r + r', num.round (r + r + delta, 3) .tolist (), '<br>')
    autoTester.check ('r - r', num.round (r - r + delta, 3) .tolist (), '<br>')
    __pragma__ ('noopov')

    # Complex
    
    __pragma__ ('opov')
    c = num.array ([
        [2.12 - 3.15j, -2.11, -1.23], 
        [2.31, 1.14, 3.15 + 2.75j], 
        [1.13, 1.98 - 4.33j, 2.81]
    ], 'complex128')
    __pragma__ ('noopov')
    
    autoTester.check ('Matrix c',  num.round (c, 2) .tolist (), '<br>')
    
    ci = linalg.inv (c)
    
    autoTester.check ('Matrix ci', num.round (ci, 2) .tolist (), '<br>')
    
    __pragma__ ('opov')
    cid = c @ ci
    __pragma__ ('noopov')
    
    # autoTester.check ('c @ ci', [['{} + j{}'.format (int (round (elem.real)), int (round (elem.imag))) for elem in row] for row in cid.tolist ()], '<br>')
    
    __pragma__ ('opov')
    delta = 0.001 + 0.001j
    autoTester.check ('c * c', num.round (c * c + delta , 3) .tolist (), '<br>')
    autoTester.check ('c / c', num.round (c / c + delta, 3) .tolist (), '<br>')
    autoTester.check ('c + c', num.round (c + c + delta, 3) .tolist (), '<br>')
    autoTester.check ('c - c', num.round (c - c + delta, 3) .tolist (), '<br>')
    __pragma__ ('noopov')
    
    autoTester.check ('====== eigen ======')
    
    __pragma__ ('opov')

    for a in (   
        num.array ([
            [0, 1j],
            [-1j, 1]
        ], 'complex128'),
        num.array ([
            [1, -2, 3, 1],
            [5, 8, -1, -5],
            [2, 1, 1, 100],
            [2, 1, -1, 0]
        ], 'complex128'),
    ):
        eVals, eVecs = linalg.eig (a)
        
        enumSorted = sorted (
            enumerate (eVals.tolist ()),
            key = lambda elem: -(elem [1].real + elem [1].imag / 1000)  # Order on primarily on real, secundarily on imag, note conjugate vals
        )
        
        indicesSorted = [elem [0] for elem in enumSorted]
        eValsSorted = [elem [1] for elem in enumSorted]
        
        eValsMat = num.empty (a.shape, a.dtype)
        for iRow in range (a.shape [0]):
            for iCol in range (a.shape [1]):
                eValsMat [iRow, iCol] = eVals [iCol]
         
        eVecsNorms = num.empty ((eVecs.shape [1], ), a.dtype)
        for iNorm in range (eVecsNorms.shape [0]):
            eVecsNorms [iNorm] = complex (linalg.norm (eVecs [:, iNorm]))
            
        eVecsCanon = num.empty (a.shape, a.dtype)
        for iRow in range (a.shape [0]):
            for iCol in range (a.shape [1]):
                eVecsCanon [iRow, iCol] = eVecs [iRow, iCol] / eVecs [0, iCol] 
            
        eVecsSorted = num.empty (a.shape, a.dtype)
        for iRow in range (a.shape [0]):
            for iCol in range (a.shape [1]):
                eVecsSorted [iRow, iCol] = eVecsCanon [iRow, indicesSorted [iCol]]
            
        '''
        autoTester.check ('\n---------------- a ----------------------')
        autoTester.check (a)
        autoTester.check ('\n---------------- eigVals ----------------')
        autoTester.check (eVals)
        autoTester.check ('\n---------------- eigValsMat--------------')
        autoTester.check (eValsMat)
        autoTester.check ('\n---------------- eigVecs ----------------')
        autoTester.check (eVecs)
        autoTester.check ('\n---------------- eigValsMat @ eigVecs ---')
        autoTester.check (eValsMat * eVecs)
        autoTester.check ('\n---------------- a @ eigVecs-------------')
        autoTester.check (a @ eVecs)
        autoTester.check ('\n---------------- eigVecsNorms -----------')
        autoTester.check (eVecsNorms)
        autoTester.check ('\n---------------- eigVecsCanon -----------')
        autoTester.check (eVecsCanon)
        '''
        autoTester.check ('\n---------------- eigVecsSorted ----------')
        autoTester.check ([[(round (value.real + 1e-3, 3), round (value.imag + 1e-3, 3)) for value in row] for row in eVecsSorted.tolist ()])
        autoTester.check ('\n---------------- eigValsSorted ----------')
        autoTester.check ([(round (value.real + 1e-3, 3), round (value.imag + 1e-3, 3)) for value in eValsSorted], '\n')
        
Exemple #13
0
 def linspace(self, start, end, disk):  # x=linspace(1,2,0.1)
     # start, end, disk float or real numbers!
     tmp = []
     for i in range(start, (end - start) / disk + 2):
         tmp[i - 1] = str(start + (i - 1) * disk)
     return (num.array(tmp, dtype=float))
Exemple #14
0
def run (autoTester):
	__pragma__ ('opov')
	delta = 0.001 + 0.001j
	__pragma__ ('noopov')
	
	autoTester.check ('<br>------ 1D ------<br>')
	
	cut = 102

	autoTester.check ('Samples computed: {}<br>'.format (tTotal  * fSample))
	autoTester.check ('Samples shown: {}<br>'.format (cut))

	orig = num.array ([
		complex (0.3 + sin (2 * pi * fSin * t) + 0.5 * cos (2 * pi * fCos * t), 0)
		for t in [
			iSample / fSample
			for iSample in range (tTotal * fSample)
		]
	], 'complex128')
	
	__pragma__ ('opov')

	autoTester.check ('Original samples', num.round (orig + delta, 3) .tolist ()[ : cut], '<br>')

	if transpiled:
		timeStartFft = getNow ()
	freqs = fft.fft (orig)
	if transpiled:
		timeStopFft = getNow ()	
		
	autoTester.check ('Frequencies', num.round (freqs + delta, 3) .tolist ()[ : cut], '<br>')
	
	if transpiled:
		timeStartIfft = getNow ()	
	reconstr = fft.ifft (freqs)
	if transpiled:
		timeStopIfft = getNow ()	
	
	autoTester.check ('Reconstructed samples', num.round (reconstr + delta, 3) .tolist ()[ : cut], '<br>')
	
	__pragma__ ('noopov')
		
	if transpiled:
		print ('FFT for {} samples took {} ms'.format (tTotal * fSample, timeStopFft - timeStartFft))
		print ('IFFT for {} samples took {} ms'.format (tTotal * fSample, timeStopIfft - timeStartIfft))
		
	autoTester.check ('<br>------ 2D ------<br>')
	
	__pragma__ ('opov')

	orig2 = num.zeros ((128, 128), 'complex128')
	orig2 [32 : 96, 32 : 96] = num.ones ((64, 64), 'complex128')
	
	autoTester.check ('Original samples', num.round (orig2 + delta, 3) [64 : 68, 16 : 112] .tolist (), '<br>')
	
	if transpiled:
		timeStartFft = getNow ()
		
	freqs2 = fft.fft2 (orig2)
	if transpiled:
		timeStopFft = getNow () 
		
	autoTester.check ('Frequencies', num.round (freqs2 + delta, 3)  [64 : 68, 16 : 112] .tolist (), '<br>')
	
	if transpiled:
		timeStartIfft = getNow ()
	reconstr2 = fft.ifft2 (freqs2)
	if transpiled:
		timeStopIfft = getNow ()	
	
	if transpiled:
		print ('FFT2 for {} samples took {} ms'.format (orig2.size, timeStopFft - timeStartFft))
		print ('IFFT2 for {} samples took {} ms'.format (orig2.size, timeStopIfft - timeStartIfft))
		
	autoTester.check ('Reconstructed samples', num.round (reconstr2 + delta, 3)  [64 : 68, 16 : 112] .tolist (), '<br>')
	
	__pragma__ ('noopov')
Exemple #15
0
from org.transcrypt.stubs.browser import *
from org.transcrypt.stubs.browser import __pragma__

import numscrypt as num
import numscrypt.random as num_rand
import numscrypt.linalg as linalg
import random

result = ''

for useComplex in (False, True):
    for transpose in (False, True):
        if useComplex:
            a = num.array ([
                [complex (random.random (), random.random ()) for iCol in range (30)]
                for iRow in range (30)
            ], 'complex128')
        else:
            a = num_rand.rand (30, 30)
        
        timeStartTranspose = __new__ (Date ())
        if transpose:
            a = a.transpose ()

        timeStartInv = __new__ (Date ())
        ai = linalg.inv (a)
        
        timeStartMul = __new__ (Date ()) 
        __pragma__ ('opov')
        id = a @ ai
        __pragma__ ('noopov')
Exemple #16
0
def colVec (*entries):
    return ns.array (entries) .reshape (len (entries), 1)
Exemple #17
0
def run(autoTester):
    autoTester.check('====== inverse ======')

    # Real

    r = num.array([[2.12, -2.11, -1.23], [2.31, 1.14, 3.15],
                   [1.13, 1.98, 2.81]])

    autoTester.check('Matrix r', num.round(r, 2).tolist(), '<br>')

    ri = linalg.inv(r)

    autoTester.check('Matrix ri', num.round(ri, 2).tolist(), '<br>')

    __pragma__('opov')
    rid = r @ ri
    __pragma__('noopov')

    autoTester.check('r @ ri', [[int(round(elem)) for elem in row]
                                for row in rid.tolist()], '<br>')

    __pragma__('opov')
    delta = 0.001
    autoTester.check('r * r', num.round(r * r + delta, 3).tolist(), '<br>')
    autoTester.check('r / r', num.round(r / r + delta, 3).tolist(), '<br>')
    autoTester.check('r + r', num.round(r + r + delta, 3).tolist(), '<br>')
    autoTester.check('r - r', num.round(r - r + delta, 3).tolist(), '<br>')
    __pragma__('noopov')

    # Complex

    __pragma__('opov')
    c = num.array([[2.12 - 3.15j, -2.11, -1.23], [2.31, 1.14, 3.15 + 2.75j],
                   [1.13, 1.98 - 4.33j, 2.81]], 'complex128')
    __pragma__('noopov')

    autoTester.check('Matrix c', num.round(c, 2).tolist(), '<br>')

    ci = linalg.inv(c)

    autoTester.check('Matrix ci', num.round(ci, 2).tolist(), '<br>')

    __pragma__('opov')
    cid = c @ ci
    __pragma__('noopov')

    # autoTester.check ('c @ ci', [['{} + j{}'.format (int (round (elem.real)), int (round (elem.imag))) for elem in row] for row in cid.tolist ()], '<br>')

    __pragma__('opov')
    delta = 0.001 + 0.001j
    autoTester.check('c * c', num.round(c * c + delta, 3).tolist(), '<br>')
    autoTester.check('c / c', num.round(c / c + delta, 3).tolist(), '<br>')
    autoTester.check('c + c', num.round(c + c + delta, 3).tolist(), '<br>')
    autoTester.check('c - c', num.round(c - c + delta, 3).tolist(), '<br>')
    __pragma__('noopov')

    autoTester.check('====== eigen ======')

    __pragma__('opov')

    for a in (
            num.array([[0, 1j], [-1j, 1]], 'complex128'),
            num.array(
                [[1, -2, 3, 1], [5, 8, -1, -5], [2, 1, 1, 100], [2, 1, -1, 0]],
                'complex128'),
    ):
        eVals, eVecs = linalg.eig(a)

        enumSorted = sorted(
            enumerate(eVals.tolist()),
            key=lambda elem: -(
                elem[1].real + elem[1].imag / 1000
            )  # Order on primarily on real, secundarily on imag, note conjugate vals
        )

        indicesSorted = [elem[0] for elem in enumSorted]
        eValsSorted = [elem[1] for elem in enumSorted]

        eValsMat = num.empty(a.shape, a.dtype)
        for iRow in range(a.shape[0]):
            for iCol in range(a.shape[1]):
                eValsMat[iRow, iCol] = eVals[iCol]

        eVecsNorms = num.empty((eVecs.shape[1], ), a.dtype)
        for iNorm in range(eVecsNorms.shape[0]):
            eVecsNorms[iNorm] = complex(linalg.norm(eVecs[:, iNorm]))

        eVecsCanon = num.empty(a.shape, a.dtype)
        for iRow in range(a.shape[0]):
            for iCol in range(a.shape[1]):
                eVecsCanon[iRow, iCol] = eVecs[iRow, iCol] / eVecs[0, iCol]

        eVecsSorted = num.empty(a.shape, a.dtype)
        for iRow in range(a.shape[0]):
            for iCol in range(a.shape[1]):
                eVecsSorted[iRow, iCol] = eVecsCanon[iRow, indicesSorted[iCol]]
        '''
        autoTester.check ('\n---------------- a ----------------------')
        autoTester.check (a)
        autoTester.check ('\n---------------- eigVals ----------------')
        autoTester.check (eVals)
        autoTester.check ('\n---------------- eigValsMat--------------')
        autoTester.check (eValsMat)
        autoTester.check ('\n---------------- eigVecs ----------------')
        autoTester.check (eVecs)
        autoTester.check ('\n---------------- eigValsMat @ eigVecs ---')
        autoTester.check (eValsMat * eVecs)
        autoTester.check ('\n---------------- a @ eigVecs-------------')
        autoTester.check (a @ eVecs)
        autoTester.check ('\n---------------- eigVecsNorms -----------')
        autoTester.check (eVecsNorms)
        autoTester.check ('\n---------------- eigVecsCanon -----------')
        autoTester.check (eVecsCanon)
        '''
        autoTester.check('\n---------------- eigVecsSorted ----------')
        autoTester.check([[(round(value.real + 1e-3,
                                  3), round(value.imag + 1e-3, 3))
                           for value in row] for row in eVecsSorted.tolist()])
        autoTester.check('\n---------------- eigValsSorted ----------')
        autoTester.check(
            [(round(value.real + 1e-3, 3), round(value.imag + 1e-3, 3))
             for value in eValsSorted], '\n')
Exemple #18
0
__pragma__('skip')
import numpy as num
import numpy.linalg as linalg

num.set_printoptions(linewidth=240)
__pragma__('noskip')

__pragma__('opov')


def show(*args):
    print(*args)


for a in (
        num.array([[0, 1j], [-1j, 1]], 'complex128'),
        num.array(
            [[1, -2, 3, 1], [5, 8, -1, -5], [2, 1, 1, 100], [2, 1, -1, 0]],
            'complex128'),
        num.array([[1, 1, 0, 0], [0, 2, 2, 0], [0, 0, 3, 3], [0, 0, 0, 4]],
                  'complex128'),
)[1:2]:
    eVals, eVecs = linalg.eig(a)

    enumSorted = sorted(
        enumerate(eVals.tolist()),
        key=lambda elem: -(
            elem[1].real + elem[1].imag / 1000
        )  # Order on primarily on real, secundarily on imag, note conjugate vals
    )
Exemple #19
0
def run (autoTester):
	z = num.zeros ((4, 3), 'int32')
	autoTester.check ('Zeros', z.tolist (), '<br>')
	
	o = num.ones ((4, 5))
	autoTester.check ('Ones', o.astype ('int32') .tolist ())
	
	i = num.identity (3, 'int32')
	autoTester.check ('Identity', i.tolist (), '<br>')
	
	a = num.array ([
		[1, 1, 2, 3],
		[4, 5, 6, 7],
		[8, 9, 10, 12]
	])
	
	autoTester.check ('Matrix a', a.tolist (), '<br>')
	
	autoTester.check ('Transpose of a', a.transpose () .tolist (), '<br>')
	
	b = num.array ([
		[2, 2, 4, 6],
		[8, 10, 12, 14],
		[16, 18, 20, 24]
	])
	
	bp =  b.transpose ()
	
	autoTester.check ('Matrix b', b.tolist (), '<br>')
	autoTester.check ('Permutation of b', bp.tolist (), '<br>')
		
	c = num.array ([
		[1, 2, 3, 4],
		[5, 6, 7, 8],
		[9, 10, 11, 12],
	], 'int32')
	
	autoTester.check ('Shape c', tuple (c.shape), '<br>')
	autoTester.check ('Matrix c', c.tolist (), '<br>')
	
	ct = c.transpose ()
	autoTester.check ('Shape ct', tuple (ct.shape), '<br>')
	autoTester.check ('Transpose of c', ct .tolist (), '<br>')

	cs0, cs1 = num.hsplit (c, 2)
	autoTester.check ('Matrix cs0', cs0.tolist (), '<br>')
	autoTester.check ('Matrix cs1', cs1.tolist (), '<br>')

	ci = num.hstack ((cs1, cs0))
	autoTester.check ('Matrix ci', ci.tolist (), '<br>')
	
	cts0, cts1, cts2 = num.hsplit (ct, 3)
	autoTester.check ('Matrix cts0', cts0.tolist (), '<br>')
	autoTester.check ('Matrix cts1', cts1.tolist (), '<br>')
	autoTester.check ('Matrix cts2', cts2.tolist (), '<br>')

	cti = num.hstack ((cts2, cts1, cts0))
	autoTester.check ('Matrix ci', cti.tolist (), '<br>')
	
	d = num.array ([
		[13, 14],
		[15, 16],
		[17, 18],
		[19, 20]
	], 'int32')
	
	autoTester.check ('Matrix d', d.tolist (), '<br>')
	dt = d.transpose ()
	autoTester.check ('Permutation of d', dt.tolist (), '<br>')
	
	ds0, ds1, ds2, ds3 = num.vsplit (d, 4)
	autoTester.check ('Matrix ds0', ds0.tolist (), '<br>')
	autoTester.check ('Matrix ds1', ds1.tolist (), '<br>')
	autoTester.check ('Matrix ds2', ds2.tolist (), '<br>')
	autoTester.check ('Matrix ds3', ds3.tolist (), '<br>')

	di = num.vstack ((ds3, ds2, ds1, ds0))
	autoTester.check ('Matrix di', di.tolist (), '<br>')
	
	dts0, dts1 = num.vsplit (dt, 2)
	autoTester.check ('Matrix dts0', dts0.tolist (), '<br>')
	autoTester.check ('Matrix dts1', dts1.tolist (), '<br>')

	dti = num.vstack ((dts1, dts0))
	autoTester.check ('Matrix dti', dti.tolist (), '<br>')
	
	v0 = num.array (range (10))	
	v1 = num.array ((1, 2, 3, 1, 2, 3, 1, 2, 3, 1))

	__pragma__ ('opov')
	
	a [1, 0] = 177
	el = b [1, 2]
	
	bsl0 = b [1, 1 : 3]
	bsl1 = b [1 : 2, 1 : 3]
	bsl2 = b [1 : 2, 1]
	bsl3 = b [1, 1 : 3]
	bsl4 = b [ : , 1]
	bsl5 = b [1, 1 : 3]
	bsl6 = b [1, 1 : 3]
	bsl7 = b [1, 2 : 3]

	bpsl0 = bp [1, 1 : 3]
	bpsl1 = bp [1 : 2, 1 : 3]
	bpsl2 = bp [1, 0 : ]
	bpsl3 = bp [1, 1 : 3]
	bpsl4 = bp [ : , 1]
	bpsl5 = bp [3, 1 : 3]
	bpsl6 = bp [2 : 4, 1 : 3]
	bpsl7 = bp [2 : 4, 2 : 3]
	
	sum = a + b
	dif = a - b
	prod = a * b
	quot = a / b
	dot = c @ d
	vsum = v0 + v1
	vel = vsum [6]
	vsum [6] = 70
	
	mul_a3 = a * 3
	mul_3a = 3 * a
	div_a3 = a / 3.1234567
	div_3a = 3.1234567 / a
	add_a3 = a + 3
	add_3a = 3 + a
	sub_a3 = a - 3
	sub_3a = 3 - a
	neg_a = -a
	
	__pragma__ ('noopov')
		
	autoTester.check ('El a [1, 2, 3] alt', a.tolist (), '<br>')
	autoTester.check ('El b [1, 2, 3]', el, '<br>')
	
	autoTester.check ('Sl b0', bsl0.tolist (), '<br>')
	autoTester.check ('Sl b1', bsl1.tolist (), '<br>')
	autoTester.check ('Sl b2', bsl2.tolist (), '<br>')
	autoTester.check ('Sl b3', bsl3.tolist (), '<br>')
	autoTester.check ('Sl b4', bsl4.tolist (), '<br>')
	autoTester.check ('Sl b5', bsl5.tolist (), '<br>')
	autoTester.check ('Sl b6', bsl6.tolist (), '<br>')
	autoTester.check ('Sl b7', bsl7.tolist (), '<br>')
	
	autoTester.check ('Sl bp0', bpsl0.tolist (), '<br>')
	autoTester.check ('Sl bp1', bpsl1.tolist (), '<br>')
	autoTester.check ('Sl bp2', bpsl2.tolist (), '<br>')
	autoTester.check ('Sl bp3', bpsl3.tolist (), '<br>')
	autoTester.check ('Sl bp4', bpsl4.tolist (), '<br>')
	autoTester.check ('Sl bp5', bpsl5.tolist (), '<br>')
	autoTester.check ('Sl bp6', bpsl6.tolist (), '<br>')
	autoTester.check ('Sl bp7', bpsl7.tolist (), '<br>')
	
	autoTester.check ('Matrix sum', sum.tolist (), '<br>')
	autoTester.check ('Matrix difference', dif.tolist (), '<br>')
	autoTester.check ('Matrix product', prod.tolist (), '<br>')
	autoTester.check ('Matrix quotient', quot.tolist (), '<br>')
	autoTester.check ('Matrix dotproduct', dot.tolist (), '<br>')
	
	autoTester.check ('Vector', v0.tolist (), '<br>')
	autoTester.check ('Vector', v1.tolist (), '<br>')
	autoTester.check ('El sum old', vel, '<br>')
	autoTester.check ('Vector sum new', vsum.tolist (), '<br>')
	
	autoTester.check ('mul_a3', mul_a3.tolist (), '<br>')
	autoTester.check ('mul_3a', mul_3a.tolist (), '<br>')
	autoTester.check ('div_a3', num.round (div_a3, 2).tolist (), '<br>')
	autoTester.check ('div_3a', num.round (div_3a, 2).tolist (), '<br>')
	autoTester.check ('add_a3', add_a3.tolist (), '<br>')
	autoTester.check ('add_3a', add_3a.tolist (), '<br>')
	autoTester.check ('sub_a3', sub_a3.tolist (), '<br>')
	autoTester.check ('sub_3a', sub_3a.tolist (), '<br>')
	autoTester.check ('neg_a', neg_a.tolist (), '<br>')
	
	__pragma__ ('opov')
	comp_a = num.array ([
		[1 + 2j, 2 - 1j, 3],
		[4, 5 + 3j, 7]
	], 'complex128')	
	comp_b = num.array ([
		[6, 8 - 1j],
		[9 + 3j, 10],
		[11, 12 - 6j]
	], 'complex128')
	comp_c = comp_a @ comp_b
	__pragma__ ('noopov')
	
	autoTester.check ('comp_a', comp_a.tolist (), '<br>')
	autoTester.check ('comp_b', comp_b.tolist (), '<br>')
	autoTester.check ('comp_c', comp_c.tolist (), '<br>')
	
	__pragma__ ('opov')
	
	comp_a_square = comp_a [ : , : 2]
	comp_b_square = comp_b [1 : , : ]
	
	comp_c_square = comp_a_square * comp_b_square
	comp_d_square = comp_a_square / comp_b_square
	comp_e_square = comp_a_square + comp_b_square
	comp_f_square = comp_a_square - comp_b_square
	
	__pragma__ ('noopov')
	
	autoTester.check ('comp_a_square', comp_a_square.tolist (), '<br>')
	autoTester.check ('comp_b_square', comp_b_square.tolist (), '<br>')
	autoTester.check ('comp_c_square', comp_c_square.tolist (), '<br>')
	autoTester.check ('comp_d_square', num.round (comp_d_square, 2).tolist (), '<br>')
	autoTester.check ('comp_e_square', comp_e_square.tolist (), '<br>')
	autoTester.check ('comp_f_square', comp_f_square.tolist (), '<br>')
	
	__pragma__ ('opov')
	sliceable_a = num.array ([
		[1, 2, 3, 4],
		[5, 6, 7, 8],
		[9, 10, 11, 12],
		[13, 14, 15, 16]
	])
	autoTester.check ('sliceable_a', sliceable_a.tolist ())

	slice_a = sliceable_a [1 : , 1 : ]
	autoTester.check ('slice_a')
	
	sliceable_at = sliceable_a.transpose ()
	slice_at = sliceable_at [1 : ]
	
	__pragma__ ('noopov')
	
Exemple #20
0
def run (autoTester):
	z = num.zeros ((4, 3, 2), 'int32')
	autoTester.check ('Zeros', z.tolist (), '<br>')
	
	o = num.ones ((1, 2, 3))
	autoTester.check ('Ones', o.astype ('int32') .tolist ())
	
	i = num.identity (3, 'int32')
	autoTester.check ('Identity', i.tolist (), '<br>')
	
	# shape: 2 blocks x 3 rows x 4 columns
	a = num.array ([
		[
			[1, 1, 2, 3],
			[4, 5, 6, 7],
			[8, 9, 10, 12]
		], [
			[100, 101, 102, 103],
			[104, 105, 106, 107],
			[108, 109, 110, 112]
		]
	])
	
	# print (a)
	
	autoTester.check ('Matrix a', a.tolist (), '<br>')
	autoTester.check ('Transpose of a', a.transpose () .tolist (), '<br>')
	
	b = num.array ([
		[
			[2, 2, 4, 6],
			[8, 10, 12, 14],
			[16, 18, 20, 24]
		], [
			[200, 202, 204, 206],
			[208, 210, 212, 214],
			[216, 218, 220, 224]
		]
	])
	
	bp =  b.transpose ((2, 1, 0))
	
	autoTester.check ('Matrix b', b.tolist (), '<br>')
	autoTester.check ('Permutation of b', bp.tolist (), '<br>')
		
	c = num.array ([
		[1, 2, 3, 4],
		[5, 6, 7, 8],
		[9, 10, 11, 12],
	], 'int32')
	
	autoTester.check ('Shape strides c', tuple (c.shape), tuple (c.strides), '<br>')
	autoTester.check ('Matrix c', c.tolist (), '<br>')
	
	ct = c.transpose ()
	autoTester.check ('Shape strids ct', tuple (ct.shape), tuple (ct.strides), '<br>')
	autoTester.check ('Transpose of c', ct .tolist (), '<br>')

	cs0, cs1 = num.hsplit (c, 2)
	autoTester.check ('Matrix cs0', cs0.tolist (), '<br>')
	autoTester.check ('Matrix cs1', cs1.tolist (), '<br>')

	ci = num.hstack ((cs1, cs0))
	autoTester.check ('Matrix ci', ci.tolist (), '<br>')
	
	cts0, cts1, cts2 = num.hsplit (ct, 3)
	autoTester.check ('Matrix cts0', cts0.tolist (), '<br>')
	autoTester.check ('Matrix cts1', cts1.tolist (), '<br>')
	autoTester.check ('Matrix cts2', cts2.tolist (), '<br>')

	cti = num.hstack ((cts2, cts1, cts0))
	autoTester.check ('Matrix ci', cti.tolist (), '<br>')
	
	d = num.array ([
		[13, 14],
		[15, 16],
		[17, 18],
		[19, 20]
	], 'int32')
	
	autoTester.check ('Matrix d', d.tolist (), '<br>')
	dt = d.transpose ()
	autoTester.check ('Permutation of d', dt.tolist (), '<br>')
	
	ds0, ds1, ds2, ds3 = num.vsplit (d, 4)
	autoTester.check ('Matrix ds0', ds0.tolist (), '<br>')
	autoTester.check ('Matrix ds1', ds1.tolist (), '<br>')
	autoTester.check ('Matrix ds2', ds2.tolist (), '<br>')
	autoTester.check ('Matrix ds3', ds3.tolist (), '<br>')

	di = num.vstack ((ds3, ds2, ds1, ds0))
	autoTester.check ('Matrix di', di.tolist (), '<br>')
	
	dts0, dts1 = num.vsplit (dt, 2)
	autoTester.check ('Matrix dts0', dts0.tolist (), '<br>')
	autoTester.check ('Matrix dts1', dts1.tolist (), '<br>')

	dti = num.vstack ((dts1, dts0))
	autoTester.check ('Matrix dti', dti.tolist (), '<br>')
	
	v0 = num.array (range (10))	
	v1 = num.array ((1, 2, 3, 1, 2, 3, 1, 2, 3, 1))
	
	__pragma__ ('opov')
	a [1, 0, 2] = 177
	el = b [1, 2, 3]

	bsl0 = b [1, 1 : 3, : ]
	bsl1 = b [1 : 2, 1 : 3, :]
	bsl2 = b [1, 1, :]
	bsl3 = b [1, 1 : 3, 1]
	bsl4 = b [ : , 1, 1]
	bsl5 = b [1, 1 : 3, :]
	bsl6 = b [1, 1 : 3, 1 : 4]
	bsl7 = b [1, 2 : 3, 2 : 4]
	
	bpsl0 = bp [1, 1 : 3, : ]
	bpsl1 = bp [1 : 2, 1 : 3, :]
	bpsl2 = bp [1, 1, :]
	bpsl3 = bp [1, 1 : 3, 1]
	bpsl4 = bp [ : , 1, 1]
	bpsl5 = bp [3, 1 : 3, :]
	bpsl6 = bp [2 : 4, 1 : 3, 0 : 1]
	bpsl7 = bp [2 : 4, 2 : 3, 1 : 2]
	
	sum = a + b
	dif = a - b
	prod = a * b
	quot = a / b
	dot = c @ d
	vsum = v0 + v1
	vel = vsum [6]
	vsum [6] = 70
	
	mul_a3 = a * 3
	mul_3a = 3 * a
	div_a3 = a / 3.1234567
	div_3a = 3.1234567 / a
	add_a3 = a + 3
	add_3a = 3 + a
	sub_a3 = a - 3
	sub_3a = 3 - a
	neg_a = -a
	
	__pragma__ ('noopov')
	
	autoTester.check ('El a [1, 2, 3] alt', a.tolist (), '<br>')
	autoTester.check ('El b [1, 2, 3]', el, '<br>')
	
	autoTester.check ('Sl b0', bsl0.tolist (), '<br>')
	autoTester.check ('Sl b1', bsl1.tolist (), '<br>')
	autoTester.check ('Sl b2', bsl2.tolist (), '<br>')
	autoTester.check ('Sl b3', bsl3.tolist (), '<br>')
	autoTester.check ('Sl b4', bsl4.tolist (), '<br>')
	autoTester.check ('Sl b5', bsl5.tolist (), '<br>')
	autoTester.check ('Sl b6', bsl6.tolist (), '<br>')
	autoTester.check ('Sl b7', bsl7.tolist (), '<br>')
	
	autoTester.check ('Sl bp0', bpsl0.tolist (), '<br>')
	autoTester.check ('Sl bp1', bpsl1.tolist (), '<br>')
	autoTester.check ('Sl bp2', bpsl2.tolist (), '<br>')
	autoTester.check ('Sl bp3', bpsl3.tolist (), '<br>')
	autoTester.check ('Sl bp4', bpsl4.tolist (), '<br>')
	autoTester.check ('Sl bp5', bpsl5.tolist (), '<br>')
	autoTester.check ('Sl bp6', bpsl6.tolist (), '<br>')
	autoTester.check ('Sl bp7', bpsl7.tolist (), '<br>')
	
	autoTester.check ('Matrix sum', sum.tolist (), '<br>')
	autoTester.check ('Matrix difference', dif.tolist (), '<br>')
	autoTester.check ('Matrix product', prod.tolist (), '<br>')
	autoTester.check ('Matrix quotient', quot.tolist (), '<br>')
	autoTester.check ('Matrix dotproduct', dot.tolist (), '<br>')
	
	autoTester.check ('Vector', v0.tolist (), '<br>')
	autoTester.check ('Vector', v1.tolist (), '<br>')
	autoTester.check ('El sum old', vel, '<br>')
	autoTester.check ('Vector sum new', vsum.tolist (), '<br>')
	
	autoTester.check ('mul_a3', mul_a3.tolist (), '<br>')
	autoTester.check ('mul_3a', mul_3a.tolist (), '<br>')
	autoTester.check ('div_a3', num.round (div_a3, 2).tolist (), '<br>')
	autoTester.check ('div_3a', num.round (div_3a, 2).tolist (), '<br>')
	autoTester.check ('add_a3', add_a3.tolist (), '<br>')
	autoTester.check ('add_3a', add_3a.tolist (), '<br>')
	autoTester.check ('sub_a3', sub_a3.tolist (), '<br>')
	autoTester.check ('sub_3a', sub_3a.tolist (), '<br>')
	autoTester.check ('neg_a', neg_a.tolist (), '<br>')
	
Exemple #21
0
from org.transcrypt.stubs.browser import *
from org.transcrypt.stubs.browser import __pragma__

import numscrypt as num
import numscrypt.random as num_rand
import numscrypt.linalg as linalg
import random

result = ''

for useComplex in (False, True):
    for transpose in (False, True):
        if useComplex:
            a = num.array([[
                complex(random.random(), random.random()) for iCol in range(30)
            ] for iRow in range(30)], 'complex128')
        else:
            a = num_rand.rand(30, 30)

        timeStartTranspose = __new__(Date())
        if transpose:
            a = a.transpose()

        timeStartInv = __new__(Date())
        ai = linalg.inv(a)

        timeStartMul = __new__(Date())
        __pragma__('opov')
        id = a @ ai
        __pragma__('noopov')
Exemple #22
0
# Imports for CPython, resolved compile time
__pragma__ ('skip')
import numpy as num
import numpy.linalg as linalg
num.set_printoptions (linewidth = 240)
__pragma__ ('noskip')

__pragma__ ('opov')

def show (*args):
    print (*args)

for a in (   
    num.array ([
        [0, 1j],
        [-1j, 1]
    ], 'complex128'),
    num.array ([
        [1, -2, 3, 1],
        [5, 8, -1, -5],
        [2, 1, 1, 100],
        [2, 1, -1, 0]
    ], 'complex128'),
    num.array ([
        [1, 1, 0, 0],
        [0, 2, 2, 0],
        [0, 0, 3, 3],
        [0, 0, 0, 4]
    ], 'complex128'),
) [1:2]:
    eVals, eVecs = linalg.eig (a)