Exemplo n.º 1
0
    def test_np_info(self):
        output = io.StringIO()
        with contextlib.closing(output):
            np.info(ibm2float32, output=output)
            self.assertIn("Examples", output.getvalue())

        output = io.StringIO()
        with contextlib.closing(output):
            np.info(ibm2float64, output=output)
            self.assertIn("Examples", output.getvalue())
Exemplo n.º 2
0
 def debug(self,pts,scales,orientations,scale_maps,heatmaps):
     print('orientations:',orientations)                     
     print('scales:',scales)            
     print('heatmaps info:')
     np.info(heatmaps)
     print('scalemaps info:')
     np.info(scale_maps)        
     heatmaps_img = img_from_floats(heatmaps)
     cv2.imshow('heatmap',heatmaps_img)             
     scalemaps_img = img_from_floats(scale_maps)
     cv2.imshow('scale maps',scalemaps_img)     
     cv2.waitKey(1)        
Exemplo n.º 3
0
    def test_py3_compat(self):
        # gh-2561
        # Test if the oldstyle class test is bypassed in python3
        class C():
            """Old-style class in python2, normal class in python3"""
            pass

        out = open(os.devnull, 'w')
        try:
            np.info(C(), output=out)
        except AttributeError:
            raise AssertionError()
        finally:
            out.close()
Exemplo n.º 4
0
    def test_py3_compat(self):
        # gh-2561
        # Test if the oldstyle class test is bypassed in python3
        class C():
            """Old-style class in python2, normal class in python3"""
            pass

        out = open(os.devnull, 'w')
        try:
            np.info(C(), output=out)
        except AttributeError:
            raise AssertionError()
        finally:
            out.close()
Exemplo n.º 5
0
def reduce_mem_usage(df, verbose=True):
    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
    start_mem = df.memory_usage().sum() / 1024**2
    for col in df.columns:
        col_type = df[col].dtypes
        if col_type in numerics:
            c_min = df[col].min()
            c_max = df[col].max()
            if str(col_type)[:3] == 'int':
                if c_min > np.info(np.int8).min and c_max < np.iinfo(
                        np.int8).max:
                    df[col] = df[col].astype(np.int8)
                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(
                        np.int16).max:
                    df[col] = df[col].astype(np.int16)
                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(
                        np.int32).max:
                    df[col] = df[col].astype(np.int32)
                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(
                        np.int64).max:
                    df[col] = df[col].astype(np.int64)
            else:
                if c_min > np.finfo(np.float16).min and c_max < np.finfo(
                        np.float16).max:
                    df[col] = df[col].astype(np.float16)
                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(
                        np.float32).max:
                    df[col] = df[col].astype(np.float32)
                else:
                    df[col] = df[col].astype(np.float64)
    end_mem = df.memory_usage().sum() / 1024**2
    if verbose:
        print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(
            end_mem, 100 * (start_mem - end_mem) / start_mem))
    return df
Exemplo n.º 6
0
def demo_numpy_describe():
    with LogicalFile.LogicalIndex(path_in) as logical_index:
        for logical_file in logical_index.logical_files:
            if logical_file.has_log_pass:
                for frame_array in logical_file.log_pass:
                    print(frame_array)
                    frame_count = logical_file.populate_frame_array(
                        frame_array)
                    print(
                        f'Loaded {frame_count} frames and {len(frame_array)} channels'
                        f' from {frame_array.ident} using {frame_array.sizeof_array} bytes.'
                    )
                    for channel in frame_array.channels:
                        print(channel)
                        # channel.array is a numpy array
                        np.info(channel.array)
                        print()
Exemplo n.º 7
0
def demo_numpy_describe_test_data():
    fobj = io.BytesIO(test_data.BASIC_FILE)
    with LogicalFile.LogicalIndex(fobj) as logical_index:
        for logical_file in logical_index.logical_files:
            if logical_file.has_log_pass:
                for frame_array in logical_file.log_pass:
                    print(frame_array)
                    frame_count = logical_file.populate_frame_array(
                        frame_array)
                    print(
                        f'Loaded {frame_count} frames and {len(frame_array)} channels'
                        f' from {frame_array.ident} using {frame_array.sizeof_array} bytes.'
                    )
                    for channel in frame_array.channels:
                        print(f'Channel: {channel}')
                        # channel.array is a numpy array
                        np.info(channel.array)
                        print()
def np_info(a: np.ndarray) -> str:
    """Emulates np.info() but as a sting rather than to stdout.
    Example::

        class:  ndarray
        shape:  (1024, 4096)
        strides:  (32768, 8)
        itemsize:  8
        aligned:  True
        contiguous:  True
        fortran:  False
        data pointer: 0x10dd6b000
        byteorder:  little
        byteswap:  False
        type: float64
    """
    with io.StringIO() as file:
        np.info(a, output=file)
        return file.getvalue().rstrip()
Exemplo n.º 9
0
    def analyse(self, picture_url, picture_mediaID, picture_msgID,
                picture_createtime):
        parameters_pic_raw = {
            "requests": [{
                "image": {
                    "source": {
                        "imageUri": '%s' % picture_url
                    }
                },
                "features": [{
                    "type": "FACE_DETECTION",
                    "maxResults": "10"
                }, {
                    "type": "LABEL_DETECTION",
                    "maxResults": "10"
                }, {
                    "type": "TEXT_DETECTION",
                    "maxResults": "10"
                }, {
                    "type": "LANDMARK_DETECTION",
                    "maxResults": "10"
                }, {
                    "type": "WEB_DETECTION",
                    "maxResults": "10"
                }]
            }]
        }

        output_filename = 'vision_parameters.json'  #%picture_mediaID
        with open(output_filename, 'w') as output_file:
            json.dump(parameters_pic_raw, output_file, indent=4)

        print('Pmid: ' + picture_msgID)
        print('Pct: ' + picture_createtime)
        print(output_filename)
        print(parameters_pic_raw)

        parameters_pic = open(output_filename, 'rb').read()
        #print ('parameters_pic: ' + parameters_pic)
        print('google key: ' + self.key)
        print('google url: ' + self.url)
        response_pic = requests.post(url=self.url + '?key=' + self.key,
                                     data=parameters_pic)
        print('response_pic_info: ' + str(np.info(response_pic)))

        vision_results = response_pic.json()
        print('vision_results: ' + str(vision_results))
        return vision_results
Exemplo n.º 10
0
integralPrimeira = np.polyint(f3grau)

integralSegunda = np.polyint(f3grau, 2)

integralTerceira = np.polyint(f3grau, 3)


#Tratamento de sinais - convolucao
#%%
sinalConvoluido = np.convolve([1, 2, 3], [0, 1, 0.5])
plt.hist(sinalConvoluido, bins=3, density=100) #altere os bins
plt.show()

#Pesquisa

print(np.info(np.polyval))
print(np.lookfor('binary representation'))
print(np.source(np.interp))#funcao Valida apenas para objetos escritos em python


