def main():
    util.line()
    print("PEP300 - Metaheuristics Techniques for Combinatorial Optimization")
    print("TSPLib")
    util.line("-")

    sourceFile = ''
    resultFile = ''

    try:
        sourceFile = sys.argv[1]
    except:
        print("Usage: tsp.py <sourceFile>")
        sys.exit(2)

    name, dimension, distances = problem.readTSPLibFiles(sourceFile)

    # print("Distances", distances)

    # pcb442 -> cost: 221440 -> 1:n
    # testSolution = [*range(1, dimension + 1)]
    # print(testSolution)
    # cost = problem.calculateCost(testSolution, distances)
    # print(cost)

    menu(name, dimension, distances)
示例#2
0
def move():
    global T
    global cnt
    head = snake[-1].copy()
    head.move(aim)
    if head in walls:
        rectangle(-200, -195, 60, 20, 'white') f
        timer()
        ontimer(move, 100)
        return
    if head in pwalls:
        if pwalls.get(head) != None:
            pwalls[head] -= 1
            if pwalls[head] == 0:
                pwalls.pop(head)
                walls.add(head)
    if head in thorns:
        again()
        return
    for body in snake:
            for i in range(len(lasers)):
                if cnt > 0 and lasers[i][0].x <= body.x <= lasers[i][1].x and lasers[i][0].y <= body.y <= lasers[i][1].y:
                    again()
                    return
    if len(foods) == 0:
        nextstage()
        return
    if head in teledict:
        head = teledict[head]
    if head in foods:
        foods.remove(head)
    else:
        snake.pop(0)

    snake.append(head)
    clear()

    for body in snake:
        square(body.x, body.y, 9, 'black')
    for telep in teledict:
        square(telep.x, telep.y, 9, 'magenta')
        square(teledict[telep].x, teledict[telep].y, 9, 'purple')
    for food in foods:
        square(food.x, food.y, 9, 'green')
    for i in range(len(lasers)):
        if cnt > 0 : line(lasers[i][0].x, lasers[i][0].y+4.5, lasers[i][1].x, lasers[i][1].y+4.5)
        cnt += 1
        if cnt == 10: cnt = -5

    for wall in walls:
        square(wall.x, wall.y, 9, 'gray')
    for pwall in pwalls:
        squarenum(pwall.x, pwall.y, 9, 'blue', pwalls[pwall])
    for thorn in thorns:
        triangle(thorn.x, thorn.y, 9, 'red')
    timer()
    update()
    ontimer(move, 100)
示例#3
0
def isvalid(x_new, x_near, constraints, obstacles):
    l = line(x_new, x_near)
    if isinstance(constraints, list):
        isinside = any(contains(c, x_new) for c in constraints)
    else:
        isinside = contains(constraints, x_new)
    return isinside and \
        all(not obs.contains(l) for obs in obstacles)
示例#4
0
    def _extend_slope(cls, h, m, n_fit_points=10):
        for i in range(m.shape[0]):

            j = util.arg_first_not_nan(m[i])
            popt, _ = so.curve_fit(util.line, h[i, j:j + n_fit_points],
                                   m[i, j:j + n_fit_points])
            m[i, 0:j] = util.line(h[i, 0:j], *popt)

        return
def menuConstructiveMethods(dimension, distances, solution):

    util.line()
    print("Métodos construtivos:")
    util.line("-")

    print("1 - Construção aleatória")
    print("2 - Construção gulosa - vizinho mais próximo")
    print("3 - Construção parcialmente gulosa")
    print("0 - Voltar")

    choice = int(input("Opção: "))
    util.line()

    if choice == 0:
        return solution
    elif choice == 1:
        solution = constructive.createRandom(dimension)
    elif choice == 2:
        solution = constructive.nearestNeighbour(dimension, distances)
    elif choice == 3:
        alpha = float(input("Informe um valor para alpha [0; 1]: "))
        solution = constructive.semiGreedyNearNeighbour(
            dimension, distances, alpha)
    else:
        print("Metodo ainda não implementado.")

    print("Solução: ", solution)
    return solution
def menu(name, dimension, distances):

    solution = []
    cost = sys.maxsize

    while True:

        util.line()
        print("Defina a operação: ")
        util.line()

        print("1 - Construir solução")
        print("2 - Refinar solução")
        print("3 - Aplicar meta-heurística")
        print("4 - Calcular custo")
        print("0 - Sair")

        util.line("-")
        choice = int(input("Opção: "))
        util.line()

        if choice == 0:
            print("The end.")
            sys.exit(0)
        elif choice == 1:
            solution = menuConstructiveMethods(dimension, distances, solution)
        elif choice == 2:
            solution, cost = menuRefiningHeuristics(dimension, distances,
                                                    solution)
        elif choice == 3:
            solution, cost = menuMetaHeuristics(dimension, distances)
        elif choice == 4:
            print("Solução: ", solution)
            cost = problem.calculateCost(solution, distances)
            util.line("-")
            print("Custo: ", cost)
        else:
            print("Metodo ainda não implementado.")
