Exemple #1
0
def main():
    key = Cache.generate_key(str(Config()))
    if Cache.check(key):
        data = Cache.get(key)
        points = data['points']
        network = data['network']
    else:
        pass
        # get points from trajectories
        preprocessor = Preprocessor(Config.DATASET_ROOT_DIR,
                                    Config.DATASET_SCALE)
        points = preprocessor.get_points()

        # use coherence expanded algorithm to form clusters
        clusters = Cluster(points).coherence_expanding()
        network = TransferNetwork(points, clusters)

        # derive transfer probability
        tp = TransferProbability(network)
        tp.derive()

        # save points and network to cache
        Cache.save(key, {"points": points, "network": network})

    # show the distribution of transfer probability
    figure = Figure(width=8)
    figure.transfer_probability(network, 8).show()

    # search the most popular route
    mpr = MostPopularRoute(network)
    route = mpr.search(0, 4)
    print(route)
    figure = Figure()
    figure.most_popular_route(points, network, route).show()
Exemple #2
0
    def __init__(self):
        self.game_score = 0
        self.game_state = ""
        self.game_figures = [Figure(0, 0), Figure(0, 0)]
        self.game_field = []

        self.screen = pygame.display.set_mode(size)
        self.font = pygame.font.SysFont('arial', 25, False, False)
        self.big_font = pygame.font.SysFont('arial', 65, False, False)
Exemple #3
0
    def create_figure(self):
        """Create figure and next figure fu9nction"""
        if self.next_figure is not None:
            self.control.canvas_next.remove_figure(self.next_figure.shifted())
            self.current_figure = self.next_figure
        else:
            self.current_figure = Figure()

        # Draw next figure
        self.next_figure = Figure()
        self.control.canvas_next.hold_figure(self.next_figure.shifted())
        self.control.canvas_next.redraw()
Exemple #4
0
def atangent(figure: Figure, radian_mode: bool = True):
    if radian_mode:
        value = math.atan(figure.value)
        error = figure.error / (1 + math.pow(figure.value, 2))
        return Figure(value,
                      error,
                      name="\\atan \\left( " + figure.name + " \\right)")

    else:
        value = _to_degree(math.atan(figure.value))
        error = _to_degree(figure.error / (1 + math.pow(figure.value, 2)))
        return Figure(value,
                      error,
                      name="\\atan \\left( " + figure.name + " \\right)")
Exemple #5
0
def sine(figure: Figure, radian_mode: bool = True):
    if radian_mode:
        value = math.sin(figure.value)
        error = math.cos(figure.value) * figure.error
        return Figure(value,
                      error,
                      name="\\sin \\left( " + figure.name + " \\right)")

    else:
        value = math.sin(_to_radian(figure.value))
        error = math.cos(_to_radian(figure.value)) * _to_radian(figure.error)
        return Figure(value,
                      error,
                      name="\\sin \\left( " + figure.name + " \\right)")
Exemple #6
0
def acosine(figure: Figure, radian_mode: bool = True):
    if radian_mode:
        value = math.acos(figure.value)
        error = figure.error / math.sqrt(1 - math.pow(figure.value, 2))
        return Figure(value,
                      error,
                      name="\\acos \\left( " + figure.name + " \\right)")

    else:
        value = _to_degree(math.acos(figure.value))
        error = _to_degree(figure.error /
                           math.sqrt(1 - math.pow(figure.value, 2)))
        return Figure(value,
                      error,
                      name="\\acos \\left( " + figure.name + " \\right)")
Exemple #7
0
def tangent(figure: Figure, radian_mode: bool = True):
    if radian_mode:
        value = math.tan(figure.value)
        error = figure.error / math.pow(math.cos(figure.value), 2)
        return Figure(value,
                      error,
                      name="\\tan \\left( " + figure.name + " \\right)")

    else:
        value = math.tan(_to_radian(figure.value))
        error = _to_radian(figure.error) / math.pow(
            math.cos(_to_radian(figure.value)), 2)
        return Figure(value,
                      error,
                      name="\\tan \\left( " + figure.name + " \\right)")
