コード例 #1
0
def go_go_excel(path, number_of_runs):
    if number_of_runs < 1:
        print("Bledna liczba uruchomiec algorytmu")
        return
    workbook = xlsxwriter.Workbook(path)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'X')
    worksheet.write(0, 1, 'Y')
    worksheet.write(0, 2, 'Odleglosc')
    worksheet.write(0, 3, 'Czas')
    worksheet.write(0, 4, 'N')
    random.seed(None)
    algorithm = Algorithm.Algorithm()
    
    my_data = Data.Data()
    
    for i in range(number_of_runs):
        Generator.generate_for_excel(my_data.list_of_cards, random.randint(1, 200000))
        algorithm.run(my_data.list_of_cards)
        final_x, final_y, final_trip, time = algorithm.return_results()
        worksheet.write(i+1, 0, final_x)
        worksheet.write(i+1, 1, final_y)
        worksheet.write(i+1, 2, final_trip)
        worksheet.write(i+1, 3, time)
        worksheet.write(i+1, 4, len(my_data.list_of_cards))
        
    workbook.close()
    return
コード例 #2
0
 def __init__(self):
     super(self.__class__, self).__init__()
     self.name = "Algorithm selection window:"
     self.if_setprn = 0
     self.if_setdate = 0
     self.progresscomplete = 0
     self.setdefaultpara()
     self.algo1para = {}
     self.algo2para = {}
     self.algo3para = {}
     self.algo4para = {}
     self.algo1para = dict(self.algo1paradefault.items() +
                           self.algo1para.items())
     self.algo2para = dict(self.algo2paradefault.items() +
                           self.algo2para.items())
     self.algo3para = dict(self.algo3paradefault.items() +
                           self.algo3para.items())
     self.algo4para = dict(self.algo4paradefault.items() +
                           self.algo4para.items())
     self.setStyleSheet(
         "QLabel{color:rgb(96,96,96,255);font-size:15px;font-weight:bold;font-family:Microsoft YaHei;}"
         "QMessageBox{background-color:#DEB887;}")
     self.algoSet = Ag.Algorithm('decision tree', self.algo1para)
     self.prnSet = 0
     self.dateSet = 0
     self.initUI()
コード例 #3
0
ファイル: App.py プロジェクト: pamhrituc/AI
def main():
    while True:
        prob = Problem()  #create problem
        size = prob.loadData(
            "data01.in")  #load data of problem, return board size
        x = Individ([0] * size)
        pop = Population(x)
        alg = Algorithm(pop)
        alg.readParameters("param.in")
        printMainMenu()
        x = input()
        if x == "1":
            bestX, sample = alg.run()
            print(bestX)
            print(bestX.fitness())
            plt.plot(sample)
            # function to show the plot
            plt.show()
        if x == "2":
            alg.run()
            sd, m = alg.statistics()
            print("Standard deviation " + str(sd))
            print("Mean " + str(m))
        if x == "0":
            return
コード例 #4
0
 def insertAlgorithmData(self, cur):
     try:
         # TODO: should think about separating out sequence accessors
         alDataSeq = AlgorithmDataSequence()
         next_id = alDataSeq.getNextVal(cur)
         
         algorithm = Algorithm.Algorithm()
         algorithmIndex = algorithm.getAlgorithmIndex(cur, self._algorithm_reff)
         
         # get the current timestamp
         timestamp = getTime(cur)
         
         cur.execute("INSERT INTO " + self._table_name + " " +
                     self._insert_order + " " +
                     "VALUES(%s, %s, %s)",
                     (
                         str(next_id),
                         str(timestamp),
                         str(algorithmIndex)
                     )
                     )
         return next_id
         
     except psycopg2.DatabaseError, e:
         print 'Error AlgorithmData: %s' % e    
