Ejemplo n.º 1
0
def test(process_input_list, cpu_count):
    scheduler_list = []
    # fcfs = FCFS(process_input_list, cpu_count)
    scheduler_list.append(RR(process_input_list, cpu_count, 2))  # quantum = 2
    scheduler_list.append(RR(process_input_list, cpu_count, 3))  # quantum = 3
    # scheduler_list.append(HRRN(process_input_list, cpu_count))
    # ...
    for test_idx, scheduler in enumerate(scheduler_list):
        print(
            "[ TEST {0} - {1}]=======================================".format(
                test_idx + 1,
                type(scheduler).__name__))
        scheduler.run()
        print_process_time_table(scheduler.processes)
Ejemplo n.º 2
0
    def calculate(self):

        if not (self.SJF_btn.isChecked() or self.FCFS_btn.isChecked()
                or self.RR_btn.isChecked() or self.SRTF_btn.isChecked()):
            self.show_popup("Enter algorithm to execute")
            return
        if len(self.processes) == 0:
            self.show_popup(
                "There must be at least one process to execute this algorithm")
            return
        self.sortDict()
        if self.SJF_btn.isChecked():
            res = SJF(self.processes)
        elif self.FCFS_btn.isChecked():
            res = FCFS(self.processes)
        elif self.RR_btn.isChecked():
            if self.quantum_time.text() == "":
                self.show_popup("Enter value for Quantum time first")
                return
            else:
                res = RR(self.processes, int(self.quantum_time.text()))
        else:
            res = SRTF(self.processes)
        self.lcdNumber.display(res[0])
        self.lcdNumber_2.display(res[1])
Ejemplo n.º 3
0
    def __init__(self):
        super().__init__()

        tabwidget = QTabWidget()
        tabwidget.addTab(RR.RRClass(), "RR")
        tabwidget.addTab(FCFS.FCFSClass(), "FCFS")
        tabwidget.addTab(SJF_Preemptive.SJFPreemptiveClass(), "SJF Preemptive")
        tabwidget.addTab(SJF_NonPreemptive.SJFNonPreemptiveClass(),
                         "SJF Non Preemptive")
        tabwidget.addTab(Priority_Preemptive.PriorityPreemptiveClass(),
                         "Priority Preemptive")
        tabwidget.addTab(Priority_NonPreemptive.PriorityNonPreemptiveClass(),
                         "Priority Non Preemptive")

        vboxLayout = QVBoxLayout()
        vboxLayout.addWidget(tabwidget)

        self.setLayout(vboxLayout)
Ejemplo n.º 4
0
    def ScheduleAlgo(self):

        InputFile = open(self.ProcessFile, "r")
        Lines = InputFile.readlines()

        ProcessNum = int(Lines[0])

        AT = []
        BT = []
        ID = []
        PT = []

        for i in range(1,ProcessNum+1):
            temp = Lines[i].split(' ')
            ID.append(int(temp[0]))
            AT.append(float(temp[1]))
            BT.append(float(temp[2]))
            PT.append(int(temp[3]))
        select = self.var.get()
        if( select == 1):
            Scheduler = HPF(AT,BT,ID,ProcessNum,int(self.ContextTime.get()),PT)
            print("hpf")
        elif( select == 2):
            Scheduler = FCFS(AT,BT,ID,ProcessNum,int(self.ContextTime.get()))
            print("fcfs")
        elif( select == 3):
            print("rr")
            Scheduler = RR(AT,BT,ID,ProcessNum,int(self.ContextTime.get()),int(self.QuantamTime.get()))
        else:
            print("srtn")
            Scheduler = SRTN(AT,BT,ID,ProcessNum,int(self.ContextTime.get()))

        Scheduler.Schedule()

        AvgTT,AvgWTT = Scheduler.TurnaroundTime()
        Processes = Scheduler.Processes

        self.OutFile("ProcessInfo2",Processes,AvgTT,AvgWTT)
        Scheduler.DisplayProcesses()
