def matlab_SurfStatStand(Y, mask=None, subtractordivide='s'): # Standardizes by subtracting the global mean, or dividing it. # Inputs # Y = numpy array of shape (n x v), v=#vertices. # = NEED TO BE DISCUSSED: it works for (n x v x k) now, DO WE NEED THAT? # mask = numpy boolean array of shape (1 x v). # True=inside the mask, False=outside. # subdiv = 's' for Y=Y-Ymean or 'd' for Y=(Y/Ymean -1)*100. # Outputs # Y = standardized data, numpy array of shape (n x v). # Ym = mean of input Y along the mask, numpy array of shape (n x 1). Y = matlab.double(Y.tolist()) if mask is None and subtractordivide == 's': Y, Ya = surfstat_eng.SurfStatStand(Y, nargout=2) elif mask is not None and subtractordivide == 's': mymask = np.array(mask, dtype=int) mymask = matlab.logical(matlab.double(mymask.tolist())) Y, Ya = surfstat_eng.SurfStatStand(Y, mymask, nargout=2) elif mask is not None and subtractordivide == 'd': mymask = np.array(mask, dtype=int) mymask = matlab.logical(matlab.double(mymask.tolist())) Y, Ya = surfstat_eng.SurfStatStand(Y, mymask, subtractordivide, nargout=2) return np.array(Y), np.array(Ya)
def matlab_SurfStatNorm(Y, mask=None, subdiv='s'): # Normalizes by subtracting the global mean, or dividing it. # Inputs # Y = numpy array of shape (n x v) or (n x v x k). # v=#vertices. # mask = numpy boolean array of shape (1 x v). # True=inside the mask, False=outside. # subdiv = 's' for Y=Y-Yav or 'd' for Y=Y/Yav. # Outputs # Y = normalized data, numpy array of shape (n x v) or (n x v x k) # Yav = mean of input Y along the mask, numpy array of shape (n x 1) or (n x k) Y = matlab.double(Y.tolist()) if mask is None and subdiv == 's': Y, Ya = surfstat_eng.SurfStatNorm(Y, nargout=2) elif mask is not None and subdiv == 's': mymask = np.array(mask, dtype=int) mymask = matlab.logical(matlab.double(mymask.tolist())) Y, Ya = surfstat_eng.SurfStatNorm(Y, mymask, nargout=2) elif mask is not None and subdiv == 'd': mymask = np.array(mask, dtype=int) mymask = matlab.logical(matlab.double(mymask.tolist())) Y, Ya = surfstat_eng.SurfStatNorm(Y, mymask, subdiv, nargout=2) return np.array(Y), np.array(Ya)
def matlab_SurfStatP(slm, mask=None, clusthresh=0.001): slm_mat = slm.copy() for key in slm_mat.keys(): if isinstance(slm_mat[key], np.ndarray): slm_mat[key] = matlab.double(slm_mat[key].tolist()) else: slm_mat[key] = surfstat_eng.double(slm_mat[key]) if mask is None: mask_mat = matlab.double([]) pval, peak, clus, clusid = surfstat_eng.SurfStatP(slm_mat, mask_mat, clusthresh, nargout=4) else: mask_mat = matlab.double(np.array(mask, dtype=int).tolist()) mask_mat = matlab.logical(mask_mat) pval, peak, clus, clusid = surfstat_eng.SurfStatP(slm_mat, mask_mat, clusthresh, nargout=4) for key in pval: pval[key] = np.array(pval[key]) for key in peak: peak[key] = np.array(peak[key]) for key in clus: clus[key] = np.array(clus[key]) clusid = np.array(clusid) return pval, peak, clus, clusid
def startMorphology(): import matlab json = request.get_json() filter_number = json['payload']['filterNumber'] image_index = json['payload']['imgNumber'] xReconstructionCoords = [] yReconstructionCoords = [] se_size = 5 if (json.get('payload').get('reconstructionCoords')): for el in json['payload']['reconstructionCoords']: xReconstructionCoords.append(el['x']) yReconstructionCoords.append(el['y']) xReconstructionCoords = matlab.double(xReconstructionCoords) yReconstructionCoords = matlab.double(yReconstructionCoords) print('MORPHOLOGY STEP2: ',filter_number,xReconstructionCoords,yReconstructionCoords) elif (json.get('payload').get('seSize')): se_size = json['payload']['seSize'] global clustered_images result = matlab_engine.morphology(str(filter_number),matlab.logical(clustered_images[int(image_index)]),xReconstructionCoords,yReconstructionCoords,float(se_size),nargout=2) clustered_images = [] clustered_images.append(result[0]) return jsonify({'response': result})
def matlab_SurfStatResels(slm, mask=None): # slm.resl = numpy array of shape (e,k) # slm.tri = numpy array of shape (t,3) # or # slm.lat = 3D logical array # mask = numpy 'bool' array of shape (1,v) slm_mat = slm.copy() for key in slm_mat.keys(): if isinstance(slm_mat[key], np.ndarray): slm_mat[key] = matlab.double(slm_mat[key].tolist()) else: slm_mat[key] = surfstat_eng.double(slm_mat[key]) # MATLAB errors if 'resl' is not provided and more than 1 output argument is requested. if 'resl' in slm: num_out = 3 else: num_out = 1 if mask is None: out = surfstat_eng.SurfStatResels(slm_mat, nargout=num_out) else: mask_mat = matlab.double(np.array(mask, dtype=int).tolist()) mask_mat = matlab.logical(mask_mat) out = surfstat_eng.SurfStatResels(slm_mat, mask_mat, nargout=num_out) return np.array(out)
def propagate_orbit(self, orb_params, end_time_s, timestep_s, include_ecef, scenario_start_utc): if not self.matlabif: self.matlabif = MatlabIF(matlab_ver=self.MATLAB_VERSION, paths=[MATLAB_PIPELINE_ENTRY]) orb_elems_flat = [] if 'kepler_meananom' in orb_params: # create inputs as needed by matlab orb_elems = orb_params['kepler_meananom'] orb_elems_flat = [ orb_elems['a_km'], orb_elems['e'], orb_elems['i_deg'], orb_elems['RAAN_deg'], orb_elems['arg_per_deg'], orb_elems['M_deg'] ] else: raise NotImplementedError # matlab-ify the args orb_elems_flat_ml = matlab.double(orb_elems_flat) end_time_s_ml = matlab.double([end_time_s]) timestep_s_ml = matlab.double([timestep_s]) params_ml = {} params_ml['scenario_start_utc'] = scenario_start_utc params_ml['calc_ecef'] = matlab.logical([include_ecef]) if orb_params['propagation_method'] == 'matlab_delkep': (t_r_eci, t_r_ecef) = self.matlabif.call_mfunc('orbit_prop_wrapper', orb_elems_flat_ml, end_time_s_ml, timestep_s_ml, params_ml, nargout=2) # convert matlab output types to python types time_pos_eci = MatlabIF.mlarray_to_list(t_r_eci) time_pos_ecef = MatlabIF.mlarray_to_list(t_r_ecef) # can add other key value pairs to this dict, to put in # final out file other_kwout = {} return time_pos_eci, time_pos_ecef, other_kwout else: raise NotImplementedError
def encode(eng, arrMsg_bin, n=7, k=4, strCoder="hamming/binary"): """ encode the message with given coder """ # convert to binary representation in matlab msg = matlab.logical(list(arrMsg_bin)) encoded = eng.encode(msg, n, k, strCoder) # convert to python array lsEncoded = [] for row in encoded: for item in row: lsEncoded.append(int(item)) return np.array(lsEncoded)
def DetectGrasps(self, cloud, viewPoints, viewPointIndices, nSamples, scoreThresh, gpuId): '''Calls the DetectGrasps Matlab script.''' viewPointIndices = viewPointIndices + 1 # convert to Matlab 1-indexing mCloud = matlab.double(cloud.T.tolist()) mViewPoints = matlab.double(viewPoints.T.tolist()) mViewPointIndices = matlab.int32(viewPointIndices.tolist(), size=(len(viewPointIndices), 1)) plotBitmap = matlab.logical([False, False, False]) mGrasps = self.eng.DetectGrasps(mCloud, mViewPoints, mViewPointIndices, nSamples, scoreThresh, plotBitmap, gpuId) return self.UnpackGrasps(mGrasps)
def FitCylinder(self, cloud, viewPoints, viewPointIndices, k): '''Utilizes Matlab's cylinder fitting capabilities for point clouds.''' mCloud = matlab.double(cloud.tolist()) mViewPoints = matlab.double(viewPoints.tolist()) mViewPointIndices = matlab.int32(viewPointIndices.tolist(), size=(1, len(viewPointIndices))) plotBitmap = matlab.logical([False, False, False, False]) mCylinder = self.eng.FitCylinder(mCloud, mViewPoints, mViewPointIndices, k, plotBitmap) center = array(mCylinder["center"]).flatten() axis = array(mCylinder["axis"]).flatten() radius = mCylinder["radius"] height = mCylinder["height"] return Cylinder(center, axis, radius, height)
def matlab_SurfStatQ(slm, mask=None): slm_mat = slm.copy() for key in slm_mat.keys(): if isinstance(slm_mat[key], np.ndarray): slm_mat[key] = matlab.double(slm_mat[key].tolist()) else: slm_mat[key] = surfstat_eng.double(slm_mat[key]) if mask is None: q_val_mat = surfstat_eng.SurfStatQ(slm_mat) else: mask_mat = matlab.double(np.array(mask, dtype=int).tolist()) mask_mat = matlab.logical(mask_mat) q_val_mat = surfstat_eng.SurfStatQ(slm_mat, mask_mat) q_val_py = {} for key in q_val_mat.keys(): q_val_py[key] = np.array(q_val_mat[key]) return q_val_py
def SampleGrasps(self, cloud, viewPoints, viewPointIndices, nSamples, minWidth, maxWidth, tablePosition, tableUpAxis, tableFingerLength, offsets): '''Calls the SampleGrasps Matlab script.''' # short circuit the process if there are no points in the cloud if cloud.shape[0] == 0: return [] mCloud = matlab.double(cloud.T.tolist()) mViewPoints = matlab.double(viewPoints.T.tolist()) mViewPointIndices = matlab.int32(viewPointIndices.tolist(), size=(len(viewPointIndices), 1)) mTablePosition = matlab.double(tablePosition.tolist(), size=(3, 1)) plotBitmap = matlab.logical([False, False, False, False]) mGrasps = self.eng.SampleGrasps(mCloud, mViewPoints, mViewPointIndices, nSamples, minWidth, maxWidth, mTablePosition, tableUpAxis, tableFingerLength, plotBitmap) return self.UnpackGrasps(mGrasps, offsets)
# connect to a session eng = matlab.engine.connect_matlab(matlab.engine.find_matlab()[0]) print('connected...') else: print('Matlab engine is already runnig...') print('Further tests....\n') # create matlab data # ------------------------------------------------------------------------ mf = eng.rand(3) mc = matlab.double([[1 + 1j, 0.3, 1j], [1.2j - 1, 0, 1 + 1j]], is_complex=True) mi64 = matlab.int64([1, 2, 3]) mi8 = matlab.int8([1, 2, 3]) mb = matlab.logical([True, True, False]) # Test conversion from matlab to numpy # ------------------------------------------------------------------------ npf = mlarray2np(mf) # no copy, if mf is changed, npf change! npc = mlarray2np(mc) # still copy for complex (only) npi64 = mlarray2np(mi64) npi8 = mlarray2np(mi8) npb = mlarray2np(mb) # Test conversion from numpy to matlab # ------------------------------------------------------------------------ npi = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=np.int64, order='F') mi = np2mlarray(npi)
def process_accesses(self, process_accesses_input, sat_orbit_data, cached_accesses_data): """ :param orbit_prop_inputs: highest-level input json object :return: output json with raw orbit prop data """ accesses_data = {} # matlab-ify the args params_ml = {} params_ml['scenario_start_utc'] = process_accesses_input['start_utc'] params_ml['num_sats'] = matlab.double( [process_accesses_input['num_satellites']]) params_ml['use_crosslinks'] = matlab.logical( [process_accesses_input['use_crosslinks']]) params_ml['all_sats_same_time_system'] = matlab.logical( [process_accesses_input['all_sats_same_time_system']]) params_ml['verbose'] = matlab.logical( [process_accesses_input['matlab_verbose']]) obs_params = process_accesses_input['obs_params'] params_ml['el_cutuff_obs_deg'] = matlab.double( [obs_params['elevation_cutoff_deg']]) lat_lon_deg = matlab.double([[o['latitude_deg'], o['longitude_deg']] for o in obs_params['targets']]) params_ml['obs_lat_lon_deg'] = matlab.double(lat_lon_deg) params_ml['num_obs_targets'] = matlab.double([len(lat_lon_deg)]) if len(lat_lon_deg) != obs_params['num_targets']: raise Exception( 'Number of observation targets is not equal to the length of observation target parameters list' ) gs_params = process_accesses_input['gs_params'] params_ml['el_cutuff_gs_deg'] = matlab.double( [gs_params['elevation_cutoff_deg']]) lat_lon_deg = matlab.double([[g['latitude_deg'], g['longitude_deg']] for g in gs_params['stations']]) params_ml['gs_lat_lon_deg'] = matlab.double(lat_lon_deg) params_ml['num_gs'] = matlab.double([len(lat_lon_deg)]) if len(lat_lon_deg) != gs_params['num_stations']: raise Exception( 'Number of ground stations is not equal to the length of ground station parameters list' ) num_satellites = process_accesses_input['num_satellites'] sat_id_prefix = process_accesses_input['sat_id_prefix'] sat_id_order = process_accesses_input['sat_id_order'] # in the case that this is default, then we need to grab a list of all the satellite IDs. We'll take this from all of the satellite IDs found in the orbit parameters if sat_id_order == 'default': dummy, all_sat_ids = io_tools.unpack_sat_entry_list( process_accesses_input['sat_orbital_elems'], force_duplicate=True) # make the satellite ID order. if the input ID order is default, then will assume that the order is the same as all of the IDs passed as argument sat_id_order = io_tools.make_and_validate_sat_id_order( sat_id_order, sat_id_prefix, num_satellites, all_sat_ids) io_tools.validate_ids(validator=sat_id_order, validatee=all_sat_ids) sat_orbit_data_sorted = io_tools.sort_input_params_by_sat_IDs( sat_orbit_data, sat_id_order) params_ml[ 'use_cached_accesses'] = True if cached_accesses_data else False time_s_pos_km_flat_ml = [] if OUTPUT_JSON_VER == "0.3": for elem in sat_orbit_data_sorted: time_s_pos_km_flat_ml.append( matlab.double(elem['time_s_pos_eci_km'])) else: raise NotImplementedError if not self.matlabif: self.matlabif = MatlabIF(matlab_ver=self.MATLAB_VERSION, paths=[MATLAB_PIPELINE_ENTRY]) (obs, obsaer, gslink, gsaer, sunecl, xlink, x_range) = \ self.matlabif.call_mfunc( 'accesses_wrapper', time_s_pos_km_flat_ml, params_ml, nargout=7) accesses_data['obs_times'] = MatlabIF.deep_convert_matlab_to_python( obs) accesses_data['obs_aer'] = MatlabIF.deep_convert_matlab_to_python( obsaer) accesses_data['dlnk_times'] = MatlabIF.deep_convert_matlab_to_python( gslink) accesses_data['dlnk_aer'] = MatlabIF.deep_convert_matlab_to_python( gsaer) if cached_accesses_data: accesses_data['ecl_times'] = cached_accesses_data['ecl_times'] accesses_data['xlnk_times'] = cached_accesses_data['xlnk_times'] accesses_data['xlnk_range'] = cached_accesses_data['xlnk_range'] else: # TODO - eclipse times came out with an inadvertent extra nesting layer. get rid of that. accesses_data[ 'ecl_times'] = MatlabIF.deep_convert_matlab_to_python( sunecl)[0] accesses_data[ 'xlnk_times'] = MatlabIF.deep_convert_matlab_to_python(xlink) accesses_data[ 'xlnk_range'] = MatlabIF.deep_convert_matlab_to_python(x_range) return accesses_data
def run(im, init_mask, method, slice=0, max_iter=1000, rad=20, alpha=0.1, energy_type=2, display=False, show=False, show_now=True): # print 'starting matlab engine ...', eng = matlab.engine.start_matlab() im_matlab = matlab.uint8(im.tolist()) mask_matlab = matlab.logical(init_mask.tolist()) # plt.figure() # plt.subplot(221), plt.imshow(im, 'gray') # plt.subplot(222), plt.imshow(im_matlab, 'gray') # plt.subplot(223), plt.imshow(init_mask, 'gray') # plt.subplot(224), plt.imshow(mask_matlab, 'gray') # plt.show() # print 'segmenting ...', if method == 'lls': eng.addpath('localized_seg') seg = eng.localized_seg(im_matlab, mask_matlab, max_iter, float(rad), alpha, energy_type, display, nargout=1) elif method == 'sfm': eng.addpath('sfm_chanvese_demo') # eng.sfm_local_demo(nargout=0) seg = eng.sfm_local_chanvese(im_matlab, mask_matlab, max_iter, alpha, float(rad), display, nargout=1) else: seg = init_mask.copy() seg = np.array(seg._data).reshape(seg._size[::-1]).T eng.quit() if show: im_vis = im if im.ndim == 2 else im[slice, ...] init_mask_vis = init_mask if init_mask.ndim == 2 else init_mask[slice, ...] seg_vis = seg if seg.ndim == 2 else seg[slice, ...] mask_bounds = skiseg.mark_boundaries(im_vis, init_mask_vis, color=(1, 0, 0), mode='thick') seg_over = skicol.label2rgb(seg_vis, im_vis, colors=['red', 'green', 'blue'], bg_label=0) seg_bounds = skiseg.mark_boundaries(im_vis, seg_vis, color=(1, 0, 0), mode='thick') plt.figure() plt.subplot(231), plt.imshow(im_vis, 'gray'), plt.title('input') plt.subplot(232), plt.imshow(init_mask_vis, 'gray'), plt.title('init mask') plt.subplot(233), plt.imshow(mask_bounds, 'gray'), plt.title('init mask') plt.subplot(234), plt.imshow(seg_vis, 'gray'), plt.title('segmentation') plt.subplot(235), plt.imshow(seg_over, 'gray'), plt.title('segmentation') plt.subplot(236), plt.imshow(seg_bounds, 'gray'), plt.title('segmentation') if show_now: plt.show() return seg
def ndarray_to_matlab(numpy_array): """Conversion of a numpy array to matlab mlarray The conversion is realised without copy for real data. First an empty initialization is realized. Then the numpy array is affected to the _data field. Thus the data field is not really an array.array but a numpy array. Matlab doesn't see anything... For complex data, the strides seems to not work properly with matlab.double. Paramerters ----------- numpy_array : numpy array the array to convert Returns ------- matlab_array : mlarray the converted array that can be passe to matlab Examples -------- >>> npi=numpy.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],dtype=numpy.int64,order='C') >>> ndarray_to_matlab(npi) matlab.int64([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) >>> npif=numpy.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],dtype=numpy.int64,order='F') >>> ndarray_to_matlab(npif) matlab.int64([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) >>> npcf=numpy.array([[1,2+0.2j,3],[4,5,6],[7,8,9],[10+0.1j,11,12]],dtype=numpy.complex,order='F') >>> ndarray_to_matlab(npcf) matlab.double([[(1+0j),(2+0.2j),(3+0j)],[(4+0j),(5+0j),(6+0j)],[(7+0j),(8+0j),(9+0j)],[(10+0.1j),(11+0j),(12+0j)]], is_complex=True) References ----------- https://scipy-lectures.org/advanced/advanced_numpy/ (strides) """ if "ndarray" not in str(type(numpy_array)): # check numpy raise TypeError(f"Expect numpy.ndarray. Got {type(numpy_array)}") shape = numpy_array.shape # get shape num_elements = numpy.prod(shape) # number of elements if numpy_array.flags.f_contiguous: # compute strides (real case) strides = get_strides_f(shape) order = "F" else: strides = get_strides_c(shape) order = "C" if numpy.iscomplexobj(numpy_array): # complex case matlab_array = matlab.double( initializer=None, size=(1, num_elements), is_complex=True ) # create empty matlab.mlarray # associate the data """ # associate the data (no copy), works on 2D array only... matlab_array._real=numpy_array.ravel(order=order) # allow to map real and imaginary part continuously! """ cpx = numpy_array.ravel(order="F") # copy except for fortran like array matlab_array._real = ( cpx.real.ravel() ) # second ravel to correct the strides 18->8 matlab_array._imag = cpx.imag.ravel() matlab_array.reshape(shape) # matlab_array._strides=strides else: # real case # create empty matlab.mlarray if numpy_array.dtype == numpy.float64: matlab_array = matlab.double( initializer=None, size=(1, num_elements), is_complex=False ) elif numpy_array.dtype == numpy.int64: matlab_array = matlab.int64(initializer=None, size=(1, num_elements)) elif numpy_array.dtype == numpy.bool: matlab_array = matlab.logical(initializer=None, size=(1, num_elements)) else: raise TypeError(f"Type {numpy_array.dtype} is missing") matlab_array._data = numpy_array.ravel(order=order) # associate the data # print(matlab_array._data.flags,matlab_array._data,'\n') # control owner matlab_array.reshape(shape) # back to original shape if ( len(shape) > 1 ): # array strides are in number of cell (numpy strides are in bytes) # if len(shape)==1 no need to change. Format pb because _stride expect (1,1) and stride = (1,) matlab_array._strides = ( strides # change stride (matlab use 'F' order ie [nc,1] ) ) return matlab_array
def asiduj_test(): """ Test of the module It runs the doctest and create other tests with matlab engine calls.""" import scipy.linalg as spl print("Run matlab engine...") if len(matlab.engine.find_matlab()) == 0: # si aucune session share, run eng = matlab.engine.start_matlab() else: # connect to a session eng = matlab.engine.connect_matlab(matlab.engine.find_matlab()[0]) print("connected...") print("Further tests....\n") # create matlab data # ------------------------------------------------------------------------ mf = eng.rand(3) mc = matlab.double([[1 + 1j, 0.3, 1j], [1.2j - 1, 0, 1 + 1j]], is_complex=True) mi64 = matlab.int64([1, 2, 3]) mi8 = matlab.int8([1, 2, 3]) mb = matlab.logical([True, True, False]) # Test conversion from matlab to numpy # ------------------------------------------------------------------------ npf = matlab_to_ndarray(mf) # no copy, if mf is changed, npf change! npc = matlab_to_ndarray(mc) # still copy for complex (only) npi64 = matlab_to_ndarray(mi64) npi8 = matlab_to_ndarray(mi8) npb = matlab_to_ndarray(mb) # Test conversion from numpy to matlab # ------------------------------------------------------------------------ npi = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=numpy.int64, order="F") mi = ndarray_to_matlab(npi) mc2 = ndarray_to_matlab(npc) mf2 = ndarray_to_matlab( npf) # copy, because npf has 'F' order (comes from mlarray) mi64_2 = ndarray_to_matlab(npi) mb2 = ndarray_to_matlab(npb) # test orientation in the matlab workspace # ------------------------------------------------------------------------ eng.workspace["mi"] = mi64_2 eng.workspace["mc2"] = mc2 # check results # ------------------------------------------------------------------------ npcc = numpy.array( [ [1.0, 1.1 + 1j], [ 1.12 + 0.13j, 22.1, ], ], dtype=numpy.complex, ) # assume C mcc = ndarray_to_matlab(npcc) npcc_inv = spl.inv(npcc) mcc_inv = eng.inv(mcc) print("Are the inverse of matrix equal ?") print(mcc_inv) print(npcc_inv) # # no copy check # # ------------------------------------------------------------------------ # # complex # # npcc[0,0]=0.25 # print("Are the data reuse ?", ", OWNDATA =", mcc._real.flags.owndata, # "same base =", mcc._real.base is npcc, # ', If one is modified, the other is modified =', mcc._real[0]==npcc[0,0]) # # test sparse matrix requiert Recast4py.m K1, K2 = eng.sptest(3.0, nargout=2) Ksp1 = dict_to_sparse(K1) Ksp2 = dict_to_sparse(K2)
def np2mlarray(npa): """ Conversion of a numpy array to matlab mlarray The conversion is realised without copy for real data. First an empty initialization is realized. Then the numpy array is affected to the _data field. Thus the data field is not really an array.array but a numpy array. Matlab doesn't see anything... For complex data, the strides seems to not work properly with matlab.double. Paramerters ----------- npa : numpy array the array to convert Returns ------- ma : mlarray the converted array that can be passe to matlab Examples -------- >>> npi=np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],dtype=np.int64,order='C') >>> np2mlarray(npi) matlab.int64([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) >>> npif=np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]],dtype=np.int64,order='F') >>> np2mlarray(npif) matlab.int64([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) >>> npcf=np.array([[1,2+0.2j,3],[4,5,6],[7,8,9],[10+0.1j,11,12]],dtype=np.complex,order='F') >>> np2mlarray(npcf) matlab.double([[(1+0j),(2+0.2j),(3+0j)],[(4+0j),(5+0j),(6+0j)],[(7+0j),(8+0j),(9+0j)],[(10+0.1j),(11+0j),(12+0j)]], is_complex=True) References ----------- https://scipy-lectures.org/advanced/advanced_numpy/ (strides) """ # check numpy if 'ndarray' not in str(type(npa)): raise TypeError('Expect numpy.ndarray. Got %s' % type(npa)) # get shape shape = npa.shape # number of elements N = np.prod(shape) # compute strides (real case) if npa.flags.f_contiguous == True: strides = _getStridesF(shape) # pour la sortie order = 'F' else: strides = _getStridesC(shape) # ok, garde le même order = 'C' # complex case if npa.dtype in (np.complex128, np.complex): # create empty matlab.mlarray ma = matlab.double(initializer=None, size=(1, N), is_complex=True) # associate the data """ # associate the data (no copy), works on 2D array only... ma._real=npa.ravel(order=order) # allow to map real and imaginary part continuously! """ cpx = npa.ravel(order='F') # copy except for fortran like array ma._real = cpx.real.ravel( ) # second ravel to correct the strides 18->8 ma._imag = cpx.imag.ravel() ma.reshape(shape) # ma._strides=strides # real case else: # create empty matlab.mlarray if npa.dtype == np.float64: ma = matlab.double(initializer=None, size=(1, N), is_complex=False) elif npa.dtype == np.int64: ma = matlab.int64(initializer=None, size=(1, N)) elif npa.dtype == np.bool: ma = matlab.logical(initializer=None, size=(1, N)) else: raise TypeError('Type %s is missing' % npa.dtype) # associate the data ma._data = npa.ravel(order=order) # print(ma._data.flags,ma._data,'\n') # control owner # back to original shape ma.reshape(shape) # array strides are in number of cell (numpy strides are in bytes) # if len(shape)==1 no need to change. Format pb because _stride expect (1,1) and stride = (1,) if len(shape) > 1: ma._strides = strides # change stride (matlab use 'F' order ie [nc,1] ) return ma
def matlab_SurfStatPeakClus(slm, mask, thresh, reselspvert=None, edg=None): # Finds peaks (local maxima) and clusters for surface data. # Usage: [ peak, clus, clusid ] = SurfStatPeakClus( slm, mask, thresh ... # [, reselspvert [, edg ] ] ); # slm = python dictionary # slm['t'] = numpy array of shape (l, v) # slm['tri'] = numpy array of shape (t, 3) # or # slm['lat'] = 3D numpy array # mask = numpy 'bool' array of shape (1, v) vector # thresh = float # reselspvert = numpy array of shape (1, v) # edg = numpy array of shape (e, 2) # The following are optional: # slm['df'] # slm['k'] slm_mat = slm.copy() for key in slm_mat.keys(): if isinstance(slm_mat[key], np.ndarray): slm_mat[key] = matlab.double(slm_mat[key].tolist()) else: slm_mat[key] = surfstat_eng.double(slm_mat[key]) mask_mat = matlab.double(np.array(mask, dtype=int).tolist()) mask_mat = matlab.logical(mask_mat) thresh_mat = surfstat_eng.double(thresh) if reselspvert is None and edg is None: peak, clus, clusid = surfstat_eng.SurfStatPeakClus(slm_mat, mask_mat, thresh_mat, nargout=3) elif reselspvert is not None and edg is None: reselspvert_mat = matlab.double(reselspvert.tolist()) peak, clus, clusid = surfstat_eng.SurfStatPeakClus(slm_mat, mask_mat, thresh_mat, reselspvert_mat, nargout=3) elif reselspvert is not None and edg is not None: reselspvert_mat = matlab.double(reselspvert.tolist()) edg_mat = matlab.double(edg.tolist()) peak, clus, clusid = surfstat_eng.SurfStatPeakClus(slm_mat, mask_mat, thresh_mat, reselspvert_mat, edg_mat, nargout=3) if isinstance(peak, matlab.double): peak_py = np.array(peak) elif isinstance(peak, dict): peak_py = {key: None for key in peak.keys()} for key in peak: peak_py[key] = np.array(peak[key]) if isinstance(clus, matlab.double): clus_py = np.array(clus) elif isinstance(clus, dict): clus_py = {key: None for key in clus.keys()} for key in clus: clus_py[key] = np.array(clus[key]) clusid_py = np.array(clusid) return peak_py, clus_py, clusid_py