'''Scipy

É uma biblioteca de computação científica, que junto ao Numpy é capaz
de realizar operações poderosas, tanto para o processamento de dados 
quanto para a prototipagem de sistemas.'''



#%%
import scipy as sp
Exemplo n.º 11
0
print(np.tan(a*np.pi/180))
print(np.tan(a*np.pi/180))
a=np.arange(9,dtype=np.float).reshape(3,3)
print(np.ptp(a,axis=1))
print(np.average((1,2,3,4)))
print(numpy.matlib.zeros((2,2)))
a=np.array([[1,2],[3,4]])
print(np.dot(a,b))
np.save('outfile.npy',a)
print(np.__version__)
np.show_config()
Z=np.zeros(10)
print(Z)
Z=np.zeros((10,10))
print(Z.size * Z.itemsize)
np.info(np.add)
Z=np.zeros(10)
Z[4]=1
print(Z)
Z=np.arange(10,50)
print(Z)
Z=np.arange(50)
z=Z[::-1]
print(z)
Z=np.arange(9).reshape(3,3)
print(Z)
nz=np.nonzero([1,2,0,0,4,0])
print(nz)
Z=np.eye(3)
print(z)
Z=np.random.random((3,3,3))
Exemplo n.º 12
0
import scipy as sp
from scipy import integrate
from scipy import cluster
from scipy import fftpack
import numpy as np

#Help/doc
help(integrate)
np.info(fftpack)

#Source code of subpackages
np.source(cluster)
Exemplo n.º 13
0
np.histogram_bin_edges
np.histogram2d
np.histogramdd
np.hsplit
np.hstack
np.hypot
np.i0
np.identity
np.iinfo
np.imag
np.in1d
np.index_exp
np.indices
np.inexact
np.inf | Inf | Infinity | PINF | infty
np.info(object=None|'', maxwidth=76, output=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, toplevel='numpy')
np.inner
np.insert(arr=∂, obj=0|[0,..], values=∂, axis=None|0)
np.int
np.int_
np.int0
np.int16
np.int32
np.int64
np.int8
np.intc
np.integer
np.interp
np.intersect1d
np.intp
np.invert
Exemplo n.º 14
0
    def backgroundSubtractionWeaver(img, bgStack, test=False):
        """
        background subtraction using C++ code works on non-fortran style 
        background stacks, is less efficient than 
        backgroundSubtractionWeaverF
        
        Args:
            img (nd array):
                                input image
            bgStack (background image stack):
                                - for computation see :func:`calculateBackgroundStack`
                                - *needs to generated with fortranStyle=False*
                        
        Returns:
            difference image
            
        .. seealso::
            :func:`backgroundSubstractionStack`
            :func:`backgroundSubstractionWeaver`
            :func:`backgroundSubstractionWeaverF`
        """
        im0 = img[:, :, 0].flatten()
        im1 = img[:, :, 1].flatten()
        im2 = img[:, :, 2].flatten()

        bg0 = bgStack[0]
        bg1 = bgStack[1]
        bg2 = bgStack[2]

        # (very wide string)
        subtractionCode = \
        """
            // subtraction on all color layers 
            short val = 0;
            for (int i = 0; i < bgn; ++i){
                for (int k = 0; k < bgx; k += 16){
                    diff[k] = ((im0[k] - bg0[k + i * imLen]) + (im1[k] - bg1[k + i * imLen]) + (im2[k] - bg2[k + i * imLen]) > diff[k]) ? (im0[k] - bg0[k + i * imLen]) + (im1[k] - bg1[k + i * imLen]) + (im2[k] - bg2[k + i * imLen]) : diff[k];
                    diff[k + 1] = ((im0[k + 1] - bg0[k + 1 + i * imLen]) + (im1[k + 1] - bg1[k + 1 + i * imLen]) + (im2[k + 1] - bg2[k + 1 + i * imLen]) > diff[k + 1]) ? (im0[k + 1] - bg0[k + 1 + i * imLen]) + (im1[k + 1] - bg1[k + 1 + i * imLen]) + (im2[k + 1] - bg2[k + 1 + i * imLen]) : diff[k + 1];
                    diff[k +2] = ((im0[k +2] - bg0[k +2 + i * imLen]) + (im1[k +2] - bg1[k +2 + i * imLen]) + (im2[k +2] - bg2[k +2 + i * imLen]) > diff[k +2]) ? (im0[k +2] - bg0[k +2 + i * imLen]) + (im1[k +2] - bg1[k +2 + i * imLen]) + (im2[k +2] - bg2[k +2 + i * imLen]) : diff[k +2];
                    diff[k + 3] = ((im0[k + 3] - bg0[k + 3 + i * imLen]) + (im1[k + 3] - bg1[k + 3 + i * imLen]) + (im2[k + 3] - bg2[k + 3 + i * imLen]) > diff[k + 3]) ? (im0[k + 3] - bg0[k + 3 + i * imLen]) + (im1[k + 3] - bg1[k + 3 + i * imLen]) + (im2[k + 3] - bg2[k + 3 + i * imLen]) : diff[k + 3];
                    diff[k + 4] = ((im0[k + 4] - bg0[k + 4 + i * imLen]) + (im1[k + 4] - bg1[k + 4 + i * imLen]) + (im2[k + 4] - bg2[k + 4 + i * imLen]) > diff[k + 4]) ? (im0[k + 4] - bg0[k + 4 + i * imLen]) + (im1[k + 4] - bg1[k + 4 + i * imLen]) + (im2[k + 4] - bg2[k + 4 + i * imLen]) : diff[k + 4];
                    diff[k + 5] = ((im0[k + 5] - bg0[k + 5 + i * imLen]) + (im1[k + 5] - bg1[k + 5 + i * imLen]) + (im2[k + 5] - bg2[k + 5 + i * imLen]) > diff[k + 5]) ? (im0[k + 5] - bg0[k + 5 + i * imLen]) + (im1[k + 5] - bg1[k + 5 + i * imLen]) + (im2[k + 5] - bg2[k + 5 + i * imLen]) : diff[k + 5];
                    diff[k + 6] = ((im0[k + 6] - bg0[k + 6 + i * imLen]) + (im1[k + 6] - bg1[k + 6 + i * imLen]) + (im2[k + 6] - bg2[k + 6 + i * imLen]) > diff[k + 6]) ? (im0[k + 6] - bg0[k + 6 + i * imLen]) + (im1[k + 6] - bg1[k + 6 + i * imLen]) + (im2[k + 6] - bg2[k + 6 + i * imLen]) : diff[k + 6];
                    diff[k + 7] = ((im0[k + 7] - bg0[k + 7 + i * imLen]) + (im1[k + 7] - bg1[k + 7 + i * imLen]) + (im2[k + 7] - bg2[k + 7 + i * imLen]) > diff[k + 7]) ? (im0[k + 7] - bg0[k + 7 + i * imLen]) + (im1[k + 7] - bg1[k + 7 + i * imLen]) + (im2[k + 7] - bg2[k + 7 + i * imLen]) : diff[k + 7];
                    diff[k + 8] = ((im0[k + 8] - bg0[k + 8 + i * imLen]) + (im1[k + 8] - bg1[k + 8 + i * imLen]) + (im2[k + 8] - bg2[k + 8 + i * imLen]) > diff[k + 8]) ? (im0[k + 8] - bg0[k + 8 + i * imLen]) + (im1[k + 8] - bg1[k + 8 + i * imLen]) + (im2[k + 8] - bg2[k + 8 + i * imLen]) : diff[k + 8];
                    diff[k + 9] = ((im0[k + 9] - bg0[k + 9 + i * imLen]) + (im1[k + 9] - bg1[k + 9 + i * imLen]) + (im2[k + 9] - bg2[k + 9 + i * imLen]) > diff[k + 9]) ? (im0[k + 9] - bg0[k + 9 + i * imLen]) + (im1[k + 9] - bg1[k + 9 + i * imLen]) + (im2[k + 9] - bg2[k + 9 + i * imLen]) : diff[k + 9];
                    diff[k + 10] = ((im0[k + 10] - bg0[k + 10 + i * imLen]) + (im1[k + 10] - bg1[k + 10 + i * imLen]) + (im2[k + 10] - bg2[k + 10 + i * imLen]) > diff[k + 10]) ? (im0[k + 10] - bg0[k + 10 + i * imLen]) + (im1[k + 10] - bg1[k + 10 + i * imLen]) + (im2[k + 10] - bg2[k + 10 + i * imLen]) : diff[k + 10];
                    diff[k + 11] = ((im0[k + 11] - bg0[k + 11 + i * imLen]) + (im1[k + 11] - bg1[k + 11 + i * imLen]) + (im2[k + 11] - bg2[k + 11 + i * imLen]) > diff[k + 11]) ? (im0[k + 11] - bg0[k + 11 + i * imLen]) + (im1[k + 11] - bg1[k + 11 + i * imLen]) + (im2[k + 11] - bg2[k + 11 + i * imLen]) : diff[k + 11];
                    diff[k + 12] = ((im0[k + 12] - bg0[k + 12 + i * imLen]) + (im1[k + 12] - bg1[k + 12 + i * imLen]) + (im2[k + 12] - bg2[k + 12 + i * imLen]) > diff[k + 12]) ? (im0[k + 12] - bg0[k + 12 + i * imLen]) + (im1[k + 12] - bg1[k + 12 + i * imLen]) + (im2[k + 12] - bg2[k + 12 + i * imLen]) : diff[k + 12];
                    diff[k + 13] = ((im0[k + 13] - bg0[k + 13 + i * imLen]) + (im1[k + 13] - bg1[k + 13 + i * imLen]) + (im2[k + 13] - bg2[k + 13 + i * imLen]) > diff[k + 13]) ? (im0[k + 13] - bg0[k + 13 + i * imLen]) + (im1[k + 13] - bg1[k + 13 + i * imLen]) + (im2[k + 13] - bg2[k + 13 + i * imLen]) : diff[k + 13];
                    diff[k + 14] = ((im0[k + 14] - bg0[k + 14 + i * imLen]) + (im1[k + 14] - bg1[k + 14 + i * imLen]) + (im2[k + 14] - bg2[k + 14 + i * imLen]) > diff[k + 14]) ? (im0[k + 14] - bg0[k + 14 + i * imLen]) + (im1[k + 14] - bg1[k + 14 + i * imLen]) + (im2[k + 14] - bg2[k + 14 + i * imLen]) : diff[k + 14];
                    diff[k + 15] = ((im0[k + 15] - bg0[k + 15 + i * imLen]) + (im1[k + 15] - bg1[k + 15 + i * imLen]) + (im2[k + 15] - bg2[k + 15 + i * imLen]) > diff[k + 15]) ? (im0[k + 15] - bg0[k + 15 + i * imLen]) + (im1[k + 15] - bg1[k + 15 + i * imLen]) + (im2[k + 15] - bg2[k + 15 + i * imLen]) : diff[k + 15];
                }
            }
        """
        diff = np.ones((img.shape[0], img.shape[1]), dtype=bgStack[0].dtype) * \
                                                np.info(bgStack[0].dtype).min
        imLen = img.shape[0] * img.shape[1]
        bgn = bg0.shape[0]
        bgx = bg1.shape[1]
        # weave.inline(subtractionCode,
        #                         ['diff', 'bg0', 'bg1', 'bg2', 'im0',
        #                          'im1', 'im2', 'imLen', 'bgn', 'bgx'],
        #                          extra_compile_args=['-march=corei7',
        #                                              '-O3', '-fopenmp'],
        #                          headers=['<omp.h>'],
        #                          extra_link_args=['-lgomp'],
        #                          compiler='gcc')
        weave.inline(subtractionCode, [
            'diff', 'bg0', 'bg1', 'bg2', 'im0', 'im1', 'im2', 'imLen', 'bgn',
            'bgx'
        ],
                     extra_compile_args=['-O3'],
                     compiler='gcc')

        if test:
            print 'Difference: ', np.sum(
                np.abs(self.backgroundSubstractionStack(img, bgStack) -
                       diff).flatten())

        return diff
