Ejemplo n.º 1
0
    def __init__(self):

        # Create the tkinter window
        self.root = Tk()

        # Create a cube instance
        self.cube = Cube()

        # Setup all of the tkinter elements
        self.frames = []
        self.face_buttons = []
        self.rotation_buttons = []
        self.action_button = None
        self.face_label = None
        self.rotation_label = None
        self.face = 0
        self.rotation = 0
        self.setup_graphics()

        # Setup the cube printing elements
        self.cube_grid = []
        self.setup_grid()

        # Print the cube
        self.print_cube()
Ejemplo n.º 2
0
    def solve():

        current = Cube()
        current.scramble(3)
        currentScore = current.h_score()
        temp = 10000
        coolingRate = 0.003
        moves = []

        while temp > 1:

            gui.draw_cube(current, gui.mainFrame, 50)

            move = choice(list(Facing))
            newGrid = deepcopy(current)
            newGrid.rotate_face(move)

            if currentScore == 0:
                gui.draw_moves(moves)
                return True

            newScore = newGrid.h_score()
            if accept_probability(currentScore, newScore, temp) > random():
                current = newGrid
                currentScore = newScore
                moves.append(move)
                gui.draw_cube(current, gui.mainFrame, 50)
                gui.mainFrame.update()

            temp = temp * (1 - coolingRate)
Ejemplo n.º 3
0
 def test_ray_intersects_cube_7(self):
     c = Cube()
     r = Ray(Point(0, 0.5, 0), Vector(0, 0, 1))
     xs = c.local_intersect(r)
     self.assertTrue(equals(xs.count, 2))
     self.assertTrue(equals(-1, xs[0].t))
     self.assertTrue(equals(1, xs[1].t))
Ejemplo n.º 4
0
def generate_and_scramble_cube():
    random_cube = Cube()
    scramble = get_random_scramble_by_length(10)
    print("Applying scramble: " + scramble_to_str(scramble))
    random_cube.apply_notation(scramble)
    print_cube(random_cube)
    return random_cube
Ejemplo n.º 5
0
def 判断setup完后的case(func, setup):
    c = Cube()
    c.Rotate("X2 Z")
    c.Rotate(setup)
    if c.colors[4] not in 色向正确颜色:
        c.Rotate("M")
    return func(c)
Ejemplo n.º 6
0
def main():
    """main: Driver function to make sure code is running correctly """
    cube1 = Cube('red', 5)
    cube2 = Cube('red', 6)
    cube3 = Cube('blue', 5)
    cube_list = [cube1, cube2, cube3]
    print(stack_cubes(cube_list))
Ejemplo n.º 7
0
    def __init__(self):
        Cube.__init__(self,
                      wall_type=Wall3x3,
                      fmt='''                        + ---- + ---- + ---- +
                        | {00} | {01} | {02} |
                        | {00} | {01} | {02} |
                        +----- U ---- U -----+
                        | {03} | {04} | {05} |
                        | {03} | {04} | {05} |
                        +----- U ---- U -----+
                        | {06} | {07} | {08} |
                        | {06} | {07} | {08} |
                        + ---- + ---- + ---- +
+ ---- + ---- + ---- +  + ---- + ---- + ---- +  + ---- + ---- + ---- +  + ---- + ---- + ---- +
| {09} | {10} | {11} |  | {18} | {19} | {20} |  | {27} | {28} | {29} |  | {36} | {37} | {38} |  
| {09} | {10} | {11} |  | {18} | {19} | {20} |  | {27} | {28} | {29} |  | {36} | {37} | {38} |  
+----- L ---- L -----+  +----- F ---- F -----+  +----- R ---- R -----+  +----- B ---- B -----+
| {12} | {13} | {14} |  | {21} | {22} | {23} |  | {30} | {31} | {32} |  | {39} | {40} | {41} |  
| {12} | {13} | {14} |  | {21} | {22} | {23} |  | {30} | {31} | {32} |  | {39} | {40} | {41} |  
+----- L ---- L -----+  +----- F ---- F -----+  +----- R ---- R -----+  +----- B ---- B -----+
| {15} | {16} | {17} |  | {24} | {25} | {26} |  | {33} | {34} | {35} |  | {42} | {43} | {44} |  
| {15} | {16} | {17} |  | {24} | {25} | {26} |  | {33} | {34} | {35} |  | {42} | {43} | {44} |  
+ ---- + ---- + ---- +  + ---- + ---- + ---- +  + ---- + ---- + ---- +  + ---- + ---- + ---- +
                        + ---- + ---- + ---- +
                        | {45} | {46} | {47} |
                        | {45} | {46} | {47} |
                        +----- D ---- D -----+
                        | {48} | {49} | {50} |
                        | {48} | {49} | {50} |
                        +----- D ---- D -----+
                        | {51} | {52} | {53} |
                        | {51} | {52} | {53} |
                        + ---- + ---- + ---- +
''')
Ejemplo n.º 8
0
    def __init__(self):
        Cube.__init__(self,
                      wall_type=Wall2x2,
                      fmt='''                + ---- + ---- +
                | {00} | {01} |  
                | {00} | {01} |  
                +----- U -----+
                | {02} | {03} |  
                | {02} | {03} |  
                + ---- + ---- +
+------+------+ +------+------+ +------+------+ +------+------+
| {04} | {05} | | {08} | {09} | | {12} | {13} | | {16} | {17} |  
| {04} | {05} | | {08} | {09} | | {12} | {13} | | {16} | {17} |  
+----- L -----+ +----- F -----+ +----- R -----+ +----- B -----+
| {06} | {07} | | {10} | {11} | | {14} | {15} | | {18} | {19} |  
| {06} | {07} | | {10} | {11} | | {14} | {15} | | {18} | {19} |  
+------+------+ +------+------+ +------+------+ +------+------+
                +------+------+
                | {20} | {21} |  
                | {20} | {21} |  
                +----- D -----+
                | {22} | {23} |  
                | {22} | {23} |  
                +------+------+
''')
Ejemplo n.º 9
0
  def __init__(self, cubesize=[64,64,64]):
    """Create empty array of cubesize"""

    # call the base class constructor
    Cube.__init__(self,cubesize)
    # note that this is self.cubesize (which is transposed) in Cube
    self.data = np.zeros ( self.cubesize, dtype=np.uint16 )
Ejemplo n.º 10
0
 def init_cube(self):
     face_rotation_ease_type = Tween.get_ease_type_by_name(self.settings.cube_face_rotation_ease_type)
     texture_id = self.textures.get(self.settings.texture_mapping_active_texture)
     if texture_id == None:
         texture_id = 0
     self.cube = Cube(self.settings, face_rotation_ease_type, texture_id, self.cube_size)
     self.map_cube_colors(self.settings.cube_color_mapping)
