예제 #1
0
def bse_ml():
    # step 1: nii.gz -> bmp
    subject_path = sys.argv[2]
    engine = matlab.engine.start_matlab()
    path = os.path.abspath(__file__)
    path_to_functions = path[:-11]
    engine.addpath(path_to_functions, nargout=0)
    engine.addpath(path_to_functions + '/NIfTI', nargout=0)
    n3 = engine.input_fn(subject_path)
    n3 = int(n3)
    engine.desktop(nargout=0)

    # step 2: create h5py
    command1 = 'python ' + path_to_functions + '/create_h5.py '
    os.system(command1)

    # step 3: predict
    command2 = 'python ' + path_to_functions + '/main.py ' + subject_path + ' ' + str(n3)
    os.system(command2)

    # step 4: save results
    if len(sys.argv) > 4:
        output_name = sys.argv[4]
        engine.save_pred(output_name, nargout=0)
        engine.desktop(nargout=0)
    else:
        engine.save_pred('meaningless', nargout=0)
        engine.desktop(nargout=0)

    # step 5: delete intermediate files
    shutil.rmtree('./pred_results/')
    shutil.rmtree('./pred_results_png/')
    shutil.rmtree('./test_data/')
예제 #2
0
def add_dir_of_file_to_path(args):
    (file_dir, file_name, file_ext) = file_attributes(args[u'file_path'])

    engine = connect_to_engine()

    engine.addpath(file_dir, nargout=0)

    is_file_in_path(args)
예제 #3
0
파일: wrapper.py 프로젝트: adouge/solensim
def mWrapper():
    """
    Returns a MATLAB engine instance, with mcode in PATH
    """
    engine = matlab.engine.start_matlab()
    mcode_path = work_dir = os.path.dirname(os.path.realpath(__file__))
    engine.addpath(mcode_path)
    return engine
예제 #4
0
def find_engine():
    global engine

    if engine is not None:
        return engine

    engines = matlab.engine.find_matlab()
    print(engines)

    if engines:
        print("Found MATLAB engine! connecting ...")
        engine = matlab.engine.connect_matlab(engines[0])
        print("Found MATLAB engine! connected")
    else:
        print("No MATLAB engine found, launching new one ...")
        engine = matlab.engine.start_matlab()
        print("No MATLAB engine found, launched new one")

    engine.addpath('amsbss/ILRMA')
    engine.addpath('amsbss/AuxIVA')
    engine.addpath('amsbss/AuxIVA/STFT')
    return engine
