def PYTHONPATH(use=False, notuse=False): ''' $PYTHONHOME $PYTHONPATH (1) use=False NOT append to sys.path notuse=False NOT remove from sys.path (2) use=None append $PYTHONPATH to sys.path (3) use=str | [str, str, ...] append it/them to sys.path (4) notuse=None like =False, NOT remove from sys.path (5) notuse=str | [str, str, ...] remove it/them from sys.path return: Updated sys.path ''' import sys, os from jizhipy.Basic import IsType, ShellCmd #---------------------------------------- if (use is True or use is False): use = [] elif (use is None): use = ShellCmd('echo $PYTHONPATH')[0].split(':') elif (IsType.isstr(use)): use = [use] elif (IsType.istuple(use)): use = list(use) #---------------------------------------- if (notuse is True or notuse is False or notuse is None): notuse = [] elif (IsType.isstr(notuse)): notuse = [notuse] elif (IsType.istuple(notuse)): notuse = list(notuse) #---------------------------------------- n = 0 while (n < len(use)): if (use[n] == ''): use.pop(n) else: if (use[n][-1] == '/'): use[n] = use[n][:-1] n += 1 if (len(use) > 0): use = [''] + use #---------------------------------------- here = os.path.abspath('') notusehere = True if ('' in notuse) else False for i in range(len(notuse)): notuse[i] = os.path.abspath(os.path.expanduser(notuse[i])) if (notusehere): notuse.append('') #---------------------------------------- sys.path = use + sys.path for i in range(len(notuse)): while (notuse[i] in sys.path): sys.path.remove(notuse[i]) return sys.path[:]
def _Hdf52Fits( dataset, hduname='' ) : if (hduname in ['', None]) : name = str(dataset.name) name = name[name.rfind('/')+1:] else : name = str(hduname) attrs = dataset.attrs.items() data = dataset.value hdulist = [] try : if (data.dtype.name[:7] == 'complex') : hdu = pyfits.ImageHDU( data.real ) hdu.name = name+'REAL' hdr = hdu.header for i in range(len(attrs)) : hdr[str(attrs[i][0])] = attrs[i][1] hdulist.append(hdu) #@#@ hdu = pyfits.ImageHDU( data.imag ) hdu.name = name+'IMAG' hdr = hdu.header for i in range(len(attrs)) : hdr[str(attrs[i][0])] = attrs[i][1] hdulist.append(hdu) #@#@ else : raise except : if (IsType.isndarray(data) or IsType.islist(data) or IsType.istuple(data)) : try : hdu = pyfits.ImageHDU( data ) except : hdu = pyfits.ImageHDU( np.array(data, np.float32) ) hdu.name = name hdr = hdu.header for i in range(len(attrs)) : hdr[str(attrs[i][0])[:8]] = attrs[i][1] hdulist.append(hdu) else : other.header[name[:8]] = data return hdulist
def Ymap( self, ymap=None ) : ''' ymap: Input y map, must be 2D array/matrix. y.shape = (nfreq, npix), row nfreq is the number of frequencies, column npix is the number of pixels at its frequency. (1) y is ndarray (2) y is list, len(y)==nfreq ''' import numpy as np from jizhipy.Basic import Raise, SysFrame, IsType from jizhipy.Array import Asarray from jizhipy.Optimize import Smooth if (ymap is None) : if (SysFrame(0,2)[-3][-2]!='') : self.ymap = None if (self.verbose) : print(' self.y = None') return else : return self.ymap pstr = ' ' if ('ymap' not in self.__dict__.keys())else ' Change: ' if (IsType.islist(ymap) or IsType.istuple(ymap)) : if (not IsType.isnum(ymap[0])) : ymap, N = list(ymap), 1e15 for i in range(len(ymap)) : if (len(ymap) < N) : N = len(ymap) for i in range(len(ymap)) : ymap[i]=jp.Smooth(ymap[i], 0,reduceshape=N) self.ymap = Asarray(ymap, np.float64) # force bit64 if (len(self.ymap.shape) not in [1, 2]) : Raise(Exception, 'jizhipy.PCA: ymap must be 1D/2D, but now ymap.shape='+str(self.ymap.shape)) if (self.verbose) : print(pstr+'self.ymap.shape =', self.ymap.shape) return self.ymap
def Save( self ) : ''' Save instance to .hdf5 ''' from jizhipy.Basic import Path, IsType, Raise import numpy as np import h5py self.outname = str(self.outname) if (self.outname[-5:] !='.hdf5') : self.outname += '.hdf5' Path.ExistsPath(self.outname, old=True) if (self.verbose) : print('jizhipy.ClassHdf5: Saveing to "'+self.outname+'"') fo = h5py.File(self.outname, 'w') if (self.value is None or self.keys is None): self.Values() fo['classinstance'] = str(type(self.classinstance)) for i in range(len(self.keys)) : if (self.values[i] is None) : fo[self.keys[i]] = '__None__' fo[self.keys[i]].attrs['type'] = 'is None, not str' #-------------------------------------------------- elif (IsType.isdtype(self.values[i])) : fo[self.keys[i]]=np.dtype(self.values[i]).name fo[self.keys[i]].attrs['type'] = 'numpy.dtype' #-------------------------------------------------- elif (IsType.ismatrix(self.values[i])) : fo[self.keys[i]] = np.array(self.values[i]) fo[self.keys[i]].attrs['type'] = 'numpy.matrix' #-------------------------------------------------- elif (IsType.ismaskedarray(self.values[i])) : fo[self.keys[i]] = self.values[i].data fo[self.keys[i]+'.mask'] = self.values[i].mask fo[self.keys[i]].attrs['type'] = 'numpy.MaskedArray .data' fo[self.keys[i]+'.mask'].attrs['type'] = 'numpy.MaskedArray .mask' #-------------------------------------------------- elif (IsType.isdict(self.values[i])) : self._OperaDict(self.values[i]) try : fo[self.keys[i]] =self.values[i].values() except : fo[self.keys[i]] = str(self.values[i].values()) fo[self.keys[i]+'.keys'] = self.values[i].keys() fo[self.keys[i]].attrs['type']='dict .values()' fo[self.keys[i]+'.keys'].attrs['type']='dict .keys()' self._OperaDict(self.values[i]) #-------------------------------------------------- else : # inside list and tuple, must not contain dict try : fo[self.keys[i]] = self.values[i] # convert to np.ndarray with same dtype, if contains string, will conver to string array except : strv = str([self.values[i]])[1:-1] Raise(Exception, "fo['"+self.keys[i]+"'] = "+strv) if (IsType.islist(self.values[i])) : fo[self.keys[i]].attrs['type'] = 'list' elif (IsType.istuple(self.values[i])) : fo[self.keys[i]].attrs['type'] = 'tuple' else : fo[self.keys[i]].attrs['type'] = 'numpy.array' #-------------------------------------------------- fo.flush() fo.close()
def Array2FitsImage( arraylist, outname, names=None, keys=None, values=None, comments=None, verbose=False ) : ''' arraylist: (1) isndarray (2) list/tuple of ndarray: [array1, array2, ...] Otherwise, raise error Examples: Array2FitsImage( [1,2,3] ), means there are 3 arrays, array1=1, array2=2, array3=3 FITS can save int/float number to ImageHDU, but will raise error "IOError: Header missing END card." when pyfits.open() it. You must convert to Array2FitsImage( np.array([1,2,3]), 'test.fits' ) OR Array2FitsImage( [[1,2,3]], 'test.fits' ) names: None | Same shape as arraylist Name of each ImageHDU in fo.info() keys: None | Same shape as arraylist (1) arraylist isndarray: keys=['key1', 'key2', ...], list of str (2) arraylist is list/tuple of ndarray: [array1, array2, ...], then keys=[arraykey1, arraykey2, ...], arraykey1=['key1', 'key2', ...] (list of list) values: Same shape as keys comments: None | same shape as keys even though is '' ''' from jizhipy.Basic import Path, IsType import pyfits outname = Path.AbsPath(outname) if (outname[-5:].lower() != '.fits') : outname += '.fits' Path.ExistsPath(outname, True) if (verbose) : print('Saving "'+outname+'"') #-------------------------------------------------- if (IsType.isstr(keys)) : keys, values = [keys], [values] if (comments is not None) : comments = [comments] else : comments = [''] #-------------------------------------------------- if (not IsType.islist(arraylist) and not IsType.istuple(arraylist)) : arraylist = [arraylist] if (names is not None) : names = [names] keys = [keys for i in range(len(arraylist))] values = [values for i in range(len(arraylist))] comments = [comments for i in range(len(arraylist))] #-------------------------------------------------- hdulist = pyfits.HDUList() for i in range(len(arraylist)) : data = arraylist[i] try : name = str(names[i]) except : name = 'hdu'+str(i) if (data.dtype.name[:7] == 'complex') : hdu = pyfits.ImageHDU( data.real ) hdu.name = name+'REAL' hdr = hdu.header for j in range(len(keys[i])) : key, value = keys[i][j], values[i][j] try : comment = comments[i][j] except : comment = '' hdr.set(key, value, comment) hdulist.append(hdu) # Real part hdu = pyfits.ImageHDU( data.imag ) hdu.name = name+'IMAG' hdr = hdu.header try : for j in range(len(keys[i])) : key, value = keys[i][j], values[i][j] try : comment = comments[i][j] except : comment = '' hdr.set(key, value, comment) except : pass hdulist.append(hdu) # Imag part #-------------------------------------------------- else : hdu = pyfits.ImageHDU( data ) hdu.name = name hdr = hdu.header try : for j in range(len(keys[i])) : key, value = keys[i][j], values[i][j] try : comment = comments[i][j] except : comment = '' hdr.set(key, value, comment) except : pass hdulist.append(hdu) #-------------------------------------------------- hdulist.writeto( outname )