Ejemplo n.º 5
0
		ufreqs = np.unique(rr_stimparams[:, 0])
		urrs = np.unique(rr_stimparams[:, 1])
		freq_played, freq_ix_played, _ = misc.closest(ufreqs, cf, log = True)
		rr_bins = np.arange(0, 6, 0.05)
		rr_psth_stim, usp = Spikes.calc_psth_by_stim(rr_rast, rr_stimparams, bins = rr_bins)
		cf_psth = rr_psth_stim[freq_ix_played, :, :]
		noise_psth = rr_psth_stim[0, :, :]
		
		fig = plt.figure()
		nrrs = cf_psth.shape[0]
		
		ax = []
		for i in range(nrrs):
			ax.append(fig.add_subplot(nrrs, 1, i+1))
			ax[-1].plot(rr_bins[:-1], cf_psth[i, :])
			RR.plot_tone_pips(urrs[i], 6, 0.05, 0.025, ax = ax[-1], color = 'r')
			if i>0:
				ax[-1].set_xticklabels('')
			
		misc.sameyaxis(ax)
	
	if len(voc_path) > 0:
		
		voc_file = h5py.File(voc_path, 'r')
		voc_rast = voc_file['rast'].value
		voc_stimparams = voc_file['stimID'].value
		voc_file.close()
		
		# voc_rast = voc_rast[1:, :]
		# voc_stimparams = voc_stimparams[:-1, :]
		voc_stimparams = voc_stimparams[:, 0]
Ejemplo n.º 6
0
		rast = frr['rast'].value
		stimparams = frr['stimID'].value
		frr.close()

		# if not np.isnan(spktimes[0]):
		cf = cfs[cfs[:, 0]==unitnum, 1][0]
		cf_hz = ix2freq[20:][int(cf)]
		freqs = stimparams[:, 0]
		rrs = stimparams[:, 1]
		ufreqs = np.unique(freqs)
		urrs = np.unique(rrs)
		nrrs = urrs.size
	
		# now we determine which of the frequencies we played is closest to this neuron's CF
		thisfreq, thisfreq_ix, thisfreq_err = misc.closest(ufreqs, cf_hz, log = True)
		if np.abs(thisfreq_err) > 0.2:
			print 'No close frequency found!'
		thisfreq = ufreqs[thisfreq_ix]
	
		# isolate the parts of the raster for this frequency and build a psth for each RR
		ix = RF.get_trials(stimparams, np.array([thisfreq, np.nan]))
		thisrast = rast[ix, :1050]
		thisstims = stimparams[ix, :]
		psths, ustims = Spikes.calc_psth_by_stim(thisrast, thisstims)
	
		rrtf = RR.calc_rrtf_all(thisrast, thisstims, thisfreq, urrs)
	
		db.resize(db.size+1)
		db[-1] = np.array((gen, exp, sess, unitnum, cf_hz, rrtf, urrs), dtype = dtype)