def main(request):
    name_num = []
    base_folder = os.path.dirname(os.path.realpath(__file__))   # get base dir
    engine.addpath(base_folder)
    folder_path = os.path.join(base_folder, "static\\djoncharts\\jpgs")      # insert the path to your directory   
    file_list =os.listdir(folder_path)
    for f in file_list:
    	num = len(os.listdir(os.path.join(folder_path, f)))
    	name_num.append((f, num))
    if request.method == 'POST':
    	typ = int(request.POST.get('type'))
    	# this part is for 
    	if typ == 0:
    		page_id = int(request.POST.get('page_id'))
    		res = {}
    		res['result'] = name_num[15*(page_id - 1) : 15 * page_id]
    		return JsonResponse(res)

    	# this part is for simplify the centerline   		
    	if typ == 1:
    		x1 = int(request.POST.get('x1'))
    		x2 = int(request.POST.get('x2'))
    		res = {}
    		engine.selected(x1, x2)
    		simple = loadmat(os.path.join(base_folder, 'simple'))['mypath']
    		print(simple.shape)
    		json_data = [['X', 'Y', 'Z', 'ind']]
    		total = simple.shape[0]
    		for index in range(total):
    			json_data.append([int(simple[index][0]), int(simple[index][1]), int(simple[index][2]), index])
    		with open(os.path.join(base_folder, 'static\\djoncharts', 'data_centerline_ind_simple.json'), 'w') as f:
    			json.dump(json_data, f)
    		res['result'] = 'success'
    		return JsonResponse(res)

    	# this part is for get centerline from the mask
    	if typ == 2:
    		path2mask = os.path.join(base_folder, "static\\djoncharts\\masks", request.POST.get('id'), 'mask.mat')
    		print(path2mask)
    		res = {}
    		engine.get_centerline(path2mask, nargout=0)
    		x = loadmat(os.path.join(base_folder, 'section_x'))['x']
    		y = loadmat(os.path.join(base_folder, 'section_y'))['y']
    		z = loadmat(os.path.join(base_folder, 'section_z'))['z']
    		ind = loadmat(os.path.join(base_folder, 'section_ind'))['ind']
    		print(x.shape)
    		json_data = [['X', 'Y', 'Z', 'ind']]
    		total = x.shape[0]
    		for index in range(total):
    			json_data.append([int(x[index][0]), int(y[index][0]), int(z[index][0]), int(ind[index][0])])
    		with open(os.path.join(base_folder, 'static\\djoncharts', 'data_centerline_ind.json'), 'w') as f:
    			json.dump(json_data, f)
    		res['result'] = 'success'
    		return JsonResponse(res)

    	if typ == 3:
    		path2mask = os.path.join(base_folder, "static\\djoncharts\\masks", request.POST.get('id'), 'mask.mat')
    		path2centerline = os.path.join(base_folder, 'simple.mat')
    		path2dicom = os.path.join(base_folder, "static\\djoncharts\\raw", request.POST.get('id'), 'raw_volume.mat')
    		print(path2dicom)
    		engine.get_section(path2dicom, path2centerline, path2mask, nargout=0)
    		data_mean = loadmat(os.path.join(base_folder, 'mean_sec'))['mean_sec']
    		data_std  = loadmat(os.path.join(base_folder, 'std_sec'))['std_sec']
    		data_long = loadmat(os.path.join(base_folder, 'long_sec'))['long_sec']
    		data_short = loadmat(os.path.join(base_folder, 'short_sec'))['short_sec']
    		data_section = loadmat(os.path.join(base_folder, 'section'))['section']

    		print(data_mean.shape)
    		total = data_mean.shape[1]
    		assert data_mean.shape == data_std.shape

    		axis_data = []
    		value_data = []
    		for index in range(total):
    			axis_data.append([data_short[0][index], data_long[0][index]])
    			value_data.append([data_mean[0][index], data_std[0][index]])
    			img_data = data_section[:, :, index]
    			max_data = np.max(img_data)
    			min_data = np.min(img_data)
    			img_data = 1.0 * (img_data - min_data)/(max_data - min_data + 1) * 256
    			img = Image.fromarray(img_data.astype(np.uint8))
    			img.convert('RGB').save(os.path.join(base_folder, 'static\\djoncharts\\sections', str(index).zfill(5) + '.jpg'))

    		with open(os.path.join(base_folder, 'static\\djoncharts', 'section_value.json'), 'w') as f:
    			json.dump(value_data, f)
    		with open(os.path.join(base_folder, 'static\\djoncharts', 'section_axis.json'), 'w') as f:
    			json.dump(axis_data, f)
    		res = {}
    		res['result'] = 'success'
    		return JsonResponse(res)

    return render(request, 'djoncharts/main.html', {'dicom_folders': name_num})
예제 #6
0
import sys
import matlab
import matlab.engine
import os
import shutil


# step 1: nii.gz -> bmp
subjects_folder_path = sys.argv[1]
engine = matlab.engine.start_matlab()
path = os.path.abspath(__file__)
path_to_functions = path[:-7]
engine.addpath(path_to_functions, nargout=0)
engine.addpath(path_to_functions + '/NIfTI', nargout=0)
n3 = engine.input_fn(subjects_folder_path)
n3 = int(n3)
engine.desktop(nargout=0)

# step 2: create h5py
command1 = 'python ' + path_to_functions + '/create_h5.py ' + subjects_folder_path
os.system(command1)

# step 3: predict
command2 = 'python ' + path_to_functions + '/main.py ' + subjects_folder_path + ' ' + str(n3)
os.system(command2)

# step 4: save results
engine.save_pred(subjects_folder_path, nargout=0)
engine.desktop(nargout=0)

# step 5: delete intermediate files
예제 #7
0
    w = s * (x2 - x1) + 1
    h = s * (y2 - y1) + 1

    x11 = cx - w // 2
    y11 = cy - h // 2

    return x11, y11, w, h


refine = params['refine']
if refine:
    import matlab
    import matlab.engine

    engine = matlab.engine.start_matlab()
    engine.addpath(ROOT_DIR)
