コード例 #1
0
ファイル: main.py プロジェクト: duke-iml/ece490-s2016
 def __init__(self):
     print "Initialized new supervisor"
     self.time_limit = 3
     self.state_machine = msm.motion_state_machine()
     self.bumper = bump.Bumper((0.161, 0, 0))
     self.start_time = time.time()
     self.vac=vacuum()
     self.hand = HandHandler()
     self.handler=jsonHandler()
     (self.origMap,self.workOrder)=self.handler.readInFile("RandomTestB.json")
     self.items_to_stow = len(self.workOrder[0])
     ##Load bin Selector
     self.binSelect=binSelector()
     ##Initialize bin Selector 
     self.binSelect.initialize("RandomTestB.json")
コード例 #2
0
import numpy as np
import pylab as pl
import glob
import vacuum

for f in sorted(glob.glob("2d/vacuum2d*.hdf5")):
    print "processing", f[:-5]
    file = h5py.File(f, "r")
    coords = np.array(file["/PartType0/Coordinates"])
    rho = np.array(file["/PartType0/Density"])
    vs = np.array(file["/PartType0/Velocities"])
    P = np.array(file["/PartType0/InternalEnergy"])
    P = 2. * rho * P / 3.
    t = file["/Header"].attrs["Time"]

    xsol, rhosol, usol, Psol = vacuum.vacuum([1., 0., 1.], [0., 0., 0.], t)

    fig, ax = pl.subplots(2, 2)
    ax[0][0].plot(xsol, rhosol, "r-")
    ax[0][0].plot(coords[:, 0], rho, "k.")
    ax[0][1].plot(xsol, usol, "r-")
    ax[0][1].plot(coords[:, 0], vs[:, 0], "k.")
    ax[1][0].plot(xsol, Psol, "r-")
    ax[1][0].plot(coords[:, 0], P, "k.")
    pl.savefig("{name}.png".format(name=f[:-5]))
    pl.close()

for f in sorted(glob.glob("3d/vacuum3d*.hdf5")):
    print "processing", f[:-5]
    file = h5py.File(f, "r")
    coords = np.array(file["/PartType0/Coordinates"])
コード例 #3
0
def main():

    zmin = -40000.
    zmax = -10100.
    xmin = -1300.
    xmax = 800.

    c1 = TCanvas("c1", "c1", 1000, 700)
    frame = gPad.DrawFrame(zmin, xmin, zmax,
                           xmax)  # xmin, ymin, xmax, ymax in ROOT
    frame.SetTitle(";Length #it{z} (mm);Horizontal #it{x} (mm)")
    siz = 0.035
    frame.SetTitleSize(siz)
    frame.SetLabelSize(siz)
    frame.SetTitleSize(siz, "Y")
    frame.SetLabelSize(siz, "Y")

    frame.GetYaxis().SetTitleOffset(1.3)
    frame.GetXaxis().SetTitleOffset(1.2)
    frame.GetYaxis().CenterTitle()
    frame.GetXaxis().CenterTitle()
    gPad.SetLeftMargin(0.09)
    gPad.SetRightMargin(0.01)
    gPad.SetTopMargin(0.02)
    gPad.SetBottomMargin(0.09)

    #geometry
    geo = rt.GeoParser("../../config/pro1/geom_all.in")

    #spectrometer magnet
    mag = magnet("lumi_dipole", geo)
    mag.label = "Spectr. dipole"
    mag.draw()

    #B2BeR magnet
    b2b = magnet("B2BeR", geo)
    b2b.label = "B2BeR"
    b2b.draw()

    #Q3eR magnet
    q3 = magnet("Q3eR", geo)
    q3.label = "Q3eR"
    q3.draw()

    #beam vacuum
    bvac = vacuum(geo)
    bvac.add_point("vac_b2b_drift", "zQB", "xQB")
    bvac.add_point("vac_b2b_drift", "zQT", "xQT")
    bvac.add_point("vac_b2b_drift", "zW", "xW")
    bvac.add_point("vac_b2b_window", "win_z", "win_xmax")
    bvac.add_point_2("vac_b2b_window.b2b_end_z", "B2BeR.r2")
    bvac.add_point("vac_tag1_win", "zB", "xB")
    bvac.draw()

    #vacuum in front of Tagger 1
    vac_t1 = vacuum(geo)
    vac_t1.add_point("vac_tag1_win", "zTB", "xTB")
    vac_t1.add_point("vac_tag1_win", "zT", "xT")
    vac_t1.add_point("vac_tag1_win", "zB", "xB")
    vac_t1.draw()

    #vacuum in front of Tagger 2
    vac_t2 = vacuum(geo)
    vac_t2.add_point("vac_tag2_win", "zTB", "xTB")
    vac_t2.add_point("vac_tag2_win", "zT", "xT")
    vac_t2.add_point("vac_tag2_win", "zB", "xB")
    vac_t2.draw()

    #vacuum from exit window to spectrometer magnet
    vac_win = vacuum(geo)
    vac_win.add_point("vac_lumi_win_mag", "z1", "dX1", -1.)
    vac_win.add_point("vac_lumi_win_mag", "z1", "dX1")
    vac_win.add_point("vac_lumi_win_mag", "z0", "dX0")
    vac_win.add_point("vac_lumi_win_mag", "z0", "dX0", -1.)
    #vac_win.add_point("", "", "")
    #vac_win.draw()

    #vacuum from spectrometer magnet to spectrometer detectors
    vac_mag = vacuum(geo)
    vac_mag.add_point("vac_lumi_mag_spec", "z1", "dX1", -1.)
    vac_mag.add_point("vac_lumi_mag_spec", "z1", "dX1")
    vac_mag.add_point("vac_lumi_mag_spec", "z0", "dX0")
    vac_mag.add_point("vac_lumi_mag_spec", "z0", "dX0", -1.)
    #vac_mag.draw()

    #vacuum section from spectrometers to direct photon detector
    vac_phot = vacuum(geo)
    vac_phot.add_point("vac_lumi_spec_phot", "z1", "dX1", -1.)
    vac_phot.add_point("vac_lumi_spec_phot", "z1", "dX1")
    vac_phot.add_point("vac_lumi_spec_phot", "z0", "dX0")
    vac_phot.add_point("vac_lumi_spec_phot", "z0", "dX0", -1.)
    #vac_phot.draw()

    #Tagger1
    tag1 = segment("Tagger1box", geo)
    tag1.label = "Tagger 1"
    tag1.draw()

    #Tagger2
    tag2 = segment("Tagger2box", geo)
    tag2.label = "Tagger 2"
    tag2.draw()

    #Luminosity exit window
    ew = segment("ExitWinBox", geo)
    ew.label = "Exit window"
    ew.fill_col = rt.kGreen + 1
    ew.draw()

    #up spectrometer for both spectrometers
    up = segment("LumiSUbox", geo)
    up.theta = 0
    up.label = "Spectrometers"
    up.draw()

    #Luminosity direct photon detector
    phot = segment("LumiDbox", geo)
    phot.label = "Photon detector"
    phot.draw()

    leg = ut.prepare_leg(0.8, 0.21, 0.25, 0.15,
                         0.03)  #, 0.027) # x, y, dx, dy, tsiz
    leg.AddEntry(tag1.gbox, "Detector", "f")
    leg.AddEntry(b2b.gbox, "Magnet", "f")
    leg.AddEntry(bvac.gbox, "Vacuum", "f")
    leg.Draw("same")

    gPad.SetGrid()

    ut.invert_col(gPad)
    c1.SaveAs("01fig.pdf")