示例#7
0
def plot_nnoutput(plotObject, kwargs):

    savename = kwargs['cname'] + '.pdf'
    cut = kwargs['cut']

    from ROOT import TH1F, TCanvas, gROOT, gStyle, kTRUE
    gROOT.SetBatch(kTRUE)
    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, gPad
    from RingerCore.util import Roc_to_histogram
    from util import setBox, line

    gStyle.SetOptStat(1111)
    curve = plotObject[0][kwargs['rocname']]
    signal, background = Roc_to_histogram(curve, kwargs['nsignal'],
                                          kwargs['nbackground'])
    hist_signal = TH1F('Signal', 'dist output;output;count', 100, -1, 1)
    hist_background = TH1F('Background', 'dist output;output;count', 100, -1,
                           1)
    for out in signal:
        hist_signal.Fill(out)
    for out in background:
        hist_background.Fill(out)
    canvas = TCanvas('canvas', 'canvas', 800, 600)

    hist_signal.SetStats(1)
    hist_background.SetStats(1)
    hist_signal.SetLineColor(kBlack)
    hist_background.SetLineColor(kRed)
    #hist_signal.GetXaxis().SetTitleSize(0.05);
    #hist_signal.GetYaxis().SetTitleSize(0.05);
    #hist_background.GetXaxis().SetTitleSize(0.05);
    #hist_background.GetYaxis().SetTitleSize(0.05);
    if hist_signal.GetEntries() > hist_background.GetEntries():
        hist_signal.Draw()
        hist_background.Draw('sames')
    else:
        hist_background.Draw()
        hist_signal.Draw('sames')

    canvas.SetLogy()
    setBox(gPad, [hist_signal, hist_background])
    l = line(cut, 0, cut, 1000, kBlue, 2, 2)
    l.Draw()
    canvas.SaveAs(savename)
    return savename
示例#8
0
def plot_nnoutput(plotObject, kwargs):

    savename = kwargs["cname"] + ".pdf"
    cut = kwargs["cut"]

    from ROOT import TH1F, TCanvas, gROOT, gStyle, kTRUE

    gROOT.SetBatch(kTRUE)
    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, gPad
    from RingerCore.util import Roc_to_histogram
    from util import setBox, line

    gStyle.SetOptStat(1111)
    curve = plotObject[0][kwargs["rocname"]]
    signal, background = Roc_to_histogram(curve, kwargs["nsignal"], kwargs["nbackground"])
    hist_signal = TH1F("Signal", "dist output;output;count", 100, -1, 1)
    hist_background = TH1F("Background", "dist output;output;count", 100, -1, 1)
    for out in signal:
        hist_signal.Fill(out)
    for out in background:
        hist_background.Fill(out)
    canvas = TCanvas("canvas", "canvas", 800, 600)

    hist_signal.SetStats(1)
    hist_background.SetStats(1)
    hist_signal.SetLineColor(kBlack)
    hist_background.SetLineColor(kRed)
    # hist_signal.GetXaxis().SetTitleSize(0.05);
    # hist_signal.GetYaxis().SetTitleSize(0.05);
    # hist_background.GetXaxis().SetTitleSize(0.05);
    # hist_background.GetYaxis().SetTitleSize(0.05);
    if hist_signal.GetEntries() > hist_background.GetEntries():
        hist_signal.Draw()
        hist_background.Draw("sames")
    else:
        hist_background.Draw()
        hist_signal.Draw("sames")

    canvas.SetLogy()
    setBox(gPad, [hist_signal, hist_background])
    l = line(cut, 0, cut, 1000, kBlue, 2, 2)
    l.Draw()
    canvas.SaveAs(savename)
    return savename
def menuMetaHeuristics(dimension, distances):
    util.line()
    print("Meta-heurísticas:")
    util.line("-")

    print("1 - Multi-start")
    print("2 - GRASP")
    print("3 - Simulated Annealing")
    print("4 - Busca Tabu")
    print("5 - VNS")
    print("6 - Iterated Local Search")
    print("7 - Algoritmos genéticos")
    print("8 - Colônia de Formigas")
    print("9 - Scatter Search")
    print("0 - Voltar")

    choice = int(input("Opção: "))
    util.line()

    solution = []
    cost = sys.maxsize

    if choice == 1:  # Multi-start
        iterMax = int(
            input(
                "Defina o número máximo de iterações sem melhora (critério de parada): "
            ))

        solution, cost = multistart.multiStart(dimension, distances, iterMax)

        print("Solução: ", solution)
        print("Custo: ", cost)

    elif choice == 2:  # GRASP

        graspMax = int(
            input("Defina o número máximo de iterações (GRASPmax): "))
        alpha = float(input("Informe um valor para alpha [0; 1]: "))
        solution, cost = grasp.grasp(dimension, distances, graspMax, alpha)

        print("Solução: ", solution)
        print("Custo: ", cost)
    else:
        print("Metodo ainda não implementado.")

    return solution, cost
示例#10
0
def view (id, fileName=''): 
  log.debug("Viewing Gist with ID: {0} and fileName: '{1}'".format(id,fileName))

  if id[0] in _cmds['#']:
    id = _get_id_for_index(id)

  if id:
    gist = _get_gist(id)
    # display line delims only if more than one file exists. facilitates piping file content
    noDelim = len(gist['files']) == 1 or fileName != ''
    for (file, data) in gist['files'].items():
      content = data['content']
      if not noDelim:
        util.line()
        print 'Gist: {0} File: {1}'.format(id, file)
        util.line()
      if fileName != '':
        if fileName.strip().lower() == file.strip().lower():
          print content
      else:
        print content
      if not noDelim:
        util.line()