np.savez(savepath, db)
Ejemplo n.º 7
0
def rr_make_contactsheets():
	'''
	loop through all the sessions and plot the rrtfs
	'''

	fig = plt.figure(figsize = (30, 18));
	txt_suptitle = fig.suptitle('')
	ax_cfrrtf = fig.add_axes((0.76, 0.76, 0.24, 0.23));
	ax_cfvs = ax_cfrrtf.twinx();
	ax_cfcircpsthall = fig.add_axes((0.62, (11/14.)-0.02, 0.1, (1/7.)+0.04), polar = True)
	ax_cfcircpsthall.set_xticklabels(''); ax_cfcircpsthall.set_yticklabels('');
	ax_rf = fig.add_axes((0.67, 0.51, 0.33, 0.23));
	ax_rfrast = fig.add_axes((0.67, 0.25, 0.33, 0.24));
	ax_rfrast.set_xticklabels('');
	ax_rfpsth = fig.add_axes((0.67, 0.01, 0.33, 0.24));

	ax_cfrr = [fig.add_axes((0.03, 1-((i+1)/7.), 0.35, 1/7.)) for i in np.arange(nrrs)]
	ax_cfalignedpsth = [fig.add_axes((0.38, 1-((i+1)/7.), 0.17, 1/7.)) for i in np.arange(nrrs)]
	ax_cfcircpsth = [fig.add_axes((0.53, 1-((i+1)/7.), 0.1, 1/7.), polar = True) for i in np.arange(nrrs)]
	# ax_noiserr = [fig.add_subplot(nrrs, 3, i) for i in np.arange(1, 3*nrrs, 3)]

	for sessionpath in sessionpaths:

		session = os.path.split(sessionpath)[1]
		unitinfos = fileconversion.get_session_unitinfo(sessionpath, onlycomplete = ('RF', 'RR', 'VOC'))
			
		for unitkey in unitinfos.keys():
			
			txt_suptitle.set_text('%s %s' % (session, unitkey))

			unitinfo = unitinfos[unitkey]

			rf_ix = unitinfo['stimtype'].index('RF')
			
			f_rf = h5py.File(unitinfo['fpath'][rf_ix], 'r')
			rf_rast = f_rf['rast'].value
			rf_stimparams = f_rf['stimID'].value
			cf_ix = f_rf['cf'].value
			f_rf.close()
			
			cf = ix2freq[20:][int(cf_ix)]

			''' calculate and plot RF, psth, and sorted raster'''
			rf = RF.calc_rf(rf_rast, rf_stimparams)
			rf_psth = Spikes.calc_psth(rf_rast)
			RF.plot_rf(rf, cf = cf_ix, axes_on = False, ax = ax_rf) # plot RF
			ax_rf.axvline(cf_ix, color = 'r', lw = 1.5)
			Spikes.plot_sorted_raster(rf_rast, rf_stimparams, ax = ax_rfrast) # plot raster
			ax_rfpsth.plot(t_rf, Spikes.exp_smoo(rf_psth, tau = 0.005)) # plot PSTH

			''' calcualte and plot RRTFs for CF and noise stimuli '''
			rr_ix = unitinfo['stimtype'].index('RR')
			
			f_rr = h5py.File(unitinfo['fpath'][rr_ix], 'r')
			rr_rast = f_rr['rast'].value
			rr_stimparams = f_rr['stimID'].value
			f_rr.close()

			# find the played CF
			rr_ufreqs = np.unique(rr_stimparams[:, 0])
			urrs = np.unique(rr_stimparams[:, 1])
			npips = (urrs*4).astype(int)
			rr_freq, rr_ufreq_ix, _ = misc.closest(rr_ufreqs, cf, log = True)

			ax_rf.axvline(RF.calc_freq2ix(rr_freq), color = 'g', lw = 1.5)
			# calculate the PSTHs for each repetition rate
			tmp = Spikes.calc_psth_by_stim(rr_rast, rr_stimparams)
			rr_cfpth = tmp[0][rr_ufreq_ix, :, :]
			# rrtf_noisepsth = tmp[0][0, :, :]

			# plot the aligned psths
			RR.aligned_psth_separate_all(rr_rast, rr_stimparams, rr_freq, npips, axs = ax_cfalignedpsth)
			[a.set_yticklabels('') for a in ax_cfalignedpsth]
			[a.set_xticklabels('') for a in ax_cfalignedpsth[:-1]]

			# plot circular psths
			r, V, theta = RR.circ_psth_all(rr_rast, rr_stimparams, rr_freq, npips, axs = ax_cfcircpsth)
			[a.set_yticklabels('') for a in ax_cfcircpsth]
			[a.set_xticklabels('') for a in ax_cfcircpsth]

			# plot all circular summed vector strengths
			ax_cfcircpsthall.plot(theta, V, '.-')
			[ax_cfcircpsthall.plot([0, th], [0, v], color = 'b', alpha = 1-(i/10.)) for i, (th, v) in enumerate(zip(theta, V))]


			# plot RRTF
			rrtf = RR.calc_rrtf_all(rr_rast, rr_stimparams, rr_freq, urrs, npips)
			ax_cfrrtf.plot(rrtf, '.-', ms = 10)
			ax_cfvs.plot(V*np.cos(theta), 'g.-', ms = 10)
			for tick in ax_cfvs.yaxis.get_major_ticks():
				tick.set_pad(-5)
				tick.label2.set_horizontalalignment('right')

			# plot repetition rate PSTHs
			for i in xrange(nrrs):
				# RR.plot_rrtf(t_rrtf, rrtf_noisepsth[i, :], urrs[i], int(4*urrs[i]), onset = 0.05, duration = 0.025, ax = ax_noiserr[i])
				RR.plot_rrtf(t_rrtf, rr_cfpth[i, :], urrs[i], int(4*urrs[i]), onset = 0.05, duration = 0.025, ax = ax_cfrr[i])

			# ax_noiserr[0].set_title('Noise RRTFs')
			ax_cfrr[0].set_title('CF RRTFs (%.0f kHz)' % (cf/1000))
			# [a.set_xlim(0, 4.5) for a in ax_noiserr]
			[a.set_xlim(0, 4.5) for a in ax_cfrr]
			misc.sameyaxis(ax_cfrr+ax_cfalignedpsth)

			figsavepath = os.path.join(studydir, 'Sheets', 'RRTFs', '%s_%s_RRTF.png' % (session, unitkey))
			print figsavepath
			fig.savefig(figsavepath)
			[a.cla() for a in fig.get_axes()] # clear all axes