Ejemplo n.º 11
0
    def run(self):
        global width, rows, s, snacks
        while True:
            data = self.net.receive()
            print(data)
            # data = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
            # for player in data:
            #     print(player)

            player_received = json.loads(
                data,
                object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
            player = Player(player_received.ip, player_received.score,
                            player_received.snake)
            snake_reaceived = player.snake
            s = Snake(
                snake_reaceived.color,
                (snake_reaceived.head.pos[0], snake_reaceived.head.pos[1]),
                snake_reaceived.dirnx, snake_reaceived.dirny)
            width = 500
            rows = 20
            win = pygame.display.set_mode((width, width))
            snacks = []
            snacks.append(Cube(self.randomSnack(rows, s), color=(0, 255, 0)))
            flag = True
            score = 0
            clock = pygame.time.Clock()

            while flag:
                pygame.time.delay(50)
                clock.tick(10)

                finish_game_flag = False
                s.move()

                if not finish_game_flag:
                    player.score = score
                    player.snake = s
                    self.send_data(player)

                for snack in snacks:
                    if s.body[0].pos == snack.pos:
                        s.addCube()
                        score += 1
                        snacks.remove(snack)
                        snacks.append(
                            Cube(self.randomSnack(rows, s), color=(0, 255, 0)))

                for x in range(len(s.body)):
                    if s.body[x].pos in list(
                            map(lambda z: z.pos, s.body[x + 1:])):
                        print('Score: ', len(s.body) - 2)
                        self.message_box('You Lost!', 'Play again...')
                        score = 0
                        finish_game_flag = True
                        s.reset((10, 10))
                        break

                self.redrawWindow(win)
        pass
Ejemplo n.º 12
0
 def test_failure(self):
     """test_failure: Make sure a ValueError is raised if you cannot stack the cubes"""
     cube1 = Cube('red', 5)
     cube2 = Cube('red', 5)
     cube_list = [cube1, cube2]
     with self.assertRaises(ValueError):
         stack_cubes(cube_list)
Ejemplo n.º 13
0
 def train(self,
           start_length=TRAIN_START_LENGTH,
           end_length=TRAIN_UNTIL_LENGTH,
           cases=TRAIN_CASES,
           optimal=False):
     successful_trainings = 0
     print("Start training...")
     for i in range(start_length, end_length + 1):
         print("Training scrambles with length " + str(i) + "...")
         successful_trainings_by_length = 0
         for j in range(0, cases):
             random_cube = Cube()
             scramble = self.find_unknown_scramble(i)
             if scramble is None:
                 print("Skipping length " + str(i) +
                       ", all scrambles already known.")
                 successful_trainings_by_length = cases
                 break
             random_cube.apply_notation(scramble)
             training_success = self.try_to_solve(random_cube, optimal)
             if training_success:
                 self.persist_scramble(scramble)
                 successful_trainings_by_length += 1
         print("Success on training length " + str(i) + ": " +
               str(successful_trainings_by_length) + "/" + str(cases))
         successful_trainings += successful_trainings_by_length
     print("TRAINING REPORT:")
     print("Overall success: " + str(successful_trainings) + "/" +
           str(cases * (end_length + 1 - start_length)))
     print("Scrambles known:")
     for key in self.known_scrambles.keys():
         print("Length " + str(key) + ": " +
               str(len(self.known_scrambles.get(key))) + "/" + str(18**key))
Ejemplo n.º 14
0
 def find_orange_corner(self, img_hsv, kinect, polyline, is_left):
     stencil = FormStencil([polyline])
     img_hsv_mask = stencil.apply(img_hsv)
     orange_corner = Cube('orange')
     if is_left:
         return orange_corner.find_position(img_hsv_mask, kinect, self.PIXEL_SHIFT)
     return orange_corner.find_position(img_hsv_mask, kinect, -self.PIXEL_SHIFT)
Ejemplo n.º 15
0
def main():
    cube = Cube(read_full_text(2020, 17), 4)

    for _ in range(6):
        cube.simulate_cycle()

    print(cube.count_active())
Ejemplo n.º 16
0
def calc(sequence):
    oriented = OrientedCube([
        U, L, L, D, U, U, U, U, R, L, R, L, R, R, U, U, R, L, R, R, R, L, U, U,
        R, R, L, R, R, L, L, D, R, R, R, R, U, U, R, R, R, L, L, D, R, U, U, R,
        U, U, R, U, L, U
    ])
    oriented.sequence(sequence)
    if oriented.is_solved():
        print("###################")
        print("# Move: %s" % sequence)
        print("------------------")
        cube = Cube(""
                    "    lo_"
                    "    ssc"
                    "    in2"
                    "6_e s_5 hp} ohH"
                    "i{a @tr tll a_V"
                    "es3 o_4 sn_ _e7"
                    "    e_a"
                    "    wkd"
                    "    _0c")
        cube.sequence(sequence)
        print(cube.flat_str())
        print(cube)
        print(oriented)
Ejemplo n.º 17
0
 def getfilecube(self, args):
     corners =args[0]
     ci =args[1]
     cubesize =args[2]
     timestep =args[3]
     step = args[4]
     filterwidth = args[5]
     components = args[6]
     datafield = args[7]
     print ("Setting cube: ", corners[0], corners[1], corners[2])
     cube = Cube(corners, cubesize, step, filterwidth, components)        
     #mortonstart = jhtdblib.JHTDBLib().createmortonindex(corners[0], corners[1], corners[2])
     #mortonend = jhtdblib.JHTDBLib().createmortonindex(corners[0] + cubesize[0], corners[1] + cubesize[1], corners[2] + cubesize[2])
     #start = time.time()        
     print ("getting cube: ", corners[0], corners[1], corners[2])
     #It appears this sometimes fails when parallel processing, so we try up to 3 times...
     retries =3
     attempt = 0
     #while (attempt < retries ):
     #    if (cube.getCubeData(ci, datafield, timestep) != True):
     #        attempt = attempt + 1
     #        print("Retrying cube.")
     #    else:
     #        attempt = 3
     #        print("Completed cube")
     if (cube.getCubeData(ci, datafield, timestep) != True):
         print("Success cube")
     print("Saving cube", corners[0], corners[1], corners[2])
     
     #tmp = NamedTemporaryFile(suffix='.RAW', mode='w+b', dir='/tmp', delete=False)
     #Save object
     #pickle.dump(cube, tmp, pickle.HIGHEST_PROTOCOL)
     #cPickle.dump(cube, tmp, cPickle.HIGHEST_PROTOCOL)
     
     return cube
Ejemplo n.º 18
0
class CubeTest(unittest.TestCase):
    """ Tests the Cube class """

    TEST_CUBE_DIMENSION = 3

    def setUp(self):
        self.cube = Cube(CubeTest.TEST_CUBE_DIMENSION)

    def tearDown(self):
        pass

    def testCellCount(self):
        self.assertEquals(CubeTest.TEST_CUBE_DIMENSION 
                          * CubeTest.TEST_CUBE_DIMENSION 
                          * CubeTest.TEST_CUBE_DIMENSION,
                          len(self.cube.get_cells()))

    def __awakenCell(self, cell):
        cell.state = Cell.LIVE

    def testForeachCellAndStateChange(self):
        for cell in self.cube.get_cells():
            self.assertEquals(Cell.DEAD, cell.state)
        
        self.cube.foreach_cell(self.__awakenCell)
        
        for cell in self.cube.get_cells():
            self.assertEquals(Cell.LIVE, cell.state)    
Ejemplo n.º 19
0
  def __init__(self, cubesize=[128,128,16]):
    """Create empty array of cubesize"""

    # call the base class constructor
    Cube.__init__(self,cubesize)
    # note that this is self.cubesize (which is transposed) in Cube
    self.data = np.zeros ( self.cubesize, dtype=np.float32 )
Ejemplo n.º 20
0
    def get(self) -> Tuple[Canvas, np.ndarray]:

        cube_center = np.array([10, 0, 0])
        edge_length = 3.2
        cube = Cube(cube_center, edge_length)
        cube.rotate(np.array([0, 0, 1]), cube.cube_center, np.radians(15))

        camera = np.array([0, 2, 4])
        canvas_distance = 3
        view_direction = cube_center - camera

        canvas = Canvas(camera, view_direction, canvas_distance)

        horizon = np.array([0, -1, 0])
        canvas.set_horizon(horizon)

        angles_h = np.radians(np.array([-29, 29]))
        angles_v = np.radians(np.array([-25, 25]))
        canvas.set_angles(angles_h, angles_v)

        img_width = 600
        img_height = 400
        canvas.set_pixels_size(img_width, img_height)

        triangles = cube.get_triangles()

        return (
            canvas,
            triangles,
        )
Ejemplo n.º 21
0
 def test_calc_height(self):
     """test_calc_height: Testing calculate_height function"""
     cube1 = Cube('red', 6)
     cube2 = Cube('blue', 5)
     stacked_list = [cube1, cube2]
     self.assertEqual(calc_height(stacked_list),
                      'The maximum tower height is 11')
Ejemplo n.º 22
0
 def portal(self, portal_count, cubes, in_auto):
     if not in_auto:
         y = self.y
         top_y = 43.0
         bottom_y = 910.0
         
         rand_angle = random.uniform(-PI/12, PI/12)
         rand_speed = random.uniform(0, 2)
         
         if self.color == self.RED:
             # If closer to top portal, try to spawn cube in upper right
             if abs(y - top_y) < abs(y - bottom_y):
                 if portal_count["red"]["top"] > 0:
                     portal_count["red"]["top"] -= 1
                     cubes.append(Cube(1854, 59, 2.262 + rand_angle, rand_speed))
 
             # Otherwise, try to spawn cube in lower right
             else:
                 if portal_count["red"]["bottom"] > 0:
                     portal_count["red"]["bottom"] -= 1
                     cubes.append(Cube(1854, 894, -2.262 + rand_angle, rand_speed))
         
         elif self.color == self.BLUE:
             # If closer to top portal, try to spawn cube in upper left
             if abs(y - top_y) < abs(y - bottom_y):
                 if portal_count["blue"]["top"] > 0:
                     portal_count["blue"]["top"] -= 1
                     cubes.append(Cube(66, 59, 0.880 + rand_angle, rand_speed))
             # Otherwise, try to drop a cube in the lower left
             else:
                 if portal_count["blue"]["bottom"] > 0:
                     portal_count["blue"]["bottom"] -= 1
                     # spawn lower left
                     cubes.append(Cube(66, 894, -0.880 + rand_angle, rand_speed))
Ejemplo n.º 23
0
def main():
    side = eval(input("What is the side length of your cube?  "))
    cube = Cube(side)
    A = cube.surfaceArea()
    V = cube.volume()
    print("The volume of your cube is {0:0.1f}.".format(V))
    print("The area of your cube is {0:0.1f}.".format(A))
Ejemplo n.º 24
0
def display():
    global mode_labels, mode

    glClear(GL_COLOR_BUFFER_BIT)
    if mode == M_DEPTH: glClear(GL_DEPTH_BUFFER_BIT)

    glLoadIdentity()

    gluLookAt(.3, 1.1, 1.5, 0, 0, 0, 0, 1, 0)
    draw_axis()
    glRotatef(360. * millis * 0.001 * .2, 1, 0, 0)
    glRotatef(360. * millis * 0.001 * .07, 0, 1, 0)
    Cube.draw()

    glMatrixMode(GL_PROJECTION)
    glPushMatrix()
    glLoadIdentity()
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()

    glColor3f(1, 1, 1)
    glRasterPos(-.2, -.9)
    displayBitmapString(mode_labels[mode])

    glMatrixMode(GL_PROJECTION)
    glPopMatrix()
    glMatrixMode(GL_MODELVIEW)

    glFlush()
Ejemplo n.º 25
0
    def run(self):
        self.draw_cube()

        running = True
        while running:
            for event in pygame.event.get():
                prime = pygame.key.get_pressed()[pygame.K_LSHIFT]
                if event.type == pygame.QUIT:
                    running = False

                if event.type == pygame.KEYDOWN:
                    key = pygame.key.name(event.key)

                    if key in {"u", "f", "l", "r", "d", "b"}:
                        self.cube._rotate(key.upper(), prime, False)
                        self.draw_cube()
                    elif key == "s":
                        self.cube = Cube(3)
                        self.cube.set_scramble(gen_scramble())
                        self.draw_cube()
                    elif event.key == pygame.K_SPACE:
                        for move in generate_solution(self.cube):
                            self.cube.do_moves([move])
                            self.draw_cube()
                            time.sleep(0.05)
Ejemplo n.º 26
0
 def draw_cubes():
     posY1 = 350
     posX1 = 60
     posY2 = 350
     posX2 = 410
     n = 0
     j = 0
     for i in range(numcubes1):
         if j < 11:
             j = j + 1
             posX1 = posX1 + 25
             cube1.add(Cube(posX1, posY1))
         else:
             j = 1
             posX1 = 60 + 25
             posY1 = posY1 - 25
             cube1.add(Cube(posX1, posY1))
     for m in range(numcubes2):
         if n < 11:
             n = n + 1
             posX2 = posX2 + 25
             cube2.add(Cube(posX2, posY2))
         else:
             n = 1
             posX2 = 410 + 25
             posY2 = posY2 - 25
             cube2.add(Cube(posX2, posY2))
Ejemplo n.º 27
0
    def __helper(self, layout, ops, visited, level, maxLevel):
        """
        Private helper to do the real recursively DFS search.
        """
        # Count node expanded for each new visiting node
        self.expanded += 1
        cube = Cube(layout)
        # Check terminal states
        if cube.isSolved():
            self.result = ''.join(ops)
            return True
        # Maximum level check
        if level == maxLevel:
            return False

        # Expand neighbors node
        for o in range(12):
            # Apply operation to cube object
            getattr(cube, self.ops[o])()
            cur_layout = cube.getLayout()
            if cur_layout not in visited:
                visited.add(cur_layout)
                # Recursion call for DFS
                if self.__helper(cur_layout, ops + [self.ops[o]], visited,
                                 level + 1, maxLevel):
                    return True
                visited.remove(cur_layout)
            # Recover cube's state using reversed operation
            getattr(cube, self.rops[o])()

        return False
Ejemplo n.º 28
0
    def getcubedrawdata(self, ci, timestep, datafield, selftask = None):
        #We need to chunk the data first
        #cubesize 16
        cubedimension = 256
        components = Datafield.objects.get(shortname=datafield).components
        fullcubesize  = [math.ceil(float(ci.zlen)/float(cubedimension))*cubedimension, math.ceil(float(ci.ylen)/float(cubedimension))*cubedimension, math.ceil(float(ci.xlen)/float(cubedimension))*cubedimension]
        fullcubesize = [int(fullcubesize[0]), int(fullcubesize[1]), int(fullcubesize[2])]
        print ("Full cube size is: ", fullcubesize)
        filterwidth = ci.filter
        corner = [ci.xstart, ci.ystart, ci.zstart]
        step = [ci.xstep, ci.ystep, ci.zstep]
        fullcube = Cube(corner, fullcubesize,step, filterwidth, components )
        cubesize = [cubedimension, cubedimension, cubedimension]
        cubecount = 0
        args = []
        for xcorner in range (ci.xstart,ci.xstart + ci.xlen, cubedimension):
            for ycorner in range (ci.ystart,ci.ystart + ci.ylen, cubedimension):
                for zcorner in range (ci.zstart,ci.zstart + ci.zlen, cubedimension):
                    print("Gettting cube: ", xcorner, ycorner, zcorner)
                    cubecount = cubecount + 1
                    corners = [xcorner, ycorner, zcorner]
                    args.append([corners, ci, cubesize, timestep, step, filterwidth, components, datafield])

        cubesfinished = 0
        for arg in args:
            cube = self.getfilecube(args[cubesfinished])
            fullcube.addData(cube, ci)
            cubesfinished=cubesfinished+1
            if (selftask != None): #Update status for progress bar when tasked
                selftask.update_state(state='PROGRESS', meta={'cubes': cubesfinished, 'total': cubecount})
        #Multiprocessing
        #if (cubecount > 4):
        #    cubecount = 4 #limit to only 8 processes
        #print("Multiprocessing... Cubes: ", (cubecount))
        #p = Pool(cubecount)

        #cubelist = p.map(self.getfilecube, args)
        #self.getfilecube(args[0])
        #print("Mapped")
        #import pdb; pdb.set_trace();
        #p.join()
        #progress = 0
        #for cube in cubelist:
            #cubefile = open( filename , 'rb')
            #cube = pickle.load(cubefile)
            #print ("Cube: " % cube)
            #fullcube.addData(cube, ci)
            #print("Added:", cube)
            #progress = progress +1

        #connection.close()
            #fullcube.addData(cube, ci)
        #p.join()
        print("Complete")
        #connection.close()
        #p.close() #frees the ram
        fullcube.trim(ci)
        print("Trimming complete, returning cube")
        return fullcube.data
Ejemplo n.º 29
0
def main():
    cube = Cube()

    moves = [choice(POSSIBLE_MOVES) for _ in range(10)]
    for move in moves:
        cube.rotate(move)
        print(cube.get_slim_representation())
        print(cube)
Ejemplo n.º 30
0
    def __init__(self, cubesize):
        """Create empty array of cubesize"""

        # call the base class constructor
        Cube.__init__(self, cubesize)
        self.data = np.zeros(self.cubesize, dtype=np.uint32)
        # variable that describes when a cube is created from zeros rather than loaded from another source
        self._newcube = False
Ejemplo n.º 31
0
 def __init__(self):
     self.cube = Cube(-1, 2)
     self.angle_x = 0
     self.angle_y = 0
     self.clock = pygame.time.Clock()
     self.gameDisplay = pygame.display.set_mode \
         ((display_width, display_height), DOUBLEBUF | OPENGL)
     open('output.txt', 'w').close()
Ejemplo n.º 32
0
def main():
    sidel = getInput()
    cube = Cube(sidel)

    area = cube.surfaceArea()
    vol = cube.volume()

    print("Area: {0} \nVolume: {1}".format(area, vol))
def test_exercise():
    os.chdir('src')

    from cube import Cube
    sand = Cube(3)

    assert sand.volume() == 27
    assert str(sand) == "The length of the edge is 3 and the volume 27"
Ejemplo n.º 34
0
    def test_cube_has_active_neighbors(self):
        _map = []
        _map.append(Cube(0, 0, 0, "#"))
        _map.append(Cube(1, 0, 0, "."))
        _map.append(Cube(2, 0, 0, "#"))

        _map[1].collectNeighbors(_map)
        self.assertEqual(2, _map[1].activeNeighbors)
Ejemplo n.º 35
0
 def getrawdata(self, ci, timestep, datafield):
     cubesize  = [ci.zlen, ci.ylen, ci.xlen]
     filterwidth = ci.filter
     corner = [ci.xstart, ci.ystart, ci.zstart]
     step = [ci.xstep, ci.ystep, ci.zstep]
     cube = Cube(corner, cubesize,step, filterwidth, 3 )
     cube.getCubeData(ci, datafield, timestep)
     return cube.data
Ejemplo n.º 36
0
def random_cube():
    """
    :return: A new scrambled Cube
    """
    scramble_moves = " ".join(random.choice(MOVES) for _ in xrange(200))
    a = Cube(SOLVED_CUBE_STR)
    a.sequence(scramble_moves)
    return a
Ejemplo n.º 37
0
  def __init__(self, cubesize):
    """Create empty array of cubesize"""

    # call the base class constructor
    Cube.__init__( self, cubesize )
    self.data = np.zeros(self.cubesize, dtype=np.uint32)
    # variable that describes when a cube is created from zeros rather than loaded from another source
    self._newcube = False
Ejemplo n.º 38
0
  def __init__(self, cubesize=[128,128,16]):
    """Create empty array of cubesize"""

    # call the base class constructor
    Cube.__init__(self,cubesize)
    # note that this is self.cubesize (which is transposed) in Cube
    self.data = np.zeros ( self.cubesize, dtype=np.uint64 )
    # variable that describes when a cube is created from zeros rather than loaded from another source
    self._newcube = False
Ejemplo n.º 39
0
 def find_orange_corner(self, img_hsv, kinect, polyline, is_left):
     stencil = FormStencil([polyline])
     img_hsv_mask = stencil.apply(img_hsv)
     orange_corner = Cube('orange')
     if is_left:
         return orange_corner.find_position(img_hsv_mask, kinect,
                                            self.PIXEL_SHIFT)
     return orange_corner.find_position(img_hsv_mask, kinect,
                                        -self.PIXEL_SHIFT)
Ejemplo n.º 40
0
    def __init__(self, cubesize=[128, 128, 16], timerange=[0, 0]):
        """Create empty array of cubesize"""

        # call the base class constructor
        Cube.__init__(self, cubesize)
        # note that this is self.cubesize (which is transposed) in Cube
        self.timerange = timerange
        self.data = np.zeros([self.timerange[1] - self.timerange[0]] + self.cubesize, dtype=np.float32)

        # variable that describes when a cube is created from zeros
        #  rather than loaded from another source
        self._newcube = False
Ejemplo n.º 41
0
  def ingest ( self ):
    """Read the stack and ingest"""
    
    with closing (ocpcaproj.OCPCAProjectsDB()) as projdb:
      proj = projdb.loadToken(self.token)
    
    with closing (ocpcadb.OCPCADB(proj)) as db:

      ch = proj.getChannelObj(self.channel)
      # get the dataset configuration
      [[ximagesz, yimagesz, zimagesz],(starttime,endtime)] = proj.datasetcfg.imageSize(self.resolution)
      [xcubedim, ycubedim, zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[self.resolution]
      [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[self.resolution]
    
      # for all specified resolutions
      for resolution in range(0,1,1):

        # extract parameters for iteration
        numxtiles = ximagesz/self.tilesz[0]
        numytiles = yimagesz/self.tilesz[1]

        # Ingest in database aligned slabs in the z dimension
        for slice_number in range(0, zimagesz, zcubedim):

          slab = np.zeros ( [zcubedim,yimagesz,ximagesz], dtype=np.uint32 )
          # over all tiles in that slice
          for b in range(zcubedim):
            for ytile in range(numytiles):
              for xtile in range(numxtiles):

                # if we are at the end of the space, quit
                if slice_number+b <= zimagesz:
                  try:
                    filename = '{}{}/{}/{}/{}.png'.format(self.tilepath, resolution, slice_number+b+zoffset, ytile+17, xtile+16)
                    print "Opening filename {}".format(filename)
                    # add tile to stack
                    imgdata = np.asarray ( Image.open(filename, 'r').convert('RGBA') )
                    imgdata = np.left_shift(imgdata[:,:,3], 24, dtype=np.uint32) | np.left_shift(imgdata[:,:,2], 16, dtype=np.uint32) | np.left_shift(imgdata[:,:,1], 8, dtype=np.uint32) | np.uint32(imgdata[:,:,0])
                    slab [b,ytile*self.tilesz[1]:(ytile+1)*self.tilesz[1],xtile*self.tilesz[0]:(xtile+1)*self.tilesz[0]] = imgdata
                  except IOError, e:
                    print "Failed to open file {}".format(filename)
                    slab [b,ytile*self.tilesz[1]:(ytile+1)*self.tilesz[1],xtile*self.tilesz[0]:(xtile+1)*self.tilesz[0]] = np.zeros([self.tilesz[1], self.tilesz[0]], dtype=np.uint32)

          for y in range (0, yimagesz+1, ycubedim):
            for x in range (0, ximagesz+1, xcubedim):
              
              # getting the cube id and ingesting the data one cube at a time
              zidx = ocplib.XYZMorton ([x/xcubedim, y/ycubedim, (slice_number)/zcubedim])
              cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
              cube.zeros()

              xmin, ymin = x, y
              xmax = min (ximagesz, x+xcubedim)
              ymax = min (yimagesz, y+ycubedim)
              zmin = 0
              zmax = min(slice_number+zcubedim, zimagesz+1)
              cube.data[0:zmax-zmin,0:ymax-ymin,0:xmax-xmin] = slab[zmin:zmax, ymin:ymax, xmin:xmax]
              
              if cube.isNotZeros():
                db.putCube(ch, zidx, self.resolution, cube, update=True)
Ejemplo n.º 42
0
 def find_unsolved(self, cube, print_debug=False):
   unsolved = []
   for n in Cube.cw_neighbor_edges('up'):
     up_color = cube.get_color('up', n)
     if up_color != 'yellow':
       unsolved.append(Unsolved(n, 'up', None, 'up', n, None))
   return unsolved
Ejemplo n.º 43
0
 def solve_case(self, cube, unsolved, print_debug=False):
   case = unsolved[0]
   steps = []
   if case.source_face == 'up':
     steps.append(cube.get_simple_move(
         'up', case.source_edge, case.dest_edge))
     steps.append((case.dest_edge, 2))
   elif case.source_face == 'down':
     steps.append((case.source_edge, 2))
     steps.append(cube.get_simple_move(
         'up', case.source_edge, case.dest_edge))
     steps.append((case.dest_edge, 2))
   elif case.source_edge == 'up':
     neighbors = Cube.cw_neighbor_edges('up')
     index = neighbors.index(case.dest_edge)
     dest_edge_offset = neighbors[(index + 1) % 4]
     steps.append(cube.get_simple_move(
         'up', case.source_face, dest_edge_offset))
     steps.append((dest_edge_offset, 1))
     steps.append((case.dest_edge, 3))
     steps.append((dest_edge_offset, 3))
   else:
     face, times = cube.get_simple_move(case.source_face, case.source_edge, 'up')
     steps.append((face, times))
     steps.append(('up', 1))
     steps.append((face, -times % 4))
   return steps
Ejemplo n.º 44
0
def main():

  parser = argparse.ArgumentParser(description='Ingest the TIFF data')
  parser.add_argument('token', action="store", type=str, help='Token for the project')
  parser.add_argument('channel', action="store", type=str, help='Channel for the project')
  parser.add_argument('path', action="store", type=str, help='Directory with the image files')
  parser.add_argument('resolution', action="store", type=int, help='Resolution of data')
  parser.add_argument('--offset', action="store", type=int, default=0, help='Offset on disk')

  result = parser.parse_args()
  
  # Load a database
  with closing (ocpcaproj.OCPCAProjectsDB()) as projdb:
    proj = projdb.loadToken(result.token)

  with closing (ocpcadb.OCPCADB(proj)) as db:

    ch = proj.getChannelObj(result.channel)
    # get the dataset configuration
    [[ximagesz, yimagesz, zimagesz],(starttime,endtime)] = proj.datasetcfg.imageSize(result.resolution)
    [xcubedim,ycubedim,zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[result.resolution]
    [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[result.resolution]

    # Get a list of the files in the directories
    for slice_number in range (zoffset, zimagesz+1, zcubedim):
      slab = np.zeros([zcubedim, yimagesz, ximagesz ], dtype=np.uint8)
      for b in range(zcubedim):
        if (slice_number + b <= zimagesz):
          try:
            # reading the raw data
            file_name = "{}{:0>5}.tif".format(result.path, (slice_number + b))
            # silvestri15
            #file_name = "{}full_{:0>6}.tif".format(result.path, slice_number + b + result.offset)
            print "Open filename {}".format(file_name)
            slab[b,:,:] = np.asarray(Image.open(file_name, 'r'))
          except IOError, e:
            print e
            slab[b,:,:] = np.zeros((yimagesz, ximagesz), dtype=np.uint8)

      for y in range ( 0, yimagesz+1, ycubedim ):
        for x in range ( 0, ximagesz+1, xcubedim ):

          # Getting a Cube id and ingesting the data one cube at a time
          zidx = ocplib.XYZMorton ( [x/xcubedim, y/ycubedim, (slice_number-zoffset)/zcubedim] )
          cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
          cube.zeros()

          xmin,ymin = x,y
          xmax = min ( ximagesz, x+xcubedim )
          ymax = min ( yimagesz, y+ycubedim )
          zmin = 0
          zmax = min(slice_number+zcubedim, zimagesz+1)

          cube.data[0:zmax-zmin,0:ymax-ymin,0:xmax-xmin] = slab[zmin:zmax, ymin:ymax, xmin:xmax]
          if cube.isNotZeros():
            db.putCube(ch, zidx, result.resolution, cube, update=True)

      slab = None
Ejemplo n.º 45
0
 def find_unsolved(self, cube, print_debug=False):
   unsolved = []
   for dest_edge, dest_edge2 in Cube.cw_corners_on_face('up'):
     #print dest_edge, dest_edge2
     if cube.get_color('up', dest_edge, dest_edge2) != 'yellow':
       corner_neighbors = Cube.cw_neighbor_corners(
           ('up', dest_edge, dest_edge2))
       #print corner_neighbors
       colors = [cube.get_color(face, edge, edge2)
           for face, edge, edge2 in corner_neighbors]
       #print colors
       yellow_index = colors.index('yellow')
       assert yellow_index == 1 or yellow_index == 2
       yellow_corner = corner_neighbors[yellow_index]
       unsolved.append(Unsolved(
           yellow_corner[0], yellow_corner[1], yellow_corner[2],
           'up', dest_edge, dest_edge2))
   return unsolved
Ejemplo n.º 46
0
 def sorter(u):
   source_cubie = (u.source_face, u.source_edge, u.source_edge2)
   dest_cubie = (u.dest_face, u.dest_edge, u.dest_edge2)
   if cube.is_cubie_in_layer(source_cubie, 'up'):
     assert dest_cubie[0] == 'down'
     cubie_above_dest = ('up', u.dest_edge, u.dest_edge2)
     if u.source_face != 'up':
       if Cube.same_cubie(source_cubie, cubie_above_dest):
         return 0
       else:
         return 1
     else:
       if Cube.same_cubie(source_cubie, cubie_above_dest):
         return 2
       else:
         return 3
   else:
     return 4
Ejemplo n.º 47
0
  def move_with_y_rotation(move, num_rotations=1):
    num_rotations = num_rotations % 4
    face, times = move
    if num_rotations == 0 or face == 'up' or face == 'down':
      return move

    up_cw_neighbor_edges = Cube.cw_neighbor_edges('up')
    new_face_index = (up_cw_neighbor_edges.index(face) - num_rotations) % 4
    return (up_cw_neighbor_edges[new_face_index], times)
Ejemplo n.º 48
0
def main():

  parser = argparse.ArgumentParser(description='Ingest the TIFF data')
  parser.add_argument('token', action="store", type=str, help='Token for the project')
  parser.add_argument('channel', action="store", type=str, help='Channel for the project')
  parser.add_argument('path', action="store", type=str, help='Directory with the image files')
  parser.add_argument('resolution', action="store", type=int, help='Resolution of data')

  result = parser.parse_args()
  
  # Load a database
  with closing (ndproj.NDProjectsDB()) as projdb:
    proj = projdb.loadToken(result.token)

  with closing (SpatialDB(proj)) as db:

    ch = proj.getChannelObj(result.channel)
    # get the dataset configuration
    [[ximagesz, yimagesz, zimagesz],(starttime,endtime)] = proj.datasetcfg.imageSize(result.resolution)
    [xcubedim,ycubedim,zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[result.resolution]
    [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[result.resolution]

    # Get a list of the files in the directories
    for slice_number in range (zoffset, zimagesz+1, zcubedim):
      slab = np.zeros([zcubedim, yimagesz, ximagesz ], dtype=np.uint32)
      for b in range(zcubedim):
        if (slice_number + b <= zimagesz):
          try:
            # reading the raw data
            file_name = "{}/{:0>4}.tif".format(result.path, slice_number+b)
            print "Open filename {}".format(file_name)
            img = Image.open(file_name, 'r').convert("RGBA")
            imgdata = np.asarray(img)
            slab[b,:,:] = np.left_shift(imgdata[:,:,3], 24, dtype=np.uint32) | np.left_shift(imgdata[:,:,2], 16, dtype=np.uint32) | np.left_shift(imgdata[:,:,1], 8, dtype=np.uint32) | np.uint32(imgdata[:,:,0])
          except IOError, e:
            print e
            imgdata = np.zeros((yimagesz, ximagesz), dtype=np.uint32)
            slab[b,:,:] = imgdata

      for y in range ( 0, yimagesz+1, ycubedim ):
        for x in range ( 0, ximagesz+1, xcubedim ):

          # Getting a Cube id and ingesting the data one cube at a time
          zidx = ndlib.XYZMorton ( [x/xcubedim, y/ycubedim, (slice_number-zoffset)/zcubedim] )
          cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
          cube.zeros()

          xmin = x
          ymin = y
          xmax = min ( ximagesz, x+xcubedim )
          ymax = min ( yimagesz, y+ycubedim )
          zmin = 0
          zmax = min(slice_number+zcubedim, zimagesz+1)

          cube.data[0:zmax-zmin,0:ymax-ymin,0:xmax-xmin] = slab[zmin:zmax, ymin:ymax, xmin:xmax]
          db.putCube(ch, zidx, result.resolution, cube, update=True)
Ejemplo n.º 49
0
  def find_unsolved(self, cube, print_debug=False):
    #print "Finding unsolved " + self.__class__.__name__
    unsolved = []
    for face in Cube.faces:
      for edge, edge2 in Cube.cw_corners_on_face(face):
        if cube.get_color(face, edge, edge2) == 'white':
          dest_face = 'down'

          other_color = cube.get_color(edge, face, edge2)
          dest_edge = cube.get_dest_face(other_color)

          other_color2 = cube.get_color(edge2, face, edge)
          dest_edge2 = cube.get_dest_face(other_color2)

          already_solved = Cube.corners_equal( \
              (face, edge, edge2), (dest_face, dest_edge, dest_edge2))
          if not already_solved:
            new_case = Unsolved(face, edge, edge2, dest_face, dest_edge, dest_edge2)
            #print new_case
            unsolved.append(new_case)

    def sorter(u):
      source_cubie = (u.source_face, u.source_edge, u.source_edge2)
      dest_cubie = (u.dest_face, u.dest_edge, u.dest_edge2)
      if cube.is_cubie_in_layer(source_cubie, 'up'):
        assert dest_cubie[0] == 'down'
        cubie_above_dest = ('up', u.dest_edge, u.dest_edge2)
        if u.source_face != 'up':
          if Cube.same_cubie(source_cubie, cubie_above_dest):
            return 0
          else:
            return 1
        else:
          if Cube.same_cubie(source_cubie, cubie_above_dest):
            return 2
          else:
            return 3
      else:
        return 4
      
    unsolved.sort(key=sorter)

    return unsolved
Ejemplo n.º 50
0
  def ingest(self):
    """ Read image stack and ingest """

    # Load a database
    with closing(ocpcaproj.OCPCAProjectsDB()) as projdb:
      proj = projdb.loadToken(self.token)

    with closing(ocpcadb.OCPCADB(proj)) as db:

      ch = proj.getChannelObj(self.channel_name)
      # get the dataset configuration
      [[ximagesz, yimagesz, zimagesz], (starttime, endtime)] = proj.datasetcfg.imageSize(self.resolution)
      [xcubedim, ycubedim, zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[self.resolution]
      [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[self.resolution]

      # Get a list of the files in the directories
      
      for slice_number in range(zoffset, zimagesz, zcubedim):
        slab = np.zeros([zcubedim, yimagesz, ximagesz], dtype=np.uint32)

        for b in range(zcubedim):
          
          if (slice_number + b <= zimagesz):
            file_name = "{}{}{:0>4}.tif".format(self.path, self.token, slice_number+b)
            print "Open filename {}".format(file_name)

            try:
              img = Image.open(file_name,'r')
              slab [b,:,:] = np.asarray(img)
            except IOError, e:
              print "Failed to open file %s" % (e)
              img = np.zeros((yimagesz,ximagesz), dtype=np.uint8)
              slab [b,:,:] = img

        for y in range(0, yimagesz + 1, ycubedim):
          for x in range(0, ximagesz + 1, xcubedim):

            # Getting a Cube id and ingesting the data one cube at a time
            zidx = ocplib.XYZMorton([x / xcubedim, y / ycubedim, (slice_number - zoffset) / zcubedim])
            cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
            cube.zeros()

            xmin = x
            ymin = y
            xmax = min(ximagesz, x + xcubedim)
            ymax = min(yimagesz, y + ycubedim)
            zmin = 0
            zmax = min(slice_number + zcubedim, zimagesz + 1)

            cube.data[0:zmax - zmin, 0:ymax - ymin, 0:xmax - xmin] = slab[zmin:zmax, ymin:ymax, xmin:xmax]
            from operator import sub
            corner = map(sub, [x,y,slice_number], [xoffset,yoffset,zoffset])
            if cube.data.any():
              db.annotateDense ( ch, corner, self.resolution, cube.data, 'O' )
Ejemplo n.º 51
0
class Environment(object):

    # Initialize a random cube
    def __init__(self, N):
        self.N = N
        self.cube = Cube(N=N)

    def suffle(self, rand_nb=None, fixed_action=None):
        if rand_nb is not None:
            moves = self.cube.randomize(rand_nb)
            return moves
        self.perform_action(fixed_action)
        return fixed_action

    # Make a move and get a reward:
    # 0 is the cube is not finish
    # 1 is the cube is done
    def perform_action(self, action):
        [f, l, d] = action
        self.cube.move(f, l, d)
        return self.reward()

    def reward(self,):
        return self.cube.finish()

        # if self.cube.finish():
        #     return 1.
        # for i in range(6):
        #     if np.array_equal(self.cube.stickers[i, :, :], i * np.ones((self.N, self.N))):
        #         return  0.1
        # return 0.

    # Select a random_action
    def random_action(self,):
        f = np.random.randint(6)
        l = np.random.randint(self.N)
        d = 1 + np.random.randint(3)
        return [f, l, d]

    def get_state(self,):
        return self.cube.stickers
Ejemplo n.º 52
0
  def find_unsolved(self, cube, print_debug=False):
    edges = []
    edges.extend([('up', f) for f in Cube.cw_neighbor_edges('up')])
    edges.extend([c for c in Cube.cw_corners_on_face('up')])
    edges.extend([('down', f) for f in Cube.cw_neighbor_edges('down')])

    unsolved = []
    for f1, f2 in edges:
      color1 = cube.get_color(f1, f2)
      color2 = cube.get_color(f2, f1)
      dest_f1 = cube.get_dest_face(color1)
      dest_f2 = cube.get_dest_face(color2)
      already_solved = (f1 == dest_f1 and f2 == dest_f2)
      if not already_solved:
        assert f1 != 'down' and f2 != 'down'
        assert dest_f1 != 'down' and dest_f2 != 'down'
        if dest_f1 != 'up' and dest_f2 != 'up':
          unsolved.append(Unsolved(f1, f2, None, dest_f1, dest_f2, None))

    def sorter(u, print_debug=False):
      if cube.is_cubie_in_layer((u.source_face, u.source_edge), 'up'):
        if u.source_face == 'up':
          non_up = u.source_edge
          non_up_dest = u.dest_edge
        else:
          non_up = u.source_face
          non_up_dest = u.dest_face
        if non_up == non_up_dest:
          return 0  # in top layer and aligned
        else:
          return 1  # in top layer but not aligned
      else:
        return 2  # not in top layer

    # NOTE: Sorting by the worst-case number of times "solve_case" must be
    # invoked to solve each cubie.
    unsolved.sort(key=sorter)

    return unsolved
Ejemplo n.º 53
0
def buildStack(token, channel, res):
  """Build the hierarchy of images"""

  with closing (ocpcaproj.OCPCAProjectsDB()) as projdb:
    proj = projdb.loadToken(token)
  
  with closing (ocpcadb.OCPCADB(proj)) as db:

    ch = proj.getChannelObj(channel)
    high_res = proj.datasetcfg.scalinglevels
    for cur_res in range(res, high_res+1):

      # Get the source database sizes
      [[ximagesz, yimagesz, zimagesz], timerange] = proj.datasetcfg.imageSize(cur_res)
      [xcubedim, ycubedim, zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[cur_res]
      [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[cur_res]

      biggercubedim = [xcubedim*2,ycubedim*2,zcubedim]

      # Set the limits for iteration on the number of cubes in each dimension
      xlimit = (ximagesz-1) / xcubedim + 1
      ylimit = (yimagesz-1) / ycubedim + 1
      zlimit = (zimagesz-1) / zcubedim + 1

      for z in range(zlimit):
        for y in range(ylimit):
          for x in range(xlimit):

            # cutout the data at the -1 resolution
            olddata = db.cutout(ch, [ x*2*xcubedim, y*2*ycubedim, z*zcubedim], biggercubedim, cur_res-1 ).data
            # target array for the new data (z,y,x) order
            newdata = np.zeros([zcubedim,ycubedim,xcubedim], dtype=np.uint16)

            for sl in range(zcubedim):

              # Convert each slice to an image
              slimage = Image.frombuffer ( 'I;16', (xcubedim*2,ycubedim*2), olddata[sl,:,:].flatten(), 'raw', 'I;16', 0, 1 )

              # Resize the image
              newimage = slimage.resize ( [xcubedim,ycubedim] )
              
              # Put to a new cube
              newdata[sl,:,:] = np.asarray ( newimage )

            zidx = ocplib.XYZMorton ( [x,y,z] )
            cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
            cube.zeros()

            cube.data = newdata
            print "Inserting Cube {} at res {}".format(zidx, cur_res)
            db.putCube(ch, zidx, cur_res, cube, update=True)
Ejemplo n.º 54
0
  def ingest(self, channel_name):
    """ Read image stack and ingest """
    
    # Load a database
    with closing(ocpcaproj.OCPCAProjectsDB()) as projdb:
      proj = projdb.loadToken(self.token)

    with closing(ocpcadb.OCPCADB(proj)) as db:

      ch = proj.getChannelObj(channel_name)
      # get the dataset configuration
      [[ximagesz, yimagesz, zimagesz], (starttime, endtime)] = proj.datasetcfg.imageSize(self.resolution)
      [xcubedim, ycubedim, zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[self.resolution]
      [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[self.resolution]

      # Get a list of the files in the directories
      file_name = "{}{}.tif".format(self.path, channel_name)
      print "Open filename {}".format(file_name)

      imgdata = tifffile.imread(file_name)

      for slice_number in range(zoffset, zimagesz + 1, zcubedim):
        slab = np.zeros([zcubedim, yimagesz, ximagesz], dtype=np.uint32)
        for b in range(zcubedim):
          if (slice_number + b <= zimagesz):

            if (slice_number + b) < zimagesz:

                slab[b, :, :] = imgdata[(slice_number + b), :, :]
            else:
                imgdata = np.zeros((yimagesz, ximagesz), dtype=np.uint32)
                slab[b, :, :] = imgdata

        for y in range(0, yimagesz + 1, ycubedim):
          for x in range(0, ximagesz + 1, xcubedim):

            # Getting a Cube id and ingesting the data one cube at a time
            zidx = ocplib.XYZMorton([x / xcubedim, y / ycubedim, (slice_number - zoffset) / zcubedim])
            cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType())
            cube.zeros()

            xmin = x
            ymin = y
            xmax = min(ximagesz, x + xcubedim)
            ymax = min(yimagesz, y + ycubedim)
            zmin = 0
            zmax = min(slice_number + zcubedim, zimagesz + 1)

            cube.data[0:zmax - zmin, 0:ymax - ymin, 0:xmax - xmin] = slab[zmin:zmax, ymin:ymax, xmin:xmax]
            db.putCube(ch, zidx, self.resolution, cube, update=True)
Ejemplo n.º 55
0
def main():

  parser = argparse.ArgumentParser(description='Ingest the TIFF data')
  parser.add_argument('token', action="store", type=str, help='Token for the project')
  parser.add_argument('channel', action="store", type=str, help='Channel for the project')
  parser.add_argument('path', action="store", type=str, help='Directory with the image files')
  parser.add_argument('resolution', action="store", type=int, help='Resolution of data')

  result = parser.parse_args()

  # Load a database
  with closing (ocpcaproj.OCPCAProjectsDB()) as projdb:
    proj = projdb.loadToken(result.token)

  with closing (ocpcadb.OCPCADB(proj)) as db:

    ch = proj.getChannelObj(result.channel)
    # get the dataset configuration
    [[ximagesz, yimagesz, zimagesz],(starttime,endtime)] = proj.datasetcfg.imageSize(result.resolution)
    [xcubedim,ycubedim,zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[result.resolution]
    [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[result.resolution]

    file_name = "{}".format(result.path)
    tif_file = tifffile.imread(file_name)
    slice_number = 0
    # Get a list of the files in the directories

    for iteration_number in range(starttime, endtime):

      slab = np.zeros([zcubedim, yimagesz, ximagesz], dtype=np.uint16)
      import pdb; pdb.set_trace()  
      slab[slice_number,:,:] = tif_file[iteration_number,:,:]

      for y in range ( 0, yimagesz+1, ycubedim ):
        for x in range ( 0, ximagesz+1, xcubedim ):

          # Getting a Cube id and ingesting the data one cube at a time
          zidx = ndlib.XYZMorton ( [x/xcubedim, y/ycubedim, (slice_number-zoffset)/zcubedim] )
          cube = Cube.getCube(cubedim, ch.getChannelType(), ch.getDataType(), timerange=[0,1])
          cube.zeros()

          xmin = x
          ymin = y
          xmax = min ( ximagesz, x+xcubedim )
          ymax = min ( yimagesz, y+ycubedim )
          zmin = 0
          zmax = min(slice_number+zcubedim, zimagesz+1)

          cube.data[0:zmax-zmin,0:ymax-ymin,0:xmax-xmin] = slab[zmin:zmax, ymin:ymax, xmin:xmax]
          db.putTimeCube(ch, zidx, iteration_number, result.resolution, cube, update=False)
Ejemplo n.º 56
0
 def find_unsolved(self, cube, print_debug=False):
   unsolved = []
   num_unsolved = 0
   for n in Cube.cw_neighbor_edges('up'):
     non_up_color = cube.get_color(n, 'up')
     dest_face = cube.get_dest_face(non_up_color)
     if dest_face != n:
       num_unsolved += 1
     unsolved.append(Unsolved(n, 'up', None, dest_face, 'up', None))
   # either return all edges, or none of them
   if num_unsolved > 0:
     return unsolved
   else:
     return []
Ejemplo n.º 57
0
 def get_rgb_calibration(self, img_hsv, kinect, form_filter=True):
     rgb_result = np.zeros((img_hsv.shape[0], img_hsv.shape[1], 3), np.uint8)
     orange_cube = Cube('orange')
     green_cube = Cube('forest_green')
     purple_cube = Cube('purple')
     if form_filter == False:
         orange_cube.form_filter = FormFilter([0, 0, 1, 1])
         green_cube.form_filter = FormFilter([0, 0, 1, 1])
         purple_cube.form_filter = FormFilter([0, 0, 1, 1])
     orange_filter = orange_cube.apply_filters(img_hsv)
     green_filter = green_cube.apply_filters(img_hsv)
     purple_filter = purple_cube.apply_filters(img_hsv)
     for i in range(180, rgb_result.shape[0]-205):
         for j in range(0, rgb_result.shape[1]):
             rgb_result[i, j][1] += int(orange_filter[i, j] * 0.5)
             rgb_result[i, j][2] += orange_filter[i, j]
             rgb_result[i, j][0] += int(purple_filter[i, j] * 0.5)
             rgb_result[i, j][2] += int(purple_filter[i, j] * 0.5)
             rgb_result[i, j][1] += int(green_filter[i, j] * 0.25)
     if kinect is not None:
         rgb_result = FormStencil(TABLE_STENCIL.get(kinect.table)).apply(rgb_result)
     return rgb_result
Ejemplo n.º 58
0
def buildStack(token, channel, res, base_res):
  """ build a zoom hierarchy of images """
  scaling = 2**(base_res-res)
  with closing (ocpcaproj.OCPCAProjectsDB()) as projdb:
    proj = projdb.loadToken(token)

  with closing(ocpcadb.OCPCADB(proj)) as db:
    ch = proj.getChannelObj(channel)
    
    # get db sizes
    [[ximagesz, yimagesz, zimagesz], timerange] = proj.datasetcfg.imageSize(base_res)
    [xcubedim, ycubedim, zcubedim] = cubedim = proj.datasetcfg.getCubeDims()[base_res]

    [xoffset, yoffset, zoffset] = proj.datasetcfg.getOffset()[base_res]

    newcubedim = proj.datasetcfg.getCubeDims()[res]

    xlimit = (ximagesz-1) / xcubedim + 1
    ylimit = (yimagesz-1) / ycubedim + 1
    zlimit = (zimagesz-1) / zcubedim + 1
  
    # iterate over the old cube 
    for z in range(zlimit):
      for y in range(ylimit):
        for x in range(xlimit):
          # cutout data
          old_data = db.cutout( ch, [x*xcubedim, y*ycubedim, z*zcubedim], cubedim, base_res ).data

          #new_data = zoomIn(old_data, scaling)
          new_data = cZoomIn(old_data, base_res-res)

          newzsize = new_data.shape[0] / newcubedim[2] #old_data.shape[0]
          newysize = new_data.shape[1] / newcubedim[1] #old_data.shape[1]
          newxsize = new_data.shape[2] / newcubedim[0] #old_data.shape[2]
          #print "sizes: {} {} {}".format(newxsize, newysize, newzsize) 
          for z2 in range(newzsize):
            for y2 in range(newysize):
              for x2 in range(newxsize):
                #print "{} {} {}".format(x*newxsize+x2,y*newysize+y2,z*newzsize+z2)
                zidx = ndlib.XYZMorton([x*newxsize+x2, y*newysize+y2, z*newzsize+z2])
                cube = Cube.getCube(newcubedim, ch.getChannelType(), ch.getDataType())
                cube.zeros()
                cube.data = new_data[z2*newcubedim[2]:(z2+1)*newcubedim[2], y2*newcubedim[1]:(y2+1)*newcubedim[1], x2*newcubedim[0]:(x2+1)*newcubedim[0]]
                #print "Grabbing cube from [{}:{} , {}:{}, {}:{}]".format(z2*newcubedim[2],(z2+1)*newcubedim[2], y2*newcubedim[1],(y2+1)*newcubedim[1], x2*newcubedim[0],(x2+1)*newcubedim[0])
                print "Inserting Cube {} at res {}".format(zidx, res)
                db.putCube(ch, zidx, res, cube, update=True)
Ejemplo n.º 59
0
 def attempt_get_position(self, kinect, attempt_no):
     new_position = None
     img_hsv = self.get_masked_hsv(kinect, attempt_no)
     purple_corner = Cube('purple')
     green_corner = Cube('forest_green')
     purple_position = purple_corner.find_position(img_hsv, kinect)
     green_position = green_corner.find_position(img_hsv, kinect)
     if purple_corner.is_valid_position(purple_position):
         new_position = self.test_other_corners(img_hsv, kinect, purple_corner, 0)
     elif green_corner.is_valid_position(green_position):
         new_position = self.test_other_corners(img_hsv, kinect, green_corner, math.pi / 2)
     return new_position
Ejemplo n.º 60
0
    def start(self):
        ## Reference for the Threaded serial adquisition
        #
        # Threaded adquisition for a serial device with interrupts
        # using Qt4 signals
        self.data = SerialThread(str(self.ui.cBox_IMU.currentText()))
        self.data.openPort(str(self.ui.cBox_Port.currentText()),
                           int(self.ui.cBox_Speed.currentText()))
        ## Register the data object with the cube
        self.cube = Cube(self.data)

        # start file
        if self.ui.chBox_export.isChecked():
            ## export data
            self.csv = CSVExport()
            self.ui.statusbar.showMessage("Exporting data")
        else:
            self.ui.statusbar.showMessage("Adquiring data")

        # start data thread
        self.data.start()
        # dataThread new data signal
        self.connect(self.data, QtCore.SIGNAL('newData()'),
                     self.updateData)
        # update UI
        self.setUILocked(True)
        # start timer for updating plot
        self.timer.start(20)
        # start timer every second for activity
        self.timerActivity.start(1000)

        ## Reference for the activity detection algorithm
        #
        # Activity detection algorithm propossed by Dr. Pablo Reyes
        self.activity = ActivityDetection(70, 175, 20, .02)

        ## Reference for the fall detection algorithm
        #
        # Fall detection algorithm propossed by Dr. Pablo Reyes
        self.fall = FallDetection(.02, 2.8, .65)
        #~ self.fall = FallDetection(.02, 2.0, .65)

        ## Reference for
        self.posture = Posture()