Exemple #8
0
    def right_offset(self) -> Figure:
        """Generate the offset for right direction.

        Returns:
            Figure: generated offset-Figure object
        """
        return Figure(self.fg.size, 0, self.fg.size, self.fg.color)
Exemple #9
0
    def test_figure_move_right(self):
        f = Figure()

        cells = f.move_right()
        for idx, cell in enumerate(f.cells):
            self.assertEqual(cells[idx][0] - 1, cell[0])
            self.assertEqual(cells[idx][1], cell[1])
Exemple #10
0
    def newfig(self, num=None):
        if num is None:
            if len(self.figs) > 0:
                num = max(self.figs.keys()) + 1
            else:
                num = 1
        thisFig = Figure(size=(600, 400))
        thisFig.show()
        win = gtk.Window()
        win.set_title("Figure %d" % num)
        win.connect("destroy", lambda *args: win.destroy())
        win.set_border_width(5)

        vbox = gtk.VBox(spacing=3)
        win.add(vbox)
        vbox.show()
        vbox.pack_start(thisFig)

        toolbar = NavigationToolbar(thisFig, win)
        toolbar.show()
        vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)
        figwin = FigureWin(thisFig, win, vbox, toolbar)
        self.figs[num] = figwin
        win.show()
        return figwin
Exemple #11
0
    def down_offset(self) -> Figure:
        """Generate the offset for down direction.

        Returns:
            Figure: generated offset-Figure object
        """
        return Figure(0, self.fg.size, self.fg.size, self.fg.color)
Exemple #12
0
def load( manipulator, filename ):

    try:
        dom = minidom.parse( filename )
    except IOError:
        print "Error. Can't read", filename
        return False

    manipulator.items = []
    for item in dom.getElementsByTagName('item'):
        
        i = None
        if item.hasAttribute('figure'):
            i = Figure( item.getAttribute('figure').encode() )
        elif item.hasAttribute('text'):
            i = TextItem( item.getAttribute('text').encode() )

        pos = item.getAttribute('pos').encode().split(',')
        pos = map( float, pos )
        i.position.setTranspose( pos[0],pos[1], 1 )
        i.refreshTransform()
        manipulator.items.append( i )
    
    dom.unlink()

    refnames.reset()

    debug('save', 'loaded from', filename )
    
    return True

        
Exemple #13
0
 def __init__(self, menu: Menu, lan):
     self.figure = Figure([])  # type: Figure
     self.stage = Stage()  # type: Stage
     self.stage.block_drawer = WiredBlockDrawer()
     self.figure.block_drawer = GhostBlockDrawer()
     self.menu = menu
     self.lan = lan
Exemple #14
0
    def test_find_complete_lines(self):
        tmp = tkinter.Frame(borderwidth=3, relief="solid")
        ttrs = CanvasGame(tmp,
                          width=400,
                          height=600,
                          borderwidth=3,
                          relief="solid",
                          bg="white",
                          rows=24,
                          columns=16,
                          cell=25)
        # fill line
        for j in range(ttrs.columns):
            ttrs.matrix[j][ttrs.rows - 1] = "blue"
            ttrs.matrix[j][ttrs.rows - 2] = "red"

        f = Figure()
        f.cells.append((1, ttrs.rows - 1))
        f.cells.append((1, ttrs.rows - 2))

        self.assertTrue(ttrs.line_complete(ttrs.rows - 1))

        count = ttrs.find_complete_lines(f)

        self.assertEqual(count, 2)
Exemple #15
0
 def add_block(self, position=None):
     block = Figure(self.board)
     block.bindStrategy(FlagStrategy())
     if position != None:
         block.strategy.placeIt(y=position[0], x=position[1], soft=True)
     else:
         block.strategy.placeIt(soft=True)
     block.color = -1
     return block
def from_yaml(data, filename="from_yaml"):
    card = Card()
    card.filename = filename
    for key, val in load(data).items():
        setattr(card, key, val)
    setattr(card, "figure_parsed", [
        Figure(line, getattr(card, "figure_source"))
        for line in getattr(card, "figure")
    ])
    return card
