Esempio n. 1
0
 def process(self):
     from pymatbridge import Matlab
     hostname = socket.gethostname()
     if 'nt' in hostname:
         matlab_executable = str(matlab_r2015a / 'bin' / 'matlab')
         mlab_process = Matlab(
             'nice -n 3 ' +
             matlab_executable +
             ' -c {}'.format(matlab_license) +
             ' -nodisplay -nosplash'
         )
     else:
         matlab_executable = 'matlab'
         mlab_process = Matlab(
             f'nice -n 3 {matlab_executable} -nodisplay -nosplash')
     if shutil.which(matlab_executable) is None:
         # pymatbridge.Matlab has a long timeout and will fail with
         # "ValueError: MATLAB failed to start" when matlab does not exists.
         raise EnvironmentError(
             'Could not find matlab.'
         )
     mlab_process.start()
     ret = mlab_process.run_code('run ' + self.matlab_startup_path)
     if not ret['success']:
         print(ret)
         raise NameError('Matlab is not working!')
     return mlab_process
Esempio n. 2
0
    def __init__(this):
        from pymatbridge import Matlab

        Tool.__init__(this)

        Simulink.__matlabConnection = Matlab(
            executable=GetConfigValue('Simulink', 'PathExe'))
 def fix_model(self,
               W,
               intMat,
               drugMat,
               targetMat,
               num,
               cvs,
               dataset,
               seed=None):
     self.dataset = dataset
     self.num = num
     self.cvs = cvs
     self.seed = seed
     R = W * intMat
     drugMat = (drugMat + drugMat.T) / 2
     targetMat = (targetMat + targetMat.T) / 2
     mlab = Matlab()
     mlab.start()
     # print os.getcwd()
     # self.predictR = mlab.run_func(os.sep.join([os.getcwd(), "kbmf2k", "kbmf.m"]), {'Kx': drugMat, 'Kz': targetMat, 'Y': R, 'R': self.num_factors})['result']
     res = mlab.run_func(
         os.path.realpath(os.sep.join(['kbmf2k', "kbmf.m"])), {
             'Kx': drugMat,
             'Kz': targetMat,
             'Y': R,
             'R': self.num_factors
         })
     self.predictR = res['result']
     # print os.path.realpath(os.sep.join(['../kbmf2k', "kbmf.m"]))
     mlab.stop()
Esempio n. 4
0
 def tucker(self, coreNway, lam, init=None):
     # 初始化
     if init is None:
         A0, C0 = self.tucker_init(*coreNway)
     else:
         assert len(init) == 4
         A0 = init[:3]
         C0 = init[-1]
     mlab = Matlab()
     mlab.start()
     while True:
         res = mlab.run_func(
             'tucker.m', self.R, coreNway, {
                 'hosvd': 1,
                 'lam': lam,
                 'maxit': 4000,
                 'A0': A0,
                 'C0': C0,
                 'tol': 1e-5
             })
         if res['success']:
             break
     mlab.stop()
     O, D, T, C = res['result']
     return TuckerResult(self.R, O, D, T, C)
Esempio n. 5
0
    def worker(cls, args):

        mlab_path, reqid, respath, srcpath, subnets = args
        mlab = Matlab(executable=mlab_path)
        mlab.start()

        try:
            # setting variables
            log.error(msg="Setting Matlab variables", context="HTTP")
            success = True
            success &= mlab_setvar(mlab, "DH_Simulator_AllSubnets",
                                   ','.join(subnets))
            success &= mlab_setvar(mlab, "DH_Simulator_SimulationID", reqid)
            success &= mlab_setvar(mlab, "DH_Simulator_ResultsPath", respath)
            success &= mlab_setvar(mlab, "DH_Simulator_ScriptPath", srcpath)

            if not success:
                log.error(msg="Unable to set some variables", context="HTTP")
            else:
                # running simulation
                log.error(msg="Starting simulation", context="HTTP")
                mlab.run_code("cd mlab")
                mlab.run_code("peak")
                log.error(msg="Simulation ended", context="HTTP")
        finally:
            mlab.stop()
            archive_dir = os.path.join(respath, reqid)
            shutil.make_archive(archive_dir, "zip", archive_dir)

        return reqid
