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])
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
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
def reset(cls): """Reset to default state.""" Box.reset() Note.reset() Figure.reset() Table.reset() Video.reset()
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
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
def reset(cls): """Reset to default state.""" Box.reset() Note.reset() Figure.reset() Table.reset() Video.reset()
def __init__(self, points): Figure.__init__(self) self.point1 = points[0] self.point2 = points[1] self.point3 = points[2] self.line1 = Line(points[0], points[1]) self.line2 = Line(points[1], points[2]) self.line3 = Line(points[0], points[2])
def __init__(self, points): Figure.__init__(self) self.point1 = points[0] self.point2 = points[1] self.point3 = points[2] self.line1 = Line(points[0], points[1]) self.line2 = Line(points[1], points[2]) self.line3 = Line(points[0], points[2])
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)
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 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()
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()
def gca(): """ Returns the currently active axes object. @rtype: Axes @return: the currently active set of axes """ if not Figure.gcf()._ca: Axes() return Figure.gcf()._ca
def gca(): """ Returns the currently active axes object. @rtype: Axes @return: the currently active set of axes """ if not Figure.gcf()._ca: Axes() return Figure.gcf()._ca
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_
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()
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_
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()
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)
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)")
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)")
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"
def start_button_clicked(self): cost_fun = str(self.cost_function.text()) max_it = int(self.max_iter.text()) eps = self.epsilon.text() div_err = float(self.div_err.text()) x0 = self.initial_cond.text() x0 = x0.replace(" ", "") x0 = x0.split(",") if len(x0) == 1: x0 = float(x0[0]) else: x0 = tuple(float(i) for i in x0) eps = eps.replace(" ", "") eps = eps.split(",") if len(eps) == 3: eps = tuple(float(i) for i in eps) else: eps = tuple(float(eps[0]) for i in range(3)) #ustawic tolerancje!!!!!! w funckacji #gtol=1e-05, xtol=1e-09, fxtol=1e-09 opts = {'gtol': eps[0], 'xtol': eps[1], 'fxtol': eps[2], 'epsilon': div_err, 'maxiter': max_it } fun = Function(cost_fun) x = fmindfp(fun, x0, disp=True, **opts) #normalizacjay wjscia: output = np.asarray(x[2]) output = output.tolist() text = '\n'.join(output) self.txt_browser.setText(text) vec = x[1] vec = np.asanyarray(vec) print(vec.shape) print(vec) fig = Figure(fun, vec) fig.show()
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)")
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)")
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)
def main(): pngfile_list = commands.getoutput('find images -name "*.png"').split('\n') for pngfile in pngfile_list: jsonfile = re.sub('^images', 'jsons', re.sub('.png$', '.json', pngfile)) testfile = re.sub('^images', 'tests', pngfile) try: confirmAndMakeDir(jsonfile) confirmAndMakeDir(testfile) figure = Figure(pngfile) figure.saveJSON(jsonfile) figure.saveTestPNG(testfile) except: print 'failed:', pngfile
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)
def parse_sequence(self, sequenceNode): sequence = [] for childNode in sequenceNode.childNodes: if childNode.nodeType == childNode.ELEMENT_NODE: sequence.append(Figure.parse(childNode)) self.sequence = sequence
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()
def parse_sequence (self, sequenceNode): sequence = [] for childNode in sequenceNode.childNodes: if childNode.nodeType == childNode.ELEMENT_NODE: sequence.append(Figure.parse(childNode)) self.sequence = sequence
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)
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)
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
class LanSecondPlayer(SecondPlayer): 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 def receive_data(self): attack = 0 data = self.lan.get_data() if data: data_array = eval(data) if len(data_array) == 7: self.figure.blocks = data_array[0] self.figure.x = data_array[1] self.figure.y = data_array[2] self.stage.blocks = data_array[3] self.stage.score = data_array[4] self.stage.completed_lines = data_array[5] attack = data_array[6] return attack def send_data(self, figure: Figure, stage: Stage, attack_power): data_array = list() data_array.append(figure.blocks) data_array.append(figure.x) data_array.append(figure.y) data_array.append(stage.blocks) data_array.append(stage.score) data_array.append(stage.completed_lines) data_array.append(attack_power) self.lan.send_data(data_array) def draw(self, stage_surface, menu_surface): self.stage.draw(stage_surface) self.figure.draw(stage_surface) self.menu.draw_second_player(menu_surface, self.stage.score, self.stage.completed_lines)
def main(): figure = Figure(80) V = [figure.nodes[0]] E = [] while len(V) < 80: nodePair = None for node1 in V: for node2 in figure.nodes.values(): if node1 != node2: if nodePair == None or node1.weight( node2) < nodePair[0].weight(nodePair[1]): if node1 not in V or node2 not in V: nodePair = (node1, node2) if nodePair != None: E.append(figure.connect(nodePair[0], nodePair[1])) if nodePair[0] not in V: V.append(nodePair[0]) if nodePair[1] not in V: V.append(nodePair[1]) print(figure.nodes[0].imc())
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 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
def __init__(self, fig=None, *args, **kwargs): self.figure = fig # grid position within figure self.at = kwargs.get('at', [0, 0]) # container for axes self.grid = {} # distance between axes self.spacing = kwargs.get('spacing', 2.) # add grid to figure if not self.figure: self.figure = Figure.gcf() self.figure.axes = [self]
def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_color="viridis"): """ Draws molecule through Molecule() and then puts the final figure together with Figure(). """ self.molecule = Molecule(self.topol_data) self.draw = Draw(self.topol_data,self.molecule,self.hbonds,self.pistacking,self.salt_bridges,self.lig_descr) self.draw.draw_molecule(data_for_color, data_for_size, data_for_clouds, rot_bonds, color_for_clouds, color_type_color) self.figure = Figure(self.molecule,self.topol_data,self.draw) self.figure.add_bigger_box() self.figure.manage_the_plots() self.figure.draw_white_circles() self.figure.put_everything_together() self.figure.write_final_draw_file(self.output_name)
if __name__ == '__main__': #start GUI, get data from GUI; from function import Function from test_functions import * given_function = goldstein fun = Function(given_function) #TODO: fmin powinno zwracac wektor osiagnietych # wartosci x podczas kazdej iteracji algorytmu #TODO: dodac warunki stopu, oraz wypisywac # ich wartosci w kazdej iteracji algorytmu #TODO: zmienic algorytm bfgs na dfp from fmindfp import fmindfp x0 = [0.4, -0.6] x = fmindfp(fun, x0, maxiter=10000, disp=False) # rysowanie wykresow 3d w myjavi, plus warstwice i wektor # olicoznych punktow kolejnych osiagnietych wattosci funckji. from figure import Figure x_vec = None fig = Figure(fun, x, x0, x_vec) fig.plot_surf()
def gcf(): """ Returns currently active figure. """ return Figure.gcf()
def __init__(self, fig=None, *args, **kwargs): """ Initializes axes properties. """ # parent figure self.figure = fig # legend self.legend = None # axis position self.at = kwargs.get('at', [0., 0.]) # width and height of axis self.width = kwargs.get('width', 8.) self.height = kwargs.get('height', 7.) # plots belonging to these axes self.children = [] # title above axes self.title = kwargs.get('title', '') # axes labels self.xlabel = kwargs.get('xlabel', '') self.ylabel = kwargs.get('ylabel', '') # axes limits self.xmin = kwargs.get('xmin', None) self.xmax = kwargs.get('xmax', None) self.ymin = kwargs.get('ymin', None) self.ymax = kwargs.get('ymax', None) # if true, put a margin between plots and axes self.enlargelimits = kwargs.get('enlargelimits', None) # tick positions self.xtick = kwargs.get('xtick', None) self.ytick = kwargs.get('ytick', None) # tick label precisions self.xticklabel_precision = kwargs.get('xticklabel_precision', 4) self.yticklabel_precision = kwargs.get('yticklabel_precision', 4) # tick positions self.xtick_align = kwargs.get('xtick_align', None) self.ytick_align = kwargs.get('ytick_align', None) # tick labels self.xticklabels = kwargs.get('xticklabels', None) self.yticklabels = kwargs.get('yticklabels', None) # linear or logarithmic axes self.axes_type = kwargs.get('axes_type', 'axis') # axis positions self.axis_x_line = kwargs.get('axis_x_line', None) self.axis_y_line = kwargs.get('axis_y_line', None) # bar plots self.ybar = kwargs.get('ybar', False) self.xbar = kwargs.get('xbar', False) self.bar_width = kwargs.get('bar_width', None) self.stacked = kwargs.get('stacked', False) self.interval = kwargs.get('interval', False) # controls aspect ratio self.equal = kwargs.get('equal', None) # color and style specifications self.colormap = kwargs.get('colormap', None) self.cycle_list = kwargs.get('cycle_list', None) self.cycle_list_name = kwargs.get('cycle_list_name', None) # grid lines self.grid = kwargs.get('grid', None) # axis on/off self.hide_axis = kwargs.get('hide_axis', False) # custom axes properties self.pgf_options = kwargs.get('pgf_options', []) if not self.figure: self.figure = Figure.gcf() # add axes to figure (if figure is not controlled by AxesGrid) from axesgrid import AxesGrid if not (self.figure.axes and isinstance(self.figure.axes[0], AxesGrid)): self.figure.axes.append(self) # make this axis active self.figure._ca = self
def pick_pts(num=1): return Figure.fromCurrent().pickPoints(num)
def pick_intervals(num=1): ''' Return list of Intervals picked from current plot ''' return map(Interval._make, Figure.fromCurrent().pickRegions(num))
class Lintools(object): """This class controls the behaviour of all other classes (Data,Plots,Molecule,Figure) of lintools and inherits and transfers them resulting in a final SVG file that contains the protein-ligand interactions. It also controls the analysis (Residence_time and HBonds classes). Takes: * topology * - topology file * trajectory * - trajectory file(s) * mol_file * - MOL file of the ligand * ligand * - MDAnalysis atomgroup of ligand that is going to be analysed * offset * - residue offset which determines by how many numbers the protein residue numbering should be offset (e.g. with offset = 30 the first residue will be changed from 1 to 30, 2 - 31, etc.) * cutoff * - cutoff distance in angstroms that defines the native contacts (default - 3.5A) * start_frame * - start frame(s) for trajectory analysis (can be different for each trajectory) * end_frame * - end frame(s) for trajectory analysis (can be different for each trajectory) * skip * - number of frames to skip (can be different for each trajectory) * analysis_cutoff * - a fraction of time a residue has to fullfil the analysis parameters for (default - 0.3) * sasa * - set this to 1 to turn on solvent accessible surface area calculation (currently only works across whole trajectory) * diagram_type * - string of the selected diagram type (e.g. "amino" or "clocks") * output_name * - name of the folder with results and the final SVG file """ __version__ = "06.2018" def __init__(self,topology,trajectory,mol_file,ligand,offset,cutoff,start_frame,end_frame,skip,analysis_cutoff,sasa,diagram_type,output_name,cfg): """Defines the input variables.""" self.topology = os.path.abspath(topology) try: self.trajectory = [] for traj in trajectory: self.trajectory.append(os.path.abspath(traj)) except Exception: self.trajectory = [] if mol_file!=None: self.mol_file = os.path.abspath(mol_file) else: self.mol_file = mol_file self.ligand = ligand self.offset = offset self.cutoff = cutoff if cfg==False: self.start = [None if start_frame==[None] else int(start_frame[i]) for i in range(len(trajectory))] self.end = [None if end_frame==[None] else int(end_frame[i]) for i in range(len(trajectory))] self.skip = [None if skip==[None] else int(skip[i]) for i in range(len(trajectory))] else: self.start = start_frame self.end = end_frame self.skip = skip self.analysis_cutoff = analysis_cutoff self.sasa = sasa self.diagram_type = diagram_type self.output_name = output_name def data_input_and_res_time_analysis(self): """ Loads the data into Data() - renumbers the residues, imports mol file in rdkit. If there are trajectories to analyse, the residues that will be plotted are determined from Residence_time() analysis. """ self.topol_data = Data() self.topol_data.load_data(self.topology,self.mol_file,self.ligand,self.offset) if len(self.trajectory) == 0: self.topol_data.analyse_topology(self.topology,self.cutoff) else: self.res_time = Residence_time(self.topol_data,self.trajectory, self.start, self.end, self.skip,self.topology, self.ligand,self.offset) self.res_time.measure_residence_time(self.cutoff) self.res_time.define_residues_for_plotting_traj(self.analysis_cutoff) self.topol_data.find_the_closest_atoms(self.topology) def analysis_of_prot_lig_interactions(self): """ The classes and function that deal with protein-ligand interaction analysis. """ self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3) self.pistacking = PiStacking(self.topol_data,self.trajectory,self.start,self.end,self.skip, self.analysis_cutoff) if self.sasa==1: self.sasa = SASA(self.topol_data,self.trajectory) self.lig_descr = LigDescr(self.topol_data) if self.trajectory!=[]: self.rmsf = RMSF_measurements(self.topol_data,self.topology,self.trajectory,self.ligand,self.start,self.end,self.skip) self.salt_bridges = SaltBridges(self.topol_data,self.trajectory,self.lig_descr,self.start,self.end,self.skip,self.analysis_cutoff) def plot_residues(self): """ Calls Plot() that plots the residues with the required diagram_type. """ self.plots = Plots(self.topol_data,self.diagram_type) def draw_figure(self,data_for_color=None, data_for_size=None, data_for_clouds=None, rot_bonds=None, color_for_clouds="Blues", color_type_color="viridis"): """ Draws molecule through Molecule() and then puts the final figure together with Figure(). """ self.molecule = Molecule(self.topol_data) self.draw = Draw(self.topol_data,self.molecule,self.hbonds,self.pistacking,self.salt_bridges,self.lig_descr) self.draw.draw_molecule(data_for_color, data_for_size, data_for_clouds, rot_bonds, color_for_clouds, color_type_color) self.figure = Figure(self.molecule,self.topol_data,self.draw) self.figure.add_bigger_box() self.figure.manage_the_plots() self.figure.draw_white_circles() self.figure.put_everything_together() self.figure.write_final_draw_file(self.output_name) def save_files(self): """Saves all output from LINTools run in a single directory named after the output name.""" while True: try: os.mkdir(self.output_name) except Exception as e: self.output_name = raw_input("This directory already exists - please enter a new name:") else: break self.workdir = os.getcwd() os.chdir(self.workdir+"/"+self.output_name) def write_config_file(self, cfg): if cfg!=None: #copy the config file to results directory shutil.copy("../"+cfg, "lintools.config") else: #If there was no config file, write one cfg_dir = {'input':{ 'topology':self.topology, 'trajectory':self.trajectory, 'mol file':self.mol_file, 'ligand':self.ligand, 'traj start':self.start, 'traj end':self.end, 'traj skip': self.skip, 'offset': self.offset, 'distance cutoff': self.cutoff, 'analysis cutoff': self.analysis_cutoff, 'sasa': self.sasa, 'diagram type': self.diagram_type, 'output name': self.output_name}, 'representation':{ 'data to show in color':None, 'data to show as size':None, 'data to show as cloud':None, 'rotatable bonds':None, 'cloud color scheme':'Blues', 'atom color scheme':'viridis', 'clock color scheme':'summer'} } with open("lintools.config","wb") as ymlfile: yaml.dump(cfg_dir,ymlfile,default_flow_style=False) def remove_files(self): """Removes intermediate files.""" file_list = ["molecule.svg","lig.pdb","HIS.pdb","PHE.pdb","TRP.pdb","TYR.pdb","lig.mol","test.xtc"] for residue in self.topol_data.dict_of_plotted_res.keys(): file_list.append(residue[1]+residue[2]+".svg") for f in file_list: if os.path.isfile(f)==True: os.remove(f)
class Game: def __init__(self): self.root= Tkinter.Tk() self.vis= Visual(self.root) self.relief= Relief() self.figure= None self.stand_latter= False self.root.after_idle(self.tick) self.root.bind('<KeyPress>', self.press_key) self.root.mainloop() 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() def redraw(self): self.vis.reset() self.vis.draw(self.relief.get_all(), 'navajo white') if self.figure: self.vis.draw(self.figure.get_all(), 'alice blue') def move_figure(self, method): method() if self.relief.have_collision(self.figure.get_all()): self.figure.rollback() else: self.redraw() self.stand_latter= True def press_key(self, event): if not self.figure: return inp= event.char.upper() if inp == 'D': self.move_figure(self.figure.right_move) elif inp == 'A': self.move_figure(self.figure.left_move) elif inp == 'S': self.move_figure(self.figure.down_move) elif inp == 'E' or inp == ' ': self.move_figure(self.figure.right_turn) elif inp == 'Q': self.move_figure(self.figure.left_turn) elif inp == 'W': while not self.relief.have_collision(self.figure.get_all()): self.figure.down_move() self.figure.rollback() self.redraw() def try_stand_figure(self): result= False if self.relief.have_collision(self.figure.get_all()): self.figure.rollback() if self.stand_latter: pass else: self.relief.extend(self.figure.get_all()) self.relief.remove_filled_lines() result= True self.stand_latter= False return result
class Stack: "A class to load and manipulate images generated during single molecule experiments" defaultROI = {} defaultDonorROI = 'donor' defaultAcceptorROI = 'acceptor' @classmethod def fromfile(cls, imgfile, camfile=''): img = fileIO.loadimg(imgfile) camfile = camfile or fileIO.to_cam_filename(imgfile) metadata = fileIO.loadcam(camfile) metadata['filename'] = imgfile stack = cls(img, metadata) # Keeping the .filename attribute for backward compatibility, but should move to # metadata lookup stack.filename = metadata['filename'] return stack # def __init__(self, filename, camFile='', deepcopy=False): 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" def copy(self, deep=True): newstack = copy.copy(self) if deep: newstack._img = copy.copy(self._img) return newstack @property def frames(self): return self._img.shape[0] def __len__(self): return self.frames @property def time(self): return np.arange(1,self.frames+1)*self.metadata['exposurems']/1000. @property def height(self): return self._img.shape[1] @property def width(self): return self._img.shape[2] @property def donor(self): if not self._roi.has_key(self._donorROIName): raise StackError, "ROI called %s hasn't been defined yet" % self._donorROIName return self.counts(self._roi[self._donorROIName]) @property def acceptor(self): if not self._roi.has_key(self._acceptorROIName): raise StackError, "ROI called %s hasn't been defined yet" % self._acceptorROIName return self.counts(self._roi[self._acceptorROIName]) @property def roi(self): return self._roi @classmethod def setDefaultROI(cls, *args): for _roi in args: cls.defaultROI[_roi.name]=_roi def toBackground(self,zfilter='median'): width, height = self.width, self.height if zfilter == 'median': self._img = np.median( self._img, axis=0, overwrite_input=True ).reshape((1,height,width)) elif zfilter == 'mean': self._img = np.mean( self._img, axis=0 ).reshape((1,height,width)) elif zfilter == 'min': self._img = np.min( self._img, axis=0 ).reshape((1,height,width)) else: raise ValueError, "Filter type can only be median, mean, or min" return self def addROI(self, *ROIs): for roi in ROIs: try: roi = ROI.copy(roi) key = roi.name roi = roi.toRelative(self.origin) if roi.right > self.width: raise StackError( "ROI 'right' {0} is outside right edge of image {1}: \n {2}".format(roi.right,self.width,roi) ) if roi.top > self.height: raise StackError, "ROI 'top' is outside top edge of image: {0}\n {1}".format(roi.top,roi) self._roi[key] = roi except AttributeError: raise TypeError, "Must use objects with ROI interface" def showROI(self,*args): for roi in args: self._roi[roi].draw() def show(self, frame=None, **kwargs): if not isinstance(frame, int) and frame is not None: raise ValueError('First argument frame must be an integer') self._figure = kwargs.pop('figure', self._figure) if frame is None: frame = next(self._frame_iter) else: self._frame_iter = dropwhile(lambda n: n<=frame, cycle(range(self.frames))) self._figure.show() self._figure.makeCurrent() plt.title('Frame %d' % frame) self[frame].show(**kwargs) return frame def setDonorROI(self, roi_name): if not self._roi.has_key(roi_name): raise KeyError, "Image.Stack does not have an ROI named %s" % roi_name self._donorROIName = roi_name return self def setAcceptorROI(self, roi_name): if not self._roi.has_key(roi_name): raise KeyError, "Image.Stack does not have an ROI named %s" % roi_name self._acceptorROIName = roi_name return self def counts(self, roi=None): if roi: if self._roi.has_key(str(roi)): roi = self._roi[roi] roi = roi.toRelative(self.origin) return self[:,roi.bottom:roi.top,roi.left:roi.right].counts() else: return np.sum( np.sum(self._img,axis=1), axis=1 ) def attime(self,time): if isinstance(time,slice): start,step = None,None exposurems = self.metadata['exposurems'] if time.start: start = time.start/exposurems if time.step: step = time.step/exposurems time = slice(start,time.stop/exposurems,step) return self[time/exposurems] def __getitem__(self,key): if isinstance(key,int): # Single frame return Frame(self._img[key], self._roi) else: # It's a slice temp = self.copy(deep=False) temp._img = temp._img[key] if isinstance(temp._img.shape,tuple) and len(temp._img.shape) > 2: temp.frames = temp._img.shape[0] else: temp.frames = 1 return temp raise IndexError, "Invalid index: %s" % str(key) def append(self, stack): temp = copy.copy(self) temp._img = np.append( temp._img, stack._img, axis=0 ) return temp def __sub__(self, stack): return self.__add__(stack.__neg__()) def __add__(self, stack): temp = self.copy() if hasattr(stack,'_img'): try: temp._img = temp._img + stack._img except ValueError: raise StackError("Couldn't add images: check sizes are the same") else: temp._img = temp._img + stack return temp def __neg__(self): temp = self.copy() temp._img = -temp._img return temp def __eq__(self, other): return np.all(self._img == other._img) def __ne__(self, other): return not self==other def __repr__(self): return "Stack %dx%dx%d" % (self.frames, self.height, self.width) def __iter__(self): for i in range(self.frames): yield self[i]
def __init__(self, y=0, x=0): Figure.__init__(self, y, x)
def setup(self): for n in range(self.amount): figure = Figure(self.board) figure.bindStrategy(self.figureStrategyFactory()) figure.strategy.placeIt() self.board.figures[0].color = 1