def menuRefiningHeuristics(dimension, distances, solution):
    util.line()
    print("Heurísticas de refinamento:")
    util.line("-")

    print("1 - First improvement descent")
    print("2 - Best improvement descent")
    print("3 - Random descent")
    print("0 - Voltar")

    choice = int(input("Opção: "))
    util.line()

    if choice == 1:
        solution, cost = refining.firstImprovementDescent(
            dimension, distances, solution)
        print("Solução: ", solution)
        print("Custo: ", cost)
    elif choice == 2:
        solution, cost = refining.bestImprovementDescent(
            dimension, distances, solution)
        print("Solução: ", solution)
        print("Custo: ", cost)
    elif choice == 3:

        iterMax = int(
            input("Defina o número máximo de iterações sem melhora: "))
        solution, cost = refining.randomDescent(dimension, distances, solution,
                                                iterMax)

        print("Solução: ", solution)
        print("Custo: ", cost)
    else:
        print("Metodo ainda não implementado.")

    return solution, cost
示例#12
0
def view(id, fileName=''):
    log.debug("Viewing Gist with ID: {0} and fileName: '{1}'".format(
        id, fileName))

    if id[0] in _cmds['#']:
        id = _get_id_for_index(id)

    if id:
        gist = _get_gist(id)
        # display line delims only if more than one file exists. facilitates piping file content
        noDelim = len(gist['files']) == 1 or fileName != ''
        for (file, data) in list(gist['files'].items()):
            content = data['content']
            if not noDelim:
                util.line()
                print('Gist: {0} File: {1}'.format(id, file))
                util.line()
            if fileName != '':
                if fileName.strip().lower() == file.strip().lower():
                    print(content)
            else:
                print(content)
            if not noDelim:
                util.line()