Exemplo n.º 15
0
gpas_as_list.append(4.0)
#can have multiple datatypes in it.
gpas_as_list.insert(1, "whatevs")
gpas_as_list.pop(1)
gpas_as_list

gpas = np.array(gpas_as_list)

study_minutes = np.zeros(100, np.uint16)
study_minutes

#%whos
study_minutes[0] = 150
first_day_minutes = study_minutes[0]

study_minutes[1] = 60
study_minutes[2:6] = [80, 60, 30, 90]
print("{}".format(study_minutes))

students_gpas = np.array(
    [[4.0, 3.286, 3.5, 4.0], [3.2, 3.8, 4.0, 4.0], [3.96, 3.92, 4.0, 3.6]],
    np.float16)
print("{}", format(students_gpas))

students_gpas.ndim

students_gpas.shape

students_gpas.size
print("{}".format(np.info(students_gpas)))
print("{}".format(students_gpas[1][2]))
Exemplo n.º 16
0
    print(('time for convert:\t%2.3f' % (t2-t1)))

  if args.dump:
    for x in data:
      val = convert(x)
      off = val - base
      print(('off = %d (0x%06x)' % (off, val)))

  # Display just the status flags, if results aren't wanted.
  if args.noresults:
    print("\nStatus flags:")
    tart.read_status(True)
  # Or else display the acquistion-unit's test-results.
  else:
    # Check the returned data.
    print('generate 24bit integer')
    resp_dec = (np.array(data[:,0],dtype='uint32')<<16) + (np.array(data[:,1], dtype='uint32')<<8) + (np.array(data[:,2],dtype='uint32'))
    print((np.info(resp_dec)))
    print('done')
    print(('first 10: ', resp_dec[:10]))
    print(('last 10: ', resp_dec[-10:]))

    diffs = (resp_dec[1:]-resp_dec[:-1])
    diffssum = diffs.__ne__(1).sum()
    print(diffs)
    print(('yo,', resp_dec[diffs.__ne__(1)]))
    print(('sum_of_errors: ', diffssum))
    index = np.arange(len(diffs))
    print((diffs[diffs.__ne__(1)]))
    print((index[diffs.__ne__(1)]))