Esempio n. 6
0
 def __init__(self, *args, **kwargs):
     super(MatlabKernel, self).__init__(*args, **kwargs)
     executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab')
     subprocess.check_call([executable, '-e'],
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
     self._matlab = Matlab(executable)
     self._matlab.start()
Esempio n. 7
0
def decision(data):
	image=data.save_to_disk('/home/user1/Downloads/Carla9.5/PythonAPI/my projects/camera_result/%06d.jpg' % data.frame_number);
	print('this is the path to send to matlab: ',image); 
	mlab = Matlab()
	mlab.start()
	overlap = mlab.run_func('parking.m', {'img': image})

	return overlap
Esempio n. 8
0
    def convertnctotiff(self):
        self.cancelbtn.config(state="disabled")

        matlabpath = "\"C:/Program Files/MATLAB/R2016b/bin/matlab\""
        mlab = Matlab(executable=matlabpath)

        ncfilefullpath = self.inputncdirtxtfield.get("1.0",
                                                     tk.END).encode("ascii")
        ncfilefullpath = ncfilefullpath[0:-1]
        #ncfilefullpathst = 'D:/NARSS/Research Project/2018-2019/01-01-2020/Task_NC-2-TIFF/input/GRCTellus.JPL.200204_201603.GLO.RL05M_1.MSCNv02CRIv02.nc'
        #print('ncfilefullpathdyn: '+ncfilefullpath, type(ncfilefullpath))

        tiffoutputdir = self.outputtiffdirtxtfield.get("1.0",
                                                       tk.END).encode("ascii")
        tiffoutputdir = tiffoutputdir[0:-1]
        tiffoutputdir = os.path.join(tiffoutputdir, '')
        #tiffoutputdirst = 'D:/NARSS/Research Project/2018-2019/01-01-2020/Task_NC-2-TIFF/output/'
        #print('tiffoutputdir: '+tiffoutputdir, type(tiffoutputdir))

        ncvar = self.ncvartxtfield.get("1.0", tk.END).encode("ascii")
        ncvar = ncvar[0:-1]
        #ncvar = 'lwe_thickness'
        #print('ncvar: '+ncvar, type(ncvar))

        nctimes = self.nctimestxtfield.get("1.0", tk.END)
        nctimes = int(nctimes)
        #nctimes = 152
        #print('nctimes: '+nctimes, type(nctimes))

        mlab.start()

        mlab.run_func(
            'C:/Users/akotb/PycharmProjects/AGP_System/resources/netcdf_to_tiff.m',
            {
                'arg1': ncfilefullpath,
                'arg2': ncvar,
                'arg3': nctimes,
                'arg4': tiffoutputdir
            })

        #self.conversionstartedlbl.grid_forget()
        self.startconvertingnctotiffbtn.grid_forget()
        self.cancelbtn.grid_forget()

        # task status
        self.conversioncompletedlbl = tk.Label(self.master,
                                               text="Conversion Completed")
        self.conversioncompletedlbl.grid(sticky='W',
                                         padx=10,
                                         pady=10,
                                         row=5,
                                         column=1)
        self.closebtn = tk.Button(self.master,
                                  text="Close",
                                  width=15,
                                  command=self.exit)
        self.closebtn.grid(sticky='E', padx=10, pady=10, row=5, column=2)
        mlab.stop()
Esempio n. 9
0
def test_init_end_to_end_distance(run_dir):
    """
    Plot the end-to-end distance distribution for a set of runs' r0 versus the
    theoretical distribution.
    """
    if not os.path.isdir(os.path.join(run_dir, 'data', 'end_to_end_r0')):
        wdata.aggregate_r0_group_NP_L0(run_dir)
    m = Matlab()
    m.start()
    m.run_code("help pcalc")
    m.stop()
Esempio n. 10
0
def start_mlab():
    dir_path = os.path.dirname(os.path.realpath(__file__))
    dir_list = [
        '/HHT_MATLAB_package', '/HHT_MATLAB_package/EEMD',
        '/HHT_MATLAB_package/checkIMFs', '/HHT_MATLAB_package/HSA'
    ]
    mlab = Matlab()
    mlab.start()
    for d in dir_list:
        res = mlab.run_func('addpath', dir_path + d)
    return mlab
Esempio n. 11
0
 def __init__(self):
     file = xlrd.open_workbook('excel/底图.xls')
     table = file.sheets()[sheet]  #通过索引顺序获取工作表
     nrows = table.nrows #行数              
     self.mlab = Matlab()
     self.mlab.start()
     # 该文件无用,只是为了避免一个路径引起的bug
     res = self.mlab.run_func('C:/Users/ovewa/Desktop/git-storage/OS-ELM-matlab/test.m',1)
     self.ditu = []
     for i in range(1,nrows):
         self.ditu.append(table.row_values(i)[1:])
Esempio n. 12
0
    def mask_to_region(self, path):
        """
		Converts mask image into corresponding regions list

		Arguments
		---------
		path : string
			Path to mask image

		Returns
		-------
		regions : list
			"regions" for the dataset that the mask belongs to
		"""
        def remove_interiors(L, region):
            """
			Removes interior pixels in neuron regions

			Arguments
			---------
			L : 2D numpy array
				Matrix containing labels for each neuron
			region : list
				List of all pixels in a neuron label
			"""
            for pixel in region:
                # Creating grid around pixel
                grid = L[pixel[0] - 1:pixel[0] + 2, pixel[1] - 1:pixel[1] + 2]
                # Removing pixels which are surrounded by similar values
                if np.unique(grid).size == 1:
                    region.remove(pixel)
            return region

        # Initializes Matlab to get labels for neurons using bwboundaries() method
        cwd = os.getcwd()
        matlab_file_path = os.path.join(cwd, 'utils',
                                        'get_region_boundaries.m')
        mlab = Matlab()
        mlab.start()
        matlab_result = mlab.run_func(matlab_file_path, {'arg1': path})
        mlab.stop()
        # `L` is 2D array with each neuron carrying a label 1 -> n
        L = matlab_result['result']
        n = int(L.max())  # Number of neurons
        # Getting coordinates of pixels of neuron regions
        # This includes interior pixels as well
        regions = [{
            "coordinates": list(zip(*np.where(L == float(i))))
        } for i in range(1, n)]
        # Removing interior pixels in neuron regions
        for region in regions:
            remove_interiors(L, region["coordinates"])

        return regions
Esempio n. 13
0
    def __init__(self, worker_id, mlab_path, socket_prefix, id_prefix):
        threading.Thread.__init__(self)
        self.redis_obj = redis.Redis()
        self.worker_id = worker_id

        #Create a matlab instance; ie one matlab instance is created per worker
        cv_socket = socket_prefix + worker_id
        mlab_id = id_prefix + worker_id
        self.mlab_inst = Matlab(matlab=mlab_path,
                                socket_addr=cv_socket,
                                id=mlab_id)
        self.mlab_inst.start()

        time.sleep(2)
        self.createHash()
    def fix_model(self, W, intMat, drugMat, targetMat,num, cvs, dataset, seed=None):
        self.dataset = dataset
        self.num = num
        self.cvs = cvs
        self.seed = seed
        R = W * intMat
        #R = np.transpose(R)
        drugMat = (drugMat + drugMat.T) / 2
        targetMat = (targetMat + targetMat.T) / 2
        mlab = Matlab()
        mlab.start()
        res = mlab.run_func(os.path.realpath(os.sep.join(['GRMF',"runGRMF.m"])),{'Kx': drugMat, 'Kz': targetMat, 'Y': R, 'cv': self.cv})
        self.predictR = res['result']

        mlab.stop()
        1+1
Esempio n. 15
0
    def train_save_sp_tensor(self, pmi=True):
        gatherer = self.get_pmi_gatherer(3)
        if pmi:
            print('creating PPMI tensor...')
        else:
            print('creating sparse count tensor...')
        indices, values = gatherer.create_pmi_tensor(positive=True,
                                                     debug=True,
                                                     symmetric=False,
                                                     pmi=pmi,
                                                     shift=-np.log2(15.))
        matfile_name = 'sp_tensor_{}_{}_log15.mat'.format(
            self.num_sents, self.min_count)
        scipy.io.savemat(matfile_name, {'indices': indices, 'values': values})
        print('saved {}. exiting.'.format(matfile_name))
        sys.exit()

        from pymatbridge import Matlab
        session = Matlab('/usr/local/bin/matlab')
        print('starting matlab session...')
        session.start()
        #session.set_variable('indices', indices+1)
        #session.set_variable('vals', values)

        print('setting up variables...')
        session.run_code("d = load('/home/eric/code/gensim/sp_tensor.mat');")
        session.run_code("indices = d.indices + 1;")
        session.run_code("vals = d.values';")
        #session.run_code('size_ = [{0} {0} {0}];'.format(len(self.model.vocab)))
        session.run_code('size_ = [{0} {0} {0}];'.format(8))
        session.run_code('R = {};'.format(self.embedding_dim))
        import pdb
        pdb.set_trace()
        res = session.run_code("T = sptensor(indices, vals, size_);")
        print('running ALS...')
        t = time.time()
        res = session.run_code('[P, U0, out] = cp_als(T, R)')
        print('ALS took {} secs'.format(time.time() - t))
        session.run_code('lambda = P.lambda;')
        session.run_code('U = P{1,1};')
        session.run_code('V = P{2,1};')
        session.run_code('W = P{3,1};')
        lambda_ = session.get_variable('lambda')
        U = session.get_variable('U')
        import pdb
        pdb.set_trace()
        '''
Esempio n. 16
0
def startMatlab(nonnegative_dir, hardthresh_dir):
    mlab = Matlab()
    mlab.start()

    # I could do a cd here to make sure that the call functions are in the working dir

    status1 = mlab.run_code("addpath %s" % nonnegative_dir)['success']
    status2 = mlab.run_code("addpath %s/Main" % hardthresh_dir)
    status3 = mlab.run_code("addpath %s/Auxiliary" % hardthresh_dir)

    if status1 and status2 and status3:
        print("Libraries succesfully loaded")
    else:
        print("Error loading libraries")
        return

    return mlab
Esempio n. 17
0
 def fix_model(self, W, intMat, drugMat, targetMat, seed=None):
     R = W * intMat
     drugMat = (drugMat + drugMat.T) / 2
     targetMat = (targetMat + targetMat.T) / 2
     mlab = Matlab('/Applications/MATLAB_R2014b.app/bin/matlab')
     mlab.start()
     # print os.getcwd()
     # self.predictR = mlab.run_func(os.sep.join([os.getcwd(), "kbmf2k", "kbmf.m"]), {'Kx': drugMat, 'Kz': targetMat, 'Y': R, 'R': self.num_factors})['result']
     self.predictR = mlab.run_func(
         os.path.realpath(os.sep.join(['./kbmf2k', "kbmf.m"])), {
             'Kx': drugMat,
             'Kz': targetMat,
             'Y': R,
             'R': self.num_factors
         })['result']
     # print os.path.realpath(os.sep.join(['./kbmf2k', "kbmf.m"]))
     mlab.stop()
    def __init__(self):
        self.mlab = Matlab(matlab='/Applications/MATLAB_R2014a.app/bin/matlab')
        self.mlab.stop()
        self.mlab.start()

        self.action_space = spaces.Discrete(4)
        self.observation_space = spaces.Discrete(4)
        self.round = 2

        self.LAM = round(random.uniform(0.1, 20), 3)
        self.D = round(np.random.uniform(5, 40), 2)
        self.N_n = np.random.randint(5, 20)
        self.N_0 = round(random.uniform(5, 20), 3)
        # self.observation = np.array([self.LAM, self.D, self.N_n, self.N_0])#.reshape(1,4)
        self.observation = (self.LAM, self.D, self.N_n, self.N_0
                            )  #.reshape(1,4)

        self._reset()
Esempio n. 19
0
    def objective_function(self, x):
        '''
        matlabpath: we need the path to matlab since we need to run it.
        
        IMPORTANT: walker_simulation.m must be included in the 
        WGCCM_three_link_walker_example file in order to work. 
        So simply modify the path below.
        '''
		mlab = Matlab(executable= matlabpath)
		mlab.start()
		output = mlab.run_func(os.path.join(self.matlab_code_directory, 'walker_simulation.m'), 
						   {'arg1': x[:, 0],'arg2': x[:, 1],'arg3': x[:, 2],
						   'arg4': x[:, 3],'arg5':x[:, 4],'arg6': x[:, 5],
						   'arg7': x[:, 6],'arg8': x[:, 7],'arg9': self.num_steps})
						   

		answer = output['result']
		simul_output = answer['speed']
		mlab.stop()
def call_peak_picking(filepath, scriptpath):
    """ Method connects to local Matlab via ZeroMQ and calls peak picking function there implemented in script path. """

    start_time = time.time()

    mlab = Matlab(
        executable='/Applications/MATLAB_R2018a_floating.app/bin/matlab')

    mlab.start()
    response = mlab.run_func(scriptpath, {'path': filepath})
    mlab.stop()

    peaks = response['result']

    print(time.time() - start_time, " seconds elapsed for peak picking")

    print("Total number of peaks", len(peaks))

    return peaks
Esempio n. 21
0
    def evaluation(self, test_data, test_label):

        mlab = Matlab()
        mlab.start()
        res = mlab.run_func(
            os.path.realpath(os.sep.join([os.getcwd(), "pudt", "PUDT.m"])), {
                'w': self.w,
                'dataset': self.dataset
            })
        self.predictR = res['result']

        mlab.stop()
        # score = self.predictR[test_data[:, 0], test_data[:, 1]]
        score = self.predictR
        import pandas as pd
        score = pd.DataFrame(score)
        score.to_csv('../data/datasets/EnsambleDTI/pudt_' + str(self.dataset) +
                     '_s' + str(self.cvs) + '_' + str(self.seed) + '_' +
                     str(self.num) + '.csv',
                     index=False)
        prec, rec, thr = precision_recall_curve(np.array(score['test_label']),
                                                np.array(score['score']))
        aupr_val = auc(rec, prec)
        # plt.step(rec, prec, color='b', alpha=0.2,
        #          where='post')
        # plt.fill_between(rec, prec, step='post', alpha=0.2,
        #                  color='b')
        #
        # plt.xlabel('Recall')
        # plt.ylabel('Precision')
        # plt.ylim([0.0, 1.05])
        # plt.xlim([0.0, 1.0])
        # plt.title('2-class Precision-Recall curve: AP={0:0.2f}')
        fpr, tpr, thr = roc_curve(np.array(score['test_label']),
                                  np.array(score['score']))
        auc_val = auc(fpr, tpr)
        print("AUPR: " + str(aupr_val) + ", AUC: " + str(auc_val))

        return aupr_val, auc_val
Esempio n. 22
0
from pymatbridge import Matlab

# Initialise MATLAB
mlab = Matlab(port=4000)
# Start the server
mlab.start()
# Run a test function: just adds 1 to the argument a
for i in range(10):
    print mlab.run('~/Sites/python-matlab-bridge/test.m', {'a': i})['result']
# Stop the MATLAB server
mlab.stop()
Esempio n. 23
0
 def __init__(self, parsed, source, mode, formatdict):
     from pymatbridge import Matlab
     self.matlab = Matlab()
     self.matlab.start()
     PwebProcessor.__init__(self, parsed, source, mode, formatdict)
Esempio n. 24
0
from pymatbridge import Matlab
mlab = Matlab(matlab='/Applications/MATLAB_R2014a.app/bin/matlab')
mlab.start()
res = mlab.run('/Users/yanguango/Lab/SpamFilter/Project/src/PCA.m', {'arg1': 3, 'arg2': 5})
print res['result']
Esempio n. 25
0
import collections

from pymatbridge import Matlab

Play = collections.namedtuple('Play', ['pid', 'card'])
mlab = Matlab(
    matlab='C:\\Program Files (x86)\\MATLAB\\R2011a Student\\bin\\matlab.exe')
Esempio n. 26
0
 def __init__(self, *args, **kwargs):
     excecutable = kwargs.pop('excecutable', 'matlab')
     super(MatlabKernel, self).__init__(*args, **kwargs)
     self._matlab = Matlab(excecutable)
     self._matlab.start()
Esempio n. 27
0
    # Run a more comprehensive set of problem sizes.  This could take more than
    # an hour to complete.
    size_set = 'full'
    use_precomputed = False
else:
    size_set = 'reduced'
    use_precomputed = True

if use_precomputed:
    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    matlab_data_file = os.path.join(data_dir, 'dwt_matlabR2012a_result.npz')
    matlab_result_dict = np.load(matlab_data_file)
else:
    try:
        from pymatbridge import Matlab
        mlab = Matlab()
        _matlab_missing = False
    except ImportError:
        print("To run Matlab compatibility tests you need to have MathWorks "
              "MATLAB, MathWorks Wavelet Toolbox and the pymatbridge Python "
              "package installed.")
        _matlab_missing = True

# list of mode names in pywt and matlab
modes = [('zpd', 'zpd'), ('cpd', 'sp0'), ('sym', 'sym'), ('ppd', 'ppd'),
         ('sp1', 'sp1'), ('per', 'per')]

families = ('db', 'sym', 'coif', 'bior', 'rbio')
wavelets = sum([pywt.wavelist(name) for name in families], [])

Esempio n. 28
0
 def __init__(self):
     self.mlab = Matlab()
     self.mlab.start()
     # 该文件无用,只是为了避免一个路径引起的bug
     res = self.mlab.run_func(
         'C:/Users/ovewa/Desktop/git-storage/OS-ELM-matlab/test.m', 1)
Esempio n. 29
0
def callMatlabFunc(mlab, funcName, inputArgs, nbOutputArg, debug=False, setupCode=""):

    if debug:
        print("Entering callMatlabFunc...")    

    closeMatlab = False
    if mlab is None:
        if debug:
            print("Starting Matlab...")
        mlab = Matlab() #Matlab(matlab='C:/Program Files/MATLAB/R2015a/bin/matlab.exe')
        mlab.start() 
        closeMatlab = True

    if len(setupCode):
        result = mlab.run_code(setupCode)
        if not result["success"]:
            raise  RuntimeError(result["content"]["stdout"]  )

    if debug:
        print("Setting input variables...")    
        
    inputStr = ""
    if len(inputArgs):
        for i, arg in enumerate(inputArgs):
            mlab.set_variable("in" + str(i), arg)
            inputStr += "in" + str(i) + ","
        inputStr = inputStr[:-1]
        
    if debug:
        print("Input variables set...")    
        
        
        
    matlabCode = ""
    if nbOutputArg == 1:
        matlabCode += "out0 = "
    elif nbOutputArg > 1:
        matlabCode += "[" 
        for i in range(nbOutputArg):
            matlabCode += "out" + str(i) + ","
        matlabCode = matlabCode[:-1]    
        matlabCode += "] = " 
        
    matlabCode += funcName + "(" + inputStr + ")"

    if debug:
        print("Matlab Code: ")
        print(matlabCode)
        
    result = mlab.run_code(matlabCode)

    if debug:
        print("run_code executed.")
        print(result)
    
    outArgs = [mlab.get_variable("out" + str(i)) for i in range(nbOutputArg)]

    if debug:
        print("Out args: ")
        print(outArgs)
    
    sucess = result["success"]
    stdout = result["content"]["stdout"]
    
    if closeMatlab :
        if debug:
            print("Stoping Matlab...")
        mlab.stop()

    if not sucess:
        raise  RuntimeError(stdout)
        
    return outArgs
Esempio n. 30
0
def main():
    #start matlab connection
    mlab = Matlab()
    mlab.start()
    vehicle = None
    data=None
    vehicle1=None
    vehicle2=None
    vehicle3=None
    vehicle4=None
    vehicle5=None
    actor_list = []
    sensors = []

   
    argparser = argparse.ArgumentParser(
        description=__doc__)
    argparser.add_argument(
        '--host',
        metavar='H',
        default='127.0.0.1',
        help='IP of the host server (default: 127.0.0.1)')
    argparser.add_argument(
        '-p', '--port',
        metavar='P',
        default=2000,
        type=int,
        help='TCP port to listen to (default: 2000)')
    args = argparser.parse_args()
    
    try:
       client = carla.Client(args.host, args.port)

       client.set_timeout(2.0)
       

       world = client.get_world()
       ourMap = world.get_map()
       debug = world.debug;
#********* setting fixed time stamp for simulation **************
       settings = world.get_settings();
       settings.fixed_delta_seconds = 0.05;
       world.apply_settings(settings);
       spectator = world.get_spectator();

#*************** deffinition of sensors ****************************
       
       camera_blueprint = world.get_blueprint_library().find('sensor.camera.rgb')
      
#*********** definition of blueprints for vehicles *******************
       blueprint = world.get_blueprint_library().find('vehicle.audi.tt') #for main(ego) vehicle
       blueprint.set_attribute('role_name', 'hero')
#*********** for non-player vehicles *********************************
       non_playerBlueprint1 = random.choice(world.get_blueprint_library().filter('vehicle.bmw.grandtourer'))
       non_playerBlueprint2 = random.choice(world.get_blueprint_library().filter('vehicle.tesla.*'))
       non_playerBlueprint4 = random.choice(world.get_blueprint_library().filter('vehicle.mercedes-benz.coupe'))
       non_playerBlueprint3 = random.choice(world.get_blueprint_library().filter('vehicle.toyota.*'))


#******************************* set weather **********************************
       weather = carla.WeatherParameters(
        cloudyness=0.0,
        precipitation=0.0,
        sun_altitude_angle=70.0,
        sun_azimuth_angle=50.0)

       world.set_weather(weather)


#************************ spawn non-player vehicles ******************************

       class spawn_vehicle:
        def __init__(self, blueprint, x, y):
            self.vehicle=None;
            spawn_points = ourMap.get_spawn_points()
            spawn_point = spawn_points[30];
            spawn_point.location.x += x;
            spawn_point.location.y += y;
            self.vehicle = world.spawn_actor(blueprint, spawn_point)

     
       


       #first non-player vehicle
       data=spawn_vehicle(non_playerBlueprint1, -20, 1.0);
       vehicle1=data.vehicle;
       actor_list.append(vehicle1)


       #second non-player vehicle
       data=spawn_vehicle(non_playerBlueprint2, -12, 1.0);
       vehicle2=data.vehicle;
       actor_list.append(vehicle2)

       # 3rd non-player vehicle
       data=spawn_vehicle(non_playerBlueprint3, 2.0, 1.0);
       vehicle3=data.vehicle;
       actor_list.append(vehicle3)

       #4th nonplayer vehicle
       data=spawn_vehicle(non_playerBlueprint4, 10.0, 1.0);
       vehicle4=data.vehicle;
       actor_list.append(vehicle4)
      


       #********************** spawn main vehicle *****************************
       data=spawn_vehicle(blueprint, -23.0, -1.5);
       vehicle=data.vehicle;
       actor_list.append(vehicle)
       #set the first movement of ego car
       control = carla.VehicleControl(throttle=0.1)
       vehicle.apply_control(control)
      
       
       #************************ camera-sensor settings ***********************
       camera_location = carla.Transform(carla.Location(x=1.3, z=2.0))
       camera_blueprint.set_attribute('sensor_tick', '0.4');
       camera_sensor = world.spawn_actor(camera_blueprint, camera_location, attach_to=vehicle);


       #=======================================obstacle sensors for maneuver==============================================================


       class ObstacleSensor(object):
        def __init__(self, parent_actor,x,y,z,angle):
          self.sensor = None
          self._parent = parent_actor
          self.actor = 0.0
          self.distance = 0.0
          self.x=x
          self.y=y
          self.z=z
          self.angle=angle;
          world = self._parent.get_world()
          bp = world.get_blueprint_library().find('sensor.other.obstacle')
          bp.set_attribute('debug_linetrace', 'false');
          self.sensor = world.spawn_actor(bp, carla.Transform(carla.Location(x=self.x, y=self.y, z=self.z), carla.Rotation(yaw=self.angle)), attach_to=self._parent);
          sensors.append(self.sensor);
          weak_self = weakref.ref(self)
          self.sensor.listen(lambda event: ObstacleSensor._on_event(weak_self, event))

        @staticmethod
        def _on_event(weak_self, event):
         self = weak_self()
         if not self:
            return
         self.actorId = event.other_actor.id
         self.actorName = event.other_actor.type_id
         self.distance = event.distance



       forward_sensor = ObstacleSensor(vehicle, x=1.3, y=0.9, z=0.6, angle=90);
       rearSide_sensor = ObstacleSensor(vehicle, x=-1.3, y=0.9, z=0.6, angle=90);
       center_sensor = ObstacleSensor(vehicle, x=0.0, y=0.9, z=0.6, angle=90);
       back_sensor = ObstacleSensor(vehicle, x=-1.3, y=0.0, z=0.6, angle=180);
       
      
  


       #====================================step1:Parking Decision==========================================================
       global image;
       time.sleep(5.0);
       textLocation = vehicle.get_location();
       textLocation.x +=5.0;
       textLocation.y -=0.8;
       textLocation.z +=1.8;
       startText = "Search for parking place"
       debug.draw_string(textLocation, startText, True, carla.Color(255,255,0), 3, True);
       textLocation.y +=1.0;
       debug.draw_box(carla.BoundingBox(textLocation,carla.Vector3D(0.2,1.5,0.5)),carla.Rotation(yaw=180), 0.1, carla.Color(255,0,0),3, True);
       camera_sensor.listen(lambda image: parking_decision(image));


       
       def parking_decision(data):
        camera_sensor.stop();
        cameraControl = carla.VehicleControl(throttle=0);
        vehicle.apply_control(cameraControl);
        output=interface.decision(data,mlab);
        overlapRatio = output['result'];
        print('rate of Overlap:', overlapRatio);
        if overlapRatio < 0.1:
          print('parking place is between the next 2 vehicles');
          location = vehicle.get_location();
          location.x +=15;
          location.y +=1.0;
          location.z +=1.8;
          text = 'Parking vacancy detected';
          debug.draw_string(location, text, True, carla.Color(255,255,0), 4.0, True);
          location.y +=1.5;
          debug.draw_box(carla.BoundingBox(location,carla.Vector3D(0.2,2.0,0.8)),carla.Rotation(yaw=180), 0.1, carla.Color(255,0,0),4.0, True);
          time.sleep(3.0);
          mlab.end();
          if hasattr(center_sensor, 'actorId'):
            print('center_sensor info in detection time:', center_sensor.actorName, center_sensor.actorId);
            if center_sensor.actorId != 0:
              number=2;
            else:
              number=1;
          print('matlab disconnected');
          parking_preparation(number);
        else:
          print('no parking place has been detected right now');
          cameraControl = carla.VehicleControl(throttle=0.2);
          vehicle.apply_control(cameraControl);
          print('car is moving');
          camera_sensor.listen(lambda image: parking_decision(image));

  
      

       #==================================step2:Parking Preparation(position phase)=============================================
       def parking_preparation(limit):
        print('limit',limit);
        x1=x2=0;
        vehicle.apply_control(carla.VehicleControl(throttle=0.3));
        while config.count < limit:
          current_vhcl = center_sensor.actorId;
          if config.nonplayer != current_vhcl and current_vhcl != 0:
            config.nonplayer = current_vhcl;
            config.count += 1;
            continue;
        
        else:
          first_parked_car = forward_sensor.actorId;
          print('first_parked_car', first_parked_car);
          while config.count == limit:
            if forward_sensor.actorId == 0:
                  print('first_parked_car passed');
                  config.parkingWidth = forward_sensor.distance; #lateral distance of the parking bay
                  x1 = vehicle.get_location().x; #vehicle first place in parking bay
                  x1 -= 1.3; #because this location is from center of the car
                  print('parkingWidth:', config.parkingWidth, 'x1:', x1);
                  break;
          while forward_sensor.actorId == 0:
            continue;

          else:
            if forward_sensor.actorId != 0 and forward_sensor.actorId != first_parked_car:
                  print('we reached second static car:', forward_sensor.actorId);
                  print('second_parked_car', forward_sensor.actorId);
                  x2 = vehicle.get_location().x; #vehicle second place in parking bay
                  x2 += 1.3; 
                  config.parkingLength = abs(x2 - x1); #length of the parking
                  print('parkingLength:', config.parkingLength, 'x2:', x2);
                  while rearSide_sensor.distance > 1.0:
                    vehicle.apply_control(carla.VehicleControl(steer=0.0, throttle=0.2));
                    time.sleep(1.0);
                    if rearSide_sensor.actorId != 0: #when the static vehicle detected
                      vehicle.apply_control(carla.VehicleControl(steer=0.0, throttle=0.0, brake=1.0));
                      parking_maneuver();
                      break;
                  else:
                    vehicle.apply_control(carla.VehicleControl(steer=0.0, throttle=0.0, brake=1.0));
                    time.sleep(3.0);
                    parking_maneuver();


       #====================================step3:Parking Maneuver=================================================================
       def parking_maneuver():
        time.sleep(3.0);
        maneuver.calculate_maneuverTime(vehicle);
        maneuver.calculate_max_steeringAng(vehicle);
        time.sleep(3.0);
        for t in numpy.arange(0,config.T,config.sampling_period):
          time.sleep(0.08);
          if (hasattr(back_sensor, 'actorId') and (back_sensor.actorId != 0) and (back_sensor.distance < 4)): #or (hasattr(rearSide_sensor, 'actorId') and (rearSide_sensor.actorId == 0) and (rearSide_sensor.distance < 5.0)):
            print('1****vehicle should be stopped!', back_sensor.distance);
            vehicle.apply_control(carla.VehicleControl(throttle=0, steer=0.0, brake=1.0));
            control=vehicle.get_control();
            print('throttle', control.throttle, 'brake', control.brake, 'steer', control.steer)
          else:
            print('2****move');
            maneuver.parking(t,vehicle); #call parking function from maneuver.py
            control=vehicle.get_control();
            print('throttle', control.throttle, 'brake', control.brake, 'steer', control.steer)
        

       

       #set simulator view to the location of the vehicle
       while True:
        time.sleep(1.0)
        viewLocation = vehicle.get_location();
        viewLocation.z += 1.0;
        spectator.set_transform(get_transform(viewLocation, -180))



    finally:
      print('\ndestroying %d actors' % len(actor_list))
      for actor in actor_list:
        if actor is not None: 
          actor.destroy()
      for sensor in sensors:
        if sensor is not None:
          sensor.destroy()