Ejemplo n.º 8
0
def analyze():

    gens = []
    exps = []
    sesss = []
    unitnums = []
    cfs = []
    noise_rrtfs = []
    cf_rrtfs = []

    for session in sessions:

        _, gen, exp, _ = session.split("_")
        unitinfos = fileconversion.get_session_unitinfo(session, onlycomplete=("RF", "RR", "VOC"))

        for unitkey in unitinfos.iterkeys():

            unitinfo = unitinfos[unitkey]

            print unitinfo["session"], unitinfo["unitnum"]

            rr_ix = unitinfo["stimtype"].index("RR")
            f = h5py.File(unitinfo["fpath"][rr_ix], "r")
            rast = f["rast"].value
            stimparams = f["stimID"].value
            cf_ix = f["cf"].value
            f.close()

            ufreqs = np.unique(stimparams[:, 0])
            nfreqs = ufreqs.size

            urrs = np.unique(stimparams[:, 1])

            cf = RF.ix2freq[20:][np.round(cf_ix).astype(int)]

            _, ix, err = misc.closest(ufreqs, cf, log=True)

            if np.abs(err) > 0.5:
                print "Repetition rate stimuli not present for this unit (nearest tone %2.2f octaves away)" % err
                continue

            ufreq_played = ufreqs[ix]

            npips = urrs * 4
            noise_rrtf = RR.calc_rrtf_all(rast, stimparams, 0.0, urrs, npips=npips)
            cf_rrtf = RR.calc_rrtf_all(rast, stimparams, ufreq_played, urrs, npips=npips)

            gens.append(gen)
            exps.append(exp)
            sesss.append(session)
            unitnums.append(unitinfo["unitnum"])
            cfs.append(cf_ix)
            noise_rrtfs.append(noise_rrtf)
            cf_rrtfs.append(cf_rrtf)

    df = pd.DataFrame(
        dict(gen=gens, exp=exps, sess=sesss, unit=unitnums, cf=cfs, noise_rrtf=noise_rrtfs, cf_rrtf=cf_rrtfs)
    )
    d = pd.HDFStore(os.path.join(studydir, "Analysis", "rrtf_data.h5"))
    d["df"] = df
    d.close()
    return df
Ejemplo n.º 9
0
print("write the scheduling algorithm name(RR,FCFS,HPF,SRTN): ")
algo = input()
if algo == "HPF":
    proc, contxtPeriods = HPF(processes)
elif algo == "FCFS":
    proc, contxtPeriods = FCFS(processes)
elif algo == "SRTN":
    print("Enter Context Switching Time: ")
    cntxt = input()
    proc, contxtPeriods = SRTN(processes, float(cntxt))
elif algo == "RR":
    print("Enter Context Switching Time: ")
    cntxt = input()
    print("Enter quantum: ")
    quantum = input()
    proc, contxtPeriods = RR(processes, int(quantum), float(cntxt))

# getting lists
x, y = getLists(proc, contxtPeriods)

plt.plot(x, y)
plt.ylabel("pid")
plt.xlabel("time steps")
plt.title(algo)
plt.grid()
plt.show()

# to be removed::
# for i in range (0,len(proc)):
#     print(proc[i].id, proc[i].startT, proc[i].finishT, proc[i].TAT)