Exemplo n.º 17
0
np.int64
np.float32
np.complex
np.bool
np.object
np.string_
np.unicode_
#inspecting your array
b.shape
len(b)
b.ndim
b.dtype
b.dtype.name
b.astype(int)
#asking for help
np.info(np.ndarray.dtype)

#Arithmetic operations
a =np.array([(2,4,6),(8,10,12)])
b = np.array([(1,3,5),(7,9,11)])
a+b
c = np.add(a,b)
print('result of addition ',c)
d = np.subtract(a,b)
print('result of subtraction ',d)
e=np.multiply(a,b)
print('result of multiplication ',e)

x = np.array([(10,4,12),(13,4,1)])
print(x)
y = x.sort()
Exemplo n.º 18
0
from io import StringIO
from typing import Any, Dict

import numpy as np

AR: np.ndarray[Any, np.dtype[np.float64]]
AR_DICT: Dict[str, np.ndarray[Any, np.dtype[np.float64]]]
FILE: StringIO

def func(a: int) -> bool: ...

reveal_type(np.deprecate(func))  # E: def (a: builtins.int) -> builtins.bool
reveal_type(np.deprecate())  # E: _Deprecate

reveal_type(np.deprecate_with_doc("test"))  # E: _Deprecate
reveal_type(np.deprecate_with_doc(None))  # E: _Deprecate

reveal_type(np.byte_bounds(AR))  # E: Tuple[builtins.int, builtins.int]
reveal_type(np.byte_bounds(np.float64()))  # E: Tuple[builtins.int, builtins.int]

reveal_type(np.who(None))  # E: None
reveal_type(np.who(AR_DICT))  # E: None

reveal_type(np.info(1, output=FILE))  # E: None

reveal_type(np.source(np.interp, output=FILE))  # E: None

reveal_type(np.lookfor("binary representation", output=FILE))  # E: None