コード例 #5
0
 def buttonsetclicked(self):
     self.buttonset.setDisabled(True)
     c = self.Algochooselist.currentItem()
     if c.text() == ("   " + self.algoSet.algorithm):
         print "algorithm not changed"
     else:
         print "algorithm changed"
         self.buttonplot.setDisabled(True)
     if c.text() == "   " + "decision tree":
         print self.algo1para
         self.infoconsole.clear()
         self.algo1 = Ag.Algorithm('decision tree', self.algo1para)
         self.algoSet = self.algo1
         self.infoconsole.addItem("Decision tree algorithm set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo1para))
         self.infoconsole.repaint()
     elif c.text() == "   " + "support vector machine":
         print self.algo2para
         self.infoconsole.clear()
         self.algo2 = Ag.Algorithm('support vector machine', self.algo2para)
         self.algoSet = self.algo2
         self.infoconsole.addItem("support vector machine set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo2para))
         self.infoconsole.repaint()
     elif c.text() == "   " + "random forest":
         print self.algo3para
         self.infoconsole.clear()
         self.algo3 = Ag.Algorithm('random forest', self.algo3para)
         self.algoSet = self.algo3
         self.infoconsole.addItem("random forest set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo3para))
         self.infoconsole.repaint()
     elif c.text() == "   " + "adaboost":
         print self.algo4para
         self.infoconsole.clear()
         self.algo4 = Ag.Algorithm('adaboost', self.algo4para)
         self.algoSet = self.algo4
         self.infoconsole.addItem("adaboost set" + "      " +
                                  str(datetime.datetime.now()))
         self.infoconsole.addItem(str(self.algo4para))
         self.infoconsole.repaint()
     self.infoconsole.addItem("Selected Satellite No = " + str(self.prnSet))
     self.infoconsole.addItem("Selected date = " + str(self.dateSet))
     self.buttonevaluate.setDisabled(False)
コード例 #6
0
def prune_lse_states_at_depth(depth):
    pruned_data = []
    if depth == 1:
        for move in move_set_list:
            for move_type in move_type_list:
                current_state = LSE_State(prune_table[0][0][1])
                current_state.apply_move(move, move_type)
                pruned_data.append([Algorithm(convert_move_to_string(move, move_type)), current_state])
    else:
        for pruned_state in prune_table[depth - 1]:
            for move_type in move_type_list:
                move = MoveSet.U if LSE_Solver.get_last_move(pruned_state[0].algorithm)[0] == MoveSet.M else MoveSet.M
                current_state = LSE_State(pruned_state[1])
                current_state.apply_move(move, move_type)
                pruned_data.append(
                    [Algorithm(pruned_state[0].algorithm + " " + convert_move_to_string(move, move_type)), current_state])
    prune_table.append(pruned_data)
コード例 #7
0
def run_algorithm(data):
    algorithm = Algorithm.Algorithm()
    algorithm.run(data.list_of_cards)
    final_x, final_y, final_trip, time = algorithm.return_results()
    print(f'Punkt, do ktorego udalo sie zajsc: X = {final_x}, Y = {final_y}.')
    print(f'przebyta odleglosc: {final_trip}.')
    print(f'Czas wykonywania algorytmu: {time}.')
    temp = input("Wcisnij enter, aby wrocic/zakonczyc.")
    return
コード例 #8
0
def main():
    grid = [[0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
    StartNode = (0, 0)
    EndNode = (2, 3)
    layout = AL.Algorithm(grid, StartNode, EndNode)
    print(layout)
コード例 #9
0
def sum_all(a1,a560,n):
s560 = n/2 # ตัวแปร s560 นำ n/2 คือ 560/2
a = a1+a560 # ตัวแปร a นำ a1+a560 คือ 42 + 42
return {'sum': s560*a} # คืนค่าผลลัพธ์ sum โดยนำ s560 มาคูณกับ a

blah = Algorithm(a1, a560, n, sum_all)
#print(blah.functions) ถ้าต้องการแสดงฟังก์ชันทั้งหมดที่มี
getsum = blah.run()
print(getsum['sum'])
[/python]
コード例 #10
0
ファイル: AI_Lab2.py プロジェクト: obp3ter/AI
def main1():

    #random.seed(datetime.now())
    prob = Problem()
    pop = Population()
    alg = Algorithm(prob, pop)
    alg.run()
    res = alg.population.v[0]

    fitnessOptim = res.fittness(prob)
    individualOptim = res.x
    print('Result: The detectet minimum point is (%3.2f %3.2f) \n with function\'s value %3.2f'% \
          (individualOptim[0],individualOptim[1], fitnessOptim) )
コード例 #11
0
def startBenchmarks(data):
    global algorithm
    global state

    # pass State object into Algorithm along with the choice of algorithm
    algorithm = alg.Algorithm(True, 1, 0.0001)

    state = algorithm.getState()
    if ('file' in data.keys()):
        algorithm.benchsetup(inputtext=data['file'])
    else:
        algorithm.benchsetup(data['size'])
    runBenchmarks()
コード例 #12
0
ファイル: GAMain.py プロジェクト: VigneswarM/GA_algo
def main():
    print("GA started!")
    year = "1"
    fitnessCalc = FitnessCalculator()
    algo = Algorithm()
    fitnessCalc.setsolution("1111")
    myPop = Population(3, True, year)
    generation_count = 0
    #myPop.generate_Fitness()
    val = myPop.get_Fittest()
    print("Fittest : ", val)
    generation_count += 1
    print("Generation: ", generation_count, " Fittest: ",
          fitnessCalc.get_fitness(val))
    print("-------Starting generations : ", generation_count,
          " ------------------")
    myPop = algo.evolve_Population(myPop)
コード例 #13
0
ファイル: __main__.py プロジェクト: NGC4258/SCI-160
 def __treading(self):
     try:
         task = Tasks(self.myIP)
         mem = Members(self.myIP)
         algor = Algorithm()
         rgtr = Register(self.myIP)
         rsync = RSYNC(self.myIP)
     except Exception as e:
         self.__error_handle(
             {
             "error":{
                      "title": "__threading",
                      "message": e
                     }
             }
         )
     else:
         self.__members_handler(mem, rgtr, task)
         self.__task_allocation(task, algor)
         self.__task_announcement(task)
コード例 #14
0
def startSorting(data):
    global state
    global algorithm

    algorithm = alg.Algorithm(True, data['choice'], data['speed'])

    if ('file' in data.keys()):
        algorithm.importText(data['file'])
    else:
        algorithm.setRandomData(data['size'])

    state = algorithm.getState()

    emit(
        'sorting', {
            'numbers': algorithm.getData(),
            'compares': state.compares,
            'swaps': state.swaps,
            'memUsage': state.memUsage,
            'runtime': str("{0:.1f}".format(state.runtime)),
            'currentLine': state.currentLine
        })
コード例 #15
0
def Camera():
    global fm
    try:
        while True:
            ret, frame = cap.read()

            algo = Algorithm.Algorithm()
            nFrame = algo.do_func(frame)

            cv2.imshow('CCD LIVE', nFrame)  # update frame

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

            print("FPS: %d" % cap.get(cv2.CAP_PROP_FPS), end='\r')

    except KeyboardInterrupt:
        fm.stop_monitor()
        cap.release()
        cv2.destroyAllWindows()

        print("\n[{0}] End Camera..!".format(sys.argv[0]))
コード例 #16
0
 def run(self):
     self.Reader = Reader.Reader()
     self.Reader.read_pickle(file_path_energy, file_path_frequency)
     self.exp = np.loadtxt(file_path_exp, usecols=(
         0,
         1,
     ))
     idx = np.argsort(self.exp[:, 0])
     self.exp = np.asarray(self.exp[idx])
     self.freq = self.Reader.get_freq()
     self.E = self.Reader.get_energy()
     self.Spectrum = Spectrum.Spectrum(self.exp,
                                       self.freq,
                                       self.E,
                                       T=T,
                                       lower_bound=u,
                                       higher_bound=h,
                                       w1=width1,
                                       w2=width2,
                                       resolution_exp=resolution,
                                       Dipol=dipol,
                                       out=out)
     Alg = Algorithm.Algorithm(self.Spectrum,
                               mu=mu,
                               sigma_0=sigma0,
                               sigma_1=sigma1,
                               cutoff=cutoff,
                               dummy_0=dummy_0,
                               dummy_1=dummy_1)
     returnvalue, freq_old, freq_new, inten_new = Alg.Needleman_IR()
     print(-returnvalue)
     self.Spectrum.set_new_freq(freq_old, freq_new, inten_new)
     self.Spectrum.plot_unshifted()
     self.Spectrum.create_shifted()
     self.Spectrum.plot()
     p = self.Spectrum.integrate()
     self.Reader.write(out, p, returnvalue, args)
     return 1
コード例 #17
0
    def __init__(self, feedername='feeder2'):
        """
        string of the file names
        """
        self.directory = os.getcwd()
        self.feedername = feedername
        self.cap_data = 'Cap Data.xls'
        self.distributed_load = 'Distriuted Load Data.xls'
        self.line_data = 'Line Data.xls'
        self.spot_load = 'Spot Load Data.xls'

        tmp = Line(self.directory + '/' + self.feedername + '/' +
                   self.line_data,
                   feedername)  #the node set is inferred from Line Data.xls
        self.node_set = tmp.node_set
        self.node_dict = tmp.node_dict

        tmp = Spot_Load(
            self.directory + '/' + self.feedername + '/' + self.spot_load,
            self.node_set, self.node_dict)
        tmp = Cap(self.directory + '/' + self.feedername + '/' + self.cap_data,
                  self.node_set, self.node_dict)

        #for n in self.node_set:
        #    print n
        #self.node_set[1].lower_control=np.array([-10j,-10j,-10j],dtype=complex)

        algorithm = Alg.Algorithm(self.node_set)
        pRes, dRes, exeTime, var, obj = algorithm.getResult()

        print "************Simulation Result*************"
        self.disp = Disp.Display(pRes, dRes, exeTime, var, obj,
                                 self.feedername)
        self.disp.plot_primalDualRes()
        self.disp.plot_normal_primalDualRes()
        self.disp.write_log()
コード例 #18
0
def table_builder(path, number_of_runs, jumps):
    if number_of_runs < 1:
        print("Bledna liczba uruchomiec algorytmu")
        return
    if jumps < 1:
        print("Bledna wartosc skoku")
        return

    workbook = xlsxwriter.Workbook(path)
    worksheet = workbook.add_worksheet()
    worksheet.write(0, 0, 'X')
    worksheet.write(0, 1, 'Y')
    worksheet.write(0, 2, 'Odleglosc')
    worksheet.write(0, 3, 'Czas')
    worksheet.write(0, 4, 'N')
    random.seed(None)
    algorithm = Algorithm.Algorithm()

    my_data = Data.Data()
    num = 0
    for i in range(number_of_runs):
        if i == 0:
            Generator.generate_for_excel(my_data.list_of_cards, 1)
        else:
            num += jumps
            Generator.generate_for_excel(my_data.list_of_cards, num)
        algorithm.run(my_data.list_of_cards)
        final_x, final_y, final_trip, time = algorithm.return_results()
        worksheet.write(i + 1, 0, final_x)
        worksheet.write(i + 1, 1, final_y)
        worksheet.write(i + 1, 2, final_trip)
        worksheet.write(i + 1, 3, time)
        worksheet.write(i + 1, 4, len(my_data.list_of_cards))

    workbook.close()
    return
コード例 #19
0
    cap = cv2.VideoCapture(camDevID)
    if not (cap.isOpened()):
        print("[{0}] Camera Open Fail..!".format(sys.argv[0]))
        sys.exit(0)

    # file monitor
    fm = FileMonitor()
    fm.add_file("./Algorithm.py", Algorithm)
    fm.start()

    try:
        print("[{0}] ==== Camera Activated ====".format(sys.argv[0]))
        while True:
            ret, frame = cap.read()

            algo = Algorithm.Algorithm()
            nFrame = algo.do_func(frame)

            cv2.imshow('CCD LIVE', nFrame)  # update frame

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

            print("FPS: %d" % cap.get(cv2.CAP_PROP_FPS), end='\r')

    except KeyboardInterrupt:
        fm.stop_monitor()
        print("\n[{0}] File Manager Stop..!".format(sys.argv[0]))
        cap.release()
        cv2.destroyAllWindows()
        print("[{0}] OpenCV Stop..!".format(sys.argv[0]))
コード例 #20
0
ファイル: Gui.py プロジェクト: Lennard94/irsa
    def click(self):
        if (self.entry == "normalize_1"):
            try:
                tmp = (g.exp_ir[:, 0] <= g.values["hb"]) & (g.exp_ir[:, 0] >=
                                                            g.values["lb"])
                g.exp_ir[:, 1] = g.exp_ir[:, 1] / np.max(g.exp_ir[tmp, 1])
                g.canvas_list[0].plot_IR()
            except:
                pass
            try:
                tmp = (g.exp_vcd[:, 0] <= g.values["hb"]) & (g.exp_vcd[:, 0] >=
                                                             g.values["lb"])
                g.exp_vcd[:, 1] = g.exp_vcd[:, 1] / np.max(
                    np.abs(g.exp_vcd[tmp, 1]))
                g.canvas_list[1].plot_VCD()
            except:
                pass
        elif (self.entry == "normalize_2"):
            try:
                tmp = (g.theo_ir[:, 0] <= g.values["hb"]) & (g.theo_ir[:, 0] >=
                                                             g.values["lb"])
                g.theo_ir[:, 1] = g.theo_ir[:, 1] / np.max(g.theo_ir[tmp, 1])
                g.canvas_list[2].plot_IR()
            except:
                pass
            try:
                tmp = (g.theo_vcd[:, 0] <=
                       g.values["hb"]) & (g.theo_vcd[:, 0] >= g.values["lb"])
                g.theo_vcd[:, 1] = g.theo_vcd[:, 1] / np.max(
                    np.abs(g.theo_vcd[tmp, 1]))
                g.canvas_list[3].plot_VCD()
            except:
                pass
        elif (self.entry == "automatic"):
            try:
                tmp = (g.exp_ir[:, 0] <= g.values["hb"]) & (g.exp_ir[:, 0] >=
                                                            g.values["lb"])
                tmp_ir = np.asarray(g.exp_ir[tmp])
                g.peak_list_x = []
                g.peak_list_y = []
                g.peak_list_VCD_y = []
                for i in range(1, len(tmp_ir) - 1):
                    if (tmp_ir[i - 1, 1] <= tmp_ir[i, 1] >= tmp_ir[i + 1, 1]):
                        g.peak_list_x.append(tmp_ir[i, 0])
                        g.peak_list_y.append(tmp_ir[i, 1])
                print(g.peak_list_x)
                g.canvas_list[0].plot_peaks()
                g.exp_peaks = np.zeros((len(g.peak_list_x), 2))
                g.exp_peaks[:, 0] = np.asarray(g.peak_list_x)
                g.exp_peaks[:, 1] = np.asarray(g.peak_list_y)
                for peak in g.peak_list_x:
                    g.peak_list_VCD_y.append(
                        g.exp_vcd[abs(g.exp_vcd[:, 0] - peak) < 10e-1, 1][0])
                g.canvas_list[1].plot_peaks_VCD()
            except:
                pass
        elif (self.entry == "align"):
            try:
                del Algo
                print("del")
            except:
                pass
            Algo = Algorithm.Algorithm()
            if (g.set_VCD == False):
                g.returnvalue, g.old_freq, g.freq_new, g.inten_new = Algo.Needleman_IR(
                )
            else:
                g.returnvalue, g.old_freq, g.freq_new, g.inten_new, g.inten_VCD_new = Algo.Needleman_IR(
                )
            g.canvas_list[4].plot_IR_assigned()
            g.Spectrum.IR_shifted()
            if (g.set_VCD == True):
                g.Spectrum.VCD_shifted()
                p_ir, p_vcd = g.Spectrum.integrate()

                self.args.setText("Score: " + str(g.returnvalue)[0:6] +
                                  "\np_ir: " + str(p_ir)[0:4] + "\np_vcd: " +
                                  str(p_vcd)[0:4] + "\n")
            else:
                p_ir = g.Spectrum.integrate()
                self.args.setText("Score: " + str(g.returnvalue)[0:6] +
                                  "\np_ir: " + str(p_ir)[0:4] + "\n")
            g.canvas_list[5].plot_IR_shifted()
コード例 #21
0
ファイル: AI_Lab2.py プロジェクト: obp3ter/AI
def main2():
    prob = Problem()
    pop = Population()
    alg = Algorithm(prob, pop)
    alg.statistics()
    plt.show()
コード例 #22
0
def MainFunction(kind, Remimg):
    os.system("clear")
    if kind == 0:
        img = FigureInput()
        try:
            Remimg = img.copy()
        except:
            return

        try:
            if img == -1:
                return
        except:
            pass

        InpStr = input("Lock the figure?[Y/ n]  ")
        if InpStr == "N" or InpStr == "n":
            kind = 0
        else:
            kind = 1
    else:
        img = Remimg.copy()

    os.system("clear")
    print("-1) Another Figure")
    print("1)  Gray level linear transformation.")
    print("2)  Gamma(power) transformation.")
    print("3)  Contrast-Stretching Transformations.")
    print("4)  Histogram Equalization")
    print("5)  Maximum entropy for thresholding")
    print("6)  Get Gradient of figure")
    print("7)  Thresholding with Gradient")
    print("8)  Statistic the figure")
    print("9)  Auto algorithm!")
    print("10) Monte Carlo Average Constrast")
    print("11) Convolution")
    print("12) Histogram Equalization with Monte Carlo")
    print("13) Gradient transformation Algorithm (GTA!)")
    print("14) 2 Side Gradient Treasholding with DFS")
    print("15) Median Filtering")
    print("16) Sobel 3 * 3 cross edge detection operator")
    print("17) Roberts cross edge detection operator")
    print("18) Gradient Treasholding with Convolution")
    print("19) The smallest variance smoothing filter")
    print("20) Canny edge detector")
    print("21) Random Walk Algorithm")
    print("22) Unsharp masking")
    print("23) Block Algorithm")
    print("24) Toboggan Algorithm")
    print("25) Linear PDE method")
    print("26) Non-linear PDE method")
    print("27) Bilateral Filter Smoothing")
    print("28) Least square estimation")
    print("29) Iterative solution")
    print("30) Fourier Transform")
    print("31) Histogram Fourier Transform")
    print("32) Entropy Analysis")
    print("33) Wavelet Algorithm")
    print("34) Gauss Random")
    print("35) ADMM Algorithm")
    print("0) EXIT")
    InpInt = 0
    while 1:
        InpStr = input("Input the algorithm you need:  ")
        try:
            InpInt = int(InpStr)
        except ValueError:
            print("Input Error")
            continue
        else:
            if InpInt < -1 or InpInt > 50:
                print("Input Error")
                continue
            else:
                break

    if InpInt == -1:
        MainFunction(0, [])
        return
    if InpInt == 0:
        return
    if InpInt == 1:
        img = Proj1.GLLT(img)
    if InpInt == 2:
        img = Proj1.GPT(img)
    if InpInt == 3:
        img = Proj1.CST(img)
    if InpInt == 4:
        img = Proj1.HE(img)
    if InpInt == 5:
        MET(img)
        MainFunction(kind, Remimg)
        return
    if InpInt == 6:
        GradFig.GetGradient(img)
        MainFunction(kind, Remimg)
        return
    if InpInt == 7:
        img = GradFig.GT(img)
    if InpInt == 8:
        GradFig.FigSta(img, 0)
        MainFunction(kind, Remimg)
        return
    if InpInt == 9:
        img = Algorithm.Algorithm(img)
    if InpInt == 10:
        img = Algorithm.MCAC(img)
    if InpInt == 11:
        img = Convolution.Convolution(img)
        Output(img)
        return
    if InpInt == 12:
        img = Algorithm.MCHE(img)
    if InpInt == 13:
        img = GradFig.GTA(img)
    if InpInt == 14:
        img = GradFig.TGT(img)
    if InpInt == 15:
        img = Proj2.MF(img)
    if InpInt == 16:
        img = Proj2.SO(img)
    if InpInt == 17:
        img = Proj2.RO(img)
    if InpInt == 18:
        img = Proj2.GOC(img)
    if InpInt == 19:
        img = Proj2.SVSF(img)
    if InpInt == 20:
        img = Algorithm.CED(img)
    if InpInt == 21:
        img = Algorithm.RWPI(img)
    if InpInt == 22:
        img = Proj3.UM(img)
    if InpInt == 23:
        img = Proj3.BlockAlg(img)
    if InpInt == 24:
        img = Algorithm.TobAlgo(img)
    if InpInt == 25:
        img = Proj4.PDEMethod(img, 1)
    if InpInt == 26:
        img = Proj4.PDEMethod(img, 2)
    if InpInt == 27:
        img = cv2.bilateralFilter(img, 9, 35, 35)
    if InpInt == 28:
        img = Proj5.LSE(img)
    if InpInt == 29:
        img = Proj5.IS(img)
    if InpInt == 30:
        img = Trans.FT(img)
    if InpInt == 31:
        Trans.HFT(img)
        MainFunction(kind, Remimg)
        return
    if InpInt == 32:
        img = ImgEnp.Main(img)
    if InpInt == 33:
        img = ProjTest.Wavelet(img)
    if InpInt == 34:
        img = ProjTest.Gauss(img)
    if InpInt == 35:
        img = ProjTest.ADMM(img)
    Output(img)
    InpStr = input("Use the new figure?[Y/n]  ")
    if InpStr == "Y" or InpStr == "y":
        Remimg = img.copy()

    MainFunction(kind, Remimg)
    return
コード例 #23
0
        args.lambda_child) + '/'
    if not os.path.exists(folder):
        os.makedirs(folder)
    train_batch_size = args.train_batch_size
    val_batch_size = args.val_batch_size
    epochs = 1
    lr = args.lr
    lambda_child = args.lambda_child
    lambda_origin = args.lambda_origin
    percent_used = 1

    train_loader_normal, train_loader_switch, val_loader = lib.build_loader_cifar_alt(
        train_batch_size, val_batch_size, num_workers=4)
    model = OneShot.NetWork(num_classes=10, save_device=OneShot.DEVICE)
    algorithm = Algorithm.Algorithm(model=model,
                                    device=OneShot.DEVICE,
                                    lambda_child=lambda_child,
                                    lambda_origin=lambda_origin)

    normal_params, switch_params = algorithm.model.return_params()
    optimizer = torch.optim.SGD(params=normal_params,
                                lr=lr,
                                momentum=args.momentum,
                                weight_decay=args.weight_decay)

    best_acc = 0
    acc_history = []
    loss_history = []

    for _ in range(args.t_max):
        # normal training&evaluation
        for epoch in range(epochs):
コード例 #24
0
ファイル: main.py プロジェクト: savi30/AI
from Algorithm import *

alg = Algorithm()
alg.read()
alg.run()
コード例 #25
0
def build_algorithms(shape):
    algorithms = {}
    source_file = ('./log_files/log_files_' + CONST_MACHINE + '/' +
                   CONST_MACHINE + '_' + shape + '/' + CONST_MACHINE + '_' +
                   shape + '_')
    # Build the map of algorithms
    for algorithm_name in CONST_ALGORITHMS_NAMES:

        for num_of_threads in CONST_THREADS:
            algorithm = Algorithm.Algorithm(algorithm_name + ':' +
                                            str(num_of_threads))

            # Overall time
            with open(
                    source_file +
                    algorithm.name.replace("/", "_").replace(":", "_") +
                    '.csv', 'rb') as f:
                first_row = True
                reader = csv.reader(f)
                for row in reader:
                    # skip first row
                    if first_row:
                        first_row = False
                        continue

                    num_of_input_points = (int(row[0]))

                    # Build array containing all measured values
                    measured_execution_times = []
                    for value in row[2:]:
                        measured_execution_times.append(float(value))

                    algorithm.execution_time[
                        num_of_input_points] = measured_execution_times

            # Mid time
            with open(
                    source_file +
                    algorithm.name.replace("/", "_").replace(":", "_") +
                    '_mid.csv', 'rb') as f:
                first_row = True
                reader = csv.reader(f)
                for row in reader:
                    # skip first row
                    if first_row:
                        first_row = False
                        continue

                    num_of_input_points = (int(row[0]))

                    # Build array containing all measured values
                    measured_execution_times = []
                    for value in row[2:]:
                        measured_execution_times.append(float(value))

                    algorithm.mid_execution_time[
                        num_of_input_points] = measured_execution_times

            # End time
            with open(
                    source_file +
                    algorithm.name.replace("/", "_").replace(":", "_") +
                    '_end.csv', 'rb') as f:
                first_row = True
                reader = csv.reader(f)
                for row in reader:
                    # skip first row
                    if first_row:
                        first_row = False
                        continue

                    num_of_input_points = (int(row[0]))

                    # Build array containing all measured values
                    measured_execution_times = []
                    for value in row[2:]:
                        measured_execution_times.append(float(value))

                    algorithm.end_execution_time[
                        num_of_input_points] = measured_execution_times

            algorithms[algorithm.name] = algorithm

    # Build Sequential algorithm
    algorithm = Algorithm.Algorithm('Sequential:1')
    first_row = True

    with open(
            source_file + algorithm.name.replace("/", "_").replace(":", "_") +
            '.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            # skip first row
            if first_row:
                first_row = False
                continue

            num_of_input_points = (int(row[0]))

            # Build array containing all measured values
            measured_execution_times = []
            for value in row[2:]:
                measured_execution_times.append(float(value))

            algorithm.execution_time[
                num_of_input_points] = measured_execution_times

    algorithms[algorithm.name] = algorithm

    return algorithms
コード例 #26
0
from Algorithm import*
from copy import deepcopy
from collections import defaultdict

amount_of_steps_to_remember = 3
critical_count_visits = 10

maze = Algorithm()
maze.read('maps\\contest9.map')

# initial values
score = 0
current = maze.R
state = State.OK
last_steps = []
unreachable_lambdas = []
count_visits = defaultdict(int)
possible_lambdas = deepcopy(maze.lambdas)

# gather lambdas
while (len(maze.lambdas) != 0) and (len(possible_lambdas) != 0):
    closest_lambda_ind = min(possible_lambdas, key=lambda x: maze.heuristic_cost_estimate(current, x))

    way = maze.astar(current, closest_lambda_ind)
    wnext = ()

    if way is None:
        unreachable_lambdas.append(closest_lambda_ind)
        if closest_lambda_ind in possible_lambdas:
            possible_lambdas.remove(closest_lambda_ind)
        continue
コード例 #27
0
ファイル: main.py プロジェクト: 4465/Disk
    def __init__(self):
        self.Al = Algorithm()
        self.track_request = [None] * self.Al.TRACK_REQUEST_COUNT
        for i in range(self.Al.TRACK_REQUEST_COUNT):
            self.track_request[i] = random.randint(0, self.Al.TRACK_MAX_COUNT)
        self.rectangle = []
        # 声明一个是否按下开始的变量
        self.isloop = False
        self.newloop = False
        Window = Tk()
        Window.geometry('1100x1100')
        Window.title("python模拟磁盘调度算法")
        frame = Frame(Window)
        frame.grid(row=0, column=0)
        frame1 = Frame(frame, bg="white", bd=2, relief=GROOVE, width=500)
        frame2 = Frame(frame)
        frame3 = Frame(frame)
        frame4 = Frame(frame)
        frame1.grid(row=1, column=1, padx=10)
        frame2.grid(row=1, column=2)
        frame3.grid(row=2, column=1)
        frame4.grid(row=2, column=2)
        self.canvas1 = Canvas(frame1, width=510, height=510)
        self.canvas2 = Canvas(frame2, width=500, height=500, bg="white")
        self.canvas1.grid(row=1, column=1)
        self.canvas2.grid(row=1, column=1)

        self.textLog = Text(frame3, height=17)
        self.textLog.grid(row=0, column=1, padx=5)
        self.textLog.insert(
            END,
            '#每次生成的磁道序列是随机的,对于不同的序列算法的算法的性能是不一样的\n#通过多次比较观察结果,SSTF是算法中移动的磁道数最少的'
        )
        self.textLog.insert(END,
                            '\n#TRACK SEQUECE:\n' + str(self.track_request))

        self.var = StringVar()
        self.var.set('FCFS')
        r1 = Radiobutton(frame4, text='FCFS', variable=self.var, value='FCFS')
        r1.grid(row=1, column=1)
        r2 = Radiobutton(frame4, text='SSTF', variable=self.var, value='SSTF')
        r2.grid(row=1, column=2)
        r3 = Radiobutton(frame4, text='SCAN', variable=self.var, value='SCAN')
        r3.grid(row=1, column=3)
        r4 = Radiobutton(frame4,
                         text='CSCAN',
                         variable=self.var,
                         value='CSCAN')
        r4.grid(row=1, column=4)
        r5 = Radiobutton(frame4,
                         text='NstepSCAN',
                         variable=self.var,
                         value='NstepSCAN')
        r5.grid(row=1, column=5)
        r6 = Radiobutton(frame4,
                         text='FSCAN',
                         variable=self.var,
                         value='FSCAN')
        r6.grid(row=1, column=6)
        self.btnAl_1 = Button(
            frame4,
            text="运行",
            command=lambda: self.displayStartLine(
                self.Al.caculate(self.track_request, self.var.get())))
        self.btnAl_1.grid(row=2, column=1)
        self.btnAl_2 = Button(
            frame4,
            text="运行",
            command=lambda: self.RectangleShow(
                self.Al.caculate(self.track_request, self.var.get())))
        self.btnAl_2.grid(row=2, column=2)
        self.displayRectangle()
        Window.mainloop()
コード例 #28
0
              axe_x="Iterarion",
              axe_y="log (adaptation)",
              max_fitness=100000):
    plt.plot(data, iterations)
    '''
    plt.xlim(0, len(iterations))
    plt.ylim(0, max(data)+5)
    '''
    plt.xlabel(axe_x)
    plt.ylabel(axe_y)
    plt.title(title)
    plt.savefig('graphics/' + filename + ".png", dpi=200)
    plt.clf()


algorithm = Algorithm()
algorithm = classic_algo()
algorithm = classic_algo_2()
algorithm = article_algo()

dataset_file = "dataset.json"

dataset = open(dataset_file, 'r')
dataset = json.loads(dataset.read())

optimizer = Optimizer(algorithm, dataset_file)
result, metrics = optimizer.optimize(100, 500, 40)

#Performances
iterations = range(1, len(metrics['worse_fitness']) + 1)
コード例 #29
0
ファイル: sortCLI.py プロジェクト: Dkerby/CSE-6214
def main(argv):

        #default values for the sort
        arrsize=200
        algochoice=1
        MAXARRAYSIZE=2048
        wait=False
        benchmark=False
        speed=0.05

        
        #parsing of command line options
        try:
                opts, args = getopt.getopt(argv,"bhwf:r:a:s:",["filename=", "randnum=", "algo=", "spd="])

        #error prints out the help info
        except getopt.GetoptError:
                print('\n\ttest.py\n\t[-r <size of array>]\n\t[-a <chosen algorithm (1-4)>]\n\t[-s <speed of algorithm>]')
                print('\n\t-h displays help info')
                print('\t-w toggles on the WAIT_FOR_USER step option\n')
                print('\t1 - Insertion Sort')
                print('\t2 - Bubble Sort')
                print('\t3 - Quick Sort')
                print('\t4 - Merge Sort')

                sys.exit(2)

        #for each option in the command line arguments
        for opt, arg in opts:

                # -h prints out help info
                if opt == '-h':
                        print('\n\ttest.py\n\t[-r <size of array>]\n\t[-a <chosen algorithm (1-4)>]\n\t[-s <speed of algorithm>]')
                        print('\n\t-h displays help info')
                        print('\t-w toggles on the WAIT_FOR_USER step option\n')
                        print('\t1 - Insertion Sort')
                        print('\t2 - Bubble Sort')
                        print('\t3 - Quick Sort')
                        print('\t4 - Merge Sort')
                        sys.exit()

                # -r lets user set the size of the randomly generated array
                elif opt in ("-r", "--randnum"):
                        arrsize = int(arg)

                elif opt=="-f":
                        arrsize = 0
                        numList = []
                        f = open(arg, "r")
                        line = f.readline()
                        for u in line.split():
                            numList.append(u)
                            arrsize = arrsize + 1

                        #creates NumberList, State, and Algorithm objects
                        x=alg.Algorithm(True, algochoice, speed, arrsize) #pass State object into Algorithm along with the choice of algorithm
                        x.setData(numList)
                        state=x.getState()

                # -a lets the user choose which algorithm they want to do
                elif opt in ("-a", "--algo"):
                        algochoice = int(arg)

                # -s lets the user set the speed of the stepping
                elif opt in ("-s", "--spd"):
                        speed=float(arg)

                # -w is a toggle on the <press enter to step> portion of the output
                elif opt =="-w":
                        wait=True

                elif opt=="-b":
                        benchmark=True
                
                    
        
        #creates NumberList, State, and Algorithm objects
        x=alg.Algorithm(True, algochoice, speed, arrsize) #pass State object into Algorithm along with the choice of algorithm
        state=x.getState()
        #print error and exit if the user's options are silly
        if(arrsize<1 or arrsize>MAXARRAYSIZE):
                print("Array inappropriately sized.")
                sys.exit(2)
        if(algochoice<1 or algochoice>5):
                print("That is not one of the available algorithms")
                sys.exit(2)

        if(speed<0.0001 or speed>5.0):
                print("That is either too fast or too slow")
                sys.exit(2)

        print('Generating array of size', arrsize)
        print('Algorithm choice is ', algochoice)

        #while algorithm is not complete, keep on steppin'
        if(benchmark):
                x.benchsetup(arrsize)
                while(state.benchmarking):
                        x.benchstep()
                        state=x.getState()
                        output=x.getFormat()
                        
                        #ADD I, J, SWAP, AND COMPARISON DATA TO OUTPUT
                        output+="\n\ni:\t\t"+str(state.i)
                        output+="\nj:\t\t"+str(state.j)
                        output+="\nComparisons:\t"+str(state.compares)
                        output+="\nMovements:\t"+str(state.swaps)
                        output+="\nMemory Used:\t"+str(state.memUsage)+" Bytes"
                        output+="\nRuntime: \t"+str("{0:.2f}".format(state.runtime))+" Seconds\n\n"


                        #Higlighting the pseudocode
                        for line in x.algo.lines:
                                if (x.algo.lines[state.currentLine]==line):
                                        output+= '\x1b[0;37;41m' + line + '\x1b[0m'
                                else:
                                        output+=line
                        
                        #clear stdout
                        os.system('clear')

                        #print to cmdline
                        print(output)


                        #this is where the -w option comes into play
                        if(wait):
                                input("<hit enter to step>")
        else:
                while(state.sorting):

                        #step it up!
                        x.step()
                        state=x.getState()
                        output=x.getFormat()

                        #ADD I, J, SWAP, AND COMPARISON DATA TO OUTPUT
                        output+="\n\ni:\t\t"+str(state.i)
                        output+="\nj:\t\t"+str(state.j)
                        output+="\nComparisons:\t"+str(state.compares)
                        output+="\nMovements:\t"+str(state.swaps)
                        output+="\nMemory Used:\t"+str(state.memUsage)+" Bytes"
                        output+="\nRuntime: \t"+str("{0:.2f}".format(state.runtime))+" Seconds\n\n"


                        #Higlighting the pseudocode
                        for line in x.algo.lines:
                                if (x.algo.lines[state.currentLine]==line):
                                        output+= '\x1b[0;37;41m' + line + '\x1b[0m'
                                else:
                                        output+=line
                        
                        #clear stdout
                        if(platform.system() == "Windows"):
                                os.system("CLS")
                        else:
                                os.system('clear')

                        #print to cmdline
                        print(output)


                        #this is where the -w option comes into play
                        if(wait):
                                input("<hit enter to step>")
コード例 #30
0
#addrto_pass= "******"

#######################################do not change anything beyond this point##########################################

Method = int(input("Please input the method: 1 or 2:  "))

if (Method) == 1 or (Method) == 2:
    #list of all images
    #images=[]
    images = numpy.empty((no_frames), dtype=object)
    images_cnt = 0

    if Method == 1:
        click_save_img(no_frames, path_img_dir_m1)
        images, images_cnt = read_Images(path_img_dir_m1)
    else:
        images, images_cnt = read_Images(path_img_dir_m2)

    for i in range(0, images_cnt):
        Algorithm(images[i], i, path_img_dir_save)

    lat, longi = getlocation()
    latstr = " Latitude : " + str(lat)
    longistr = "  Longitude : " + str(longi)
    body = body + latstr + longistr

    send(from_name, from_passwd, subject, body, addrto_name, path_img_dir_save)
else:
    print "Please input valid method"
    exit(1)