else:
    engine = None

handle = vot.VOT("polygon")
gt_bbox = handle.region()
gt_bbox = np.array(gt_bbox).reshape((1, 4, 2))
init_bbox = get_axis_aligned_bbox(gt_bbox)

tracker = create_tracker(params)
image_file = handle.frame()
if not image_file:
    sys.exit(0)
im = cv2.cvtColor(cv2.imread(image_file), cv2.COLOR_BGR2RGB)  # HxWxC
tracker.initialize(im, init_bbox)
tracker.engine = engine
예제 #8
0
파일: log.py 프로젝트: Fiink/EIT5gr510
#!/usr/bin/env python
import os,sys,io
import time,subprocess
import matlab.engine
engine=matlab.engine.start_matlab("-Desktop")

engine.addpath(r'/home/user/Documents/matlab',nargout=0)
print('Engine started...');

mac =[
    '6c:72:20',
    '90:03:b7',
    '60:60:1f',
    'd4:d9:19',
    'f4:dd:9e',
    'd4:32:60',
    'd4:41:69',
    'd8:96:85']

print("Initiating Tracking Protocol")
os.system("sudo modprobe -r iwldvm iwlwifi mac80211")
print("Initiating Driver")
os.system("sudo modprobe iwlwifi connector_log=0x1")
time.sleep(0.5)

print("Activating WiFi Antennas")
os.system("sudo ifconfig wlan0 up")
time.sleep(0.2)
print("Connecting to Specified WiFi Object")
result = subprocess.check_output('sudo iw dev wlan0 connect -w accesspoint',shell=True)
time.sleep(0.2)
예제 #9
0
    density = 'mog'
    n_mades = 5  # number of MADES

    hyperparameters = dict()
    hyperparameters['n_train'] = n_train
    hyperparameters['n_rounds'] = n_rounds
    hyperparameters['val_frac'] = val_frac
    hyperparameters['n_hiddens'] = n_hiddens
    hyperparameters['density'] = density
    hyperparameters['n_mades'] = n_mades

    # start matlab enigne and set path
    engine = matlab.engine.start_matlab()
    try:
        ps = engine.genpath('/scratch/sliu88/APT')
        engine.addpath(ps)
    except:
        pass
    # save inference method settings (hyperparameters)
    savemat(os.path.join(savefolder, 'hyperparameters.mat'),
            {'hyperparameters': hyperparameters})
    priorC_list = [1, 2, 3]
    gamma_list = [1, 2, 3]
    lapse_list = [1, 2, 3]
    samples_list = [1, 2, 3]
    for s in samples_list:
        for l in lapse_list:
            for g in gamma_list:
                for C in priorC_list:

                    # load data
예제 #10
0
파일: test.py 프로젝트: WXR1998/Tiaoyitiao
            + str(pos[0]) + ' ' + str(pos[1]))


while True:
    get_screenshot()
    screenshot = cv2.imread('./autojump.png')

    score, restart_pos = check.check_result(screenshot)
    if score >= 0:
        with open("./result.txt", 'a') as f:
            f.write("score: ", score)
            f.write("\n")
        restart(restart_pos)

    press_time = 0
    if lang == "python":
        press_time = jumper.jumper()
    elif lang == "cpp":
        if platform == "win32":
            press_time = subprocess.getoutput('cd jump_cpp && jumper.exe')
        if platform == "darwin":
            press_time = subprocess.getoutput('cd jump_cpp && ./jumper')
    else:
        engine.addpath("./jump_matlab")
        press_time = engine.jumper()

    print('Press time: ' + str(press_time))
    press_screen(press_time)

    time.sleep(2)
예제 #11
0
    # Check test platform
    platform = sys.platform
    if platform != "win32" and platform != "darwin":
        print("Unsupported platform. Exiting...")
        exit()

    # Check source files
    engine = None
    if lang == "matlab":
        if not os.path.isfile(work_dir + '/jumper.m'):
            print('Source code does not exist! Exiting...')
            exit()
        import matlab.engine
        engine = matlab.engine.start_matlab()
        engine.addpath(work_dir)
    elif lang == "python":
        if not os.path.isfile(work_dir + '/jumper.py'):
            print('Source code does not exist! Exiting...')
            exit()
        for f in os.listdir(work_dir):
            shutil.copy(work_dir + '/' + f, './' + student_id)
        jumper = importlib.import_module(student_id + '.jumper')
    else:
        if platform == "win32":
            if not os.path.isfile(work_dir + '/jumper.exe'):
                print('Executable file does not exist! Exiting...')
                exit()
        if platform == "darwin":
            if not os.path.isfile(work_dir + '/jumper'):
                print('Executable file does not exist! Exiting...')