reveal_type(np.safe_eval("1 + 1"))  # E: Any
Exemplo n.º 19
0
    def backgroundSubtractionWeaver(img, bgStack, test=False):
        """
        background subtraction using C++ code works on non-fortran style 
        background stacks, is less efficient than 
        backgroundSubtractionWeaverF
        
        Args:
            img (nd array):
                                input image
            bgStack (background image stack):
                                - for computation see :func:`calculateBackgroundStack`
                                - *needs to generated with fortranStyle=False*
                        
        Returns:
            difference image
            
        .. seealso::
            :func:`backgroundSubstractionStack`
            :func:`backgroundSubstractionWeaver`
            :func:`backgroundSubstractionWeaverF`
        """
        im0 = img[:,:,0].flatten()
        im1 = img[:,:,1].flatten()
        im2 = img[:,:,2].flatten()
        
        bg0 = bgStack[0]
        bg1 = bgStack[1]
        bg2 = bgStack[2]    
        
        # (very wide string)
        subtractionCode = \
        """
            // subtraction on all color layers 
            short val = 0;
            for (int i = 0; i < bgn; ++i){
                for (int k = 0; k < bgx; k += 16){
                    diff[k] = ((im0[k] - bg0[k + i * imLen]) + (im1[k] - bg1[k + i * imLen]) + (im2[k] - bg2[k + i * imLen]) > diff[k]) ? (im0[k] - bg0[k + i * imLen]) + (im1[k] - bg1[k + i * imLen]) + (im2[k] - bg2[k + i * imLen]) : diff[k];
                    diff[k + 1] = ((im0[k + 1] - bg0[k + 1 + i * imLen]) + (im1[k + 1] - bg1[k + 1 + i * imLen]) + (im2[k + 1] - bg2[k + 1 + i * imLen]) > diff[k + 1]) ? (im0[k + 1] - bg0[k + 1 + i * imLen]) + (im1[k + 1] - bg1[k + 1 + i * imLen]) + (im2[k + 1] - bg2[k + 1 + i * imLen]) : diff[k + 1];
                    diff[k +2] = ((im0[k +2] - bg0[k +2 + i * imLen]) + (im1[k +2] - bg1[k +2 + i * imLen]) + (im2[k +2] - bg2[k +2 + i * imLen]) > diff[k +2]) ? (im0[k +2] - bg0[k +2 + i * imLen]) + (im1[k +2] - bg1[k +2 + i * imLen]) + (im2[k +2] - bg2[k +2 + i * imLen]) : diff[k +2];
                    diff[k + 3] = ((im0[k + 3] - bg0[k + 3 + i * imLen]) + (im1[k + 3] - bg1[k + 3 + i * imLen]) + (im2[k + 3] - bg2[k + 3 + i * imLen]) > diff[k + 3]) ? (im0[k + 3] - bg0[k + 3 + i * imLen]) + (im1[k + 3] - bg1[k + 3 + i * imLen]) + (im2[k + 3] - bg2[k + 3 + i * imLen]) : diff[k + 3];
                    diff[k + 4] = ((im0[k + 4] - bg0[k + 4 + i * imLen]) + (im1[k + 4] - bg1[k + 4 + i * imLen]) + (im2[k + 4] - bg2[k + 4 + i * imLen]) > diff[k + 4]) ? (im0[k + 4] - bg0[k + 4 + i * imLen]) + (im1[k + 4] - bg1[k + 4 + i * imLen]) + (im2[k + 4] - bg2[k + 4 + i * imLen]) : diff[k + 4];
                    diff[k + 5] = ((im0[k + 5] - bg0[k + 5 + i * imLen]) + (im1[k + 5] - bg1[k + 5 + i * imLen]) + (im2[k + 5] - bg2[k + 5 + i * imLen]) > diff[k + 5]) ? (im0[k + 5] - bg0[k + 5 + i * imLen]) + (im1[k + 5] - bg1[k + 5 + i * imLen]) + (im2[k + 5] - bg2[k + 5 + i * imLen]) : diff[k + 5];
                    diff[k + 6] = ((im0[k + 6] - bg0[k + 6 + i * imLen]) + (im1[k + 6] - bg1[k + 6 + i * imLen]) + (im2[k + 6] - bg2[k + 6 + i * imLen]) > diff[k + 6]) ? (im0[k + 6] - bg0[k + 6 + i * imLen]) + (im1[k + 6] - bg1[k + 6 + i * imLen]) + (im2[k + 6] - bg2[k + 6 + i * imLen]) : diff[k + 6];
                    diff[k + 7] = ((im0[k + 7] - bg0[k + 7 + i * imLen]) + (im1[k + 7] - bg1[k + 7 + i * imLen]) + (im2[k + 7] - bg2[k + 7 + i * imLen]) > diff[k + 7]) ? (im0[k + 7] - bg0[k + 7 + i * imLen]) + (im1[k + 7] - bg1[k + 7 + i * imLen]) + (im2[k + 7] - bg2[k + 7 + i * imLen]) : diff[k + 7];
                    diff[k + 8] = ((im0[k + 8] - bg0[k + 8 + i * imLen]) + (im1[k + 8] - bg1[k + 8 + i * imLen]) + (im2[k + 8] - bg2[k + 8 + i * imLen]) > diff[k + 8]) ? (im0[k + 8] - bg0[k + 8 + i * imLen]) + (im1[k + 8] - bg1[k + 8 + i * imLen]) + (im2[k + 8] - bg2[k + 8 + i * imLen]) : diff[k + 8];
                    diff[k + 9] = ((im0[k + 9] - bg0[k + 9 + i * imLen]) + (im1[k + 9] - bg1[k + 9 + i * imLen]) + (im2[k + 9] - bg2[k + 9 + i * imLen]) > diff[k + 9]) ? (im0[k + 9] - bg0[k + 9 + i * imLen]) + (im1[k + 9] - bg1[k + 9 + i * imLen]) + (im2[k + 9] - bg2[k + 9 + i * imLen]) : diff[k + 9];
                    diff[k + 10] = ((im0[k + 10] - bg0[k + 10 + i * imLen]) + (im1[k + 10] - bg1[k + 10 + i * imLen]) + (im2[k + 10] - bg2[k + 10 + i * imLen]) > diff[k + 10]) ? (im0[k + 10] - bg0[k + 10 + i * imLen]) + (im1[k + 10] - bg1[k + 10 + i * imLen]) + (im2[k + 10] - bg2[k + 10 + i * imLen]) : diff[k + 10];
                    diff[k + 11] = ((im0[k + 11] - bg0[k + 11 + i * imLen]) + (im1[k + 11] - bg1[k + 11 + i * imLen]) + (im2[k + 11] - bg2[k + 11 + i * imLen]) > diff[k + 11]) ? (im0[k + 11] - bg0[k + 11 + i * imLen]) + (im1[k + 11] - bg1[k + 11 + i * imLen]) + (im2[k + 11] - bg2[k + 11 + i * imLen]) : diff[k + 11];
                    diff[k + 12] = ((im0[k + 12] - bg0[k + 12 + i * imLen]) + (im1[k + 12] - bg1[k + 12 + i * imLen]) + (im2[k + 12] - bg2[k + 12 + i * imLen]) > diff[k + 12]) ? (im0[k + 12] - bg0[k + 12 + i * imLen]) + (im1[k + 12] - bg1[k + 12 + i * imLen]) + (im2[k + 12] - bg2[k + 12 + i * imLen]) : diff[k + 12];
                    diff[k + 13] = ((im0[k + 13] - bg0[k + 13 + i * imLen]) + (im1[k + 13] - bg1[k + 13 + i * imLen]) + (im2[k + 13] - bg2[k + 13 + i * imLen]) > diff[k + 13]) ? (im0[k + 13] - bg0[k + 13 + i * imLen]) + (im1[k + 13] - bg1[k + 13 + i * imLen]) + (im2[k + 13] - bg2[k + 13 + i * imLen]) : diff[k + 13];
                    diff[k + 14] = ((im0[k + 14] - bg0[k + 14 + i * imLen]) + (im1[k + 14] - bg1[k + 14 + i * imLen]) + (im2[k + 14] - bg2[k + 14 + i * imLen]) > diff[k + 14]) ? (im0[k + 14] - bg0[k + 14 + i * imLen]) + (im1[k + 14] - bg1[k + 14 + i * imLen]) + (im2[k + 14] - bg2[k + 14 + i * imLen]) : diff[k + 14];
                    diff[k + 15] = ((im0[k + 15] - bg0[k + 15 + i * imLen]) + (im1[k + 15] - bg1[k + 15 + i * imLen]) + (im2[k + 15] - bg2[k + 15 + i * imLen]) > diff[k + 15]) ? (im0[k + 15] - bg0[k + 15 + i * imLen]) + (im1[k + 15] - bg1[k + 15 + i * imLen]) + (im2[k + 15] - bg2[k + 15 + i * imLen]) : diff[k + 15];
                }
            }
        """
        diff = np.ones((img.shape[0], img.shape[1]), dtype=bgStack[0].dtype) * \
                                                np.info(bgStack[0].dtype).min
        imLen = img.shape[0] * img.shape[1]
        bgn = bg0.shape[0]
        bgx = bg1.shape[1]
        # weave.inline(subtractionCode,
        #                         ['diff', 'bg0', 'bg1', 'bg2', 'im0',
        #                          'im1', 'im2', 'imLen', 'bgn', 'bgx'],
        #                          extra_compile_args=['-march=corei7',
        #                                              '-O3', '-fopenmp'],
        #                          headers=['<omp.h>'],
        #                          extra_link_args=['-lgomp'],
        #                          compiler='gcc')
        weave.inline(subtractionCode,
                                ['diff', 'bg0', 'bg1', 'bg2', 'im0',
                                 'im1', 'im2', 'imLen', 'bgn', 'bgx'],
                                 extra_compile_args=['-O3'],
                                 compiler='gcc')
        
        if test:
            print 'Difference: ', np.sum(np.abs(self.backgroundSubstractionStack(img,bgStack) - diff).flatten())

        return diff
Exemplo n.º 20
0
matrix.dot(matrix2)  #Скалярное произведение.
""" Axis """
# axis 0 - ось строк (направление)
# axis 1 - ось столбцов (направление)

np.hstack((arr3, arr7))  #Соединение массивов как строки

np.vstack((arr3, arr9))  #Соединение массивов как столбцы

matrix4 = np.array([(1, 2, 3), (4, 5, 6), (7, 8, 9)])

matrix4 = matrix4.T  # Транспонирование - стобцы и строки меняются местами

matrix4.flatten()  # "Сжатие" в 1D массив

np.linalg.inv(matrix4)  # Обратная матрица

np.linalg.det(matrix4)  # Определитель

np.linalg.matrix_rank(matrix4)  # Ранк матрицы

np.linalg.eig(matrix4)  # Находит собственные числа и векторы матрицы
""" Доп.функции """

np.info(np.eye)  # Справка. Как работает та или иная функция

np.loadtxt('')
np.genfromtxt()
np.savetxt('.txt')
np.savetxt('.csv')
Exemplo n.º 21
0
# How to get the documentation of the numpy add function from the command line ? (★☆☆)
import numpy as np

np.info(np.add)
Exemplo n.º 22
0
print("Convert the array into different type: ", my_array.astype(int))

