示例#1
0
def generate_diagram(boards, b2l, add_board_func,
                    show_wires = True,
                    cabinet_system = None, cabinet_scale = 1.0):
	"""
	Generates a diagram using the board positions shown and the mapping from board
	to coordinate to use as a label.
	"""
	
	d = diagram.Diagram()
	
	d.set_cabinet_system(cabinet_system, cabinet_scale)
	
	for board, coord in boards:
		# Add board
		add_board_func(d, board, coord)
		if cabinet_system is not None:
			d.add_label(board, r"\tiny %d,%d"%(b2l[board]), ["rotate=90"])
		else:
			d.add_label(board, r"\tiny %d,%d"%(b2l[board]))
		
		# Add wires
		if show_wires:
			for direction, colour in DIRECTION_COLOURS:
				d.add_wire(board, direction, ["thick",colour])
	
	return d
示例#2
0
    def run(self, initial, params):
        """
        Run the orchestrator

        :param initial: initial pipeline
        :param params: parameters needed ro run pipelines
        :return:
        """
        azk_diagram = diagram.Diagram("diagram", self.diagram_file_name)
        edges, clusters = azk_diagram.parse_diagram()

        azk_graph = graph.Graph(edges, clusters, params, self.host,
                                self.username, self.password, self.logger)

        initial = diagram.Diagram.parse_node(initial) if initial else None

        azk_graph.traverse(initial=initial)
    def _on_save_sim_clicked(self, button):
        """ Is called if the save simulation button sends the clicked event. """

        try:
            # create a new Diagram object which stores the configuration of the chosen simulation
            d_obj = diagram.Diagram()
            # set properties
            d_obj.title = self._ent_subplot_title.get_text()
            d_obj.xlabel = self._ent_subplot_xlabel.get_text()
            d_obj.ylabel = self._ent_subplot_ylabel.get_text()
            d_obj.legend_position = int(self._ent_subplot_legend_position.get_text())
            d_obj.subplot_position = int(self._ent_subplot_position.get_text())
            d_obj.title_visibility = self._check_button_subplot_title.get_active()
            d_obj.legend_visibility = self._check_button_subplot_legend.get_active()
            # add or replace the Diagram object
            self._simulations[self._selected_simulation_index] = d_obj
        except ValueError:
            self.show_message_box_error("There are invalid entries!")
示例#4
0
def generate_cabinet_colouring_diagram(colouring, num_colours, cabinet_system, cabinet_scale):
	"""
	Takes a dict {cabinet_coord: colour_index} and the maximum color_index. Returns
	a diagram for a coloured set of racks.
	"""
	d = diagram.Diagram()
	d.set_cabinet_system(cabinet_system, cabinet_scale)
	
	
	# Generate pallet
	colours = []
	spectrum = ["red","green","blue", "yellow"]
	segment_size = (num_colours+len(spectrum)-2) / (len(spectrum)-1)
	for i in range(num_colours):
		start_colour, end_colour = spectrum[i / segment_size:][:2]
		point = 100 - (((i % segment_size) * 100) / segment_size)
		colours.append("%s!%d!%s"%(start_colour, point, end_colour))
	
	# Add the boards
	for coord, colour_index in colouring.iteritems():
		d.add_board_cabinet(coord, coord, ["fill=%s"%colours[colour_index]])
	
	return d
示例#5
0
def draw_by_bio(info, cates, long_intervals, seqlen, filename):
    import diagram as _dia
    reload(_dia)
    diagram = _dia.Diagram('Test Diagram')

    inner_colors, outer_colors = read_colors()
    if len(cates) > len(outer_colors):
        raise Exception('outer_colors num: %s, cannot satisfy category num: %s' % (len(outer_colors), len(cates)))
    color_map = zip(cates, outer_colors)
    color_trans = ColorTranslator()
    color_name_pairs = [(color_trans.translate(t[1]), t[0]) for t in color_map]
    color_map = dict(color_map)

    def _add_feats(feature_set, i, width=3, minimal_angle_margin=20):
        loc, concur_cates = info[i]
        concur_cates = concur_cates.keys()
        concur_num = len(concur_cates)

        # -------- calc width --------
        prev = 0
        if i > 0:
            prev = info[i - 1][0]

        next = seqlen
        if i < len(info) - 1:
            next = info[i + 1][0]

        width = min((next - prev) / concur_num, width)
        if width < 1:
            raise Exception('too narrow')

        # -------- add feature --------
        if concur_num > 1:
            angle_sum = (concur_num - 1) * minimal_angle_margin
            assert angle_sum < 180
            angle_slice = angle_sum / (concur_num - 1)

        def _add_feat(cate_i):
            color = color_map[concur_cates[cate_i]]
            start = loc  # - (cate_i - concur_num / 2) * width
            end = start + width
            feat = SeqFeature(FeatureLocation(start, end, strand=1))
            titled_angle = 0
            if concur_num > 1:
                titled_angle = cate_i * angle_slice - angle_sum / 2
            feature_set.add_feature(feat, color=color, tilted_angle=titled_angle)

        [_add_feat(cate_i) for cate_i in xrange(concur_num)]

    def _add_intervals(feature_set, i):
        start, end = long_intervals[i]
        feat = SeqFeature(FeatureLocation(start, end, strand=-1))
        color = inner_colors[i % len(inner_colors)]
        feature_set.add_feature(feat, color=color)

    def _add(track):
        feature_set = track.new_set()
        [_add_feats(feature_set, i, 1) for i in xrange(len(info))]
        if long_intervals is not None:
            [_add_intervals(feature_set, i) for i in xrange(len(long_intervals))]

    def _track(track_level):
        track = diagram.new_track(track_level, greytrack=False)
        _add(track)

    _track(1)

    diagram.draw(format='circular', circular=True, pagesize=(8 * cm, 8 * cm), fragments=1, orientation='portrait',
                 start=0, end=seqlen, circle_core=.7, inner_circle_core=1, color_name_pairs=color_name_pairs)
    diagram.write("%s.svg" % filename, "svg")
    text = u'输出为%s.svg' % filename
    print text.encode(codec)