예제 #12
0
#%%
from utils import extract_data_from_matlabFile

import numpy as np
import matlab.engine
#%% read pickle
with open(
        os.path.join(os.path.join(PROJROOT, "001 data"), 'sampleData_0528.p'),
        'rb') as fp:
    data = pickle.load(fp)

print(data.keys())
#%%

engine = matlab.engine.start_matlab()
baseFolderPath = "C:\\Users\\Evan\MyFile\\Python\\MultiFactorBackTestModule\\002 src\\03 FactorFunctions\\matlab"

engine.workspace

allMatLabPath = engine.genpath(baseFolderPath)
engine.addpath(allMatLabPath)
engine.alpha053(data['close'])
engine.double(data['close'])
close = data['close']
img = np.random.rand(87, 195, 126)
imgMatlab = matlab.double(img)

close.shape

engine.load()
예제 #13
0
def render_diagram(app, node, docname):

    global engine

    uri = node['uri']

    # do not regenerate
    if os.path.exists(uri):
        pass

    ensuredir(os.path.dirname(uri))

    try:

        # reuse last engine to save loading time
        if engine == None:
            engine = matlab.engine.start_matlab()
        else:
            # clean up used engines
            engine.restoredefaultpath(nargout=0)
            engine.close('all', nargout=0)
            engine.bdclose('all', nargout=0)
            engine.clear('classes', nargout=0)

        # start engine from document directory
        engine.cd(os.path.dirname(app.env.doc2path(docname)))

        # then, support changing directory (relative to document)
        dir = node.get('dir')
        if dir:
            engine.cd(dir)

        # finally, add the MATLAB paths relative to the changed directory
        pathlist = node.get('addpath')
        if pathlist:
            for path in pathlist:
                engine.addpath(path)

        # preload script
        preload = node.get('preload')
        if preload:
            engine.eval(preload + ';', nargout=0)

        # load system
        system = node.get('system')
        if system:
            engine.load_system(system)

        # if subsystem specified, print from this layer
        subsystem = node.get('subsystem')
        if subsystem:
            system = "/".join([system, subsystem])

        # print from Simulink handle to .png
        engine.eval(
            "print( get_param( '{}', 'Handle' ), '-dpng', '{}' )".format(
                system, uri),
            nargout=0)

    except matlab.engine.MatlabExecutionError as err:
        raise SimulinkDiagramError('Unable to render Simulink diagram due ' +
                                   'to MATLAB execution error')
예제 #14
0
from waitress import serve
from flask import request
from flask import Flask

import time

import json

if __name__ == '__main__':

    app = Flask(__name__)

    # initialize MATLAB
    engine = matlab.engine.start_matlab()
    engine.cd('./matlab')
    engine.addpath('./utils')

    @app.route('/api/vrptw', methods=['POST'])
    def callVrptw():
        req_json = request.json

        if req_json is None or req_json == 'null':
            return 'Error parsing request! Should be in JSON format!'

        incidence_mat = req_json['incidenceMat']
        cost_mat = req_json['costMat']
        edge_time_vec = req_json['edgeTimeV']
        start_vec = req_json['startV']
        end_vec = req_json['endV']
        distr_vec = req_json['nodeDistributionV']
        vehicle_capacity_vec = req_json['vehicleCapacityV']