# TRANSPOSING ARRAY

# Transpose `x`
print("Array using transpose : \n", np.transpose(x))

# Or use `T` to transpose `my_2d_array`
print("Array using .T option to transpose :\n ", x.T)

# Use lookfor() to do a keyword search on docstrings.
# Look up info on `mean` with `np.lookfor()`

print(np.lookfor("mean"))
# Get info on data types with `np.info()`
print(np.info(np.x.dtype))

# Initialize your array
my_3d_array = np.array(
    [[[1, 2, 3, 4], [5, 6, 7, 8]], [[1, 2, 3, 4], [9, 10, 11, 12]]],
    dtype=np.int64)

# Pass the array to `np.histogram()`
# histogram computes the occurrences of the array that fall within each
# bin which determines the area that each bar of your histogram takes up

print(np.histogram(my_3d_array))

# Specify the number of bins
print(np.histogram(my_3d_array, bins=range(0, 13)))
Exemplo n.º 23
0
e = np.full((2, 2), 7)
e

f = np.eye(2)
f
np.eye(3, 4)

np.random.random((2, 2))
np.empty((3, 2))          #!!!!! ?????
z = np.empty((3, 2))          #!!!!! ?????
z
np.empty((8, 9))    # WHAT THE HELL IT IS ????

#%%

np.info(np.ndarray)   # ???

#%%
#%% SAVING AND LOADING

#%% BINARY

#%%

np.save('arr1', a)
# ls
del(a)
np.load('arr1.npy')
a
a = np.load('arr1.npy')
a
Exemplo n.º 24
0
    def wx_proc_msg(self, body):
        try:
            wechat.parse_data(body)
        except ParseError:
            print('[ERROR] Parse message failed.')
            return
        id = wechat.message.id  # MsgId
        target = wechat.message.target  # ToUserName
        source = wechat.message.source  # FromUserName
        time = wechat.message.time  # CreateTime
        type = wechat.message.type  # MsgType
        raw = wechat.message.raw  # raw text
        if isinstance(wechat.message, TextMessage):
            content = wechat.message.content
            if len(content.replace(' ', '')) == 0:
                return wechat.response_none()
            reply = auto_reply.reply(content)
            if reply is not None:
                return wechat.response_text(content=reply)
            else:
                return wechat.response_none()

#        if isinstance(wechat.message, ImageMessage):
#            picurl = wechat.message.picurl                     # PicUrl
#            media_id = wechat.message.media_id                 # MediaId
#            msg_id = wechat.message.msg_id                     # MsgId
#            create_time = wechat.message.create_time           # CreateTime
##            wechat.response_text(content=u'%s'%picurl)
#            return wechat.response_text(content=u'尝试做下图片分析~')

        if isinstance(wechat.message, ImageMessage):
            picurl = wechat.message.picurl  # PicUrl
            media_id = wechat.message.media_id  # MediaId
            msg_id = wechat.message.msg_id  # MsgId
            create_time = wechat.message.create_time  # CreateTime
            #            wechat.response_text(content=u'%s'%picurl)
            #            wechat.response_text(content=u'尝试做下图片分析~')

            vision_results = google_vision_analysis.analyse(
                picture_url=picurl,
                picture_mediaID=media_id,
                picture_msgID=msg_id,
                picture_createtime=create_time)
            print('vis_results_info: ' + str(np.info(vision_results)))
            if vision_results is not None:

                vision_results_text = 'text: '
                vision_results_label = 'label: '
                vision_results_simurl = 'weburl: '
                vision_results_face = 'face: '
                vision_results_landmark = 'landmark: '

                try:
                    vision_results_text = (
                        'Albert Mozart:\n 图片文字:' + vision_results['responses']
                        [0]['textAnnotations'][0]['description'])
                    print(vision_results_text)
#                    wechat.response_text(content=vision_results_text)
                except:
                    pass

                try:
                    vision_results_label = ('Albert Mozart:\n 图片内容分析:' + str([
                        vision_results['responses'][0]['labelAnnotations']
                        [index]['description'] for index in range(
                            len(vision_results['responses'][0]
                                ['labelAnnotations']))
                    ])[1:-1])
                    print(vision_results_label)
                    #vision_results_label = ('Albert Mozart:\n 图片内容分析:' + str([(vision_results['responses'][0]['labelAnnotations'][index]['description'], vision_results['responses'][0]['labelAnnotations'][index]['description']) for index in range(len(vision_results['responses'][0]['labelAnnotations']))])[1:-1])
                except:
                    pass

                try:
                    vision_results_simurl = ('Albert Mozart:\n 联想图片:' + str(
                        vision_results['responses'][0]['webDetection']
                        ['bestGuessLabels'][0]['label']) + ', ' + str([
                            vision_results['responses'][0]['webDetection']
                            ['visuallySimilarImages'][ind]['url']
                            for ind in range(
                                len(vision_results['responses'][0]
                                    ['webDetection']['visuallySimilarImages']))
                        ])[1:-1])
                    print(vision_results_simurl)
                except:
                    pass

                try:
                    vision_results_face_raw = vision_results['responses'][0][
                        'faceAnnotations'][0]
                    vision_results_face = dict(vision_results_face_raw)
                    del vision_results_face['landmarks']
                    del vision_results_face['boundingPoly']
                    del vision_results_face['fdBoundingPoly']
                    vision_results_face = ('Albert Mozart:\n 人脸分析:' +
                                           str(vision_results_face)[1:-1])
                    print(vision_results_face)
                except:
                    pass

                try:
                    vision_results_landmark = ('Albert Mozart:\n 地标分析:' + str(
                        [(vision_results['responses'][0]['landmarkAnnotations']
                          [index]['description'], vision_results['responses']
                          [0]['landmarkAnnotations'][index]['locations'])
                         for index in range(
                             len(vision_results['responses'][0]
                                 ['landmarkAnnotations']))])[1:-1])
                    print(vision_results_landmark)
                except:
                    pass

                return wechat.response_text(
                    content=(vision_results_text + '\n' +
                             vision_results_label + '\n\n' +
                             vision_results_simurl + '\n\n' +
                             vision_results_face + '\n\n' +
                             vision_results_landmark + '\n\n')
                )  #, wechat.response_text(content=vision_results_label), wechat.response_text(content=vision_results_simurl), wechat.response_text(content=vistion_results_face), wechat.response_text(content=vision_results_landmark)