示例#6
0
#!/usr/bin/env python

import sys
sys.path.append("/home/jonathan/Programing/Python/SpiNNer")

import diagram

from model import board
from model import transforms
from model import topology

d = diagram.Diagram()

# Create a small system of boards on a hexagonal coordinate system
boards = board.create_torus(4,4)

# Create a dictionary which maps boards to coordinates to use for labelling
# boards in the diagram.
board2coord = dict(boards)

# Draw the boards on the diagram as a hexagons
for board, coords in boards:
	d.add_board_hexagon(board, coords)
	
	# Draw only long wires
	for direction, colour in ( (topology.NORTH,      "red")
	                         , (topology.NORTH_EAST, "green")
	                         , (topology.EAST,       "blue")):
		if sum(map(abs, board2coord[board.follow_wire(direction)] - board2coord[board])) > 2:
			d.add_wire(board, direction, [colour])
    def _on_ok_clicked(self, button):
        """ Is called if the OK button sends the clicked event. """

        try:
        # iteration through the list of places
            item =  self._p_list_store.get_iter_first()
            while (item != None):
                #print self._p_list_store.get_value(item, 0)
                # get key of the current place
                key = self._p_list_store.get_value(item, 1)
                if self._p_list_store.get_value(item, 0):
                    # check if a Trajectory object for the current place is available
                    if not self._places.has_key(key):
                        # create a new Trajectory object with standard values because the user didn't create one
                        t_obj = trajectory.Trajectory()
                        # set properties
                        t_obj.legend_text = self._p_list_store.get_value(item, 2)
                        t_obj.auto_color_allocation = True
                        # add Trajectory object to the dictionary
                        self._places[key] = t_obj
                else:
                    # remove invalid Trajectory object from the list
                    if self._places.has_key(key):
                        del self._places[key]
                # next item
                item = self._p_list_store.iter_next(item)

            # iteration through the list of simulations
            item =  self._sim_list_store.get_iter_first()
            ctr = 0
            ctr_subplot = 1
            while (item != None):
                ctr += 1
                if self._sim_list_store.get_value(item, 0):
                    # check if a Diagram object for the current simulation is available
                    if not self._simulations.has_key(ctr):
                        # create a new Diagram object with standard values because the user didn't create one
                        d_obj = diagram.Diagram()
                        # set properties
                        d_obj.title = self._sim_list_store.get_value(item, 1)
                        d_obj.xlabel = self._ent_xlabel.get_text()
                        d_obj.ylabel = self._ent_ylabel.get_text()
                        d_obj.legend_position = int(self._ent_legend_position.get_text())

                        # determine automatically the position of the subplot
                        ctr_subplot = 0
                        loop = True
                        while loop:
                            loop = False
                            for key, item_sim in self._simulations.items():
                                if ctr_subplot == item_sim.subplot_position:
                                    ctr_subplot += 1
                                    loop = True
                                    break

                        d_obj.subplot_position = int(ctr_subplot)
                        d_obj.title_visibility = self._check_button_title.get_active()
                        d_obj.legend_visibility = self._check_button_legend.get_active()

                        # add Diagram object to the dictionary
                        self._simulations[ctr] = d_obj
                else:
                    # remove invalid Diagram object
                    if self._simulations.has_key(ctr):
                        del self._simulations[ctr]
                # next item
                item = self._sim_list_store.iter_next(item)

            if len(self._simulations) == 0:
                self.show_message_box_error("Visualisation is not possible without any data!")
                return

            # set properties for the controller
            self._controller.simulations = self._simulations
            self._controller.run_time = float(self._ent_runtime.get_text())
            self._controller.time_step = float(self._ent_time_step.get_text())
            self._controller.number_simulations = int(self._ent_num_sim.get_text())
            self._controller.epsilon = float(self._ent_epsilon.get_text())
            self._controller.num_ssa_runs = int(self._ent_num_ssa_runs.get_text())
            self._controller.control_parameter = float(self._ent_control_parameter.get_text())
            self._controller.number_rows = int(self._ent_num_rows.get_text())
            self._controller.number_columns = int(self._ent_num_cols.get_text())
            self._controller.auto_subplot_position_allocation = self._check_button_auto_position_subplot.get_active()
            if self._controller.number_rows * self._controller.number_columns < self._controller.number_simulations:
                if self._create_subplots:
                    self.show_message_box_error("Invalid grid dimensions for the subplot!\nAll suplots will be allocated automatically.")
                self._controller.auto_subplot_position_allocation = True
            self._controller.title = self._ent_title.get_text()
            self._controller.title_visibility = self._check_button_title.get_active()
            self._controller.xlabel = self._ent_xlabel.get_text()
            self._controller.ylabel = self._ent_ylabel.get_text()
            self._controller.line_width = int(self._ent_line_width.get_text())
            self._controller.legend_position = int(self._ent_legend_position.get_text())
            self._controller.legend_visibility = self._check_button_legend.get_active()
            self._controller.subplots = self._create_subplots

            self._controller.trajectory_configuration = self._places
            # plot diagram
            self._controller.plot()
        except ValueError:
            self.show_message_box_error("There are invalid entries!")