예제 #15
0
def render_diagram(app, node, docname):

    global engine

    uri = node['uri']

    # do not regenerate
    if os.path.exists( uri ):
        pass

    ensuredir( os.path.dirname( uri ) )

    try:

        # reuse last engine to save loading time
        if engine == None:
            engine = matlab.engine.start_matlab()
        else:
            # clean up used engines
            engine.restoredefaultpath(nargout=0)
            engine.close('all', nargout=0)
            engine.bdclose('all', nargout=0)
            engine.clear('classes', nargout=0)

        # start engine from document directory
        engine.cd( os.path.dirname( app.env.doc2path( docname ) ) )

        # then, support changing directory (relative to document)
        dir = node.get('dir')
        if dir:
            engine.cd( dir )

        # finally, add the MATLAB paths relative to the changed directory
        pathlist = node.get('addpath')
        if pathlist:
            for path in pathlist:
                engine.addpath( path )

        # preload script
        preload = node.get('preload')
        if preload:
            engine.eval( preload + ';', nargout=0)

        # load system
        system = node.get('system')
        if system:
            engine.load_system( system );

        # if subsystem specified, print from this layer
        subsystem = node.get('subsystem')
        if subsystem:
            system = "/".join( [ system, subsystem ] )

        # print from Simulink handle to .png
        engine.eval(
            "print( get_param( '{}', 'Handle' ), '-dpng', '{}' )".
                format( system, uri ),
            nargout=0
            )

    except matlab.engine.MatlabExecutionError as err:
        raise SimulinkDiagramError('Unable to render Simulink diagram due ' +
            'to MATLAB execution error'
        )
예제 #16
0
def main():
    print(f"Initializing MATLAB engine.")
    engine = matlab.engine.start_matlab()
    engine.addpath(str(siftflow_path))
    engine.addpath(str(siftflow_path / 'mexDenseSIFT'))
    engine.addpath(str(siftflow_path / 'mexDiscreteFlow'))

    warnings.simplefilter("error", UserWarning)

    filters = []
    if args.category:
        filters.append(ExemplarShapePair.shape.has(category=args.category))

    with session_scope() as sess:
        pairs, count = controllers.fetch_pairs_default(sess, filters=filters)
        # pairs, count = controllers.fetch_pairs(
        #     sess,
        #     by_shape=True,
        #     order_by=ExemplarShapePair.shape_id.asc(),
        # )

        print(f"Fetched {count} pairs")

        pairs = [
            pair for pair in pairs
            if (pair.data_exists(config.SHAPE_REND_SEGMENT_MAP_NAME)
                and not pair.data_exists(config.FLOW_DATA_NAME))
        ]

        print(f"Computing flows for {len(pairs)} pairs.")

        pbar = tqdm(pairs)
        pair: ExemplarShapePair
        for pair in pbar:
            pbar.set_description(f'Pair {pair.id}')
            # if not pair.exemplar.data_exists(config.EXEMPLAR_SUBST_MAP_NAME, type='numpy'):
            #     logger.warning('pair %d does not have substance map', pair.id)
            #     continue

            if not pair.data_exists(config.SHAPE_REND_SEGMENT_MAP_NAME):
                print(f'Pair {pair.id} does not have segment map')
                continue

            if pair.data_exists(config.FLOW_DATA_NAME):
                continue

            exemplar_im = transform.resize(pair.exemplar.load_cropped_image(),
                                           config.SHAPE_REND_SHAPE,
                                           anti_aliasing=True,
                                           mode='reflect')
            seg_vis = pair.load_data(config.SHAPE_REND_SEGMENT_VIS_NAME)

            vx, vy = compute_silhouette_flow(engine, pair)
            flow_vis = visualize_flow(vx, vy)

            vis.image(flow_vis.transpose((2, 0, 1)),
                      win='sil-flow',
                      opts={'title': 'sil-flow'})
            vis.image(
                ((exemplar_im + apply_flow(seg_vis, vx, vy)) / 2).transpose(
                    (2, 0, 1)),
                win='sil-flow-applied',
                opts={'title': 'sil-flow-applied'})

            # vx, vy = compute_phong_flow(engine, exemplar_im, phong_im)
            #
            # flow_vis = visualize_flow(vx, vy)
            # vis.image(flow_vis.transpose((2, 0, 1)),
            #           win='phong-flow',
            #           opts={'title': 'phong-flow'})
            # vis.image(
            #     ((exemplar_im + apply_flow(seg_vis, vx, vy))/2).transpose((2, 0, 1)),
            #     win='phong-flow-applied',
            #     opts={'title': 'phong-flow-applied'})

            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                pair.save_data(config.FLOW_VIS_DATA_NAME, flow_vis)
            pair.save_data(config.FLOW_DATA_NAME, np.dstack((vx, vy)))