#                except:
#                    return wechat.response_text(content=u'突然有事儿,下次吧...')

            else:
                return wechat.response_text(content=u'这次不大行了,下次吧...')

        if isinstance(wechat.message, VoiceMessage):
            media_id = wechat.message.media_id  # MediaId
            format = wechat.message.format  # Format
            recognition = wechat.message.recognition  # Recognition
        if isinstance(wechat.message, VideoMessage) or isinstance(
                wechat.message, ShortVideoMessage):
            media_id = wechat.message.media_id  # MediaId
            thumb_media_id = wechat.message.thumb_media_id  # ThumbMediaId
        if isinstance(wechat.message, LocationMessage):
            location = wechat.message.location  # Tuple(X, Y),(Location_X, Location_Y)
            scale = wechat.message.scale  # Scale
            label = wechat.message.label  # Label
        if isinstance(wechat.message, LinkMessage):
            title = wechat.message.title  # Title
            description = wechat.message.description  # Description
            url = wechat.message.url  # Url
        if isinstance(wechat.message, EventMessage):
            if wechat.message.type == 'subscribe':  # subscribe
                key = wechat.message.key  # EventKey
                ticket = wechat.message.ticket  # Ticket
                mongo.upsert_user(source)
                return wechat.response_text(content=u'''欢迎关注''')
            elif wechat.message.type == 'unsubscribe':  # unsubscribe
                mongo.delete_user(source)
                return None
            elif wechat.message.type == 'scan':  # scan
                key = wechat.message.key  # EventKey
                ticket = wechat.message.ticket  # Ticket
            elif wechat.message.type == 'location':  # location
                latitude = wechat.message.latitude  # Latitude
                longitude = wechat.message.longitude  # Longitude
                precision = wechat.message.precision  # Precision
            elif wechat.message.type == 'click':  # menu click
                key = wechat.message.key  # EventKey
                if key == 'HOST_ADD':
                    host_count = mongo.host_count(source)
                    if host_count >= max_host_count:
                        return wechat.response_text(
                            content=u'添加主机失败,已达到最大主机数目')
                    host_id = mongo.insert_host(source)
                    return wechat.response_text(content=u'添加主机成功,主机ID:' +
                                                host_id)
                elif key == 'HOST_DELETE':
                    hosts = mongo.query_hosts(source)
                    if hosts is None or len(hosts) == 0:
                        return wechat.response_text(content=u'您还尚未添加任何主机')
                    resp = u'选择需要删除的主机:\n'
                    for i in range(len(hosts)):
                        resp += u'''<a href="http://lwons.com/fw/host_delete?id=%s">%s</a>\n''' % (
                            hosts[i]['id'], hosts[i]['id'])
                    return wechat.response_text(content=resp)
                elif key == 'HOST_STATUS':
                    return wechat.response_text(
                        content=
                        u'''<a href="http://lwons.com/fw/host_status?id=%s">点击查看主机状态</a>'''
                        % source)
                elif key == 'HOST_COMMAND':
                    return wechat.response_text(
                        content=
                        u'''<a href="http://lwons.com/fw/host_cmmd?id=%s">进入命令页</a>'''
                        % source)
                elif key == 'MINE_PROFILE':
                    return wechat.response_text(content=u'个人信息')
                elif key == 'MINE_HOSTS':
                    hosts = mongo.query_hosts(source)
                    if hosts is None or len(hosts) == 0:
                        return wechat.response_text(content=u'您还尚未添加任何主机')
                    resp = u'您的所有主机:\n'
                    for i in range(len(hosts)):
                        resp += u'%s  %s\n' % (hosts[i]['id'],
                                               hosts[i]['time'])
                    return wechat.response_text(content=resp)
            elif wechat.message.type == 'view':  # menu link view
                key = wechat.message.key  # EventKey
                return wechat.response_text(key, escape=True)
            elif wechat.message.type == 'templatesendjobfinish':  # template
                status = wechat.message.status  # Status
            elif wechat.message.type in [
                    'scancode_push', 'scancode_waitmsg', 'pic_sysphoto',
                    'pic_photo_or_album', 'pic_weixin', 'location_select'
            ]:  # others
                key = wechat.message.key  # EventKey
        return wechat.response_text(content=u'知道了')
Exemplo n.º 25
0
print(xmean, xmean - 2.576 * sigma / scipy.sqrt(n),
      xmean + 2.576 * sigma / scipy.sqrt(n))
plt.stem(scores)
plt.show()

result = scipy.stats.bayes_mvs(scores)
help(scipy.stats.bayes_mvs)
print(result[0])

print('#', 50 * "-")
# -----------------------
import scipy.stats
help(scipy.stats)
help(scipy.stats.bayes_mvs)
help(scipy.stats.kurtosis)
numpy.info('random')
print('#', 50 * "-")
# -----------------------
import scipy.misc
img = scipy.misc.ascent()
plt.imshow(img)
plt.show()
print(img[0:3, 0:7])
print(img)
img = scipy.misc.face()
plt.imshow(img)
plt.show()
print(img[0:3, 0:7])
print(img)
print('#', 50 * "-")
# -----------------------
Exemplo n.º 26
0
    Time=np.linspace(0, len(signal)/rate, num=len(signal))

    plt.figure(1)
    plt.title('Signal Wave of test file (with filter)')
    plt.xlabel('Time (s)')
    plt.ylabel('frequency')
    plt.plot(Time,signal)
    plt.show()

rate, signal = wavfile.read("data/recording-0.wav")

#mask = envelope(signal, rate, 100)#this works at filtering out silence but thats actually not what I want because then I cant tell when events start and when they end
#signal = signal[mask]

print(rate)
print(np.info(signal))

plot_signals()

