def get_colour(self, val, colformat='hex'):
        """ Given a value, return a colour within the colour scale """
        try:
            # Sanity checks
            val = re.sub("[^0-9\.]", "", str(val))
            if val == '':
                val = self.minval
            val = float(val)
            val = max(val, self.minval)
            val = min(val, self.maxval)

            domain_nums = list(
                np.linspace(self.minval, self.maxval, len(self.colours)))
            my_scale = spectra.scale(self.colours).domain(domain_nums)

            # Weird, I know. I ported this from the original JavaScript for continuity
            # Seems to work better than adjusting brightness / saturation / luminosity
            rgb_converter = lambda x: max(0, min(1, 1 + ((x - 1) * 0.3)))
            thecolour = spectra.rgb(
                *[rgb_converter(v) for v in my_scale(val).rgb])

            return thecolour.hexcode

        except:
            # Shouldn't crash all of MultiQC just for colours
            return ''
Пример #2
0
def gender_color_for_people(people):
    gender_values = [get_gender_for_name(p.name) for p in people]
    average_gender = sum(gender_values)/len(gender_values)

    # now we turn the number into a color.  Yellow for men, red for women.
    scale = spectra.scale(['red', 'purple'])
    # this library returns the hexcode with the hash, we don't expect it, so chop it off
    color = scale(average_gender).hexcode[1:]
    return color
Пример #3
0
def test_polylinear():
    """
    via: https://github.com/jsvine/spectra/issues/4
    """
    colors = ['yellow', 'red', 'black']
    domain = [0, 50, 100]
    color_scale = spectra.scale(colors).domain(domain)
    r = color_scale.range(5)
    results = [ c.hexcode for c in r ]
    goal = ['#ffff00', '#ff8000', '#ff0000', '#800000', '#000000']
    assert(results == goal)
Пример #4
0
    def get_colour(self, val, colformat="hex", lighten=0.3):
        """Given a value, return a colour within the colour scale"""

        # Ported from the original JavaScript for continuity
        # Seems to work better than adjusting brightness / saturation / luminosity
        rgb_converter = lambda x: max(0, min(1, 1 + ((x - 1) * lighten)))

        try:
            # When we have non-numeric values (e.g. Male/Female, Yes/No, chromosome names, etc), and a qualitive
            # scale (Set1, Set3, etc), we don't want to attempt to parse numbers, otherwise we will end up with all
            # values assigned with the same color. But instead we will geta has from a string to hope to assign
            # a unique color for each possible enumeration value.
            if self.name in mqc_colour_scale.qualitative_scales and isinstance(
                    val, str):
                thecolour = spectra.html(self.colours[hash(val) %
                                                      len(self.colours)])
                thecolour = spectra.rgb(
                    *[rgb_converter(v) for v in thecolour.rgb])
                return thecolour.hexcode

            # When there is only 1 color in scale, spectra.scale() will crash with DevisionByZero
            elif len(self.colours) == 1:
                thecolour = spectra.html(self.colours[0])
                thecolour = spectra.rgb(
                    *[rgb_converter(v) for v in thecolour.rgb])
                return thecolour.hexcode

            else:
                # Sanity checks
                val = re.sub("[^0-9\.-e]", "", str(val))
                if val == "":
                    val = self.minval
                val = float(val)
                val = max(val, self.minval)
                val = min(val, self.maxval)

                domain_nums = list(
                    np.linspace(self.minval, self.maxval, len(self.colours)))
                my_scale = spectra.scale(self.colours).domain(domain_nums)

                # Lighten colours
                thecolour = spectra.rgb(
                    *[rgb_converter(v) for v in my_scale(val).rgb])

                return thecolour.hexcode

        except:
            # Shouldn't crash all of MultiQC just for colours
            return ""
Пример #5
0
	def get_colour(self, val, colformat='hex'):
		""" Given a value, return a colour within the colour scale """
		try:
			# Sanity checks
			val = re.sub("[^0-9\.]", "", str(val))
			if val == '':
				val = self.minval
			val = float(val)
			val = max(val, self.minval)
			val = min(val, self.maxval)

			domain_nums = list( np.linspace(self.minval, self.maxval, len(self.colours)) )
			my_scale = spectra.scale(self.colours).domain(domain_nums)

			# Weird, I know. I ported this from the original JavaScript for continuity
			# Seems to work better than adjusting brightness / saturation / luminosity
			rgb_converter = lambda x: max(0, min(1, 1+((x-1)*0.3)))
			thecolour = spectra.rgb( *[rgb_converter(v) for v in my_scale(val).rgb] )

			return thecolour.hexcode

		except:
			# Shouldn't crash all of MultiQC just for colours
			return ''