示例#13
0
        label = kp[-1]
        xs = [int(float(i)) for i in kp[2:-1:2]]
        ys = [int(float(i)) for i in kp[3:-1:2]]

        # Show the keypoints
        if SHOW:
            plt.scatter(xs, ys)

        # Sort the keypoints to head, tail, and wings of plane
        pH = (xs[0], ys[0])
        pT = (xs[1], ys[1])
        pW1 = (xs[2], ys[2])
        pW2 = (xs[3], ys[3])

        # Find the major/longest axis for the plane and the points of the major and minor axis
        LMaj = u.line(pH, pT)
        pMaj = (pH, pT)
        pMin = (pW1, pW2)
        # if u.longer((pW1, pW2), (pH, pT)):
        #     LMaj = u.line(pW1, pW2)
        #     pMaj = (pW1, pW2)
        #     pMin = (pH, pT)

        # Find the equations of the long and short edges of the bounding box
        le = (u.linePointSlope(LMaj, pMin[0]), 
            u.linePointSlope(LMaj, pMin[1]))
        se = (u.linePointSlopeInverted(LMaj, pMaj[0]), 
            u.linePointSlopeInverted(LMaj, pMaj[1]))

        # Find the vertices of the bounding box from the lines
        v = (u.intersection(le[0], se[0]), 
示例#14
0
def plot_rocs(plotObjects, kwargs):

    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray, kWhite, kYellow
    Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
    from RingerCore import StdPair as std_pair
    from util import line, minmax

    dset = kwargs['set']
    ref = kwargs['reference']
    refVal = kwargs['refVal']
    eps = kwargs['eps']
    savename = kwargs['cname'] + '.pdf'

    #Some protection
    if not ('operation' in dset or 'tst' in dset):
        raise ValueError('Option set must be: tst (test) or val (validation)')
    if not ('SP' in ref or 'Pd' in ref or 'Pf' in ref):
        raise ValueError('Option reference must be: SP, Pd or Pf')

    #Create dict to hold all list plots
    curves = dict()
    #list of dicts to dict of lists
    for name in plotObjects.keys():
        curves[name] = plotObjects.tolist(name)

    paintIdx = kwargs['paintListIdx']  # [best, worst]
    paintCurves = [
        std_pair(plotObjects.index_correction(paintIdx[0]), kBlack),
        std_pair(plotObjects.index_correction(paintIdx[1]), kRed)
    ]
    curves['roc'] = curves['roc_' + dset]

    #Start to build all ROOT objects
    from ROOT import TCanvas, gROOT, kTRUE
    gROOT.SetBatch(kTRUE)
    canvas = TCanvas('canvas', 'canvas', 1600, 1300)

    x_limits = [0.00, 0.40]
    y_limits = [0.6, 1.03]

    #create dummy graph
    dummy = curves['roc'][0]
    dummy.SetTitle('Receive Operation Curve')
    dummy.GetXaxis().SetTitle('False Alarm')
    dummy.GetYaxis().SetTitle('Detection')
    dummy.GetHistogram().SetAxisRange(y_limits[0], y_limits[1], 'Y')
    dummy.GetHistogram().SetAxisRange(x_limits[0], x_limits[1], 'X')
    dummy.Draw('AL')

    corredor = None
    target = None
    from ROOT import TBox
    if ref == 'Pf':
        corredor = TBox(refVal - eps, y_limits[0], refVal + eps, y_limits[1])
        target = line(refVal, y_limits[0], refVal, y_limits[1], kBlack, 2, 1,
                      '')
    elif ref == 'Pd':
        corredor = TBox(x_limits[0], refVal - eps, x_limits[1], refVal + eps)
        target = line(x_limits[0], refVal, x_limits[1], refVal, kBlack, 2, 1,
                      '')

    if ref != 'SP':
        corredor.SetFillColor(kYellow - 9)
        corredor.Draw('same')
        target.Draw('same')
        canvas.Modified()
        canvas.Update()

    #Plot curves
    for c in curves['roc']:
        c.SetLineColor(kGray + 1)
        #c.SetMarkerStyle(7)
        #c.SetMarkerColor(kBlue)
        c.SetLineWidth(1)
        c.SetLineStyle(3)
        #c.Draw('PLsame')
        c.Draw('same')

    marker = list()
    #Paint a specifical curve
    for pair in paintCurves:
        curves['roc'][pair.first].SetLineWidth(1)
        curves['roc'][pair.first].SetLineStyle(1)
        #curves['roc'][pair.first].SetMarkerStyle(7)
        #curves['roc'][pair.first].SetMarkerColor(kBlue)
        curves['roc'][pair.first].SetLineColor(pair.second)
        #curves['roc'][pair.first].Draw('PLsame')
        curves['roc'][pair.first].Draw('same')

        if ref == 'SP':
            faVec = curves['roc'][pair.first].GetX()
            detVec = curves['roc'][pair.first].GetY()
            from RingerCore import calcSP
            spVec = [
                calcSP(detVec[i], 1 - faVec[i])
                for i in range(curves['roc'][pair.first].GetN())
            ]
            imax = spVec.index(max(spVec))
            from ROOT import TMarker
            marker.append(TMarker(faVec[imax], detVec[imax], 4))
            marker[-1].SetMarkerColor(pair.second)
            marker[-1].Draw('same')

    #Update Canvas
    canvas.Modified()
    canvas.Update()
    canvas.SaveAs(savename)
    del canvas

    return savename
示例#15
0
def plot_4c(plotObjects, kwargs):
    """
  kwargs is a dict with all kwargsion needed to config the figure and the
  curves. The kwargsions will be:
   reference: Pd, SP or Pf
   operation: True or False
   set: tst or val
  plot 4 curves
  """
    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray
    Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
    from RingerCore import StdPair as std_pair
    from util import line

    ref = kwargs['reference']
    refVal = kwargs['refVal']
    dset = kwargs['set']
    isOperation = kwargs['operation']
    detailed = True if plotObjects.size() == 1 else False
    percent = 0.03  #(default for now)
    savename = kwargs['cname'] + '.pdf'
    lines = []

    #Some protection
    if not ('val' in dset or 'tst' in dset):
        raise ValueError('Option set must be: tst (test) or val (validation)')
    if not ('SP' in ref or 'Pd' in ref or 'Pf' in ref):
        raise ValueError('Option reference must be: SP, Pd or Pf')

    ylabel = {
        'mse': 'MSE (' + dset + ')',
        'sp': 'SP (' + dset + ')',
        'det': 'Det (' + dset + ')',
        'fa': 'FA (' + dset + ')'
    }

    #Create dict to hold all list plots
    curves = dict()
    #list of dicts to dict of lists
    for name in plotObjects.keys():
        curves[name] = plotObjects.tolist(name)

    #Adapt reference into the validation set
    #mse_trn, mse_val, mse_tst
    if ref == 'Pd':
        curves['sp_val'] = curves['det_point_sp_val']
        curves['det_val'] = curves['det_point_det_val']  # det_fitted
        curves['fa_val'] = curves['det_point_fa_val']
        curves['sp_tst'] = curves['det_point_sp_tst']
        curves['det_tst'] = curves['det_point_det_tst']
        curves['fa_tst'] = curves['det_point_fa_tst']
    elif ref == 'Pf':
        curves['sp_val'] = curves['fa_point_sp_val']
        curves['det_val'] = curves['fa_point_det_val']
        curves['fa_val'] = curves['fa_point_fa_val']  # fa_fitted
        curves['sp_tst'] = curves['fa_point_sp_tst']
        curves['det_tst'] = curves['fa_point_det_tst']
        curves['fa_tst'] = curves['fa_point_fa_tst']
    else:  # ref == 'SP'
        curves['sp_val'] = curves['bestsp_point_sp_val']  # best SP curve
        curves['det_val'] = curves['bestsp_point_det_val']
        curves['fa_val'] = curves['bestsp_point_fa_val']
        curves['sp_tst'] = curves['bestsp_point_sp_tst']
        curves['det_tst'] = curves['bestsp_point_det_tst']
        curves['fa_tst'] = curves['bestsp_point_fa_tst']

    from util import minmax

    #check if the test set is zeros
    hasTst = True if curves['mse_tst'][0].GetMean(2) > 1e-10 else False

    if dset == 'tst' and not hasTst:
        print 'We dont have test set into plotObjects, abort plot!'
        return False

    #If only one plot per key, enabled analysis using all sets
    if detailed:
        #train, validation and test
        paint_curves = [std_pair(i, Colors[i]) for i in range(3)]
        curves['mse'] = [curves['mse_trn'][0], curves['mse_val'][0]]
        curves['sp'] = [curves['sp_val'][0]]
        curves['det'] = [curves['det_val'][0]]
        curves['fa'] = [curves['fa_val'][0]]
        if hasTst:
            for key in ['mse', 'sp', 'det', 'fa']:
                curves[key].append(curves[key + '_tst'][0])
        ylabel = {'mse': 'MSE', 'sp': 'SP', 'det': 'Det', 'fa': 'FA'}

    else:  #Do analysis for each set type
        paintIdx = kwargs['paintListIdx']  # [best, worst]
        paint_curves = [
            std_pair(plotObjects.index_correction(paintIdx[0]), kBlack),
            std_pair(plotObjects.index_correction(paintIdx[1]), kRed)
        ]
        curves['mse'] = curves['mse_' + dset]
        curves['sp'] = curves['sp_' + dset]
        curves['det'] = curves['det_' + dset]
        curves['fa'] = curves['fa_' + dset]

    #Adapt the legend and percent vec
    pmask = [1, 1, 1, 1]
    if ref == 'Pd':
        ylabel['det'] = ylabel['det'] + ' [Reference]'
        ylabel['fa'] = ylabel['fa'] + ' [benchmark]'
        pmask = [1, 1, 0, 1]
    elif ref == 'Pf':
        ylabel['det'] = ylabel['det'] + ' [benchmark]'
        ylabel['fa'] = ylabel['fa'] + ' [Reference]'
        pmask = [1, 1, 1, 0]
    else:
        ylabel['sp'] = ylabel['sp'] + ' [benchmark]'

    #Build lines
    lines = {'mse': [], 'sp': [], 'det': [], 'fa': [], 'ref': None}
    if detailed:  # Hard code setting lines
        y = dict()
        x = dict()
        for idx, key in enumerate(['mse', 'sp', 'det', 'fa']):
            y[key] = minmax(curves[key], 8, pmask[idx] * percent)
            x[key] = curves[key + '_stop'][0]
        #Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
        lines['mse'].append(
            line(x['mse'], y['mse'][0], x['mse'], y['mse'][1], Colors[3], 1,
                 2))
        lines['sp'].append(
            line(x['sp'], y['sp'][0], x['sp'], y['sp'][1], Colors[3], 1, 2))
        if ref == 'Pd':
            lines['det'].append(
                line(x['det'], y['det'][0], x['det'], y['det'][1], Colors[2],
                     1, 2))
            lines['fa'].append(
                line(x['det'], y['fa'][0], x['det'], y['fa'][1], Colors[2], 2,
                     2))
        if ref == 'Pf':
            lines['det'].append(
                line(x['fa'], y['det'][0], x['fa'], y['det'][1], Colors[2], 2,
                     2))
            lines['fa'].append(
                line(x['fa'], y['fa'][0], x['fa'], y['fa'][1], Colors[2], 1,
                     2))

    #Start to build all ROOT objects
    from ROOT import TCanvas, gROOT, kTRUE
    gROOT.SetBatch(kTRUE)
    canvas = TCanvas('canvas', 'canvas', 1600, 1300)
    canvas.Divide(1, 4)

    def __plot_curves(tpad, curves, y_limits, **kw):
        from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray
        title = kw.pop('title', '')
        xlabel = kw.pop('xlabel', '')
        ylabel = kw.pop('ylabel', '')
        paintCurves = kw.pop('paintCurves', None)
        colorCurves = kw.pop('colorCurves', kGray)
        lines = kw.pop('lines', [])
        #create dummy graph
        x_max = 0
        dummy = None
        for i in range(len(curves)):
            curves[i].SetLineColor(colorCurves)
            x = curves[i].GetXaxis().GetXmax()
            if x > x_max:
                x_max = x
                dummy = curves[i]
        dummy.SetTitle(title)
        dummy.GetXaxis().SetTitle(xlabel)
        dummy.GetYaxis().SetTitle(ylabel)
        dummy.GetHistogram().SetAxisRange(y_limits[0], y_limits[1], 'Y')
        dummy.Draw('AL')
        #Plot curves
        for c in curves:
            c.SetLineWidth(1)
            c.SetLineStyle(3)
            c.Draw('same')
        #Paint a specifical curve
        if paintCurves:
            if len(paintCurves) > len(curves):
                for idx, c in enumerate(curves):
                    c.SetLineWidth(1)
                    c.SetLineColor(paintCurves[idx].second)
                    c.SetLineStyle(1)
                    c.Draw('same')
            else:
                for pair in paintCurves:
                    curves[pair.first].SetLineWidth(1)
                    curves[pair.first].SetLineStyle(1)
                    curves[pair.first].SetLineColor(pair.second)
                    curves[pair.first].Draw('same')
        #Plot lines
        for l in lines:
            l.Draw()
        #Update TPad
        tpad.Modified()
        tpad.Update()
        return x_max

    #__plot_curves end

    xlimits = list()
    for idx, key in enumerate(['mse', 'sp', 'det', 'fa']):
        #There are more plots
        x_max = __plot_curves(canvas.cd(idx + 1),
                              curves[key],
                              minmax(curves[key], 8, pmask[idx] * percent),
                              xlabel='Epoch',
                              ylabel=ylabel[key],
                              paintCurves=paint_curves,
                              colorCurves=kGray + 1,
                              lines=lines[key])
        xlimits.append(x_max)
    #Loop over plots

    #Check if there is any label
    if 'label' in kwargs.keys():
        tpad = canvas.cd(1)
        from TuningStyle import Label
        Label(0.6, 0.7, kwargs['label'], 1, 0.15)
        tpad.Modified()
        tpad.Update()

    # Reference base line
    if ref == 'Pd':
        tpad = canvas.cd(3)
        lines['ref'] = line(0.0, refVal, xlimits[2], refVal, kGreen, 2, 1)
        lines['ref'].Draw()
        tpad.Modified()
        tpad.Update()
    if ref == 'Pf':
        tpad = canvas.cd(4)
        lines['ref'] = line(0.0, refVal, xlimits[3], refVal, kGreen, 2, 1)
        lines['ref'].Draw()
        tpad.Modified()
        tpad.Update()

    canvas.Modified()
    canvas.Update()
    canvas.SaveAs(savename)
    del canvas
    return savename
示例#16
0
 def test_misc(self):
     self.assertEqual(util.hr(width=10, char='#'), "##########")
     self.assertEqual(util.line(width=11, char='@'), "@@@@@@@@@@@")
示例#17
0
setup(600, 600, 370, 0)
hideturtle()
tracer(False)
listen()

#stage setting
snake = [vector(20, 20)]
walls = {vector(100, 0), vector(-100, 0)}
pwalls = {vector(150, 0): 5}
thorns = {vector(10, 10)}
lasers = [[vector(-100, 0), vector(100, 0)]]
teledict = {vector(0, 100): vector(0, -100)}
foods = {vector(0, 0), vector(50, 50)}

for body in snake:
    square(body.x, body.y, 9, 'black')
for telep in teledict:
    square(telep.x, telep.y, 9, 'magenta')
    square(teledict[telep].x, teledict[telep].y, 9, 'purple')
for food in foods:
    square(food.x, food.y, 9, 'green')
for i in range(len(lasers)):
    line(lasers[i][0].x, lasers[i][0].y + 4.5, lasers[i][1].x,
         lasers[i][1].y + 4.5)
for wall in walls:
    square(wall.x, wall.y, 9, 'gray')
for pwall in pwalls:
    squarenum(pwall.x, pwall.y, 9, 'blue', pwalls[pwall])
for thorn in thorns:
    triangle(thorn.x, thorn.y, 9, 'red')
done()
示例#18
0
def plot_4c(plotObjects, kwargs):
    """
  kwargs is a dict with all kwargsion needed to config the figure and the
  curves. The kwargsions will be:
   reference: Pd, SP or Pf
   operation: True or False
   set: tst or val
  plot 4 curves
  """
    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray

    Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
    from RingerCore import StdPair as std_pair
    from util import line

    ref = kwargs["reference"]
    refVal = kwargs["refVal"]
    dset = kwargs["set"]
    isOperation = kwargs["operation"]
    detailed = True if plotObjects.size() == 1 else False
    percent = 0.03  # (default for now)
    savename = kwargs["cname"] + ".pdf"
    lines = []

    # Some protection
    if not ("val" in dset or "tst" in dset):
        raise ValueError("Option set must be: tst (test) or val (validation)")
    if not ("SP" in ref or "Pd" in ref or "Pf" in ref):
        raise ValueError("Option reference must be: SP, Pd or Pf")

    ylabel = {
        "mse": "MSE (" + dset + ")",
        "sp": "SP (" + dset + ")",
        "det": "Det (" + dset + ")",
        "fa": "FA (" + dset + ")",
    }

    # Create dict to hold all list plots
    curves = dict()
    # list of dicts to dict of lists
    for name in plotObjects.keys():
        curves[name] = plotObjects.tolist(name)

    # Adapt reference into the validation set
    # mse_trn, mse_val, mse_tst
    if ref == "Pd":
        curves["sp_val"] = curves["det_point_sp_val"]
        curves["det_val"] = curves["det_point_det_val"]  # det_fitted
        curves["fa_val"] = curves["det_point_fa_val"]
        curves["sp_tst"] = curves["det_point_sp_tst"]
        curves["det_tst"] = curves["det_point_det_tst"]
        curves["fa_tst"] = curves["det_point_fa_tst"]
    elif ref == "Pf":
        curves["sp_val"] = curves["fa_point_sp_val"]
        curves["det_val"] = curves["fa_point_det_val"]
        curves["fa_val"] = curves["fa_point_fa_val"]  # fa_fitted
        curves["sp_tst"] = curves["fa_point_sp_tst"]
        curves["det_tst"] = curves["fa_point_det_tst"]
        curves["fa_tst"] = curves["fa_point_fa_tst"]
    else:  # ref == 'SP'
        curves["sp_val"] = curves["bestsp_point_sp_val"]  # best SP curve
        curves["det_val"] = curves["bestsp_point_det_val"]
        curves["fa_val"] = curves["bestsp_point_fa_val"]
        curves["sp_tst"] = curves["bestsp_point_sp_tst"]
        curves["det_tst"] = curves["bestsp_point_det_tst"]
        curves["fa_tst"] = curves["bestsp_point_fa_tst"]

    from util import minmax

    # check if the test set is zeros
    hasTst = True if curves["mse_tst"][0].GetMean(2) > 1e-10 else False

    if dset == "tst" and not hasTst:
        print "We dont have test set into plotObjects, abort plot!"
        return False

    # If only one plot per key, enabled analysis using all sets
    if detailed:
        # train, validation and test
        paint_curves = [std_pair(i, Colors[i]) for i in range(3)]
        curves["mse"] = [curves["mse_trn"][0], curves["mse_val"][0]]
        curves["sp"] = [curves["sp_val"][0]]
        curves["det"] = [curves["det_val"][0]]
        curves["fa"] = [curves["fa_val"][0]]
        if hasTst:
            for key in ["mse", "sp", "det", "fa"]:
                curves[key].append(curves[key + "_tst"][0])
        ylabel = {"mse": "MSE", "sp": "SP", "det": "Det", "fa": "FA"}

    else:  # Do analysis for each set type
        paintIdx = kwargs["paintListIdx"]  # [best, worst]
        paint_curves = [
            std_pair(plotObjects.index_correction(paintIdx[0]), kBlack),
            std_pair(plotObjects.index_correction(paintIdx[1]), kRed),
        ]
        curves["mse"] = curves["mse_" + dset]
        curves["sp"] = curves["sp_" + dset]
        curves["det"] = curves["det_" + dset]
        curves["fa"] = curves["fa_" + dset]

    # Adapt the legend and percent vec
    pmask = [1, 1, 1, 1]
    if ref == "Pd":
        ylabel["det"] = ylabel["det"] + " [Reference]"
        ylabel["fa"] = ylabel["fa"] + " [benchmark]"
        pmask = [1, 1, 0, 1]
    elif ref == "Pf":
        ylabel["det"] = ylabel["det"] + " [benchmark]"
        ylabel["fa"] = ylabel["fa"] + " [Reference]"
        pmask = [1, 1, 1, 0]
    else:
        ylabel["sp"] = ylabel["sp"] + " [benchmark]"

    # Build lines
    lines = {"mse": [], "sp": [], "det": [], "fa": [], "ref": None}
    if detailed:  # Hard code setting lines
        y = dict()
        x = dict()
        for idx, key in enumerate(["mse", "sp", "det", "fa"]):
            y[key] = minmax(curves[key], 8, pmask[idx] * percent)
            x[key] = curves[key + "_stop"][0]
        # Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
        lines["mse"].append(line(x["mse"], y["mse"][0], x["mse"], y["mse"][1], Colors[3], 1, 2))
        lines["sp"].append(line(x["sp"], y["sp"][0], x["sp"], y["sp"][1], Colors[3], 1, 2))
        if ref == "Pd":
            lines["det"].append(line(x["det"], y["det"][0], x["det"], y["det"][1], Colors[2], 1, 2))
            lines["fa"].append(line(x["det"], y["fa"][0], x["det"], y["fa"][1], Colors[2], 2, 2))
        if ref == "Pf":
            lines["det"].append(line(x["fa"], y["det"][0], x["fa"], y["det"][1], Colors[2], 2, 2))
            lines["fa"].append(line(x["fa"], y["fa"][0], x["fa"], y["fa"][1], Colors[2], 1, 2))

    # Start to build all ROOT objects
    from ROOT import TCanvas, gROOT, kTRUE

    gROOT.SetBatch(kTRUE)
    canvas = TCanvas("canvas", "canvas", 1600, 1300)
    canvas.Divide(1, 4)

    def __plot_curves(tpad, curves, y_limits, **kw):
        from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray

        title = kw.pop("title", "")
        xlabel = kw.pop("xlabel", "")
        ylabel = kw.pop("ylabel", "")
        paintCurves = kw.pop("paintCurves", None)
        colorCurves = kw.pop("colorCurves", kGray)
        lines = kw.pop("lines", [])
        # create dummy graph
        x_max = 0
        dummy = None
        for i in range(len(curves)):
            curves[i].SetLineColor(colorCurves)
            x = curves[i].GetXaxis().GetXmax()
            if x > x_max:
                x_max = x
                dummy = curves[i]
        dummy.SetTitle(title)
        dummy.GetXaxis().SetTitle(xlabel)
        dummy.GetYaxis().SetTitle(ylabel)
        dummy.GetHistogram().SetAxisRange(y_limits[0], y_limits[1], "Y")
        dummy.Draw("AL")
        # Plot curves
        for c in curves:
            c.SetLineWidth(1)
            c.SetLineStyle(3)
            c.Draw("same")
        # Paint a specifical curve
        if paintCurves:
            if len(paintCurves) > len(curves):
                for idx, c in enumerate(curves):
                    c.SetLineWidth(1)
                    c.SetLineColor(paintCurves[idx].second)
                    c.SetLineStyle(1)
                    c.Draw("same")
            else:
                for pair in paintCurves:
                    curves[pair.first].SetLineWidth(1)
                    curves[pair.first].SetLineStyle(1)
                    curves[pair.first].SetLineColor(pair.second)
                    curves[pair.first].Draw("same")
        # Plot lines
        for l in lines:
            l.Draw()
        # Update TPad
        tpad.Modified()
        tpad.Update()
        return x_max

    # __plot_curves end

    xlimits = list()
    for idx, key in enumerate(["mse", "sp", "det", "fa"]):
        # There are more plots
        x_max = __plot_curves(
            canvas.cd(idx + 1),
            curves[key],
            minmax(curves[key], 8, pmask[idx] * percent),
            xlabel="Epoch",
            ylabel=ylabel[key],
            paintCurves=paint_curves,
            colorCurves=kGray + 1,
            lines=lines[key],
        )
        xlimits.append(x_max)
    # Loop over plots

    # Check if there is any label
    if "label" in kwargs.keys():
        tpad = canvas.cd(1)
        from TuningStyle import Label

        Label(0.6, 0.7, kwargs["label"], 1, 0.15)
        tpad.Modified()
        tpad.Update()

    # Reference base line
    if ref == "Pd":
        tpad = canvas.cd(3)
        lines["ref"] = line(0.0, refVal, xlimits[2], refVal, kGreen, 2, 1)
        lines["ref"].Draw()
        tpad.Modified()
        tpad.Update()
    if ref == "Pf":
        tpad = canvas.cd(4)
        lines["ref"] = line(0.0, refVal, xlimits[3], refVal, kGreen, 2, 1)
        lines["ref"].Draw()
        tpad.Modified()
        tpad.Update()

    canvas.Modified()
    canvas.Update()
    canvas.SaveAs(savename)
    del canvas
    return savename
示例#19
0
def plot_rocs(plotObjects, kwargs):

    from ROOT import kCyan, kRed, kGreen, kBlue, kBlack, kMagenta, kGray, kWhite, kYellow

    Colors = [kBlue, kRed, kMagenta, kBlack, kCyan, kGreen]
    from RingerCore import StdPair as std_pair
    from util import line, minmax

    dset = kwargs["set"]
    ref = kwargs["reference"]
    refVal = kwargs["refVal"]
    eps = kwargs["eps"]
    savename = kwargs["cname"] + ".pdf"

    # Some protection
    if not ("op" in dset or "tst" in dset):
        raise ValueError("Option set must be: tst (test) or val (validation)")
    if not ("SP" in ref or "Pd" in ref or "Pf" in ref):
        raise ValueError("Option reference must be: SP, Pd or Pf")

    # Create dict to hold all list plots
    curves = dict()
    # list of dicts to dict of lists
    for name in plotObjects.keys():
        curves[name] = plotObjects.tolist(name)

    paintIdx = kwargs["paintListIdx"]  # [best, worst]
    paintCurves = [
        std_pair(plotObjects.index_correction(paintIdx[0]), kBlack),
        std_pair(plotObjects.index_correction(paintIdx[1]), kRed),
    ]
    curves["roc"] = curves["roc_" + dset]

    # Start to build all ROOT objects
    from ROOT import TCanvas, gROOT, kTRUE

    gROOT.SetBatch(kTRUE)
    canvas = TCanvas("canvas", "canvas", 1600, 1300)

    x_limits = [0.00, 0.40]
    y_limits = [0.6, 1.03]

    # create dummy graph
    dummy = curves["roc"][0]
    dummy.SetTitle("Receive Operation Curve")
    dummy.GetXaxis().SetTitle("False Alarm")
    dummy.GetYaxis().SetTitle("Detection")
    dummy.GetHistogram().SetAxisRange(y_limits[0], y_limits[1], "Y")
    dummy.GetHistogram().SetAxisRange(x_limits[0], x_limits[1], "X")
    dummy.Draw("AL")

    corredor = None
    target = None
    from ROOT import TBox

    if ref == "Pf":
        corredor = TBox(refVal - eps, y_limits[0], refVal + eps, y_limits[1])
        target = line(refVal, y_limits[0], refVal, y_limits[1], kBlack, 2, 1, "")
    elif ref == "Pd":
        corredor = TBox(x_limits[0], refVal - eps, x_limits[1], refVal + eps)
        target = line(x_limits[0], refVal, x_limits[1], refVal, kBlack, 2, 1, "")

    if ref != "SP":
        corredor.SetFillColor(kYellow - 9)
        corredor.Draw("same")
        target.Draw("same")
        canvas.Modified()
        canvas.Update()

    # Plot curves
    for c in curves["roc"]:
        c.SetLineColor(kGray + 1)
        # c.SetMarkerStyle(7)
        # c.SetMarkerColor(kBlue)
        c.SetLineWidth(1)
        c.SetLineStyle(3)
        # c.Draw('PLsame')
        c.Draw("same")

    marker = list()
    # Paint a specifical curve
    for pair in paintCurves:
        curves["roc"][pair.first].SetLineWidth(1)
        curves["roc"][pair.first].SetLineStyle(1)
        # curves['roc'][pair.first].SetMarkerStyle(7)
        # curves['roc'][pair.first].SetMarkerColor(kBlue)
        curves["roc"][pair.first].SetLineColor(pair.second)
        # curves['roc'][pair.first].Draw('PLsame')
        curves["roc"][pair.first].Draw("same")

        if ref == "SP":
            faVec = curves["roc"][pair.first].GetX()
            detVec = curves["roc"][pair.first].GetY()
            from RingerCore import calcSP

            spVec = [calcSP(detVec[i], 1 - faVec[i]) for i in range(curves["roc"][pair.first].GetN())]
            imax = spVec.index(max(spVec))
            from ROOT import TMarker

            marker.append(TMarker(faVec[imax], detVec[imax], 4))
            marker[-1].SetMarkerColor(pair.second)
            marker[-1].Draw("same")

    # Update Canvas
    canvas.Modified()
    canvas.Update()
    canvas.SaveAs(savename)
    del canvas

    return savename
示例#20
0
comma.scale(1.3, 1.3).rotate(-30).move(5.5,
                                       0).rotate(0).fill(ax, facecolor='black')
circle.scale(0.7, 0.7).move(5.5, 0).rotate(0).fill(ax, facecolor='white')
comma.scale(1.3, 1.3).rotate(-30).move(5.5,
                                       0).rotate(120).fill(ax,
                                                           facecolor='black')
circle.scale(0.7, 0.7).move(5.5, 0).rotate(120).fill(ax, facecolor='white')
comma.scale(1.3, 1.3).rotate(-30).move(5.5,
                                       0).rotate(240).fill(ax,
                                                           facecolor='black')
circle.scale(0.7, 0.7).move(5.5, 0).rotate(240).fill(ax, facecolor='white')

#block
theta = 15 / 180 * np.pi
block = Shape()
block.add_array(line([-np.sin(theta), 0], [np.sin(theta), 0]))
block.add_array(line([np.sin(theta), 0], [np.sin(theta), -np.cos(theta)]))
block.add_array(
    arc([np.sin(theta), -np.cos(theta)], [-np.sin(theta), -np.cos(theta)], 1))
block.add_array(line([-np.sin(theta), -np.cos(theta)], [-np.sin(theta), 0]))
block.loop()

#moon
moon = Shape()
moon.add_array(arc([0, 0], [0, 1], 0.53))
moon.add_array(arc([0, 1], [0, 0], 1, out=False))
moon.loop()

#2, 2
ax = axs[5]
circle.scale(11, 11).fill(ax, facecolor='black')