######################################################## Copyright (c) 2015, ArrayFire# All rights reserved.## This file is distributed under 3-clause BSD license.# The complete license agreement can be obtained at:# http://arrayfire.com/licenses/BSD-3-Clause########################################################"""Module containing enums and other constants."""importplatformimportctypesasctimporttracebackimportosimportsysc_float_t=ct.c_floatc_double_t=ct.c_doublec_int_t=ct.c_intc_uint_t=ct.c_uintc_longlong_t=ct.c_longlongc_ulonglong_t=ct.c_ulonglongc_char_t=ct.c_charc_bool_t=ct.c_boolc_uchar_t=ct.c_ubytec_short_t=ct.c_shortc_ushort_t=ct.c_ushortc_pointer=ct.pointerc_void_ptr_t=ct.c_void_pc_char_ptr_t=ct.c_char_pc_size_t=ct.c_size_tc_cast=ct.cast[docs]classaf_cfloat_t(ct.Structure):_fields_=[("real",ct.c_float),("imag",ct.c_float)] [docs]classaf_cdouble_t(ct.Structure):_fields_=[("real",ct.c_double),("imag",ct.c_double)] AF_VER_MAJOR='3'FORGE_VER_MAJOR='1'# Work around for unexpected architecturesif'c_dim_t_forced'inglobals():globalc_dim_t_forcedc_dim_t=c_dim_t_forcedelse:# dim_t is long long by defaultc_dim_t=c_longlong_t# Change to int for 32 bit x86 and amr architecturesif(platform.architecture()[0][0:2]=='32'and(platform.machine()[-2:]=='86'orplatform.machine()[0:3]=='arm')):c_dim_t=c_int_ttry:fromenumimportEnumas_Enumdef_Enum_Type(v):returnvexceptImportError:class_MetaEnum(type):def__init__(cls,name,bases,attrs):forattrname,attrvalueinattrs.iteritems():ifname!='_Enum'andisinstance(attrvalue,_Enum_Type):attrvalue.__class__=clsattrs[attrname]=attrvalueclass_Enum(object):__metaclass__=_MetaEnumclass_Enum_Type(object):def__init__(self,v):self.value=v[docs]classERR(_Enum):""" Error values. For internal use only. """NONE=_Enum_Type(0)#100-199 Errors in environmentNO_MEM=_Enum_Type(101)DRIVER=_Enum_Type(102)RUNTIME=_Enum_Type(103)# 200-299 Errors in input parametersINVALID_ARRAY=_Enum_Type(201)ARG=_Enum_Type(202)SIZE=_Enum_Type(203)TYPE=_Enum_Type(204)DIFF_TYPE=_Enum_Type(205)BATCH=_Enum_Type(207)DEVICE=_Enum_Type(208)# 300-399 Errors for missing software featuresNOT_SUPPORTED=_Enum_Type(301)NOT_CONFIGURED=_Enum_Type(302)NONFREE=_Enum_Type(303)# 400-499 Errors for missing hardware featuresNO_DBL=_Enum_Type(401)NO_GFX=_Enum_Type(402)NO_HALF=_Enum_Type(403)# 500-599 Errors specific to the heterogeneous APILOAD_LIB=_Enum_Type(501)LOAD_SYM=_Enum_Type(502)ARR_BKND_MISMATCH=_Enum_Type(503)# 900-999 Errors from upstream libraries and runtimesINTERNAL=_Enum_Type(998)UNKNOWN=_Enum_Type(999) [docs]classDtype(_Enum):""" Error values. For internal use only. """f32=_Enum_Type(0)c32=_Enum_Type(1)f64=_Enum_Type(2)c64=_Enum_Type(3)b8=_Enum_Type(4)s32=_Enum_Type(5)u32=_Enum_Type(6)u8=_Enum_Type(7)s64=_Enum_Type(8)u64=_Enum_Type(9)s16=_Enum_Type(10)u16=_Enum_Type(11)f16=_Enum_Type(12) [docs]classSource(_Enum):""" Source of the pointer """device=_Enum_Type(0)host=_Enum_Type(1) [docs]classINTERP(_Enum):""" Interpolation method """NEAREST=_Enum_Type(0)LINEAR=_Enum_Type(1)BILINEAR=_Enum_Type(2)CUBIC=_Enum_Type(3)LOWER=_Enum_Type(4)LINEAR_COSINE=_Enum_Type(5)BILINEAR_COSINE=_Enum_Type(6)BICUBIC=_Enum_Type(7)CUBIC_SPLINE=_Enum_Type(8)BICUBIC_SPLINE=_Enum_Type(9) [docs]classPAD(_Enum):""" Edge padding types """ZERO=_Enum_Type(0)SYM=_Enum_Type(1)CLAMP_TO_EDGE=_Enum_Type(2)PERIODIC=_Enum_Type(3) [docs]classCONNECTIVITY(_Enum):""" Neighborhood connectivity """FOUR=_Enum_Type(4)EIGHT=_Enum_Type(8) [docs]classCONV_MODE(_Enum):""" Convolution mode """DEFAULT=_Enum_Type(0)EXPAND=_Enum_Type(1) [docs]classCONV_DOMAIN(_Enum):""" Convolution domain """AUTO=_Enum_Type(0)SPATIAL=_Enum_Type(1)FREQ=_Enum_Type(2) [docs]classCONV_GRADIENT(_Enum):""" Convolution gradient type """DEFAULT=_Enum_Type(0)FILTER=_Enum_Type(1)DATA=_Enum_Type(2)BIAS=_Enum_Type(3) [docs]classMATCH(_Enum):""" Match type """""" Sum of absolute differences """SAD=_Enum_Type(0)""" Zero mean SAD """ZSAD=_Enum_Type(1)""" Locally scaled SAD """LSAD=_Enum_Type(2)""" Sum of squared differences """SSD=_Enum_Type(3)""" Zero mean SSD """ZSSD=_Enum_Type(4)""" Locally scaled SSD """LSSD=_Enum_Type(5)""" Normalized cross correlation """NCC=_Enum_Type(6)""" Zero mean NCC """ZNCC=_Enum_Type(7)""" Sum of hamming distances """SHD=_Enum_Type(8) [docs]classYCC_STD(_Enum):""" YCC Standard formats """BT_601=_Enum_Type(601)BT_709=_Enum_Type(709)BT_2020=_Enum_Type(2020) [docs]classCSPACE(_Enum):""" Colorspace formats """GRAY=_Enum_Type(0)RGB=_Enum_Type(1)HSV=_Enum_Type(2)YCbCr=_Enum_Type(3) [docs]classMATPROP(_Enum):""" Matrix properties """""" None, general. """NONE=_Enum_Type(0)""" Transposed. """TRANS=_Enum_Type(1)""" Conjugate transposed. """CTRANS=_Enum_Type(2)""" Upper triangular matrix. """UPPER=_Enum_Type(32)""" Lower triangular matrix. """LOWER=_Enum_Type(64)""" Treat diagonal as units. """DIAG_UNIT=_Enum_Type(128)""" Symmetric matrix. """SYM=_Enum_Type(512)""" Positive definite matrix. """POSDEF=_Enum_Type(1024)""" Orthogonal matrix. """ORTHOG=_Enum_Type(2048)""" Tri diagonal matrix. """TRI_DIAG=_Enum_Type(4096)""" Block diagonal matrix. """BLOCK_DIAG=_Enum_Type(8192) [docs]classNORM(_Enum):""" Norm types """VECTOR_1=_Enum_Type(0)VECTOR_INF=_Enum_Type(1)VECTOR_2=_Enum_Type(2)VECTOR_P=_Enum_Type(3)MATRIX_1=_Enum_Type(4)MATRIX_INF=_Enum_Type(5)MATRIX_2=_Enum_Type(6)MATRIX_L_PQ=_Enum_Type(7)EUCLID=VECTOR_2 [docs]classCOLORMAP(_Enum):""" Colormaps """DEFAULT=_Enum_Type(0)SPECTRUM=_Enum_Type(1)COLORS=_Enum_Type(2)RED=_Enum_Type(3)MOOD=_Enum_Type(4)HEAT=_Enum_Type(5)BLUE=_Enum_Type(6) [docs]classIMAGE_FORMAT(_Enum):""" Image Formats """BMP=_Enum_Type(0)ICO=_Enum_Type(1)JPEG=_Enum_Type(2)JNG=_Enum_Type(3)PNG=_Enum_Type(13)PPM=_Enum_Type(14)PPMRAW=_Enum_Type(15)TIFF=_Enum_Type(18)PSD=_Enum_Type(20)HDR=_Enum_Type(26)EXR=_Enum_Type(29)JP2=_Enum_Type(31)RAW=_Enum_Type(34) [docs]classHOMOGRAPHY(_Enum):""" Homography Types """RANSAC=_Enum_Type(0)LMEDS=_Enum_Type(1) [docs]classBACKEND(_Enum):""" Backend libraries """DEFAULT=_Enum_Type(0)CPU=_Enum_Type(1)CUDA=_Enum_Type(2)OPENCL=_Enum_Type(4) [docs]classMARKER(_Enum):""" Markers used for different points in graphics plots """NONE=_Enum_Type(0)POINT=_Enum_Type(1)CIRCLE=_Enum_Type(2)SQUARE=_Enum_Type(3)TRIANGE=_Enum_Type(4)CROSS=_Enum_Type(5)PLUS=_Enum_Type(6)STAR=_Enum_Type(7) [docs]classMOMENT(_Enum):""" Image Moments types """M00=_Enum_Type(1)M01=_Enum_Type(2)M10=_Enum_Type(4)M11=_Enum_Type(8)FIRST_ORDER=_Enum_Type(15) [docs]classBINARYOP(_Enum):""" Binary Operators """ADD=_Enum_Type(0)MUL=_Enum_Type(1)MIN=_Enum_Type(2)MAX=_Enum_Type(3) [docs]classRANDOM_ENGINE(_Enum):""" Random engine types """PHILOX_4X32_10=_Enum_Type(100)THREEFRY_2X32_16=_Enum_Type(200)MERSENNE_GP11213=_Enum_Type(300)PHILOX=PHILOX_4X32_10THREEFRY=THREEFRY_2X32_16DEFAULT=PHILOX [docs]classSTORAGE(_Enum):""" Matrix Storage types """DENSE=_Enum_Type(0)CSR=_Enum_Type(1)CSC=_Enum_Type(2)COO=_Enum_Type(3) [docs]classCANNY_THRESHOLD(_Enum):""" Canny Edge Threshold types """MANUAL=_Enum_Type(0)AUTO_OTSU=_Enum_Type(1) [docs]classFLUX(_Enum):""" Flux functions """DEFAULT=_Enum_Type(0)QUADRATIC=_Enum_Type(1)EXPONENTIAL=_Enum_Type(2) [docs]classDIFFUSION(_Enum):""" Diffusion equations """DEFAULT=_Enum_Type(0)GRAD=_Enum_Type(1)MCDE=_Enum_Type(2) [docs]classTOPK(_Enum):""" Top-K ordering """DEFAULT=_Enum_Type(0)MIN=_Enum_Type(1)MAX=_Enum_Type(2) [docs]classITERATIVE_DECONV(_Enum):""" Iterative deconvolution algorithm """DEFAULT=_Enum_Type(0)LANDWEBER=_Enum_Type(1)RICHARDSONLUCY=_Enum_Type(2) [docs]classINVERSE_DECONV(_Enum):""" Inverse deconvolution algorithm """DEFAULT=_Enum_Type(0)TIKHONOV=_Enum_Type(1) [docs]classVARIANCE(_Enum):""" Variance bias type """DEFAULT=_Enum_Type(0)SAMPLE=_Enum_Type(1)POPULATION=_Enum_Type(2) _VER_MAJOR_PLACEHOLDER="__VER_MAJOR__"def_setup():platform_name=platform.system()try:AF_PATH=os.environ['AF_PATH']exceptKeyError:AF_PATH=NonepassAF_SEARCH_PATH=AF_PATHtry:CUDA_PATH=os.environ['CUDA_PATH']exceptKeyError:CUDA_PATH=NonepassCUDA_FOUND=Falseassert(len(platform_name)>=3)ifplatform_name=='Windows'orplatform_name[:3]=='CYG':## Windows specific setuppre=''post='.dll'ifplatform_name=="Windows":''' Supressing crashes caused by missing dlls http://stackoverflow.com/questions/8347266/missing-dll-print-message-instead-of-launching-a-popup https://msdn.microsoft.com/en-us/library/windows/desktop/ms680621.aspx '''ct.windll.kernel32.SetErrorMode(0x0001|0x0002)ifAF_SEARCH_PATHisNone:AF_SEARCH_PATH="C:/Program Files/ArrayFire/v"+AF_VER_MAJOR+"/"ifCUDA_PATHisnotNone:CUDA_FOUND=os.path.isdir(CUDA_PATH+'/bin')andos.path.isdir(CUDA_PATH+'/nvvm/bin/')elifplatform_name=='Darwin':## OSX specific setuppre='lib'post='.'+_VER_MAJOR_PLACEHOLDER+'.dylib'ifAF_SEARCH_PATHisNone:ifos.path.exists('/opt/arrayfire'):AF_SEARCH_PATH='/opt/arrayfire/'else:AF_SEARCH_PATH='/usr/local/'ifCUDA_PATHisNone:CUDA_PATH='/usr/local/cuda/'CUDA_FOUND=os.path.isdir(CUDA_PATH+'/lib')andos.path.isdir(CUDA_PATH+'/nvvm/lib')elifplatform_name=='Linux':pre='lib'post='.so.'+_VER_MAJOR_PLACEHOLDERifAF_SEARCH_PATHisNone:ifos.path.exists('/opt/arrayfire-'+AF_VER_MAJOR+'/'):AF_SEARCH_PATH='/opt/arrayfire-'+AF_VER_MAJOR+'/'elifos.path.exists('/opt/arrayfire/'):AF_SEARCH_PATH='/opt/arrayfire/'else:AF_SEARCH_PATH='/usr/local/'ifCUDA_PATHisNone:CUDA_PATH='/usr/local/cuda/'ifplatform.architecture()[0][:2]=='64':CUDA_FOUND=os.path.isdir(CUDA_PATH+'/lib64')andos.path.isdir(CUDA_PATH+'/nvvm/lib64')else:CUDA_FOUND=os.path.isdir(CUDA_PATH+'/lib')andos.path.isdir(CUDA_PATH+'/nvvm/lib')else:raiseOSError(platform_name+' not supported')returnpre,post,AF_PATH,AF_SEARCH_PATH,CUDA_FOUNDclass_clibrary(object):def__find_nvrtc_builtins_libname(self,search_path):filelist=os.listdir(search_path)forfinfilelist:if'nvrtc-builtins'inf:returnfreturnNonedef__libname(self,name,head='af',ver_major=AF_VER_MAJOR):post=self.__post.replace(_VER_MAJOR_PLACEHOLDER,ver_major)libname=self.__pre+head+name+postifself.AF_PATH:ifos.path.isdir(self.AF_PATH+'/lib64'):path_search=self.AF_PATH+'/lib64/'else:path_search=self.AF_PATH+'/lib/'else:ifos.path.isdir(self.AF_SEARCH_PATH+'/lib64'):path_search=self.AF_SEARCH_PATH+'/lib64/'else:path_search=self.AF_SEARCH_PATH+'/lib/'ifplatform.architecture()[0][:2]=='64':path_site=sys.prefix+'/lib64/'else:path_site=sys.prefix+'/lib/'path_local=self.AF_PYMODULE_PATHlibpaths=[('',libname),(path_site,libname),(path_local,libname)]ifself.AF_PATH:#prefer specified AF_PATH if existslibpaths.append((path_search,libname))else:libpaths.insert(2,(path_search,libname))returnlibpathsdefset_unsafe(self,name):lib=self.__clibs[name]if(libisNone):raiseRuntimeError("Backend not found")self.__name=namedef__init__(self):more_info_str="Please look at https://github.com/arrayfire/arrayfire-python/wiki for more information."pre,post,AF_PATH,AF_SEARCH_PATH,CUDA_FOUND=_setup()self.__pre=preself.__post=postself.AF_PATH=AF_PATHself.AF_SEARCH_PATH=AF_SEARCH_PATHself.CUDA_FOUND=CUDA_FOUND# prefer locally packaged arrayfire libraries if they existaf_module=__import__(__name__)self.AF_PYMODULE_PATH=af_module.__path__[0]+'/'ifaf_module.__path__elseNoneself.__name=Noneself.__clibs={'cuda':None,'opencl':None,'cpu':None,'unified':None}self.__backend_map={0:'unified',1:'cpu',2:'cuda',4:'opencl'}self.__backend_name_map={'default':0,'unified':0,'cpu':1,'cuda':2,'opencl':4}# Try to pre-load forge library if it existslibnames=reversed(self.__libname('forge',head='',ver_major=FORGE_VER_MAJOR))try:VERBOSE_LOADS=os.environ['AF_VERBOSE_LOADS']=='1'exceptKeyError:VERBOSE_LOADS=Falsepassforlibnameinlibnames:try:full_libname=libname[0]+libname[1]ct.cdll.LoadLibrary(full_libname)ifVERBOSE_LOADS:print('Loaded '+full_libname)breakexceptOSError:ifVERBOSE_LOADS:traceback.print_exc()print('Unable to load '+full_libname)passc_dim4=c_dim_t*4out=c_void_ptr_t(0)dims=c_dim4(10,10,1,1)# Iterate in reverse order of preferencefornamein('cpu','opencl','cuda',''):libnames=reversed(self.__libname(name))forlibnameinlibnames:try:full_libname=libname[0]+libname[1]ct.cdll.LoadLibrary(full_libname)__name='unified'ifname==''elsenameclib=ct.CDLL(full_libname)self.__clibs[__name]=cliberr=clib.af_randu(c_pointer(out),4,c_pointer(dims),Dtype.f32.value)if(err==ERR.NONE.value):self.__name=__nameclib.af_release_array(out)ifVERBOSE_LOADS:print('Loaded '+full_libname)# load nvrtc-builtins library if using cudaifname=='cuda':nvrtc_name=self.__find_nvrtc_builtins_libname(libname[0])ifnvrtc_name:ct.cdll.LoadLibrary(libname[0]+nvrtc_name)ifVERBOSE_LOADS:print('Loaded '+libname[0]+nvrtc_name)else:ifVERBOSE_LOADS:print('Could not find local nvrtc-builtins libarary')break;exceptOSError:ifVERBOSE_LOADS:traceback.print_exc()print('Unable to load '+full_libname)passif(self.__nameisNone):raiseRuntimeError("Could not load any ArrayFire libraries.\n"+more_info_str)defget_id(self,name):returnself.__backend_name_map[name]defget_name(self,bk_id):returnself.__backend_map[bk_id]defget(self):returnself.__clibs[self.__name]defname(self):returnself.__namedefis_unified(self):returnself.__name=='unified'defparse(self,res):lst=[]forkey,valueinself.__backend_name_map.items():if(value&res):lst.append(key)returntuple(lst)backend=_clibrary()[docs]defset_backend(name,unsafe=False):""" Set a specific backend by name Parameters ---------- name : str. unsafe : optional: bool. Default: False. If False, does not switch backend if current backend is not unified backend. """if(backend.is_unified()==Falseandunsafe==False):raiseRuntimeError("Can not change backend to%s after loading%s"%(name,backend.name()))if(backend.is_unified()):safe_call(backend.get().af_set_backend(backend.get_id(name)))else:backend.set_unsafe(name)return [docs]defget_backend():""" Return the name of the backend """returnbackend.name() [docs]defget_backend_id(A):""" Get backend name of an array Parameters ---------- A : af.Array Returns ---------- name : str. Backend name """backend_id=c_int_t(BACKEND.CPU.value)safe_call(backend.get().af_get_backend_id(c_pointer(backend_id),A.arr))returnbackend.get_name(backend_id.value) [docs]defget_backend_count():""" Get number of available backends Returns ---------- count : int Number of available backends """count=c_int_t(0)safe_call(backend.get().af_get_backend_count(c_pointer(count)))returncount.value [docs]defget_available_backends():""" Get names of available backends Returns ---------- names : tuple of strings Names of available backends """available=c_int_t(0)safe_call(backend.get().af_get_available_backends(c_pointer(available)))returnbackend.parse(int(available.value)) [docs]defget_active_backend():""" Get the current active backend name : str. Backend name """backend_id=c_int_t(BACKEND.CPU.value)safe_call(backend.get().af_get_active_backend(c_pointer(backend_id)))returnbackend.get_name(backend_id.value) [docs]defget_device_id(A):""" Get the device id of the array Parameters ---------- A : af.Array Returns ---------- dev : Integer id of the device array was created on """device_id=c_int_t(0)safe_call(backend.get().af_get_device_id(c_pointer(device_id),A.arr))returndevice_id [docs]defget_size_of(dtype):""" Get the size of the type represented by arrayfire.Dtype """size=c_size_t(0)safe_call(backend.get().af_get_size_of(c_pointer(size),dtype.value))returnsize.value from.utilimportsafe_call