示例#8
0
    def plot(self):

        # check if the simulation was executed before
        if not self._simulated:
            # abort method
            return

        # instantiate a general object that includes the single diagrams
        vis = diagram_visualisation.DiagramVisualisation()
        # set properties
        vis.title = self._title
        vis.legend_visibility = self._legend
        vis.title_visibility = self._title_visibility
        vis.subplots = self._subplots
        vis.number_rows = self._num_rows
        vis.number_cols = self._num_cols
        vis.auto_subplot_allocation = self._auto_subplot
        vis.line_width = self._line_width

        try:
            # iteration through all simulations
            for index_sim, item_sim in self._simulations.items():
                # recreate the object - otherwise you would have a referencing problem
                # instantiate an object that combines single trajectories
                d_obj = diagram.Diagram()
                # set properties
                d_obj.title = item_sim.title
                if not self._subplots:
                    d_obj.xlabel = self._xlabel
                    d_obj.ylabel = self._ylabel
                else:
                    d_obj.xlabel = item_sim.xlabel
                    d_obj.ylabel = item_sim.ylabel
                d_obj.legend_position = int(item_sim.legend_position)
                d_obj.subplot_position = int(item_sim.subplot_position)
                d_obj.title_visibility = item_sim.title_visibility
                d_obj.legend_visibility = item_sim.legend_visibility
                # determine x data
                x = []
                for i in range(len(self._model.output[index_sim - 1].times)):
                    x.append(self._model.output[index_sim - 1].times[i])

                # iteration through all trajectories
                for key, item in self._places.items():
                    # recreate the object - otherwise you would have a referencing problem
                    # instantiate a trajectory object
                    t_obj = trajectory.Trajectory()
                    # set properties
                    t_obj.color = item.color
                    t_obj.legend_text = item.legend_text
                    if not self._subplots and len(self._simulations) > 1:
                        t_obj.legend_text = t_obj.legend_text + " - Simulation " + str(index_sim)
                    t_obj.auto_color_allocation = item.auto_color_allocation
                    # set trajectory data
                    t_obj.x_data = copy.deepcopy(x)
                    t_obj.y_data = []
                    index = -1
                    for i in range(len(self._model.data.petri_net_data.places)):
                        if self._model.data.petri_net_data.places[i] == key:
                            index = i
                            break
                    if index != -1:
                        for i in range(len(self._model.output[index_sim - 1].markings)):
                            t_obj.y_data.append(self._model.output[index_sim - 1].markings[i][index])
                    # add trajectory object to the diagram object
                    d_obj.add(t_obj, t_obj.legend_text)

                    if len(self._simulations) == 1 and self._subplots:
                        d_obj_t = diagram.Diagram()
                        # set properties
                        d_obj_t.title = item.legend_text
                        if not self._subplots:
                            d_obj_t.xlabel = self._xlabel
                            d_obj_t.ylabel = self._ylabel
                        else:
                            d_obj_t.xlabel = item_sim.xlabel
                            d_obj_t.ylabel = item_sim.ylabel
                        d_obj_t.legend_position = int(item_sim.legend_position)
                        #d_obj_t.subplot_position = int(item_sim.subplot_position)
                        d_obj_t.title_visibility = item_sim.title_visibility
                        d_obj_t.legend_visibility = item_sim.legend_visibility
                        # add trajectory object to the diagram object
                        d_obj_t.add(t_obj, t_obj.legend_text)
                        vis.add(d_obj_t, d_obj_t.title)

                if len(self._simulations) > 1 or not self._subplots:
                    # add diagram object to the visualisation object
                    vis.add(d_obj, d_obj.title)
            # visualise diagrams
            vis.plot()
        except IndexError:
            print "Simulation needs to be executed after changing simulation parameter. "