Exemple #17
0
    def eventAddVariable(self):
        fig = Figure(let.Variable())

        # Set position to center of view
        v = self.centerOfView()
        fig.position.setTranspose(v[0], v[1], 1)
        fig.refreshTransform()

        self.items.insert(0, fig)
        self.invalidate()
Exemple #18
0
 def setupBoard(self):
     for i in range(0, self.boardWith):
         self.board[1][i] = Figure(0, i, 1, True)
     for i in range(0, self.boardWith):
         self.board[self.boardHight - 2][i] = Figure(0, i, 6, False)
     for i in range(2):
         if i == 0:
             blackColor = True
             useIndex = 0
         else:
             blackColor = False
             useIndex = 7
         self.board[useIndex][0] = Figure(1, 0, useIndex, blackColor)
         self.board[useIndex][1] = Figure(2, 1, useIndex, blackColor)
         self.board[useIndex][2] = Figure(3, 2, useIndex, blackColor)
         self.board[useIndex][3] = Figure(4, 3, useIndex, blackColor)
         self.board[useIndex][4] = Figure(5, 4, useIndex, blackColor)
         self.board[useIndex][5] = Figure(3, 5, useIndex, blackColor)
         self.board[useIndex][6] = Figure(2, 6, useIndex, blackColor)
         self.board[useIndex][7] = Figure(1, 7, useIndex, blackColor)
def figure(idx=None, *args, **kwargs):
    """
	Creates a new figure or moves the focus to an existing figure.

	@type  idx: integer
	@param idx: a number identifying a figure

	@rtype: Figure
	@return: currently active figure
	"""

    return Figure(idx, *args, **kwargs)
Exemple #20
0
def fig(name, title=''):
    '''Create and return new Figure window with internal @name
    If @title is True, automatically set to @name (default no title)
    Set window title to @title if string.
    '''
    fig_ = Figure(name).new()
    fig_.clear()
    if title is True:
        title = name
    if title:
        plt.title(title)
    return fig_
Exemple #21
0
def from_yaml(data, filename="from_yaml"):
    card = Card()
    card.filename = filename
    for key, val in load(data).items():
        if key == "tag":
            setattr(card, "tags", [val])
            continue
        if type(getattr(Card, key)) is int:
            val = int(val)
        setattr(card, key, val)
    setattr(card, "figure_parsed", [Figure(line, getattr(card, "figure_source")) for line in getattr(card, "figure")])
    return card
Exemple #22
0
    def generate_figures(self, chess_board):
        w_figures = []
        b_figures = []

        w_names = ["R1", "H1", "B1", "Q1", "K1", "B2", "H2", "R2"]
        b_names = ["R1", "H1", "B1", "Q1", "K1", "B2", "H2", "R2"]

        for i in range(8):
            w_figures.append(
                Figure(w_names[i], chess_board, chr(ord('A') + i), 1, "white"))
            b_figures.append(
                Figure(b_names[i], chess_board, chr(ord('A') + i), 8, "black"))

        for i in range(8):
            w_figures.append(
                Figure("P" + str(i + 1), chess_board, chr(ord('A') + i), 2,
                       "white"))
            b_figures.append(
                Figure("P" + str(i + 1), chess_board, chr(ord('A') + i), 7,
                       "black"))

        return w_figures, b_figures
def find_relatives(soup, pattern):
    tags = soup.find('th', {
        'scope': 'row'
    }, text=re.compile(pattern)).parent.find_all('a')
    relatives = set()
    for tag in tags:
        wiki_extension = (tag['href'].encode('utf-8').strip().replace(
            '/wiki/', ''))
        name = unwikify_name(wiki_extension)
        if any(c.isalpha() for c in name) and '#' not in wiki_extension:
            relative = Figure(name, wiki_extension)
            relatives.add(relative)
    return relatives