data_size = len(signal)
#focus_size = int(0.15 * rate)
length = int(4 * rate)  #rate is how many samples per seccond, so for 5 seconds we will need the number of samples x 5 ahead of the peak
min_val = 1000
#noise_thresh = 500
focuses = []
#distances = []
sub_signals = []
idx = 0
while idx < data_size:
    if( abs(signal[idx]) > min_val):
        point = {
Exemplo n.º 27
0
np.zeros(3)#:创建长度为3的一维数组且数组元素均为0,返回ndarray对象
np.ones((3,4))#:创建3×4的二维数组且数组元素均为1,返回ndarray对象
np.eye(5)#:创建一个5×5的二维数组且对角线元素均为1,其他元素均为0,返回ndarray对象
np.linspace(0,100,6)#:创建一维数组且其元素为0到100之间的6等分数字,返回ndarray对象
np.arange(0,10,3)#:创建一维数组且其元素为以0为起点,步长为3,直到小于10的所有数值,返回ndarray对象
np.full((2,3),8)#:创建2×3二维数组且其所有元素均为8,返回ndarray对象
np.random.rand(4,5)#:创建4×5二维数组且其所有元素为0-1之间的随机小数,返回ndarray对象
np.random.rand(6,7)*100#:创建6×7二维数组且其所有元素为0-100之间的随机小数,返回ndarray对象
np.random.randint(5,size=(2,3))#:创建2×3二维数组且其所有元素为0-4之间的随机整数,返回ndarray对象
#3)获取数组属性
arr.size#:返回数组arr中元素的个数
arr.shape#:返回数组arr的维数(行数和列数)
arr.dtype#:返回数组arr中元素的类型
arr.astype(dtype)#:强制转换数组arr中元素的类型为dtype
arr.tolist()#:将数组arr强制转换为Python列表
np.info(np.eye)#:查看关于np.eye的文档
#4)复制、排序和调整数组
np.copy(arr)#:复制数组arr,返回ndarray对象
arr.view(dtype)#:以指定dtype类型为数组arr每个元素建立视图
arr.sort()#:排序数组,返回ndarray对象
arr.sort(axis=0)#:按指定的轴排序数组,返回ndarray对象
two_d_arr.flatten()#:将二维数组two_d_arr转换为一维数组,返回ndarray对象
arr.T#:返回数组arr的转置(行与列互换)
arr.reshape(3,4)#:将数组arr调整为3行4列,并不改变数据,返回ndarray对象
arr.resize((5,6))#:将数组arr调整为5行6列,空值用0填充,返回ndarray对象
#5)增加、删除元素
np.append(arr,values)#:为数组arr增加元素values,返回ndarray对象
np.insert(arr,2,values)#:为数组arr在索引为2的元素之前插入元素values,返回ndarray对象
np.delete(arr,3,axis=0)#:删除数组arr第3行所有的元素,返回ndarray对象
np.delete(arr,4,axis=1)#:删除数组arr第4列所有的元素,返回ndarray对象
#6)组合与拆分
Exemplo n.º 28
0
 def task2(self):
     np.info(np.add)
Exemplo n.º 29
0
from __future__ import annotations

from io import StringIO
from typing import Any

import numpy as np

FILE = StringIO()
AR: np.ndarray[Any, np.dtype[np.float64]] = np.arange(10).astype(np.float64)


def func(a: int) -> bool:
    ...


np.deprecate(func)
np.deprecate()

np.deprecate_with_doc("test")
np.deprecate_with_doc(None)

np.byte_bounds(AR)
np.byte_bounds(np.float64())

np.info(1, output=FILE)

np.source(np.interp, output=FILE)

np.lookfor("binary representation", output=FILE)
Exemplo n.º 30
0
import numpy as np
import scipy
import scipy.spatial

print(np.__version__)
np.show_config()


Z = np.zeros(10)
print(Z)

print(np.info(np.add))

Z = np.arange(10, 50)
print(Z)

Z=Z[::-1] #reverse the array
print(Z)

Z = np.arange(0,9)
Z=Z.reshape(3,3)
print(Z)

Z = np.array([1,2,0,0,4,0])
Z = np.nonzero(Z)
print(Z) #index of the nonzero

Z = np.eye(3,3)
print(Z)

Z = np.random.random((3,3,3))
Exemplo n.º 31
0
import numpy as np 

# NumPy Version 
np.__version__

# NumPy build config 
np.show_config() 

\begin{exercise}
Write a NumPy program to get help on the add function.
\end{exercise}


# get help from NumPy 
np.info(np.add)

\begin{exercise}
Write a NumPy program to test whether none of the elements of a given array is zero.
\end{exercise}

# Solution: if zero not exist 
A1 = np.array([2, 3, 4, 5 , 6]) 
np.all(A1)

# Solution: if zero exist in array 
A2 = np.array([0, 0, 2, 3, 4, 5 , 6]) 
np.all(A2)

\begin{exercise}
Write a NumPy program to test whether any of the elements of a given array is non-zero.
Exemplo n.º 32
0
print(np.__version__)

n = int(input())
Z = np.zeros(n)
print(Z)

params = input().split()
t = 'float64' if params[-1].isdigit() else params.pop()
Z = np.zeros(tuple(map(int, params)), dtype=t)
print(Z)

Z = np.zeros((10, 10))
print(Z.size * Z.itemsize)

np.info(np.add)
np.info(np.array)

Z = np.zeros(int(input()))
Z[int(input())] = 1
print(Z)

Z = np.arange(int(input()), int(input()) + 1)

Z = np.arange(50)
Z = Z[::-1]
print(Z)

Z = np.arange(int(input())).reshape(list(map(int, input().split())))
print(Z)
Exemplo n.º 33
0
#C# Numpy arrays
#C# - Array data types
#C# - Array operations
#C# Functions
#C# - Array creation
#C# - Random number generation
#C# - Arithmetic
#C# - Trigonometry

#T# Beginning of content

# |-------------------------------------------------------------
#T# numpy has an specific function to get help for names in the namespace of numpy, it's the numpy.info function which is used as the builtin help function from Python, this is important because numpy ufuncs are written in C, an so the help function can't show their help
import numpy as np
np.info(np.array)  #| shows the numpy help for np.array
# |-------------------------------------------------------------

#C# Numpy arrays

# |-------------------------------------------------------------
#T# arrays are one of the main aspects of the numpy package, numpy does not support jagged arrays for its operations

#T# numpy arrays are multidimensional, the rank of an array is the amount of dimensions of the array, the size of an array is the total amount of individual elements in the array

#T# several numpy operations and functions can handle operand arrays of different sizes and with different number of dimensions, this is called broadcasting, in it, the smaller array is broadcasted (repeated) over the larger array, e.g. a 3 element vector can be broadcasted over a 4x3 matrix, by repeating it in each of the 4 rows and then operating element-wise

#T# numpy arrays can be created with the array function
import numpy as np
arr1 = np.array(('a', 'b', 'c'))  # array(['a', 'b', 'c'], dtype='<U1')
arr1 = np.array([1, 2, 3])  # array([1, 2, 3])
Exemplo n.º 34
0
  t.debug(on=1)
  t.debug(on=0)
  t.debug(on=0)
  t.reset()
  t.reset()
  t.reset()





  t.debug(args.internal)
  t.start_acquisition(sleeptime=3)

  data = t.read_data(num_bytes=num_bytes, blocksize=1024)
  print 'generate 24bit integer'
  resp_dec = (np.array(data[:,0],dtype='uint32')<<16) + (np.array(data[:,1], dtype='uint32')<<8) + (np.array(data[:,2],dtype='uint32'))
  print np.info(resp_dec)
  print 'done'
  print 'first 10: ', resp_dec[:10]
  print 'last 10: ', resp_dec[-10:]

  diffs = (resp_dec[1:]-resp_dec[:-1])
  diffssum = diffs.__ne__(1).sum()
  print diffs
  print 'yo,', resp_dec[diffs.__ne__(1)]
  print 'sum_of_errors: ', diffssum
  index = np.arange(len(diffs))
  print diffs[diffs.__ne__(1)]
  print index[diffs.__ne__(1)] 
Exemplo n.º 35
0
# -*- coding: utf-8 -*-
"""
Write a NumPy program to get help on the add function. 

@author: dreamy
"""
import numpy as np
print(np.info(np.add))
# coding: utf-8

# In[1]:

import numpy as np

# In[2]:

np.__version__

# Q1. Search for docstrings of the numpy functions on linear algebra.

# In[4]:

np.lookfor('linear algebra')

# Q2. Get help information for numpy dot function.

# In[9]:

np.info(np.dot)