コード例 #4
0
def main():
    game_over = False
    game__over=False
    rows, cols = 15, 15
    borders = 0
    dirty_tiles=0
    while(rows >= 15 or cols >= 15 or rows==0 or cols==0 or borders==0 or dirty_tiles==0):
        try:

            layout = [  [sg.Text('Necessary Inputs')],
            [sg.Text('Please enter number of rows as an integer:'), sg.InputText()],
            [sg.Text('Please enter number of cols as an integer:'), sg.InputText()],
            [sg.Text('Please enter number of dirty tiles:'), sg.InputText()],
            [sg.Text('Please enter number of borders:'), sg.InputText()],
            [sg.Text('Speed:'),sg.Slider(range=(1000,30),default_value=1000,size=(20,15),orientation='horizontal', disable_number_display=True)],
            [sg.Text('Window dirt Period'),sg.Slider(range=(2,10),default_value=5,size=(20,15),orientation='horizontal', disable_number_display=True)],
            [sg.Text('Agent Period'),sg.Slider(range=(2,10),default_value=5,size=(20,15),orientation='horizontal', disable_number_display=True)],
            [sg.Spin([i for i in range(1,5)], initial_value=1), sg.Text('Cleaning Agents')],
            [sg.Spin([i for i in range(0,5)], initial_value=0), sg.Text('Dirt Agents')],
            [sg.Frame(layout=[
            [sg.Radio('Case1 (Fully observable map and once generated dirt):', "Case1", default=False)],
            [sg.Radio('Case2 (Fully observable map and continuously added dirt):', "Case1", default=False)],
            [sg.Radio('Case3 (Fully observable borders and unknown dirt positions):', "Case1", default=False)],
            [sg.Radio('Case4 (Unknown borders and dirt positions):', "Case1", default=False)],

            [sg.Checkbox('Alternate Dirt Algorithm',  default=False)],
            [sg.Checkbox('Box In',  default=False)]],

            title='Choose Any of these Cases',title_color='red', relief=sg.RELIEF_SUNKEN, tooltip='Use these to set flags')],
            [sg.Submit()]]
            window = sg.Window('Vacuum Cleaner Agent', layout)
            event, values = window.Read()
            case1=values[9]
            case2=values[10]
            case3=values[11]
            case4=values[12]
            
            intelligenceDirtFirst=values[13]

            boxIn = values[14]
            
            rows=int(values[0])
            cols=int(values[1])
            dirty_tiles= int(values[2])
            borders=int(values[3])
            globals.globals.speed=int(values[4])
            globals.globals.frequency=int(values[5])
            globals.globals.period=int(values[6])
            globals.globals.cleaning_agents=int(values[7])
            globals.globals.dirt_agents=int(values[8])
            if event in ('Submit'):
                print('Borders are placed randomly')
            window.Close()
        except ValueError:
            print("No valid integer! Please try again ...")
    CELL_SIZE = 40
    window_size = [cols * CELL_SIZE, rows * CELL_SIZE]


    pygame.init()

    window = pygame.display.set_mode(window_size)
    pygame.display.set_caption("Vacuum Cleaner Agent")
    run = True
    clock = pygame.time.Clock()
    r = room(CELL_SIZE, rows, cols, window)
    r.draw_grid()
    r.draw_borders(borders)
    vacuums = []
    dirt_machines = []

    for x in range(globals.globals.cleaning_agents):
        vacuums.append(vacuum(r, window, x))
        print("creating vacuum with ID: ",  x)

    if(globals.globals.dirt_agents > 0):
        for x in range(globals.globals.dirt_agents):
            dirt_machines.append(dirt_machine(r, window, x))
            print("creating dirt machine with ID: ", x)
    else:
        pass
    # print(dirt_machines)
    d = dirt(r, window, dirty_tiles)

    pos = None
    mySolver = solver(r.get_array())

    tempLastLoc = None
    pos2 = None

    globals.globals.start_duration = datetime.now().timestamp()

    