LOG_FILENAME = "/tmp/blotre-moisutre.log"

SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25

# Stream
TARGET_STREAM_NAME = "Mr Tree"

# Range of sensor reading, from just watered to dry soil
MOISTURE_SENSOR_MAX = 825
MOISTURE_SENSOR_MIN = 400

MOISTURE_SCALE = spectra.scale(["#654d00", "green"]).domain([MOISTURE_SENSOR_MIN, MOISTURE_SENSOR_MAX])

# How often should the sensor be checked? (in seconds)
INTERVAL = 60 * 5

GPIO.setmode(GPIO.BCM)

# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)                                                                                                 
# Taken from: https://learn.adafruit.com/reading-a-analog-in-and-controlling-audio-volume-with-the-raspberry-pi
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
    if (adcnum > 7) or (adcnum < 0):
        return -1
    GPIO.output(cspin, True)

    GPIO.output(clockpin, False)  # start clock low                                                                                                        
    GPIO.output(cspin, False)     # bring CS low                                                                                                           
LOG_FILENAME = "/tmp/blotre-moisutre.log"

SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25

# Stream
TARGET_STREAM_NAME = "Mr Tree"

# Range of sensor reading, from just watered to dry soil
MOISTURE_SENSOR_MAX = 825
MOISTURE_SENSOR_MIN = 400

MOISTURE_SCALE = spectra.scale(["#654d00", "green"]).domain(
    [MOISTURE_SENSOR_MIN, MOISTURE_SENSOR_MAX])

# How often should the sensor be checked? (in seconds)
INTERVAL = 60 * 5

GPIO.setmode(GPIO.BCM)


# read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
# Taken from: https://learn.adafruit.com/reading-a-analog-in-and-controlling-audio-volume-with-the-raspberry-pi
def readadc(adcnum, clockpin, mosipin, misopin, cspin):
    if (adcnum > 7) or (adcnum < 0):
        return -1
    GPIO.output(cspin, True)

    GPIO.output(clockpin, False)  # start clock low
Пример #8
0
def get_graph_color_scale(n):
    my_scale = spectra.scale(GRAPH_COLOR_SCALE)
    my_range = my_scale.range(n)
    return ["rgb{}".format(c.clamped_rgb) for c in my_range]