Exemple #24
0
    def draw_figure(self):
        """
        Draws molecule through Molecule() and then puts the final figure together with
        Figure().
        """
        self.molecule = Molecule(self.topol_data)

        self.figure = Figure(self.molecule, self.topol_data, self.hbonds)
        self.figure.add_bigger_box()
        self.figure.manage_the_plots()
        self.figure.draw_hydrogen_bonds()
        self.figure.draw_white_circles()
        self.figure.put_everything_together()
        self.figure.write_final_draw_file(self.output_name)
Exemple #25
0
 def setup(self, s=None):
     # setup obstacles
     for i in range(self.obstacle_count):
         obs = self.add_block()
         self.board.obstacles.append(obs)
     # setup flag
     self.Flag = Figure(self.board)
     self.Flag.bindStrategy(FlagStrategy())
     if self.goal == None:
         self.Flag.strategy.placeIt()
         self.goal = self.Flag.position()
     else:
         self.Flag.strategy.placeIt(y=self.goal[0], x=self.goal[1])
     self.Flag.color = 2
     # setup navigator
     self.Navigator = Figure(self.board)
     if s == None: s = NaviStrategy(goal=(self.goal[0], self.goal[1]))
     self.Navigator.bindStrategy(s)
     self.Navigator.strategy.placeIt()
     self.Navigator.color = 3
     _, dist_test = self.Navigator.strategy.get_input()
     if dist_test < self.board.height - 1:
         self.reset()
Exemple #26
0
 def __init__(self, data, metadata={}, roi={}):
   self._img = copy.copy(data)
   self.metadata = dict(metadata)
   self._donorROIName = Stack.defaultDonorROI
   self._acceptorROIName = Stack.defaultAcceptorROI
   self._figure = Figure()
   self._roi = roi
   if not roi:
     self.addROI(*self.defaultROI.values())
   self._frame_iter = cycle(range(self.frames))
   if metadata:
     self.origin = (self.metadata['roileft'],self.metadata['roibottom'])
     if self._img.shape != (self.metadata['frames'],self.metadata['height'],self.metadata['width']):
       raise StackError, ".img file and .cam file dimensions do not agree"
Exemple #27
0
def start_game():
    pygame.init()

    ai_settings = Settings()

    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Blue Sky & Character")

    character = Figure(screen)

    while True:
        gf.check_events()
        gf.update_screen(ai_settings, screen, character)
Exemple #28
0
 def draw_molecule_and_figure(self, tests=False):
     self.molecule = Molecule(self.topol_data, self.rmsf)
     self.figure = Figure(self.molecule, self.diagram_type, self.topol_data,
                          self.hbonds, self.plots, self.rmsf, tests)
     if self.HB_flag != True:
         self.figure.draw_hbonds_in_graph(self.diagram_type)
     self.figure.draw_white_circles_at_atoms(self.diagram_type)
     if self.debug_flag == True:
         self.figure.draw_lines_in_graph(
         )  #a function for debugging purposes
     self.figure.put_everything_together()
     self.figure.write_final_draw_file(self.output_name)
     if self.trajectory != None and self.resinfo_flag != True:
         self.res_info = Residue_Info(self.topol_data, self.occurrence,
                                      self.figure)
Exemple #29
0
	def tick(self):
		self.root.after(300, self.tick)
		if not self.figure:
			self.figure= Figure()
			if self.relief.have_collision(self.figure.get_all()):
				print 'generate collision with relief'
				self.root.quit()
		
		self.figure.down_move()
		if self.try_stand_figure():
			self.figure= None
			if self.relief.overload():
				print 'You Fail'
				self.root.quit()
		
		self.redraw()		
Exemple #30
0
    def test_hold_figure(self):
        tmp = tkinter.Frame(borderwidth=3, relief="solid")
        ttrs = CanvasGame(tmp,
                          width=400,
                          height=600,
                          borderwidth=3,
                          relief="solid",
                          bg="white",
                          rows=24,
                          columns=16,
                          cell=25)

        f = Figure()
        ttrs.hold_figure(f)
        for cell in f.cells:
            self.assertEqual(ttrs.matrix[cell[0]][cell[1]], f.color)