# depending on the Specific case
    if(case1):  # fully observable with set amount of dirt
        while run:

            pygame.time.delay(globals.globals.speed)
            clock.tick(10)
            for event in pygame.event.get():

                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    game_over = True
                    r.clear_room()
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    vacuums[0].set_position((rows//2)+1,(cols//2)-1)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)
                    vacuums[0].move_left()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_LEFT:
                        v.move_left()
                    if event.key == pygame.K_RIGHT:
                        v.move_right()
                    if event.key == pygame.K_UP:
                        v.move_up()
                    if event.key == pygame.K_DOWN:
                        v.move_down()
                    if event.key == pygame.K_SPACE:
                        pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            if(not game_over):
                
                if(not intelligenceDirtFirst):
                    for x in vacuums:
                        x.move_to_closest_dirt()
                
                
                
                if(globals.globals.dirt_agents != 0):
                    if(intelligenceDirtFirst):
                       #Alternate Algrthm 
                        paths = mySolver.getFirstPathForDirt(r,dirt_machines,vacuums, boxIn)
                       
                        index = -1
                        if(not paths is None):
                            
                            m = len(paths[0])
                            for p in paths:
                                if(len(p) < m):
                                    m = len(p)
                            
                            for idx in range(0,m):
                                for pathX in paths:
                                    index += 1

                                    if( pathX is None or pathX == [] or len(pathX) == 0 or pathX[0] == None):
                                        continue

                                    if(idx >= len(pathX)):
                                        continue    

                                    try:
                                        
                                        didMove = False

                                        if(pathX[idx] == 'L'):
                                            dirt_machines[index].move_left()
                                            didMove = True
                                        if(pathX[idx] == 'U'):
                                            dirt_machines[index].move_up()
                                            didMove = True
                                        if(pathX[idx] == 'D'):
                                            dirt_machines[index].move_down()
                                            didMove = True
                                        if(pathX[idx] == 'R'):
                                            dirt_machines[index].move_right()
                                            didMove = True

                                       # if(idx >= 1):
                                        for x in vacuums:
                                            x.move_to_closest_dirt()
                            
                                        if( intelligenceDirtFirst):
                                            pygame.time.delay(globals.globals.speed)

                                    except Exception:
                                        pass
                                    
                                    

                                
                                
                    else:
                        for x in dirt_machines:
                            x.move_from_closest_dirt()


    elif(case2):  # fully observable and dirt keeps getting added
        count = 0
        while run:
            if(count == globals.globals.frequency):
                d.probabilistic_dirt(1)
                count = 0
            
            if(not intelligenceDirtFirst):
                pygame.time.delay(globals.globals.speed)
            clock.tick(10)

            for event in pygame.event.get():

                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    game_over = True
                    r.clear_room()
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    vacuums[0].set_position((rows//2)+1,(cols//2)-1)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)
                    vacuums[0].move_left()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()
                    pygame.time.delay(500)
                    vacuums[0].move_right()

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                        pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
            if(not game_over):
                
                if(not intelligenceDirtFirst):
                    for x in vacuums:
                        x.move_to_closest_dirt()
                
                
                
                if(globals.globals.dirt_agents != 0):
                    if(intelligenceDirtFirst):
                       #Alternate Algrthm 
                        paths = mySolver.getFirstPathForDirt(r,dirt_machines,vacuums, boxIn)
                       
                        index = -1
                        if(not paths is None):
                            
                            m = len(paths[0])
                            for p in paths:
                                if(len(p) < m):
                                    m = len(p)
                            
                            for idx in range(0,m):
                                for pathX in paths:
                                    index += 1

                                    if( pathX is None or pathX == [] or len(pathX) == 0 or pathX[0] == None):
                                        continue

                                    if(idx >= len(pathX)):
                                        continue    

                                    try:
                                        
                                        didMove = False

                                        if(pathX[idx] == 'L'):
                                            dirt_machines[index].move_left()
                                            didMove = True
                                        if(pathX[idx] == 'U'):
                                            dirt_machines[index].move_up()
                                            didMove = True
                                        if(pathX[idx] == 'D'):
                                            dirt_machines[index].move_down()
                                            didMove = True
                                        if(pathX[idx] == 'R'):
                                            dirt_machines[index].move_right()
                                            didMove = True

                                       # if(idx >= 1):
                                        for x in vacuums:
                                            x.move_to_closest_dirt()
                            
                                        if( intelligenceDirtFirst):
                                            pygame.time.delay(globals.globals.speed)

                                    except Exception:
                                        pass
                                    
                                    

                                
                                
                    else:
                        for x in dirt_machines:
                            x.move_from_closest_dirt()

            count += 1

    #Partially visible in HERE
    elif(case3):

        dirtMachineIntelligence = 0
        if(intelligenceDirtFirst):
            dirtMachineIntelligence = 1

        path = []
        pathDirt = []

        count = 0

        mySolver.expoloreAllBorders()

        cyclesStuckCount = [1]
        cycleStuckPos = [ [0,0] ]

        cyclesStuckCountDirt = [1]
        cycleStuckPosDirt = [ [0,0] ]

        while run:

            if(count >= globals.globals.frequency):
                d.probabilistic_dirt(1)
                count = 0
            #FOR DEBUGGING
            #NOTE TO SELF => REMOVE LATER ON
            #d.rnd_dirt_DEBUG(1)
            count += 1
            #////////////////////////////////////

            pygame.time.delay(globals.globals.speed)
            clock.tick(10)

            for event in pygame.event.get():
                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    game__over=True
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    r.clear_room()
                    path=["R","R","R","R"]
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    vacuums[0].set_position((rows//2)+1,(cols//2)-1)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                        pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            index = -1
            for v in vacuums:

                index += 1
                if(len(path) < index + 1):
                    path.append([])
                if(len(cyclesStuckCount) < index + 1):
                    cyclesStuckCount.append(1)
                    cycleStuckPos.append( [0,0] )

                if(pos2 is None):
                    pos2 = r.vacuum_position(index)

                pos2 = copy.deepcopy ( r.vacuum_position(index) )
                #pos2 = r.vacuum_position()

                pos2 = mySolver.dirtPathIterator( copy.deepcopy( pos2 ) )

                #print("pos 2")
                #print(pos2)

                if(not game__over):
                    path[index] = mySolver.getLastActualUsedPath()
                    #machine.move_from_closest_dirt()


                # Take care of dynmaic collision

                #if stuck by other agent abort mission
                if(cyclesStuckCount[index] > 1):
                    #print(cycleStuckPos[index])
                    cyclesStuckCount[index] = 1
                    mySolver.escapeFromAgent(r.vacuum_position(index), cycleStuckPos[index] )
                    path[index] = mySolver.getLastActualUsedPath();

            if(dirtMachineIntelligence == 0):
                index = -1
                for _ in dirt_machines:

                    index += 1
                    if(len(pathDirt) < index + 1):
                        pathDirt.append([])
                    if(len(cyclesStuckCountDirt) < index + 1):
                        cyclesStuckCountDirt.append(1)
                        cycleStuckPosDirt.append( [0,0] )

                    if(pos2 is None):
                        pos2 = r.dirt_machine_position(index)

                    pos2 = copy.deepcopy ( r.dirt_machine_position(index) )
                    #pos2 = r.vacuum_position()

                    pos2 = mySolver.addDirtPathIterator( copy.deepcopy( pos2 ) )

                    #print("pos 2")
                    #print(pos2)

                    if(not game__over):
                        pathDirt[index] = mySolver.getLastActualUsedPath()
                        #machine.move_from_closest_dirt()


                    # Take care of dynmaic collision

                    #if stuck by other agent abort mission
                    if(cyclesStuckCountDirt[index] > 1):
                        #print(cycleStuckPos[index])
                        cyclesStuckCountDirt[index] = 1
                        mySolver.escapeFromAgent(r.dirt_machine_position(index), cycleStuckPosDirt[index] )
                        pathDirt[index] = mySolver.getLastActualUsedPath();


            m = len(path[0])
            for p in path:
                if(len(p) < m):
                    m = len(p)

            if(dirtMachineIntelligence == 0):
                for p in pathDirt:
                    if(len(p) < m):
                        m = len(p)



            for idx in range(0,m):

                index = -1
                for pathX in path:

                    index += 1

                    #print(index)
                    #print(idx)

                    p = pathX[idx]

                    # Take care of dynmaic collision
                    if( not p in vacuums[index].get_valid_moves() ):
                        #print("Vacuum Was Gonna Hit")
                        #exit(0)
                        cyclesStuckCount[index] += 1

                        deltX = 0
                        deltaY = 0
                        if(p == "L"):
                            deltX = -1
                        elif(p == "R"):
                            deltX = 1
                        elif(p == "U"):
                            deltaY = -1
                        elif(p == "D"):
                            deltaY = 1

                        cycleStuckPos[index] = [r.vacuum_position(index)[0] + deltaY, r.vacuum_position(index)[1] + deltX, ]

                        continue;


                    if(p == "L"):
                        vacuums[index].move_left()
                    elif(p == "R"):
                        vacuums[index].move_right()
                    elif(p == "U"):
                        vacuums[index].move_up()
                    elif(p == "D"):
                        vacuums[index].move_down()

                    mySolver.addExploredToGrid(r.get_array(), r.vacuum_position(index)[0], r.vacuum_position(index)[1] )

                    # if(globals.globals.dirt_agents != 0):
                    #     for x in dirt_machines:
                    #         x.move_from_closest_dirt()
                    # else:
                    #     pass

                    #if(not game__over and globals.globals.dirt_agents > 0):
                    #    dirt_machines[0].move_from_closest_dirt()

                if(dirtMachineIntelligence == 0):
                    index = -1
                    for pathX in pathDirt:

                        index += 1

                        if(isVacuumNeghbr(r,vacuums, r.dirt_machine_position(index), boxIn )):
                            continue

                        p = pathX[idx]

                        # Take care of dynmaic collision
                        if( not p in dirt_machines[index].get_valid_moves() ):
                            #print("Vacuum Was Gonna Hit")
                            #exit(0)
                            cyclesStuckCountDirt[index] += 1

                            deltX = 0
                            deltaY = 0
                            if(p == "L"):
                                deltX = -1
                            elif(p == "R"):
                                deltX = 1
                            elif(p == "U"):
                                deltaY = -1
                            elif(p == "D"):
                                deltaY = 1

                            cycleStuckPosDirt[index] = [r.dirt_machine_position(index)[0] + deltaY, r.dirt_machine_position(index)[1] + deltX, ]

                            continue;


                        if(p == "L"):
                            dirt_machines[index].move_left()
                        elif(p == "R"):
                            dirt_machines[index].move_right()
                        elif(p == "U"):
                            dirt_machines[index].move_up()
                        elif(p == "D"):
                            dirt_machines[index].move_down()
                        
                        dirt_machines[index].incrementCountForDirt(8)


                if(dirtMachineIntelligence == 1):
                    for mac in dirt_machines:
                        mac.move_from_closest_dirt()

                pygame.time.delay(globals.globals.speed)

            #pos2 = r.vacuum_position();

            pygame.display.update()

    elif(case4):

        path = []

        count = 0

        dirtMachineIntelligence = 0
        if(intelligenceDirtFirst):
            dirtMachineIntelligence = 1

        cyclesStuckCount = [1]
        cycleStuckPos = [ [0,0] ]

        tempLastLoc = []

        pathDirt = []

        cyclesStuckCountDirt = [1]
        cycleStuckPosDirt = [ [0,0] ]

        while run:

            if(count >= globals.globals.frequency):
                d.probabilistic_dirt(1)
                count = 0
            #FOR DEBUGGING
            #NOTE TO SELF => REMOVE LATER ON
            #d.rnd_dirt_DEBUG(1)
            count += 1
            #////////////////////////////////////

            pygame.time.delay(globals.globals.speed)
            clock.tick(10)

            for event in pygame.event.get():
                #gameover
                if (event.type == pygame.QUIT or ((event.type == pygame.KEYDOWN or event.type == pygame.KEYUP) and (event.key == pygame.K_ESCAPE))):
                    game__over=True
                    globals.globals.end_duration= datetime.now().timestamp()
                    layout2 = [[sg.Text('Duration: ' + str(round(globals.globals.end_duration-globals.globals.start_duration,3)))],
                    [sg.Text('Number of cleaned tiles: '+ str(globals.globals.nb_clean_tiles))],
                    [sg.Text('Number of steps: '+ str(globals.globals.nb_steps))],
                    [sg.Text('Number of added dirt: '+ str(globals.globals.nb_added_dirt))],
                    [sg.Text('Average number of steps per dirt: '+ str(round(globals.globals.nb_steps/globals.globals.nb_clean_tiles)))],
                    [sg.Text('Average time to clean a dirt: ' + str(round(round(globals.globals.end_duration-globals.globals.start_duration,3)/globals.globals.nb_clean_tiles, 2)))],
                    [sg.Button('Exit')]]
                    window1 = sg.Window('Measures', layout2)
                    window1.Read()
                    r.clear_room()
                    path=["R","R","R","R"]
                    window.fill((0,0,0))
                    font = pygame.font.Font('freesansbold.ttf', 20)
                    text_surface = font.render("Game Over", True, (150,150,150))
                    text_rect = text_surface.get_rect()
                    text_rect.center = (window.get_width()//2, window.get_height()//2)
                    window.blit(text_surface, text_rect)
                    pygame.display.update()
                    v.set_position((rows//2)+1,(cols//2)-3)
                    pygame.mixer.music.load('game-over.wav')
                    pygame.mixer.music.play(2)

                    run = False
                    #arrows as input
                if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
                    if event.key == pygame.K_SPACE:
                       pygame.time.delay(5000)



            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            #EXPLORE MAP CODE

            index = -1
            for v in vacuums:

                index += 1
                if(len(path) < index + 1):
                    path.append([])
                if(len(cyclesStuckCount) < index + 1):
                    cyclesStuckCount.append(1)
                    cycleStuckPos.append( [0,0] )
                if(len(tempLastLoc) < index + 1):
                    tempLastLoc.append( [] )

                #if(index > 1):
                #    print("Impossible Indx")
                #    exit(0)

                if (pos is None or not pos[0] == -1):

                    if(not pos is None):
                        tempLastLoc[index] = copy.deepcopy( pos )


                    pos = mySolver.discoverMapIter( copy.deepcopy(r.vacuum_position(index)) )
                    #print('target pos: ' + str(pos) )


                    if(not game__over):
                        path[index] = mySolver.getLastActualUsedPath()

                    #print('path: ' + str(path) )
                    #print(r.vacuum_position() )


                else:

                    #print("Dirt Phase")

                    if(pos2 is None):
                        pos2 = tempLastLoc[index]



                    pos2 = mySolver.dirtPathIterator( copy.deepcopy( r.vacuum_position(index) ) )

                    #pos2 = mySolver.dirtPathIterator( copy.deepcopy( pos2 ) )


                    #print("pos 2")
                    #print(pos2)
                    if(not game__over):
                        path[index] = mySolver.getLastActualUsedPath()

                pst = [-1,-1]
                #if stuck by other agent abort mission
                if(cyclesStuckCount[index] > 1):
                    #print("getting out")
                    cyclesStuckCount[index] = 1
                    pst = mySolver.escapeFromAgent(r.vacuum_position(index), cycleStuckPos[index] )
                    path[index] = mySolver.getLastActualUsedPath();
                    #print("agent")
                    #print(index)
                    #print(pst)

                #print(index)
                #print("My pos")
                #print(r.vacuum_position(index))
                #print("dest")
                #if(pst[0] == -1):
                #    print(pos2)
                #else:
                #    print(pst)
                #print("path")
                #print(path[index])

            if(dirtMachineIntelligence == 0):
                index = -1
                for _ in dirt_machines:

                    index += 1
                    if(len(pathDirt) < index + 1):
                        pathDirt.append([])
                    if(len(cyclesStuckCountDirt) < index + 1):
                        cyclesStuckCountDirt.append(1)
                        cycleStuckPosDirt.append( [0,0] )

                    if(pos2 is None):
                        pos2 = r.dirt_machine_position(index)

                    pos2 = copy.deepcopy ( r.dirt_machine_position(index) )
                    #pos2 = r.vacuum_position()

                    pos2 = mySolver.addDirtPathIterator( copy.deepcopy( pos2 ) )

                    #print("pos 2")
                    #print(pos2)

                    if(not game__over):
                        pathDirt[index] = mySolver.getLastActualUsedPath()
                        #machine.move_from_closest_dirt()


                    # Take care of dynmaic collision

                    #if stuck by other agent abort mission
                    if(cyclesStuckCountDirt[index] > 1):
                        #print(cycleStuckPos[index])
                        cyclesStuckCountDirt[index] = 1
                        mySolver.escapeFromAgent(r.dirt_machine_position(index), cycleStuckPosDirt[index] )
                        pathDirt[index] = mySolver.getLastActualUsedPath();


            #END OF EXPLORATION

            #print("paths")
            #print(path[0])
            #print(path[1])

            m = len(path[0])
            for p in path:
                if(len(p) < m):
                    m = len(p)

            if(dirtMachineIntelligence == 0):
                for p in pathDirt:
                    if(len(p) < m):
                        m = len(p)

            if(m < 2):
                m = 3

            #print("M value")
            #print(m)

            for idx in range(0,m):

                index = -1
                for pathX in path:

                    index += 1

                    #print(index)
                    #print(idx)

                    if(idx >= len(pathX)):
                        continue


                    p = pathX[idx]

                    #mySolver.addExploredToGrid(r.get_array(), r.vacuum_position(index)[0], r.vacuum_position(index)[1] )
                    #print("in pathX loop")

                    if( not p in vacuums[index].get_valid_moves() ):
                       # print(p + " Vacuum Was Gonna Hit")
                        #exit(0)

                        cyclesStuckCount[index] += 1

                        deltX = 0
                        deltaY = 0
                        if(p == "L"):
                            deltX = -1
                        elif(p == "R"):
                            deltX = 1
                        elif(p == "U"):
                            deltaY = -1
                        elif(p == "D"):
                            deltaY = 1

                        cycleStuckPos[index] = [r.vacuum_position(index)[0] + deltaY, r.vacuum_position(index)[1] + deltX ]

                        #print(cycleStuckPos[index])

                        #print(cyclesStuckCount[index])

                        continue;

                    if(p == "L"):
                        vacuums[index].move_left()
                    elif(p == "R"):
                        vacuums[index].move_right()
                    elif(p == "U"):
                        vacuums[index].move_up()
                    elif(p == "D"):
                        vacuums[index].move_down()

                    #print("moved vacuum " + str(index) )


                    mySolver.addExploredToGrid(r.get_array(), r.vacuum_position(index)[0], r.vacuum_position(index)[1] )

                    #if(not game__over):
                    #    machine.move_from_closest_dirt()

                if(dirtMachineIntelligence == 0):
                    index = -1
                    for pathX in pathDirt:

                        index += 1

                        if(isVacuumNeghbr(r,vacuums, r.dirt_machine_position(index) , boxIn)):
                            continue

                        if(idx >= len(pathX)):
                            continue

                        p = pathX[idx]

                        # Take care of dynmaic collision
                        if( not p in dirt_machines[index].get_valid_moves() ):
                            #print("Vacuum Was Gonna Hit")
                            #exit(0)
                            cyclesStuckCountDirt[index] += 1

                            deltX = 0
                            deltaY = 0
                            if(p == "L"):
                                deltX = -1
                            elif(p == "R"):
                                deltX = 1
                            elif(p == "U"):
                                deltaY = -1
                            elif(p == "D"):
                                deltaY = 1

                            cycleStuckPosDirt[index] = [r.dirt_machine_position(index)[0] + deltaY, r.dirt_machine_position(index)[1] + deltX, ]

                            continue;


                        if(p == "L"):
                            dirt_machines[index].move_left()
                        elif(p == "R"):
                            dirt_machines[index].move_right()
                        elif(p == "U"):
                            dirt_machines[index].move_up()
                        elif(p == "D"):
                            dirt_machines[index].move_down()

                        dirt_machines[index].incrementCountForDirt(8)


                        #print("moved machine " + str(index) )

                if(dirtMachineIntelligence == 1):
                    for mac in dirt_machines:
                        mac.move_from_closest_dirt()

                pygame.time.delay(globals.globals.speed)

            path[index] = []
            if(dirtMachineIntelligence == 0):
                pathDirt[index] = []
           

            #print("idx loop")

            pygame.display.update()



    pygame.quit()
コード例 #5
0
def main():

    zmin = -40000.
    zmax = -4000.
    xmin = -1300.
    xmax = 800.

    c1 = TCanvas("c1","c1",1000,700)
    frame = gPad.DrawFrame(zmin, xmin, zmax, xmax) # xmin, ymin, xmax, ymax in ROOT
    frame.SetTitle(";Length #it{z} (mm);Horizontal #it{x} (mm)")
    siz = 0.035
    frame.SetTitleSize(siz)
    frame.SetLabelSize(siz)
    frame.SetTitleSize(siz, "Y")
    frame.SetLabelSize(siz, "Y")

    frame.GetYaxis().SetTitleOffset(1.3)
    frame.GetXaxis().SetTitleOffset(1.2)
    frame.GetYaxis().CenterTitle()
    frame.GetXaxis().CenterTitle()
    gPad.SetLeftMargin(0.09)
    gPad.SetRightMargin(0.01)
    gPad.SetTopMargin(0.02)
    gPad.SetBottomMargin(0.09)

    #geometry
    geo = rt.GeoParser("../../config/pro2/geom_pro2.in")

    #Q1eR magnet
    q1 = magnet("Q1eR", geo)
    q1.label = "Q1eR"
    q1.draw()

    #Q2eR magnet
    q2 = magnet("Q2eR", geo)
    q2.label = "Q2eR"
    q2.draw()

    #B2eR magnet
    b2 = magnet("B2eR", geo)
    b2.label = "B2eR"
    b2.draw()

    #Q3eR magnet
    q3 = magnet("Q3eR", geo)
    q3.label = "Q3eR"
    q3.draw()

    #vacuum from Q1eR to Q2eR
    q1q2 = vacuum(geo)
    q1q2.add_point_const("Q1eR_End_Z", "Q1eR_InnerRadius", -1)
    q1q2.add_point_const("Q2eR_Start_Z", "Q1eR_InnerRadius", -1)
    q1q2.add_point_const("Q2eR_Start_Z", "Q1eR_InnerRadius")
    q1q2.add_point_const("Q1eR_End_Z", "Q1eR_InnerRadius")
    q1q2.draw()

    #vacuum from Q2eR to B2eR
    q2b2 = vacuum(geo)
    q2b2.add_point_const("Q2eR_End_Z", "Q2eR_InnerRadius", -1)
    q2b2.add_point_const("B2eR_Start_Z", "Q2eR_InnerRadius", -1)
    q2b2.add_point_const("B2eR_Start_Z", "Q2eR_InnerRadius")
    q2b2.add_point_const("Q2eR_End_Z", "Q2eR_InnerRadius")
    q2b2.draw()

    #beam vacuum
    bvac = vacuum(geo)
    bvac.add_point("vac_B2", "z1BI", "x1BI")
    bvac.add_point("vac_win_tag1", "z0BI", "x0BI")
    bvac.add_point("vac_win_tag1", "z0TO", "x0TO")
    bvac.add_point("vac_win_tag2", "z0BI", "x0BI")
    bvac.add_point("vac_win_tag2", "z0TO", "x0TO")
    bvac.add_point("vac_Q3", "z0BI", "x0BI")
    bvac.add_point("vac_Q3", "z0TI", "x0TI")
    bvac.add_point_2("vac_B2.z0TO", "ExitWinBox.dx", -0.5)
    bvac.add_point("vac_B2", "z0TO", "x0TI")
    bvac.add_point("vac_B2", "z1TI", "x1TI")
    bvac.draw()

    #geometry from pro1 for luminosity
    geo2 = rt.GeoParser("../../config/pro1/geom_all.in")

    #spectrometer magnet
    spec_mag = magnet("lumi_dipole", geo2)
    spec_mag.label = "Spectr. dipole"
    spec_mag.draw()

    #vacuum from exit window to spectrometer magnet
    vac_win = vacuum(geo2)
    vac_win.add_point("vac_lumi_win_mag", "z1", "dX1", -1.)
    vac_win.add_point("vac_lumi_win_mag", "z1", "dX1")
    vac_win.add_point("vac_lumi_win_mag", "z0", "dX0")
    vac_win.add_point("vac_lumi_win_mag", "z0", "dX0", -1.)
    vac_win.draw()

    #vacuum from spectrometer magnet to spectrometer detectors
    vac_mag = vacuum(geo2)
    vac_mag.add_point("vac_lumi_mag_spec", "z1", "dX1", -1.)
    vac_mag.add_point("vac_lumi_mag_spec", "z1", "dX1")
    vac_mag.add_point("vac_lumi_mag_spec", "z0", "dX0")
    vac_mag.add_point("vac_lumi_mag_spec", "z0", "dX0", -1.)
    vac_mag.draw()

    #vacuum section from spectrometers to direct photon detector
    vac_phot = vacuum(geo2)
    vac_phot.add_point("vac_lumi_spec_phot", "z1", "dX1", -1.)
    vac_phot.add_point("vac_lumi_spec_phot", "z1", "dX1")
    vac_phot.add_point("vac_lumi_spec_phot", "z0", "dX0")
    vac_phot.add_point("vac_lumi_spec_phot", "z0", "dX0", -1.)
    vac_phot.draw()

    #up spectrometer for both spectrometers
    up = segment("LumiSUbox", geo2)
    up.theta = 0
    up.label = "Spectrometers"
    up.draw()

    #Luminosity direct photon detector
    phot = segment("LumiDbox", geo2)
    phot.label = "Photon detector"
    phot.draw()

    #Luminosity exit window
    ew = segment("ExitWinBox", geo)
    ew.label = "Exit window"
    ew.fill_col = rt.kGreen+1
    ew.draw()

    #Tagger1
    tag1 = segment("Tagger1box", geo)
    tag1.label = "Tagger 1"
    tag1.draw()

    #Tagger2
    tag2 = segment("Tagger2box", geo)
    tag2.label = "Tagger 2"
    tag2.draw()

    leg = ut.prepare_leg(0.8, 0.21, 0.25, 0.15, 0.03)#, 0.027) # x, y, dx, dy, tsiz
    leg.AddEntry(tag1.gbox, "Detector", "f")
    leg.AddEntry(b2.gbox, "Magnet", "f")
    leg.AddEntry(bvac.gbox, "Vacuum", "f")
    leg.Draw("same")

    gPad.SetGrid()

    #ut.invert_col(gPad)
    c1.SaveAs("01fig.pdf")
コード例 #6
0
ファイル: plot.py プロジェクト: AstroUGent/shadowfax
import numpy as np
import pylab as pl
import glob
import vacuum

for f in sorted(glob.glob("2d/vacuum2d*.hdf5")):
    print "processing", f[:-5]
    file = h5py.File(f, "r")
    coords = np.array(file["/PartType0/Coordinates"])
    rho = np.array(file["/PartType0/Density"])
    vs = np.array(file["/PartType0/Velocities"])
    P = np.array(file["/PartType0/InternalEnergy"])
    P = 2.*rho*P/3.
    t = file["/Header"].attrs["Time"]
    
    xsol, rhosol, usol, Psol = vacuum.vacuum([1., 0., 1.], [0., 0., 0.], t)
    
    fig, ax = pl.subplots(2, 2)
    ax[0][0].plot(xsol, rhosol, "r-")
    ax[0][0].plot(coords[:,0], rho, "k.")
    ax[0][1].plot(xsol, usol, "r-")
    ax[0][1].plot(coords[:,0], vs[:,0], "k.")
    ax[1][0].plot(xsol, Psol, "r-")
    ax[1][0].plot(coords[:,0], P, "k.")
    pl.savefig("{name}.png".format(name=f[:-5]))
    pl.close()

for f in sorted(glob.glob("3d/vacuum3d*.hdf5")):
    print "processing", f[:-5]
    file = h5py.File(f, "r")
    coords = np.array(file["/PartType0/Coordinates"])
コード例 #7
0
def main():

    zmin = -40000.
    zmax = -10100.
    ymin = -800
    ymax = 800.

    c1 = TCanvas("c1", "c1", 1000, 700)
    frame = gPad.DrawFrame(zmin, ymin, zmax,
                           ymax)  # xmin, ymin, xmax, ymax in ROOT
    frame.SetTitle(";Length #it{z} (mm);Vertical #it{y} (mm)")
    siz = 0.035
    frame.SetTitleSize(siz)
    frame.SetLabelSize(siz)
    frame.SetTitleSize(siz, "Y")
    frame.SetLabelSize(siz, "Y")

    frame.GetYaxis().SetTitleOffset(1.3)
    frame.GetXaxis().SetTitleOffset(1.2)
    frame.GetYaxis().CenterTitle()
    frame.GetXaxis().CenterTitle()
    gPad.SetLeftMargin(0.09)
    gPad.SetRightMargin(0.01)
    gPad.SetTopMargin(0.02)
    gPad.SetBottomMargin(0.09)

    #geometry
    geo = rt.GeoParser("../../config/geom_all.in")

    #B2BeR magnet
    b2b = magnet("B2BeR", geo)
    b2b.label = "B2BeR"
    b2b.draw()

    #beam vacuum from B2BeR to exit window
    bvac = vacuum(geo)
    bvac.add_point("vac_b2b_window", "b2b_end_z", "b2b_end_xy", -0.5)
    bvac.add_point("vac_b2b_window", "win_z", "win_xmax", -1)
    bvac.add_point("vac_b2b_window", "win_z", "win_xmax")
    bvac.add_point("vac_b2b_window", "b2b_end_z", "b2b_end_xy", 0.5)
    bvac.draw()

    #vacuum from exit window to spectometer magnet
    vac_win_spec = vacuum(geo)
    vac_win_spec.add_point("vac_lumi_win_mag", "z0", "dY0", -1)
    vac_win_spec.add_point("vac_lumi_win_mag", "z1", "dY1", -1)
    vac_win_spec.add_point("vac_lumi_win_mag", "z1", "dY1")
    vac_win_spec.add_point("vac_lumi_win_mag", "z0", "dY0")
    vac_win_spec.draw()

    #vacuum from specrometer magnet to detectors
    vac_det = vacuum(geo)
    vac_det.add_point("vac_lumi_mag_spec", "z0", "dY0", -1)
    vac_det.add_point("vac_lumi_mag_spec", "z1", "dY1", -1)
    vac_det.add_point("vac_lumi_spec_mid", "z0", "dY0", -1)
    vac_det.add_point("vac_lumi_spec_phot", "z0", "dY0", -1)
    vac_det.add_point("vac_lumi_spec_phot", "z1", "dY1", -1)
    vac_det.add_point("vac_lumi_spec_phot", "z1", "dY1")
    vac_det.add_point("vac_lumi_spec_phot", "z0", "dY0")
    vac_det.add_point("vac_lumi_spec_mid", "z0", "dY0")
    vac_det.add_point("vac_lumi_mag_spec", "z1", "dY1")
    vac_det.add_point("vac_lumi_mag_spec", "z0", "dY0")
    vac_det.draw()

    #spectrometer magnet
    mag = magnet("lumi_dipole", geo)
    mag.label = "Spectr. dipole"
    mag.draw()

    #luminosity exit window
    ew = segment("ExitWinBox", geo)
    ew.y_project = True
    ew.label = "Exit window"
    ew.fill_col = rt.kGreen + 1
    ew.draw()

    #up spectrometer
    up = segment("LumiSUbox", geo)
    up.y_project = True
    up.theta = -1. * up.theta
    up.label = "Up"
    up.draw()

    #down spectrometer
    down = segment("LumiSDbox", geo)
    down.y_project = True
    down.theta = -1. * down.theta
    down.label = "Down"
    down.draw()

    #photon detector
    phot = segment("LumiDbox", geo)
    phot.y_project = True
    phot.label = "Photon detector"
    phot.draw()

    leg = ut.prepare_leg(0.8, 0.21, 0.25, 0.15,
                         0.03)  #, 0.027) # x, y, dx, dy, tsiz
    leg.AddEntry(phot.gbox, "Detector", "f")
    leg.AddEntry(b2b.gbox, "Magnet", "f")
    leg.AddEntry(bvac.gbox, "Vacuum", "f")
    leg.Draw("same")

    l2 = ut.prepare_leg(0.64, 0.75, 0.25, 0.12, 0.027)
    l2.AddEntry("", "Space for exit window:", "")
    l2.AddEntry("", "Center #it{z}: " + str(ew.zpos), "")
    l2.AddEntry("", "Size in #it{xy}: " + str(ew.dy), "")
    l2.AddEntry("", "Lenght in #it{z}: " + str(ew.dz), "")
    l2.Draw("same")

    l3 = ut.prepare_leg(0.45, 0.75, 0.25, 0.12, 0.027)
    l3.AddEntry("", "Specrometer dipole:", "")
    l3.AddEntry("", "Center #it{z}: " + str(mag.zpos), "")
    l3.AddEntry("", "Radius: " + str(mag.r1), "")
    l3.AddEntry("", "Lenght in #it{z}: " + str(mag.dz), "")
    l3.Draw("same")

    l4 = ut.prepare_leg(0.15, 0.75, 0.25, 0.15, 0.027)
    l4.AddEntry("", "Up detector:", "")
    l4.AddEntry("", "Center #it{z}: " + "{0:.1f}".format(up.zpos), "")
    l4.AddEntry("", "Center #it{y}: " + "{0:.1f}".format(up.ypos), "")
    l4.AddEntry("", "Size in #it{xy}: " + str(up.dy), "")
    l4.AddEntry("", "Lenght in #it{z}: " + str(up.dz), "")
    l4.Draw("same")

    l5 = ut.prepare_leg(0.1, 0.12, 0.25, 0.15, 0.027)
    l5.AddEntry("", "Down detector:", "")
    l5.AddEntry("", "Center #it{z}: " + "{0:.1f}".format(down.zpos), "")
    l5.AddEntry("", "Center #it{y}: " + "{0:.1f}".format(down.ypos), "")
    l5.AddEntry("", "Size in #it{xy}: " + str(down.dy), "")
    l5.AddEntry("", "Lenght in #it{z}: " + str(down.dz), "")
    l5.Draw("same")

    l6 = ut.prepare_leg(0.3, 0.11, 0.25, 0.12, 0.027)
    l6.AddEntry("", "Photon detector:", "")
    l6.AddEntry("", "Center #it{z}: " + "{0:.1f}".format(phot.zpos), "")
    l6.AddEntry("", "Size in #it{xy}: " + str(phot.dy), "")
    l6.AddEntry("", "Lenght in #it{z}: " + str(phot.dz), "")
    l6.Draw("same")

    l7 = ut.prepare_leg(0.5, 0.11, 0.25, 0.12, 0.027)
    l7.AddEntry("", "B2BeR magnet:", "")
    l7.AddEntry("", "Center #it{z}: " + str(b2b.zpos), "")
    l7.AddEntry("", "Radius: " + str(b2b.r1), "")
    l7.AddEntry("", "Lenght in #it{z}: " + str(b2b.dz), "")
    l7.Draw("same")

    l8 = ut.prepare_leg(0.3, 0.92, 0.25, 0.01, 0.03)
    l8.AddEntry("", "Luminosity layout, side view. All dimensions in mm.", "")
    l8.Draw("same")

    #gPad.SetGrid()

    ut.invert_col(gPad)
    c1.SaveAs("01fig.pdf")