def pathwayVisualization(KEGG_id, path_to_csv, redirect=True, compound=False):
    """
    The pathwayVisualization function returns a graph visualization based on user input
    
    Args:
        KEGG_id     (str): string specifying KEGG pathway ID to visualize
        path_to_csv (str): string specifying data to overlay on graph
        redirect    (bool): True to split nodes into their components. Defaults to True
        compound    (bool): True to display compounds (such as Ca2+). Defaults to False
        
    Returns:
        A graph visualization using the visjs_network function from visjs_2_jupyter
    """
    
    s = KEGG()
    result = s.parse_kgml_pathway(KEGG_id)
    
    ETroot = parsingXML(KEGG_id, s)
    
    G=nx.DiGraph()
    
    max_id, compound_array = addNodes(G, result)
    setCoord(G, ETroot)
    
    if redirect is False:
        getNodeSymbols(G, s, compound)
    else:
        parent_list, parent_dict = splitNodes(G, s, max_id)
    
    complex_array, component_array, node_dict, comp_dict = undefNodes(G, ETroot)
    
    if redirect is False:
        addEdges(G, result, component_array, node_dict)
    else:
        addAndRedirectEdges(G, result, complex_array, component_array, parent_list, parent_dict, node_dict, comp_dict)
    
    #add reactions to graph
    addReaction(G, ETroot)
    
    edge_to_name = dict()
    for edge in G.edges():
        print edge
        if G.edge[edge[0]][edge[1]]['name'] == 'phosphorylation':
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['value']
        elif G.edge[edge[0]][edge[1]]['name'] == 'dephosphorylation':
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['value']
        elif 'dephosphorylation' in G.edge[edge[0]][edge[1]]['name']:
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['name'].replace('dephosphorylation', '-p')
            edge_to_name[edge] = edge_to_name[edge].replace('\n', ', ')
        elif 'phosphorylation' in G.edge[edge[0]][edge[1]]['name']:
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['name'].replace('phosphorylation', '+p')
            edge_to_name[edge] = edge_to_name[edge].replace('\n', ', ')
        #remove activation and inhibition labels
        elif 'activation' in G.edge[edge[0]][edge[1]]['name']:
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['name'].remove('activation')
            edge_to_name[edge] = edge_to_name[edge].replace('\n', ', ')
        elif 'inhibition' in G.edge[edge[0]][edge[1]]['name']:
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['name'].remove('inhibition')
            edge_to_name[edge] = edge_to_name[edge].replace('\n', ', ')
        else:
            edge_to_name[edge] = G.edge[edge[0]][edge[1]]['name']
            #print edge_to_name[edge]

    #edges are transparent
    edge_to_color = dict()
    for edge in G.edges():
        if 'activation' in G.edge[edge[0]][edge[1]]['name']:
            edge_to_color[edge] = 'rgba(26, 148, 49, 0.3)' #green
        elif 'inhibition' in G.edge[edge[0]][edge[1]]['name']:
            edge_to_color[edge] = 'rgba(255, 0, 0, 0.3)' #red
        else:
            edge_to_color[edge] = 'rgba(0, 0, 255, 0.3)' #blue
    
    #for graph with split nodes
    if redirect is True:
        #remove undefined nodes from graph
        G.remove_nodes_from(complex_array)

        #remove nodes with more than one gene
        G.remove_nodes_from(parent_list)

    if compound is False:
        #remove compound nodes
        G.remove_nodes_from(compound_array)
        
    node_to_symbol = dict()
    for node in G.node:
        if G.node[node]['type'] == 'map':
            node_to_symbol[node] = G.node[node]['gene_names']
        else:
            if 'symbol' in G.node[node]:
                node_to_symbol[node] = G.node[node]['symbol']
            elif 'gene_names'in G.node[node]:
                node_to_symbol[node] = G.node[node]['gene_names']
            else: 
                node_to_symbol[node] = G.node[node]['name']
            
    # getting name of nodes
    node_to_gene = dict()
    for node in G.node:
        node_to_gene[node] = G.node[node]['gene_names']
            
    # getting x coord of nodes
    node_to_x = dict()
    for node in G.node:
        node_to_x[node] = G.node[node]['x']
    
    # getting y coord of nodes
    node_to_y = dict()
    for node in G.node:
        node_to_y[node] = G.node[node]['y']
    
    id_to_log2fold = log2FoldChange(G, path_to_csv)
    
    # Create color scale with negative as green and positive as red
    my_scale = spectra.scale([ "green", "#CCC", "red" ]).domain([ -4, 0, 4 ])
    
    # color nodes based on log2fold data
    node_to_color = dict()
    
    for node in G.nodes():

        if node in id_to_log2fold:
            node_to_color[node] = my_scale(id_to_log2fold[node][0]).hexcode

        else:
            node_to_color[node] = '#f1f1f1'

    # getting nodes in graph
    nodes = G.nodes()
    numnodes = len(nodes)
    node_map = dict(zip(nodes,range(numnodes)))  # map to indices for source/target in edges
    
    # getting edges in graph
    edges = G.edges()
    numedges = len(edges)

    # dictionaries that hold per node and per edge attributes
    nodes_dict = [{"id":node_to_gene[n],"degree":G.degree(n),"color":node_to_color[n], "node_shape":"box",
                 "node_size":10,'border_width':1, "id_num":node_to_symbol[n], "x":node_to_x[n], "y":node_to_y[n]} for n in nodes]

    edges_dict = [{"source":node_map[edges[i][0]], "target":node_map[edges[i][1]], 
                  "color":edge_to_color[edges[i]], "id":edge_to_name[edges[i]], "edge_label":'',
                 "hidden":'false', "physics":'true'} for i in range(numedges)]        

    # html file label for first graph (must manually increment later)
    time = 1700

    # create graph here
    #return G
    return visJS_module.visjs_network(nodes_dict, edges_dict, time_stamp = time, node_label_field = "id_num", 
                               edge_width = 3, border_color = "black", edge_arrow_to = True, edge_font_size = 15,
                               edge_font_align= "top", physics_enabled = False, graph_width = 1000, graph_height = 1000)
Пример #10
0
def test_polylinear_fail():
    colors = ['yellow', 'red', 'black']
    domain = [ 0, 50 ] # Domain has one too few items
    spectra.scale(colors).domain(domain)