コード例 #1
0
ファイル: rainbow.py プロジェクト: z/rainbow.py
    def generate(self, phrase):
    
        phrase_length = len(phrase)

        # chars per color
        cpc = ceil(phrase_length / self.color_count)

        color_start = Color(self.start_color)
        color_end = Color(self.end_color)
        rainbow = list(color_start.range_to(color_end, self.color_count))

        characters = list(phrase)
        characters.reverse()

        s = ''
        for color in rainbow:

            s += self.template['tag_open_before'] + color.hex + self.template['tag_open_after']

            i = 0
            while i < cpc and len(characters) > 0:
                next_char = characters.pop()
                s += next_char
                i += 1

            s += self.template['tag_close']

            if len(characters) < 1:
                break

        return s
コード例 #2
0
ファイル: buildsunburst.py プロジェクト: edraizen/HistoneDB
def build_sunburst(sequences):
    from djangophylocore.models import TaxonomyReference
    import networkx as nx
    from networkx.readwrite import json_graph

    scores = sequences.values_list("score", flat=True)
    scores_min = min(scores) if scores else 0
    scores_max = max(scores) if scores else 100

    green = Color("#66c2a5")
    red = Color("#fc8d62")
    color_range = list(red.range_to(green, 100))

    def get_color_for_taxa(taxon): 
        avg_score = taxon.children.filter(sequence__all_model_scores__used_for_classification=True).aggregate(score=Avg("sequence__all_model_scores__score"))["score"]
        avg_score = avg_score if avg_score else scores_min
        scaled = int(floor((float(avg_score-scores_min)/float(scores_max-scores_min))*100))
        color_index = scaled if scaled <= 99 else 99
        color_index = color_index if color_index >= 0 else 0
        return str(color_range[color_index])

    taxa = list(sequences.values_list("taxonomy__parent__parent__parent", flat=True).distinct())
    allow_ranks = ["kingdom", "phylum", "order"]
    tree = TaxonomyReference().get_filtered_reference_graph(taxa, allow_ranks=allow_ranks)
    nx.set_node_attributes(tree, "colour", {n:get_color_for_taxa(Taxonomy.objects.get(name=n)) for n,d in tree.out_degree_iter() if d==0})
    
    return json_graph.tree_data(tree, "root", attrs={'children': 'children', 'id': 'name'})
コード例 #3
0
ファイル: views.py プロジェクト: molsim/HistoneDB
def search(request):
    data = {"filter_form": AdvancedFilterForm()}

    if request.method == "POST": 
        query = request.POST.copy()
    else:
        query = request.GET.copy()
    result = HistoneSearch(query, navbar="search" in query.keys())

    data["original_query"] = query

    if len(result.errors) == 0:
        data["result"] = True
    else:
        data["filter_errors"] = result.errors

    if result.redirect: 
        return result.redirect

    green = Color("#66c2a5")
    red = Color("#fc8d62")
    data["colors"] = map(str, red.range_to(green, 12))

    data["score_min"], data["score_max"] = result.get_score_range()

    return render(request, 'search.html', data)
コード例 #4
0
ファイル: database.py プロジェクト: yymm/MemoMemo
    def generate_tag_list(self):
        memos = self.memos
        if len(memos) <= 0:
            return []
        countHash = {}
        for memo in memos:
            tags = memo.tag.split(',')
            for tag in tags:
                s = tag.strip()
                if countHash.has_key(s):
                    countHash[s] += 1
                else:
                    countHash[s] = 1
        tag_list = []
        s = Color('#d16b16')
        e = Color('#87ceed')
        l = len(countHash) if len(countHash) > 1 else 2
        color_list = list(s.range_to(e, l))
        color_cnt = 0
        max_val = max(countHash.values())
        for key, val in sorted(countHash.items(),
                               key=lambda x:x[1],
                               reverse=True):
            tag_dic = {}
            tag_dic['name'] = key
            tag_dic['size'] = (val / max_val) * 100
            tag_dic['num'] = val
            tag_dic['color'] = color_list[color_cnt]
            color_cnt += 1
            tag_list.append(tag_dic)

        return tag_list
コード例 #5
0
    def plot_window_distribution_pie_chart(self):
        """
        Plots a pie chart of how the windows used in the session.
        """
        # Get data
        win_distrib = self.get_time_by_active_window()
        del win_distrib['total']
        keys = win_distrib.keys()
        values = win_distrib.values()

        # Pick colors
        start_color = Color("#CCE5FF")
        colors = map(convert_to_hex, list(start_color.range_to(Color("#003366"), len(keys))))

        # Plot pie chart
        fig, ax = plt.subplots(figsize=(12,8))
        ax.pie(values,
               autopct='%1.0f%%',
               pctdistance=1.1,
               labeldistance=0.5,
               shadow=True,
               startangle=10,
               colors=colors)
        ax.set_title("Pie chart: Time spent by window")
        plt.legend(keys, loc="best",shadow=True)
        plt.show()
コード例 #6
0
ファイル: pymodoroi3.py プロジェクト: dattanchu/pymodoro
    def pymodoro_main(self, i3s_output_list, i3s_config):

        # Don't pass any arguments to pymodoro to avoid conflicts with
        # py3status arguments
        save_argv = sys.argv
        sys.argv = [sys.argv[0]]

        pymodoro = Pymodoro()
        pymodoro.update_state()

        # Get pymodoro output and remove newline
        text = pymodoro.make_output().rstrip()
        pymodoro.tick_sound()

        # Restore argv
        sys.argv = save_argv

        try:
            # If colour is installed, we will display a nice gradient
            # from red to green depending on how many time is left
            # in the current pomodoro
            from colour import Color
            start_c = Color(self.start_color)
            end_c = Color(self.end_color)
            break_c = Color(self.break_color)

            if pymodoro.state == pymodoro.ACTIVE_STATE:
                nb_minutes = int(
                    math.floor(pymodoro.config.session_duration_secs / 60)
                )
                colors = list(end_c.range_to(start_c, nb_minutes))

                seconds_left = pymodoro.get_seconds_left()

                if seconds_left is not None:
                    nb_minutes_left = int(math.floor(seconds_left / 60))
                    if nb_minutes_left >= len(colors):
                        nb_minutes_left = len(colors)-1
                    self.color = colors[nb_minutes_left].hex
                else:
                    self.color = start_c.hex
            else:
                self.color = break_c.hex

        except ImportError:
            # If colour is not installed, use the default color
            pass

        response = {
            'full_text': text,
            'color': self.color,
            # Don't cache anything
            'cached_until': time.time()
        }

        return response
コード例 #7
0
ファイル: color.py プロジェクト: dalou/django-workon
def generate_colors(num, from_color='#f7aabc', to_color='#404a58'):
    """
    Generate `num` distinct Hexadecimal colors
    """
    from_color = Color(from_color)
    to_color = Color(to_color)

    if num == 0:
        return []
    elif num == 1:
        return [from_color.hex]
    return list(c.hex for c in from_color.range_to(to_color, num))
コード例 #8
0
ファイル: util.py プロジェクト: Jonnymcc/circonus
def colors(items):
    """Create a generator which returns colors for each item in ``items``.

    :param list items: The list to generate colors for.
    :rtype: generator(`colour.Color <https://pypi.python.org/pypi/colour>`_)

    """
    if len(items) < 2:
        c = (c for c in (Color("red"),))
    else:
        color_from = Color("red")
        color_to = Color("green")
        c = (color_from.range_to(color_to, len(items)))
    return c
コード例 #9
0
ファイル: rainbow.py プロジェクト: z/rainbow.py
    def get_rainbow(self, phrase):

        phrase_length = len(phrase)

        # chars per color
        cpc = ceil(phrase_length / self.color_count)

        color_start = Color(self.start_color)
        color_end = Color(self.end_color)
        rainbow = list(color_start.range_to(color_end, self.color_count))

        self.rainbow = rainbow
        self.cpc = cpc
        # self.index = next(rainbow)
        self.index = 0

        return {'rainbow': rainbow, 'cpc': cpc}
コード例 #10
0
ファイル: hit.py プロジェクト: davidmcclure/osp
    def color(self, steps=100):

        """
        Get a green -> red scoring color.

        Args:
            steps (int): The number of gradient steps.

        Returns:
            str: A hex color.
        """

        r = Color('#f02424')
        g = Color('#29b730')

        gradient = list(r.range_to(g, steps))
        idx = round(self.field('score')*(steps-1))

        return gradient[idx].get_hex()
コード例 #11
0
ファイル: views.py プロジェクト: Klortho/HistoneDB
def browse_variant(request, histone_type, variant):
    try:
        variant = Variant.objects.get(id=variant)
    except:
        return "404"

    green = Color("#66c2a5")
    red = Color("#fc8d62")
    color_range = map(str, red.range_to(green, 12))

    scores = Sequence.objects.filter(variant__id=variant).filter(all_model_scores__used_for_classifiation=True).annotate(score=Max("all_model_scores__score")).aggregate(max=Max("score"), min=Min("score"))

    data = {
        "core_type": variant.core_type.id,
        "variant": variant.id,
        "name": variant.id,
        "sunburst_url": "browse/sunbursts/{}/{}.json".format(variant.core_type.id, variant.id),
        "seed_file":"browse/seeds/{}/{}".format(variant.core_type.id, variant.id),
        "colors":color_range,
        "score_min":scores["min"],
        "score_max":scores["max"],
        "browse_section": "variant",
        "description": variant.description,
        "filter_form": AdvancedFilterForm(),
    }

    original_query = {"id_variant":variant.id}
    if request.method == "POST":
        query = request.POST.copy()
    else:
        query = original_query
    result = HistoneSearch(request, query, reset=True)

    data["original_query"] = original_query
    if result.errors:
        query = original_query
        data["filter_errors"] = result.errors
    data["current_query"] = query

    return render(request, 'browse_variant.html', data)
コード例 #12
0
def iterateoverList(distribution, time, location):
	print time
	red = Color("red")
	blue = Color("blue")
	colours = list(red.range_to(blue, 100))
   

	client = MongoClient('localhost', 27017)
	db = client.hadoopOuput
	collection = db['13082013']


	with open(time+".css", "a") as myfile:
		for tweet in collection.find({"time": time }):
			for i in range(0, 100):
				if tweet["type"] == "hourly":
					if tweet["location"] in location:
						if tweet["score"] < scoreatpercentile(distribution, i):
							myfile.write("#"+tweet["location"]+"{fill:"+str(colours[i])+"}\n")
							break

	print "Exiting"
	print ""
コード例 #13
0
    def plotGraph(self, g, members, numOfClus):
        """
        generating the graph of vertices and edges
        :param g: graph file to be plotted
        :param members: vector of membership (size = # of SKUs)
        :param numOfClus: number of clusters
        :return: None
        """

        # Setting up the ends of the spectrum
        lime = Color("lime")
        red = Color("red")
        cols = list(red.range_to(lime, numOfClus))
        cols = [str(rang).split()[0] for rang in cols]

        colDict = dict(zip(range(numOfClus), cols))
        print colDict
        # [colDict[m] for m in members]

        visual_style = {}
        visual_style["vertex_size"] = 80
        visual_style["vertex_shape"] = "rectangle"
        visual_style["vertex_color"] = [colDict[m] for m in members]   #[color_dict[gender] for gender in g.vs["gender"]]
        visual_style["vertex_label"] = g.vs['name']
        visual_style["edge_width"] = [w/10 for w in g.es['weight']] #[1 + 2 * int(is_formal) for is_formal in g.es["is_formal"]]
        # visual_style["layout"] = layout
        visual_style["bbox"] = (5500, 4000)
        # visual_style["margin"] = 120
        visual_style["edge_curved"] = False

        plot(g, **visual_style).save(fname= 'graphClus_' +
                                            str(self.timeThresh) + '_' +
                                            str(self.jointViewThresh) + '_' +
                                            str(self.pmiPerc) + '_' +
                                            str(self.method) + '_' +
                                            str(self.sg_lambda))  # , target="diagram.svg" layout = layout,
コード例 #14
0
ファイル: piechart.py プロジェクト: dngroup/simuservice
def do_plot(file):
    title = os.path.basename(file)[:-5]
    fig = plt.figure()
    ax = fig.gca()

    # read the file
    data = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))
    data_pc = collections.defaultdict(lambda: collections.defaultdict(lambda: 0))
    print(("%s" % file))
    with open(file) as f:

        for name, bw, type in [x for x in list(csv.reader(f)) if len(x) == 3]:
            data[type][name] += float(bw) / 1000.0

    # get the %
    total_size = np.sum([data[a][b] for a in data for b in data[a]])
    for key1 in data:
        for key2 in data[key1]:
            data_pc[key1][key2] = data[key1][key2] * 1.0 / total_size

    for type in list(data.keys()):
        print(("%s" % type))
        for name in data[type]:
            print(("\t%s:%lf%% or %lf" % (name, 100 * data_pc[type][name], data[type][name])))

    # solution here: http://stackoverflow.com/questions/20549016/explode-multiple-slices-of-pie-together-in-matplotlib


    ax.set_aspect('equal')
    ax.axis('off')

    colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']

    sizes_cat = [np.sum([data[a][b] for b in sorted(data[a])]) for a in sorted(data) if a != "Content"]
    sizes_cat_labels = ["%s (%1.1lf Gbps)" % (a, np.sum(list(data[a].values()))) for a in sorted(data) if a != "Content"]
    sizes_content = [data[a][b] for a in sorted(data) for b in sorted(data[a]) if a == "Content" if
                     data_pc[a][b] > CUTOFF]
    sizes_content_other_content = np.sum([data[a][b] for a in sorted(data) for b in sorted(data[a]) if a == "Content" if
                                          data_pc[a][b] <= CUTOFF])
    sizes_content_labels = ["%s (%1.1lf Gbps)" % (b, data[a][b]) for a in sorted(data) for b in sorted(data[a]) if
                            a == "Content" if data_pc[a][b] > CUTOFF]

    sizes_content.append(sizes_content_other_content)
    sizes_content_labels.append("Other Content (%1.1lf Gbps)" % sizes_content[-1])

    from colour import Color
    grey = Color("#cccccc")
    red = Color("red")
    orange = Color("#880000")

    color_cat = [c.get_hex_l() for c in grey.range_to(Color("white"), len(sizes_cat))]
    color_content = [c.get_hex_l() for c in red.range_to(orange, len(sizes_content))]

    wedges, texts, _ = ax.pie(np.append(sizes_cat, sizes_content),
                              labels=np.append(sizes_cat_labels, sizes_content_labels),
                              colors=np.append(color_cat, color_content), radius=1.5, autopct='%1.1f%%', startangle=90,
                              shadow=True, )

    for wedge in wedges[len(color_cat):]:
        wedge.set_lw(2)

    plt.xkcd()
    ax.autoscale(True)
    ax.set_title(title)
    plt.savefig("pie.svg")
    plt.show()
コード例 #15
0
ファイル: main.py プロジェクト: dterracino/PirateMap
def render(seed=None):
    random.seed(seed)
    width = height = 512
    scale = 2
    surface = cairo.ImageSurface(cairo.FORMAT_RGB24,
        width * scale, height * scale)
    dc = cairo.Context(surface)
    dc.set_line_cap(cairo.LINE_CAP_ROUND)
    dc.set_line_join(cairo.LINE_JOIN_ROUND)
    dc.scale(scale, scale)
    layer = make_layer()
    # layer.save('layer.png', 0, 0, width, height)
    points = poisson_disc(0, 0, width, height, 8, 16)
    shape1 = layer.alpha_shape(points, 0.1, 1, 0.1).buffer(-4).buffer(4)
    shape2 = layer.alpha_shape(points, 0.3, 1, 0.1).buffer(-8).buffer(4)
    shape3 = layer.alpha_shape(points, 0.12, 0.28, 0.1).buffer(-12).buffer(4)
    points = [x for x in points
        if shape1.contains(Point(*x)) and layer.get(*x) >= 0.25]
    path = find_path(layer, points, 16)
    mark = path[0]
    # water background
    dc.set_source_rgb(*Color('#2185C5').rgb)
    dc.paint()
    # shallow water
    n = 5
    shape = shape1.simplify(8).buffer(32).buffer(-16)
    shapes = [shape]
    for _ in range(n):
        shape = shape.simplify(8).buffer(64).buffer(-32)
        shape = xkcdify(shape, 2, 8)
        shapes.append(shape)
    shapes.reverse()
    c1 = Color('#4FA9E1')
    c2 = Color('#2185C5')
    for c, shape in zip(c2.range_to(c1, n), shapes):
        dc.set_source_rgb(*c.rgb)
        render_shape(dc, shape)
        dc.fill()
    # height
    dc.save()
    dc.set_source_rgb(*Color('#CFC291').rgb)
    for _ in range(5):
        render_shape(dc, shape1)
        dc.fill()
        dc.translate(0, 1)
    dc.restore()
    # sandy land
    dc.set_source_rgb(*Color('#FFFFA6').rgb)
    render_shape(dc, shape1)
    dc.fill()
    # grassy land
    dc.set_source_rgb(*Color('#BDF271').rgb)
    render_shape(dc, shape2)
    dc.fill()
    # dark sand
    dc.set_source_rgb(*Color('#CFC291').rgb)
    render_shape(dc, shape3)
    dc.fill()
    # path
    dc.set_source_rgb(*Color('#DC3522').rgb)
    render_curve(dc, path, 4)
    dc.set_dash([4])
    dc.stroke()
    dc.set_dash([])
    # mark
    dc.set_source_rgb(*Color('#DC3522').rgb)
    render_mark(dc, *mark)
    dc.set_line_width(4)
    dc.stroke()
    # compass
    dc.save()
    dc.translate(48, height - 64)
    dc.rotate(random.random() * math.pi / 4 - math.pi / 8)
    render_compass(dc)
    dc.restore()
    return surface
コード例 #16
0
fdataT = np.zeros((nb_channels, buffersize))

dataRS1 = np.zeros(
    (nb_channels, buffersize,
     restingStateDuration))  # need to store every chunk to reprocess the ratio
fdataRS1 = np.zeros((nb_channels, buffersize, restingStateDuration))

dataRS2 = np.zeros(
    (nb_channels, buffersize,
     restingStateDuration))  # need to store every chunk to reprocess the ratio
fdataRS2 = np.zeros((nb_channels, buffersize, restingStateDuration))
'''background'''
screen = pg.display.set_mode((w_display, h_display), RESIZABLE)
'''training game'''
red = Color("red")
colors = list(red.range_to(Color("green"), 100))
'''Resting state'''
timerImage = pg.image.load(timer[0])
timerImage = pg.transform.scale(
    timerImage,
    (int(math.floor(0.068 * w_display)), int(math.floor(0.156 * h_display))))
restingDebutImage = pg.image.load(restingStateDebutPath).convert()
restingFinImage = pg.image.load(restingStateFinPath).convert()
restingStateDebutImage = pg.transform.scale(restingDebutImage,
                                            (w_display, h_display))
restingStateFinImage = pg.transform.scale(restingFinImage,
                                          (w_display, h_display))

# '''Tinnitus questionnaire '''
# questionsSerie1Image = pg.image.load(questionsSerie1)
# questionsSerie1Image = pg.transform.scale(questionsSerie1Image, (w_display, h_display))
コード例 #17
0
def probToHex(prob: float):
    lightBlue = Color("#CDD9EE")
    darkBlue = Color("#02235B")
    colors = list(lightBlue.range_to(darkBlue, 101))
    probIndex = int(round(prob, 2) * 100)
    return colors[probIndex]
コード例 #18
0
set_option('display.max_rows', 500)
figure(figsize=(30, 27), dpi=200)
start = df.launched
start = [x.split(" ")[0] for x in start]
weekdays = []
date_format = "%Y-%m-%d"
for i in range(len(start)):
    date = datetime.strptime(start[i], date_format)
    weekdays.append(date.weekday())

df3 = DataFrame({"weekdays": weekdays, "state": df.state})

categories = df3.groupby(['weekdays', 'state']).size()

red = Color("gold")
colors = list(red.range_to(Color("blue"), 5))
colors = [x.get_hex() for x in colors if len(x.get_hex()) == 7]
colors = colors[2:]

z = categories.index.set_levels(
    [[calendar.day_name[i] for i in range(0, 7)],
     ['canceled', 'failed', 'live', 'successful', 'suspended']])
categories.index = z

ax = categories.plot(
    kind='bar',
    color=['yellow', 'red', 'blue', 'lime', 'purple'],
    title='Money collected by projects started in particular years',
    fontsize=20)
ax.set_xlabel("Years", fontsize=25)
ax.set_ylabel("Collected money [USD]", fontsize=25)
コード例 #19
0
ファイル: camera.py プロジェクト: yosemitebandit/setbot
print 'done.'
say('ready')

# Setup the output image for the debug and gameplay windows.
output_image_width = output_card_height * cards_per_col
display_width_buffer = output_card_width
output_image_height = (output_card_width * max_number_of_cols +
                       display_width_buffer +
                       output_card_width * max_number_of_cols +
                       output_card_width)
gameplay_output_frame_width = 1000

# Setup a green-to-red color gradient for drawing rectangles.
red = Color('red')
lime = Color('lime')
gradient = list(red.range_to(lime, 100))

# Start the camera.
while True:
  _, frame = vc.read()

  if frame is not None:
    # Get time for fps.
    now = time.time()

    # Set white threshold.
    lower_white = np.array([0, 0, 255-sensitivity])
    upper_white = np.array([255, sensitivity, 255])

    # Set white threshold and find possible cards.
    hsv_img = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
コード例 #20
0
ファイル: views.py プロジェクト: molsim/HistoneDB
def browse_variant(request, histone_type, variant, gi=None):
    """"Dispaly the browse variant page

    Parameters
    ----------
    request : Django request
    histone_type : {"H2A", "H2B", "H3", "H4", "H1"}
    variant : str
        Name of variant
    gi : str or int
        GI to select to show it curated sequence browser. Optional. If specified, should open curated sequences page and activate this variant.
    """
    # variant = variant.replace("_", "") if "canonical" in variant else variant
    #the previous line currenly breaks the code. ALEXEY, 12/30/15
    try:
        variant = Variant.objects.get(id=variant)
    except:
        return "404"

    #This is a hack to open a page with features from Analyze your seqs page, where we do not know the type
    # Then we say type is ALL , ALEXEY
    if histone_type=='ALL':
        histone_type=Variant.objects.get(id=variant).hist_type

    go_to_curated = gi is not None
    print gi, "!!!!!!!"
    go_to_gi = gi if gi is not None else 0
    highlight_human=False
#Here we want always by default highlight human
    if not go_to_curated:
        try:
            go_to_gi=Sequence.objects.filter(variant=variant,taxonomy__id__in=["9606","10090"]).order_by('taxonomy').first().gi
            highlight_human=True
        except:
            pass

    green = Color("#66c2a5")
    red = Color("#fc8d62")
    color_range = map(str, red.range_to(green, 12))
    
    scores = Sequence.objects.filter(
            variant__id=variant,
            all_model_scores__used_for_classification=True
        ).annotate(
            score=Max("all_model_scores__score")
        ).aggregate(
            max=Max("score"), 
            min=Min("score")
        )

#Distinct will not work here, because we order by "start", which is also included - see https://docs.djangoproject.com/en/dev/ref/models/querysets/#distinct
    features_gen = Feature.objects.filter(template__variant="General{}".format(histone_type)).values_list("name", "description", "color").distinct()
    features_var = Feature.objects.filter(template__variant=variant).values_list("name", "description", "color").distinct()

    features_gen=list(unique_everseen(features_gen))
    features_var=list(unique_everseen(features_var))

    sequences = Sequence.objects.filter(
            variant__id=variant,
            all_model_scores__used_for_classification=True
        ).annotate(
            score=Max("all_model_scores__score")
        ).order_by("score")

    human_sequence = sequences.filter(taxonomy__name="h**o sapiens", reviewed=True).first()
    # if not human_sequence:
    #     human_sequence = sequences.filter(taxonomy__name="h**o sapiens").first()
    if not human_sequence:
        human_sequence = sequences.filter(reviewed=True).first()
    print human_sequence

    try:
        publication_ids = ",".join(map(str, variant.publication_set.values_list("id", flat=True)))
        handle = Entrez.efetch(db="pubmed", id=publication_ids, rettype="medline", retmode="text")
        records = Medline.parse(handle)
        publications = ['{}. "{}" <i>{}</i>, {}. PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/?term={}">{}</a>'.format(
            "{}, {}, et al".format(*record["AU"][0:2]) if len(record["AU"])>2 else " and ".join(record["AU"]) if len(record["AU"])==2 else record["AU"][0],
            record["TI"],
            record["TA"],
            re.search("\d\d\d\d",record["SO"]).group(0),
            record["PMID"],
            record["PMID"],
            ) for record in records]
    except:
        publications=map(lambda x: "PMID: "+str(x),variant.publication_set.values_list("id", flat=True))

    data = {
        "hist_type": variant.hist_type.id,
        "variant": variant.id,
        "name": variant.id,
        "features_gen": features_gen,
        "features_var": features_var,
        "human_sequence":human_sequence.id,
        "publications":publications,
        "sunburst_url": static("browse/sunbursts/{}/{}.json".format(variant.hist_type.id, variant.id)),
        "seed_url": reverse("browse.views.get_seed_aln_and_features", args=[variant.id]),
        "colors":color_range,
        "score_min":scores["min"],
        "score_max":scores["max"],
        "browse_section": "variant",
        "description": variant.description,
        "alternate_names": ", ".join(variant.old_names.values_list("name", flat=True)),
        "filter_form": AdvancedFilterForm(),
        "go_to_curated":go_to_curated,
        "go_to_gi":go_to_gi,
        "highlight_human":highlight_human,
    }

    data["original_query"] = {"id_variant":variant.id}

    return render(request, 'browse_variant.html', data)
コード例 #21
0
def main():
    global payload

    # argument parsing
    parser = argparse.ArgumentParser()
    parser.add_argument('--headless',
                        help='run the pygame headlessly',
                        action='store_true')

    parser.add_argument("--color_depth",
                        help="integer number of colors to use to draw temps",
                        type=int)
    parser.add_argument('--max_temp', help='initial max temperature', type=int)
    parser.add_argument(
        '--ambient_offset',
        help='value to offset ambient temperature by to get rolling MAXTEMP',
        type=int)
    parser.add_argument(
        '--ambient_time',
        help='length of ambient temperature collecting intervals in seconds',
        type=int)

    parser.add_argument('--blob_min_threshold',
                        help='blod detection min threshold',
                        type=int)
    parser.add_argument('--blob_max_threshold',
                        help='blod detection min threshold',
                        type=int)

    parser.add_argument('--blob_filterbyarea',
                        help='blod detection filter by area',
                        action='store_true')
    parser.add_argument('--blob_min_area',
                        help='blod detection filter by area min area',
                        type=int)

    parser.add_argument('--blob_filterbycircularity',
                        help='blod detection filter by circularity',
                        action='store_true')
    parser.add_argument(
        '--blob_min_circularity',
        help='blod detection filter by circularity min circularity',
        type=float)

    parser.add_argument('--blob_filterbyconvexity',
                        help='blod detection filter by convexity',
                        action='store_true')
    parser.add_argument(
        '--blob_min_convexity',
        help='blod detection filter by convexity min convexity',
        type=float)

    parser.add_argument('--blob_filterbyinertia',
                        help='blod detection filter by inertia',
                        action='store_true')
    parser.add_argument('--blob_min_inertiaratio',
                        help='blod detection filter by inertia inertia ratio',
                        type=float)

    parser.add_argument('--csv_save_interval',
                        help='csv file saving interval in seconds',
                        type=int)

    args = parser.parse_args()
    print(args)

    COLOR_DEPTH = args.color_depth
    MAX_TEMP = args.max_temp
    AMBIENT_OFFSET = args.ambient_offset
    AMBIENT_TIME = args.ambient_time

    BLOB_MIN_THRESHOLD = args.blob_min_threshold
    BLOB_MAX_THRESHOLD = args.blob_max_threshold

    BLOB_FILTERBYAREA = args.blob_filterbyarea
    BLOB_MIN_AREA = args.blob_min_area

    BLOB_FILTERBYCIRCULARITY = args.blob_filterbycircularity
    BLOB_MIN_CIRCULARITY = args.blob_min_circularity

    BLOB_FILTERBYCONVEXITY = args.blob_filterbyconvexity
    BLOB_MIN_CONVEXITY = args.blob_min_convexity

    BLOB_FILTERBYINERTIA = args.blob_filterbyinertia
    BLOB_MIN_INERTIARATIO = args.blob_min_inertiaratio

    CSV_SAVE_INTERVAL = args.csv_save_interval

    # create data folders if they don't exist
    if not os.path.exists(get_filepath('../data')):
        os.makedirs(get_filepath('../data'))

    i2c_bus = busio.I2C(board.SCL, board.SDA)

    # For headless pygame
    if args.headless:
        os.putenv('SDL_VIDEODRIVER', 'dummy')
    else:
        os.putenv('SDL_FBDEV', '/dev/fb1')

    pygame.init()

    # initialize the sensor
    sensor = adafruit_amg88xx.AMG88XX(i2c_bus)

    points = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
    grid_x, grid_y = np.mgrid[0:7:32j, 0:7:32j]

    # sensor is an 8x8 grid so lets do a square
    height = 240
    width = 240

    # the list of colors we can choose from
    black = Color("black")
    colors = list(black.range_to(Color("white"), COLOR_DEPTH))

    # create the array of colors
    colors = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255))
              for c in colors]

    displayPixelWidth = width / 30
    displayPixelHeight = height / 30

    lcd = pygame.display.set_mode((width, height))

    lcd.fill((255, 0, 0))

    pygame.display.update()
    pygame.mouse.set_visible(False)

    lcd.fill((0, 0, 0))
    pygame.display.update()

    # Setup SimpleBlobDetector parameters.
    params = cv2.SimpleBlobDetector_Params()

    # Change thresholds
    if BLOB_MIN_THRESHOLD:
        params.minThreshold = BLOB_MIN_THRESHOLD
    if BLOB_MAX_THRESHOLD:
        params.maxThreshold = BLOB_MAX_THRESHOLD

    # Filter by Area.
    if BLOB_FILTERBYAREA:
        params.filterByArea = BLOB_FILTERBYAREA
        params.minArea = BLOB_MIN_AREA

    # Filter by Circularity
    if BLOB_FILTERBYCIRCULARITY:
        params.filterByCircularity = BLOB_FILTERBYCIRCULARITY
        params.minCircularity = BLOB_MIN_CIRCULARITY

    # Filter by Convexity
    if BLOB_FILTERBYCONVEXITY:
        params.filterByConvexity = BLOB_FILTERBYCONVEXITY
        params.minConvexity = BLOB_MIN_CONVEXITY

    # Filter by Inertia
    if BLOB_FILTERBYINERTIA:
        params.filterByInertia = BLOB_FILTERBYINERTIA
        params.minInertiaRatio = BLOB_MIN_INERTIARATIO

    # Set up the detector with default parameters.
    detector = cv2.SimpleBlobDetector_create(params)

    # initialize centroid tracker
    ct = CentroidTracker()

    # a dictionary to map each unique object ID to a TrackableObject
    trackableObjects = {}

    # the total number of objects that have moved either up or down
    total_down = 0
    total_up = 0
    total_down_old = 0
    total_up_old = 0

    # let the sensor initialize
    time.sleep(.1)

    # press key to exit
    screencap = True

    # array to hold mode of last 10 minutes of temperatures
    mode_list = []

    # thread for saving data
    save_thread = threading.Thread(target=csv_save, args=(CSV_SAVE_INTERVAL, ))
    save_thread.start()

    print('sensor started!')

    while (screencap):
        start = time.time()

        # read the pixels
        pixels = []
        for row in sensor.pixels:
            pixels = pixels + row

        payload = [
            str(datetime.now().isoformat()),
            ct.get_count(), total_up, total_down
        ]

        mode_result = stats.mode([round(p) for p in pixels])
        mode_list.append(int(mode_result[0]))

        # instead of taking the ambient temperature over one frame of data take it over a set amount of time
        MAX_TEMP = float(np.mean(mode_list)) + AMBIENT_OFFSET
        pixels = [
            map_value(p,
                      np.mean(mode_list) + 1, MAX_TEMP, 0, COLOR_DEPTH - 1)
            for p in pixels
        ]

        # perform interpolation
        bicubic = griddata(points, pixels, (grid_x, grid_y), method='cubic')

        # draw everything
        for ix, row in enumerate(bicubic):
            for jx, pixel in enumerate(row):
                try:
                    pygame.draw.rect(
                        lcd, colors[constrain(int(pixel), 0, COLOR_DEPTH - 1)],
                        (displayPixelHeight * ix, displayPixelWidth * jx,
                         displayPixelHeight, displayPixelWidth))
                except:
                    print("Caught drawing error")

        surface = pygame.display.get_surface()
        myfont = pygame.font.SysFont("comicsansms", 25)

        img = pygame.surfarray.array3d(surface)
        img = np.swapaxes(img, 0, 1)

        # Read image
        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        img_not = cv2.bitwise_not(img)

        # Detect blobs.
        keypoints = detector.detect(img_not)
        img_with_keypoints = cv2.drawKeypoints(
            img, keypoints, np.array([]), (0, 0, 255),
            cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

        # draw a horizontal line in the center of the frame -- once an
        # object crosses this line we will determine whether they were
        # moving 'up' or 'down'
        pygame.draw.line(lcd, (255, 255, 255), (0, height // 2),
                         (width, height // 2), 2)
        pygame.display.update()

        for i in range(0, len(keypoints)):
            x = keypoints[i].pt[0]
            y = keypoints[i].pt[1]

            # print circle around blob
            pygame.draw.circle(lcd, (200, 0, 0), (int(x), int(y)),
                               round(keypoints[i].size), 2)

        # update our centroid tracker using the detected centroids
        objects = ct.update(keypoints)

        # loop over the tracked objects
        for (objectID, centroid) in objects.items():
            # check to see if a trackable object exists for the current
            # object ID
            to = trackableObjects.get(objectID, None)

            # if there is no existing trackable object, create one
            if to is None:
                to = TrackableObject(objectID, centroid)

            # otherwise, there is a trackable object so we can utilize it
            # to determine direction
            else:
                # the difference between the y-coordinate of the *current*
                # centroid and the mean of *previous* centroids will tell
                # us in which direction the object is moving (negative for
                # 'up' and positive for 'down')
                y = [c[1] for c in to.centroids]
                direction = centroid[1] - np.mean(y)
                to.centroids.append(centroid)

                # check to see if the object has been counted or not
                if not to.counted:
                    # if the direction is negative (indicating the object
                    # is moving up) AND the centroid is above the center
                    # line, count the object
                    # the historical centroid must present in the lower half of the screen
                    if direction < 0 and centroid[
                            1] < height // 2 and count_within_range(
                                y, height // 2, height) > 0:
                        total_up += 1
                        to.counted = True

                    # if the direction is positive (indicating the object
                    # is moving down) AND the centroid is below the
                    # center line, count the object
                    # the historical centroid must present in the upper half of the screen
                    elif direction > 0 and centroid[
                            1] > height // 2 and count_within_range(
                                y, 0, height // 2) > 0:
                        total_down += 1
                        to.counted = True

            # store the trackable object in our dictionary
            trackableObjects[objectID] = to

        # update counter in top left
        textsurface1 = myfont.render("IN: " + str(total_up), False,
                                     (255, 255, 255))
        textsurface2 = myfont.render('OUT: ' + str(total_down), False,
                                     (255, 255, 255))
        lcd.blit(textsurface1, (0, 0))
        lcd.blit(textsurface2, (0, 25))

        total_up_old = total_up
        total_down_old = total_down

        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                print('terminating...')
                screencap = False
                break

        # for running the save on for a certain amount of time
        # if time.time() - start_time >= 10:
        #    print('terminating...')
        #    screencap = False

        # empty mode_list every AMBIENT_TIME seconds
        if len(mode_list) > AMBIENT_TIME:
            mode_list = []
        time.sleep(max(1. / 25 - (time.time() - start), 0))

    # Release everything if job is finished
    cv2.destroyAllWindows()
コード例 #22
0
import unicornhat as unicorn

unicorn.set_layout(unicorn.PHAT) # mini hat
unicorn.brightness(0.5)
unicorn.rotation(0)


# Make these global values to save calculating them each time
white = Color("white")
blue = Color("blue")
green = Color("green")
yellow = Color("yellow")
red = Color("red")

blue_to_white = list(blue.range_to(white, 11))
white_to_green = list(white.range_to(green, 11))
green_to_yellow = list(green.range_to(yellow, 11))
yellow_to_red = list(yellow.range_to(red, 11))

colours_range_total = blue_to_white + white_to_green[1:] + green_to_yellow[1:] + yellow_to_red[1:]
# Got to make sure we get rid of repeated fencepost colours


def temperature_to_hue(temperature):
    if temperature < -10:
        colour_choice = one_range_to_255_range(blue.rgb)
    elif temperature > 30:
        colour_choice = one_range_to_255_range(red.rgb)
    else:
        index = int(temperature) + 10
    def render(self, mode='human'):
        from gym.envs.classic_control import rendering
        from colour import Color
        red = Color('red')
        colors = list(red.range_to(Color('green'), self.num_aircraft))

        if self.viewer is None:
            self.viewer = rendering.Viewer(self.window_width,
                                           self.window_height)
            self.viewer.set_bounds(0, self.window_width, 0, self.window_height)

        import os
        __location__ = os.path.realpath(
            os.path.join(os.getcwd(), os.path.dirname(__file__)))

        # vertiport_map_img = rendering.Image(os.path.join(__location__, 'images/vertiport_map.png'), 800, 800)
        # jtransform = rendering.Transform(rotation=0, translation=[400, 400])
        # vertiport_map_img.add_attr(jtransform)
        # self.viewer.onetime_geoms.append(vertiport_map_img)

        for id, aircraft in self.aircraft_dict.ac_dict.items():
            aircraft_img = rendering.Image(
                os.path.join(__location__, 'images/aircraft.png'), 32, 32)
            jtransform = rendering.Transform(rotation=aircraft.heading -
                                             math.pi / 2,
                                             translation=aircraft.position)
            aircraft_img.add_attr(jtransform)
            r, g, b = colors[aircraft.id % self.num_aircraft].get_rgb()
            aircraft_img.set_color(r, g, b)
            self.viewer.onetime_geoms.append(aircraft_img)

            goal_img = rendering.Image(
                os.path.join(__location__, 'images/goal.png'), 32, 32)
            jtransform = rendering.Transform(
                rotation=0, translation=aircraft.goal.position)
            goal_img.add_attr(jtransform)
            goal_img.set_color(r, g, b)
            self.viewer.onetime_geoms.append(goal_img)

        for veriport in self.vertiport_list:
            vertiport_img = rendering.Image(
                os.path.join(__location__, 'images/verti.png'), 32, 32)
            jtransform = rendering.Transform(rotation=0,
                                             translation=veriport.position)
            vertiport_img.add_attr(jtransform)
            self.viewer.onetime_geoms.append(vertiport_img)

        for sector in self.sectors:
            if sector.id == 0:
                for i, exit in enumerate(sector.exits):
                    exit_img = self.viewer.draw_polygon(Config.vertices)
                    jtransform = rendering.Transform(
                        rotation=math.radians(60 * i - 90),
                        translation=exit[0])
                    exit_img.add_attr(jtransform)
                    exit_img.set_color(255 / 255.0, 165 / 255.0, 0)
                    self.viewer.onetime_geoms.append(exit_img)

            else:
                for i, exit in enumerate(sector.exits):
                    exit_img = self.viewer.draw_polygon(Config.vertices)
                    angle = 60 * (sector.id + i) + 30
                    jtransform = rendering.Transform(
                        rotation=math.radians(angle), translation=exit[0])
                    exit_img.add_attr(jtransform)
                    exit_img.set_color(255 / 255.0, 165 / 255.0, 0)
                    # if i % 2 == 0:
                    #     exit_img.set_color(255 / 255.0, 192 / 255.0, 203 / 255.0)  # pick
                    # else:
                    #     exit_img.set_color(255 / 255.0, 165 / 255.0, 0)  # yellow
                    self.viewer.onetime_geoms.append(exit_img)

        self.viewer.draw_polyline(
            Config.vertiport_loc[[1, 2, 3, 4, 5, 6, 1], :])
        for sector in self.sectors:
            self.viewer.draw_polyline(
                sector.vertices[[0, 1, 2, 3, 4, 5, 0], :])

        return self.viewer.render(return_rgb_array=False)
コード例 #24
0
import plotly.io as pio
from colour import Color

#Color Reference
#============================================================================================

c1 = Color('#ff0074')
c2 = Color('#19000b')
gradient1 = list(c1.range_to(Color(c2), 10))
gradient1 = [c.get_hex() for c in gradient1]

c1 = Color('#00bfff')
c2 = Color('#001319')
gradient2 = list(c1.range_to(Color(c2), 10))
gradient2 = [c.get_hex() for c in gradient2]

colors = [gradient1, gradient2]

#Plotly Settings
#============================================================================================

pio.templates.default = "plotly_dark"
template = pio.templates["plotly_dark"].layout

template.paper_bgcolor = '#1a1818'
template.font = {'color': '#f2f5fa', 'family': 'Rockwell'}

template.title = {'x': 0.5, 'font_size': 22}
template.xaxis.title = {'font_size': 18}
template.yaxis.title = {'font_size': 18}
コード例 #25
0
net = CrowdCounter()

trained_model = os.path.join(model_path)
network.load_net(trained_model, net)
net.cuda()
net.eval()

fff = time.time()
count = 0

density_range = 1000
gradient = np.linspace(0, 1, density_range)
cmap = plt.get_cmap("rainbow")
initial = Color("blue")
hex_colors = list(initial.range_to(Color("red"), density_range))
rgb_colors = [[rgb * 255 for rgb in color.rgb] for color in hex_colors]

es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 3))

starttime = time.time()
for image in os.listdir(data_path):
    video_path = os.path.join(data_path, image)
    print(video_path)
    cap = cv2.VideoCapture(video_path)
    print("OK1!")
    fps = cap.get(cv2.CAP_PROP_FPS)
    #fps =1
    size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
            int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    fourcc = cv2.VideoWriter_fourcc(*'X264')
コード例 #26
0
# The Mapbox Access Token
mapbox_access_token = "pk.eyJ1IjoiYWRpMDAwMTQiLCJhIjoiY2p1dTdkbWY4MGVpaTQzbzFva2cweWxseCJ9.t96aiUa7p4oBmGy2XDtrkg"

df = pd.read_csv('automation_data.csv', sep=',', engine='python')
lat_long = pd.read_csv('statelatlong.csv', sep=',', engine='python')
categoryCode = pd.DataFrame(df['SOC'].str.slice(start=0, stop=2))

jobs_criteria = df[lat_long['State']][(df.Probability >= 0.7)
                                      & (df.Probability <= 1.0)].sum()
total = df[lat_long['State']].sum()
percentage = ((jobs_criteria / total) * 100).values.astype(str)
lat_long['percentage'] = percentage

green = Color("#08db28")
colors = (list(green.range_to(Color("#db0808"), 52)))

legend_range = [
    '<10%', '11-20%', '21-30%', '31-40%', '41-50%', '51-60%', '61-70%',
    '71-80%', '81-90%', '91-100%'
]

app.title = 'The Automation Wave'

# Main Div
app.layout = html.Div(children=[

    # Header
    html.Div(
        [
            html.H1(['The Automation Wave'],
コード例 #27
0
ファイル: _timemaps.py プロジェクト: zephyrthenoble/time-maps
def make_time_map(
        times, times_tot_mins, sep_array, Ncolors,
        title):  # plot standard, scatter-plot time map. Nothing is returned

    print("rendering normal time map ...")

    ## set up color list
    red = Color("red")
    blue = Color("blue")
    color_list = list(
        red.range_to(blue, Ncolors)
    )  # range of colors evenly speced on the spectrum between red and blue. Each element is a colour object
    color_list = [c.hex for c in color_list]  # give hex version

    fig = plt.figure()
    ax = fig.add_subplot(111)

    plt.rc("text", usetex=False)
    plt.rc("font", family="serif")

    colormap = plt.cm.get_cmap(
        "rainbow"
    )  # see color maps at http://matplotlib.org/users/colormaps.html

    order = np.argsort(times_tot_mins[1:-1])  # so that the red dots are on top
    # 	order=np.arange(1,len(times_tot_mins)-2) # dots are unsorted

    sc = ax.scatter(
        sep_array[:, 0][order],
        sep_array[:, 1][order],
        c=times_tot_mins[1:-1][order],
        vmin=0,
        vmax=24 * 60,
        s=25,
        cmap=colormap,
        marker="o",
        edgecolors="none",
    )
    # taken from http://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter

    color_bar = fig.colorbar(
        sc,
        ticks=[0, 24 * 15, 24 * 30, 24 * 45, 24 * 60],
        orientation="horizontal",
        shrink=0.5,
    )
    color_bar.ax.set_xticklabels(
        ["Midnight", "18:00", "Noon", "6:00", "Midnight"])
    color_bar.ax.invert_xaxis()
    color_bar.ax.tick_params(labelsize=16)

    ax.set_yscale("log")  # logarithmic axes
    ax.set_xscale("log")

    plt.minorticks_off()
    pure_ticks = np.array([
        1e-3, 1, 10, 60 * 10, 2 * 3600, 1 * 24 * 3600, 7 * 24 * 3600
    ])  # where the tick marks will be placed, in units of seconds.
    labels = [
        "1 ms",
        "1 s",
        "10 s",
        "10 m",
        "2 h",
        "1 d",
        "1 w",
    ]  # tick labels

    max_val = np.max([np.max(sep_array[:, 0]), np.max(sep_array[:, 1])])

    ticks = np.hstack((pure_ticks, max_val))

    min_val = np.min([np.min(sep_array[:, 0]), np.min(sep_array[:, 1])])

    plt.xticks(ticks, labels, fontsize=16)
    plt.yticks(ticks, labels, fontsize=16)

    plt.xlabel("Time Before Tweet", fontsize=18)
    plt.ylabel("Time After Tweet", fontsize=18)
    plt.title(title)

    plt.xlim((min_val, max_val))
    plt.ylim((min_val, max_val))

    ax.set_aspect("equal")
    plt.tight_layout()

    plt.show()
コード例 #28
0
                    "0.45-0.475",
                    "0.475-0.5",
                    "0.5-0.525",
                    "0.525-0.55",
                    "0.55-0.575",
                    "0.575-0.6",
                    "0.6-0.625",
                    "0.625-0.65"
                    ]  # 0.95-0.975 and 0.975-1.0 have been removed, add it again

topology = 'fc'  
step = 0.025
bins = 100
num_colors = len(results_folders)
red = Color("green")
colors = list(red.range_to(Color("red"),num_colors))
files_pattern = "./results/@topology@/@accuracy@/*fixed_topology-64-32-10_random-normal-0-10.00*.npy"  # wildcards for topology and accuracy
files_pattern = files_pattern.replace('@topology@', topology)
saved_images_path = "./images/{}/".format(topology)


###############################################################################
# HISTOGRAMS
###############################################################################

# LINK WEIGHTS
# INPUT: Link weights histogram (LAYER 0)
print("\n[logger]: Link weights histogram")
for acc, i in zip(results_folders, range(num_colors)):
    print("[logger]: Processing results {}".format(acc))    
    files_ = files_pattern.replace('@accuracy@', acc)    
コード例 #29
0
ファイル: flowlib.py プロジェクト: RainbowFS/flow-matrix
from influxdb import DataFrameClient
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib

matplotlib.use('Agg')
import matplotlib.pyplot as plt

import io
from colour import Color

white = Color("white")
to_blue = list(white.range_to(Color("blue"), 10))
to_red = list(white.range_to(Color("red"), 10))

query_template = """SELECT last("bytes") as value FROM "telegraf"."autogen"."nftables" WHERE time > now() - 1h AND "host_app_dst"='%s' AND "host_app_src"='%s' GROUP BY time(10w) FILL(null)"""
query_template_full = """SELECT last("bytes") as value FROM "telegraf"."autogen"."nftables" WHERE time > now() - 1h AND "host_app_dst_port"='%s' AND "host_app_src"='%s' GROUP BY time(10w) FILL(null)"""


def sizeof_get_color(num, matrix_mean=0, std_dev=999999999999):
    try:
        if num < matrix_mean:
            col = to_blue[min(int(abs(num - matrix_mean) / std_dev),
                              len(to_blue) - 1)]
        else:
            col = to_red[min(int(abs(num - matrix_mean) / std_dev),
                             len(to_red) - 1)]

        return col.get_web()
    except:
コード例 #30
0
ファイル: imageTest.py プロジェクト: iMurfyD/Lepton-Balloon
import png
from colour import Color
import math
import sys

WIDTH = 80
HEIGHT = 40
MAXVAL = 255

red = Color("red")
colors = list(red.range_to(Color("blue"),WIDTH*HEIGHT))

frame = []
row = []

#img = Image.new('RGB',(WIDTH,HEIGHT))
for j in range(0,HEIGHT):
    row = []
    for i in range(0,WIDTH):
        row.append( math.floor(colors[WIDTH*j+i].red*MAXVAL))
        row.append(math.floor(colors[WIDTH*j+i].green*MAXVAL))
        row.append(math.floor(colors[WIDTH*j+i].blue*MAXVAL))
    frame.append(row)
        #hex_data[WIDTH*j+i] = pix_color
        #print(hex_data)
print(frame)
png.from_array(frame,'RGB').save('gradient.png')
コード例 #31
0
ファイル: flowlib.py プロジェクト: RainbowFS/flow-matrix
def get_svg(d):
    black = Color("black")
    to_red = list(black.range_to(Color("red"), 5))
    to_blue = list(black.range_to(Color("blue"), 5))

    d.apply(lambda x: 1 / x)

    def sizeof_get_color(num, matrix_mean=0, std_dev=999999999999):
        try:
            if num < matrix_mean:
                col = to_blue[min(int(abs(num - matrix_mean) / std_dev),
                                  len(to_blue) - 1)]
            else:
                col = to_red[min(int(abs(num - matrix_mean) / std_dev),
                                 len(to_red) - 1)]
            return col.get_web(), min(max((num - matrix_mean) / std_dev, 1),
                                      15)
        except:
            return black.get_web(), 1

    def type_to_col(name_full):
        name = name_full.split("_")[0]
        return Color(rgb=(hash("r" + name) % 256 / 255,
                          hash("g" + name) % 256 / 255,
                          hash("b" + name) % 256 / 255))

    # Todo adapt for FULL page
    upper = d.where(~np.tril(np.ones(d.shape)).astype(np.bool))
    bottom = d.transpose().where(~np.tril(np.ones(d.shape)).astype(np.bool))
    bc = upper + bottom
    bc = bc.where(bc != 0)

    g = nx.Graph()

    mmean = np.mean(bc.mean())
    mstd = np.mean(bc.std())

    for row, array in bc.items():
        for column in array.index:
            if not pd.isnull(array[column]):
                g.add_edge(row, column, length=array[column], type=row)

    values = [type_to_col(node).hex for node in g.nodes()]
    node_labels = {node: node for node in g.nodes()}
    values_edge_color = [
        sizeof_get_color(e[2]["length"], mmean, mstd)[0]
        for e in g.edges(data=True)
    ]
    values_edge_width = [
        2 * sizeof_get_color(e[2]["length"], mmean, mstd)[1]
        for e in g.edges(data=True)
    ]

    nx.draw(g,
            with_labels=True,
            node_color=values,
            edge_color=values_edge_color,
            width=values_edge_width,
            labels=node_labels)
    # plt.show()
    s = io.StringIO()
    plt.legend(numpoints=1)
    plt.savefig(s, format="svg")
    plt.cla()
    return s.getvalue()
コード例 #32
0
ファイル: project2.py プロジェクト: victor7246/newtemp
import pandas
import matplotlib as ma
import gmplot
from colour import Color
import pygmaps 
import matplotlib.pyplot as plt
import numpy
import scipy
from scipy.cluster.vq import kmeans2, whiten

data = pandas.read_csv("work.csv")
columns = ['TRIP_ID','TAXI_ID','TIMESTAMP','DAY_TYPE','POLYLINE']
main_data = data[columns]
red = Color("red")
blue = Color("blue")
array_color = list(red.range_to(blue, main_data.shape[0]))
all_location = []
str = main_data['POLYLINE'][1]
str = str.split("],[")
str[0] = str[0].split("[[")[1]
str[len(str)-1] = str[len(str)-1].split("]]")[0]
str = [x.split(",") for x in str]
str = [[float(x),float(y)] for [x,y] in str]
lan = [x for [x,y] in str]
lat = [y for [x,y] in str]
path = [(y,x) for [x,y] in str]
gmap = pygmaps.maps(lat[0],lan[0],12)
all_location += str

for i in range(2,100):
	if main_data['POLYLINE'][i] != '[]':
コード例 #33
0
# -*- coding: utf-8 -*-
"""
Created on Thu Apr  2 17:06:22 2020

@author: NatalyR
"""
import folium
#from folium.plugins import MarkerCluster

from colour import Color

db = Color("red")
colors = list(db.range_to(Color("yellow"), 10))


def color_price(data):
    if (data < 19.81):
        return str(colors[9]).split()[0]
    elif (19.81 >= data < 32.02):
        return str(colors[8]).split()[0]
    elif (32.02 >= data < 44.23):
        return str(colors[7]).split()[0]
    elif (44.23 >= data < 56.44):
        return str(colors[6]).split()[0]
    elif (56.44 >= data < 68.66):
        return str(colors[4]).split()[0]
    elif (68.66 >= data < 80.87):
        return str(colors[3]).split()[0]
    elif (80.87 >= data < 93.08):
        return str(colors[2]).split()[0]
    elif (93.08 >= data < 105.29):
コード例 #34
0
MAXTEMP = 32.0
COLORDEPTH = 1024
SENSOR = adafruit_amg88xx.AMG88XX(I2C_BUS)

# pylint: disable=invalid-slice-index
POINTS = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
GRID_X, GRID_Y = np.mgrid[0:7:32j, 0:7:32j]
# pylint: enable=invalid-slice-index

# sensor is an 8x8 grid so lets do a square
HEIGHT = 240
WIDTH = 240

# the list of colors we can choose from
BLUE = Color("indigo")
COLORS = list(BLUE.range_to(Color("red"), COLORDEPTH))

# create the array of colors
COLORS = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255))
          for c in COLORS]
CONSOLE_COLORS = [
    17,
    18,
    19,
    20,
    21,
    57,
    93,
    129,
    165,
    201,
コード例 #35
0
    def generate(self):
        columns = list(self.dataframe.columns)
        # put std to the end
        columns.sort(key=lambda x: 'std' in x)
        self.dataframe = self.dataframe[columns]

        # create intervals for coloring
        # ---- interval 1 for all but std
        closed_on = 'right'
        lower_bound = 0.3
        upper_bound = 0.9
        mid_periods = 15

        intervals1 = pd.IntervalIndex.from_breaks([0, lower_bound], closed=closed_on)
        intervals2 = pd.interval_range(lower_bound, upper_bound, periods=mid_periods, closed=closed_on)
        intervals3 = pd.IntervalIndex.from_breaks([upper_bound, 1], closed=closed_on)

        interval_list_1 = intervals1.append([intervals2, intervals3])

        # ---- interval 2 for std
        closed_on = 'right'
        lower_bound = 0.05
        upper_bound = 0.1
        mid_periods = 15

        intervals1 = pd.IntervalIndex.from_breaks([0, lower_bound], closed=closed_on)
        intervals2 = pd.interval_range(lower_bound, upper_bound, periods=mid_periods, closed=closed_on)
        intervals3 = pd.IntervalIndex.from_breaks([upper_bound, 1], closed=closed_on)

        interval_list_2 = intervals1.append([intervals2, intervals3])

        # interval matrix, exclude first column (Class)
        interval_dataframe = self.dataframe.iloc[:, 1:]
        for column in self.dataframe.select_dtypes(exclude=['object']):
            if 'std' in column:
                interval_list = interval_list_2
            else:
                interval_list = interval_list_1

            interval_dataframe[column] = self.dataframe[column].map(
                lambda value: get_interval_index_of_value(interval_list, value))

        # colors
        color_low = Color('#e60000')  # red
        color_lower_bound = Color('#ffa31a')  # orange
        color_upper_bound = Color('#248f24')  # green
        color_mid = Color('#ffcc00')  # yellow
        color_high = Color('#006622')  # dark green

        colors = list(color_lower_bound.range_to(color_mid, (mid_periods // 2) if mid_periods % 2 == 0 else (
                mid_periods // 2 + 1)))
        colors.extend(
            list(color_mid.range_to(color_upper_bound, mid_periods // 2 + 1)))  # +1 because first one has to be deleted

        # get unique hex values of colors
        unique_colors = []
        for color in colors:
            if color.hex in unique_colors:
                continue
            else:
                unique_colors.append(color.hex)

        colors = [color_low.hex]
        colors.extend(unique_colors)
        colors.append(color_high.hex)

        # fill color matrix
        color_matrix = [['#808080' for _ in range(len(interval_dataframe))]]  # Class column, gray

        # reversed colors for low=good and high=bad
        colors_reversed = colors.copy()
        colors_reversed.reverse()

        # fill color matrix
        for column in interval_dataframe.columns:
            colors = colors_reversed if 'std' in column else colors
            color_matrix.append([colors[value] for value in interval_dataframe[column]])

        # round values, except first column (Class)
        values = self.dataframe
        values.iloc[:, 1:] = values.iloc[:, 1:].applymap(lambda x: round(x, self.precision))

        # create figure
        fig = go.Figure(
            data=[go.Table(
                header=dict(
                    values=values.columns,
                    line_color='white', fill_color='white',
                    align='center', font=dict(color='black', size=9)
                ),

                cells=dict(
                    values=values.T,
                    fill_color=color_matrix,
                    line_color=color_matrix,
                    align='center', font=dict(color='white', size=8)
                )
            )]
        )

        # set layout
        fig.update_layout(
            width=len(self.dataframe.columns) * 100
        )

        return fig
コード例 #36
0
    def forward(self, x, test, enhance=1, debug=False):

        if not test and np.random.random() > 0.5:
            return nn.functional.interpolate(x,
                                             size=(self.targetH, self.targetW),
                                             mode='bilinear',
                                             align_corners=True)
        if not test:
            enhance = 0

        assert x.size(0) <= self.maxBatch
        assert x.data.type() == self.inputDataType

        grid = self.grid[:x.size(0)]
        grid_x = self.grid_x[:x.size(0)]
        grid_y = self.grid_y[:x.size(0)]
        x_small = nn.functional.interpolate(x,
                                            size=(self.targetH, self.targetW),
                                            mode='bilinear',
                                            align_corners=True)

        offsets = self.cnn(x_small)
        offsets_posi = nn.functional.relu(offsets, inplace=False)
        offsets_nega = nn.functional.relu(-offsets, inplace=False)
        offsets_pool = self.pool(offsets_posi) - self.pool(offsets_nega)

        offsets_grid = nn.functional.grid_sample(offsets_pool, grid)
        offsets_grid = offsets_grid.permute(0, 2, 3, 1).contiguous()
        offsets_x = torch.cat([grid_x, grid_y + offsets_grid], 3)
        x_rectified = nn.functional.grid_sample(x, offsets_x)

        for iteration in range(enhance):
            offsets = self.cnn(x_rectified)

            offsets_posi = nn.functional.relu(offsets, inplace=False)
            offsets_nega = nn.functional.relu(-offsets, inplace=False)
            offsets_pool = self.pool(offsets_posi) - self.pool(offsets_nega)

            offsets_grid += nn.functional.grid_sample(
                offsets_pool, grid).permute(0, 2, 3, 1).contiguous()
            offsets_x = torch.cat([grid_x, grid_y + offsets_grid], 3)
            x_rectified = nn.functional.grid_sample(x, offsets_x)

        if debug:

            offsets_mean = torch.mean(offsets_grid.view(x.size(0), -1), 1)
            offsets_max, _ = torch.max(offsets_grid.view(x.size(0), -1), 1)
            offsets_min, _ = torch.min(offsets_grid.view(x.size(0), -1), 1)

            import matplotlib.pyplot as plt
            from colour import Color
            from torchvision import transforms
            import cv2

            alpha = 0.7
            density_range = 256
            color_map = np.empty([self.targetH, self.targetW, 3], dtype=int)
            cmap = plt.get_cmap("rainbow")
            blue = Color("blue")
            hex_colors = list(blue.range_to(Color("red"), density_range))
            rgb_colors = [[rgb * 255 for rgb in color.rgb]
                          for color in hex_colors][::-1]
            to_pil_image = transforms.ToPILImage()

            for i in range(x.size(0)):

                img_small = x_small[i].data.cpu().mul_(0.5).add_(0.5)
                img = to_pil_image(img_small)
                img = np.array(img)
                if len(img.shape) == 2:
                    img = cv2.merge([img.copy()] * 3)
                img_copy = img.copy()

                v_max = offsets_max.data[i]
                v_min = offsets_min.data[i]
                img_offsets = (offsets_grid[i]).view(
                    1, self.targetH,
                    self.targetW).data.cpu().add_(-v_min).mul_(1. /
                                                               (v_max - v_min))
                img_offsets = to_pil_image(img_offsets)
                img_offsets = np.array(img_offsets)
                color_map = np.empty([self.targetH, self.targetW, 3],
                                     dtype=int)
                for h_i in range(self.targetH):
                    for w_i in range(self.targetW):
                        color_map[h_i][w_i] = rgb_colors[int(
                            img_offsets[h_i, w_i] / 256. * density_range)]
                color_map = color_map.astype(np.uint8)
                cv2.addWeighted(color_map, alpha, img_copy, 1 - alpha, 0,
                                img_copy)

                img_processed = x_rectified[i].data.cpu().mul_(0.5).add_(0.5)
                img_processed = to_pil_image(img_processed)
                img_processed = np.array(img_processed)
                if len(img_processed.shape) == 2:
                    img_processed = cv2.merge([img_processed.copy()] * 3)

                total_img = np.ones([self.targetH, self.targetW * 3 + 10, 3],
                                    dtype=int) * 255
                total_img[0:self.targetH, 0:self.targetW] = img
                total_img[0:self.targetH,
                          self.targetW + 5:2 * self.targetW + 5] = img_copy
                total_img[0:self.targetH, self.targetW * 2 +
                          10:3 * self.targetW + 10] = img_processed
                total_img = cv2.resize(total_img.astype(np.uint8), (300, 50))
                # cv2.imshow("Input_Offsets_Output", total_img)
                # cv2.waitKey()

            return x_rectified, total_img

        return x_rectified
コード例 #37
0
def format( tree , genedict , detection , includenames , filename , speciescolors = None):
	print 'final output...'
	red = Color('red')
	blue = Color('blue')
	colorvec = list(red.range_to(blue, len(genedict.keys())))
	colormap = {}
	columnmap = {}
	for i,ref in enumerate(genedict):
		if ref not in detection:	
			columnmap[ref] = 3
			if 'hybrid' in ref.lower():
				columnmap[ref] = 0
			if 'eff' in ref.lower():
				columnmap[ref] = 1
			if 'hap' in ref.lower():
				columnmap[ref] = 2
			colormap[ref] = colorvec[i].hex
	for i,ref in enumerate(detection):
		columnmap[ref] = 3 + i
		colormap[ref] = colorvec[i].hex 

	print columnmap
	print colormap

	circledict = {}
	for n in t.traverse():
		
		nst = NodeStyle()
		nst["size"] = 0
		nst["fgcolor"] = 'black'
		nst["hz_line_width"] = 4
		nst["vt_line_width"]= 4
		nst.show_name = False
		if n.is_leaf():
			if speciescolors != None and n.name in speciescolors:
				nst["bgcolor"] = colors[n.name]
			nst.show_name = True			
			n.add_face( AttrFace(attr = 'name', ftype='Helvetica', fgcolor='black', fsize =18 ,fstyle = 'normal'   ), column =0 )
			refs = json.loads(n.refs)
			for ref in genedict:
				if ref in refs and ref in detection:
					n.add_face( CircleFace ( 10 , colormap[ref]), column =  2 + columnmap[ref] )
					n.img_style = nst
				if ref in refs and ref not in detection:
					n.add_face( RectFace ( 20 , 20 , colormap[ref], colormap[ref] ), column =  2 + columnmap[ref] )
					n.img_style = nst
				if ref not in refs and ref not in detection:
					n.add_face( RectFace ( 20 , 20 , colormap[ref], 'white' ), column =  2 + columnmap[ref] )
					n.img_style = nst
			###color by species
			if n.name in speciescolors:
				nst['bgcolor'] = speciescolors[n.name]
		else:
			if n.name.strip() in includenames:
				n.add_face( AttrFace(attr = 'name', ftype='Helvetica', fgcolor='black', fsize =20 ,fstyle = 'normal'   ), column =0 )
				nst.size = 2
				n.img_style = nst
			else:
				nst.size = 0
				n.img_style = nst 
	ts = TreeStyle()
	for i,ref in enumerate(colormap.keys()):
		if 'ubi' not in ref:
			ts.title.add_face(TextFace(ref, fsize=12), column=0)
			ts.title.add_face( RectFace(10 , 10 , colormap[ref] , colormap[ref]), column = 1)
	ts.show_leaf_name=False 

	"""ts.mode = "c"
				ts.arc_start = 270
				ts.arc_span = 359
				ts.root_opening_factor = 1
			"""
	ts.scale =  190
	
	t.show(tree_style = ts)
	t.render(filename + ".png", tree_style = ts)
	t.render( filename +".svg" , tree_style = ts)
コード例 #38
0
    BasicTicker,
    PrintfTickFormatter,
    ColorBar,
)
from bokeh.plotting import (figure, output_file)
from colour import Color

df = pd.read_csv("../Data/DataFrames/relativeheatmap.csv").drop(
    columns="Unnamed: 0")
output_file("../Data/HTML/relativeheatmap.html")
b = list(df["B1"].unique())

blue = Color("blue")
white = Color("white")
green = Color("green")
colors = [c.hex_l for c in blue.range_to(white, 25)
          ] + [c.hex_l for c in white.range_to(green, 25)]
mapper = LinearColorMapper(palette=colors,
                           low=min(df["corr"].tolist()),
                           high=max(df["corr"].tolist()))

source = ColumnDataSource(df)
#.loc[df["B1"] == "B Delfstoffenwinning"]

TOOLS = "hover,save,box_zoom,reset,wheel_zoom"

p = figure(title="heatmap correlatie",
           x_range=b,
           y_range=list(reversed(b)),
           x_axis_location="above",
           plot_width=1000,
コード例 #39
0
class CamTherm(AMG8833):
    def __init__(self, alamat, ukuran_pix=120j, minTemp=30, maxTemp=38):
        self._cam = AMG8833(addr=alamat)
        self._points = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
        self._ukuran = ukuran_pix
        self._grid_x, self._grid_y = np.mgrid[0:7:self._ukuran,
                                              0:7:self._ukuran]
        #low range of the sensor (this will be blue on the screen)
        self._MINTEMP = minTemp

        #high range of the sensor (this will be red on the screen)
        self._MAXTEMP = 31

        #how many color values we can have
        self._COLORDEPTH = 1024
        self._points = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
        self._blue = Color("indigo")
        self._colors = list(self._blue.range_to(Color("red"),
                                                self._COLORDEPTH))
        self._colors = [(int(c.red * 255), int(c.green * 255),
                         int(c.blue * 255)) for c in self._colors]

#some utility functions

    def _constrain(self, val, min_val, max_val):
        return min(max_val, max(min_val, val))

    def _map(self, x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

    def _regresikan(self, pixels_list, shape=(8, 8)):
        print(type(pixels_list), pixels_list)

        rata2 = np.array(list(pixels_list)).mean()
        pixels_2d = np.array(pixels_list).reshape(shape)

        logical_greater = pixels_2d > rata2 + 1.7
        logical_minor = pixels_2d < rata2 + 0.7

        factor_greater = pixels_2d[logical_greater] * (-0.014523) + 1.456925
        factor_minor = pixels_2d[logical_minor] * (-0.009277) + 1.115660

        greater = pixels_2d[logical_greater] * factor_greater
        minor = pixels_2d[logical_minor] * factor_minor

        pixels_2d[logical_greater] = greater
        pixels_2d[logical_minor] = minor
        # print(rata2)
        # print(np.array(list(pixels_list)).reshape(-1,1).shape)
        pixels_1d = pixels_2d.reshape(
            (1, max(np.array(list(pixels_list)).reshape(-1, 1).shape)))

        return pixels_2d, list(pixels_1d[0]), rata2

    def getThermal(self, ):
        pixels_origin = self._cam.read_temp()
        #print(pixels_origin, type(pixels_origin))

        pixels_2d, pixels_origin, rata2 = self._regresikan(pixels_origin)
        # print(pixels_origin, type(pixels_origin))

        pixels = [
            self._map(p, self._MINTEMP, self._MAXTEMP, 0, self._COLORDEPTH - 1)
            for p in pixels_origin
        ]

        #perdorm interpolation
        bicubic = griddata(self._points,
                           pixels, (self._grid_x, self._grid_y),
                           method='cubic')

        #--- proses kalibrasi
        suhu = np.max(pixels_origin)
        # print(suhu)

        #draw everything
        data_img = np.zeros((bicubic.shape[0], bicubic.shape[1], 3),
                            dtype=np.uint8)
        for ix, row in enumerate(bicubic):
            for jx, pixel in enumerate(row):
                r, g, b = self._colors[self._constrain(int(pixel), 0,
                                                       self._COLORDEPTH - 1)]
                data_img[jx, ix] = [r, g, b]
        # pygame.display.update()
        data_img = np.rot90(data_img, k=1)
        data_img = np.flip(data_img, 1)

        return data_img, suhu
コード例 #40
0
ファイル: main.py プロジェクト: windweaver828/weather
    def addWeather(self):
        QtGui.QApplication.processEvents()
        blue1 = Color('#6a9dcf')
        blue2 = Color('#1D2951')
        colors = list(blue1.range_to(blue2, 50))
        self.skipped = False
        for location, x in LOCATIONS.items():
            lat, lng = x
            self.weather_list = self.get_weather(location, lat, lng)
            self.current_weather = self.weather_list[0]
            self.hour1 = self.weather_list[1]
            self.hour2 = self.weather_list[2]
            self.hour3 = self.weather_list[3]
            self.hour4 = self.weather_list[4]
            self.hour5 = self.weather_list[5]
            self.hour6 = self.weather_list[6]
            self.hour7 = self.weather_list[7]
            self.hour8 = self.weather_list[8]
            self.hour9 = self.weather_list[9]
            self.hour10 = self.weather_list[10]
            self.hour11 = self.weather_list[11]
            self.space1 = '\t\t'
            self.space2 = '\t\t\t'
            self.space3 = '\t\t\t'

            if self.current_weather['location'] == 'Lucedale':
                self.timelabel.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.timelabel.setText(time.strftime("%I:%M %p"))
                self.summary.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.summary.setText(self.current_weather['Conditions'])
                self.temperature.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.temperature.setText('Temp: ' + str(self.current_weather['Temperature']) + u"\u00B0" + ' F')
                self.feelslike.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.feelslike.setText('Feels like: ' + self.current_weather['FeelsLike'] + u"\u00B0" + ' F')
                self.dewpoint.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.dewpoint.setText('Dew Point: ' + self.current_weather['DewPoint'] + u"\u00B0" + ' F')
                self.humidity.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.humidity.setText('Humidity: ' + self.current_weather['Humidity'])
                self.wind.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.wind.setText('Wind: ' + self.current_weather['Wind'])
                self.chanceofrain.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.chanceofrain.setText(self.current_weather['ChanceofRain'] + ' Chance of Rain')
                self.hightemp.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.get_image(self.current_weather)
                self.hightemp.setText("Today's High: " + self.current_weather['HighTemp'] + u"\u00B0" + ' F')
                self.lowtemp.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.lowtemp.setText("Today's Low: " + self.current_weather['LowTemp'] + u"\u00B0" + ' F')
                self.hourlabel1.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour1['summary']) < 8:
                    self.hourlabel1.setText(str(self.hour1['time']) + self.space1 + self.hour1['summary'] + self.space2 + str(self.hour1['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel1.setText(str(self.hour1['time']) + self.space1 + self.hour1['summary'] + self.space1 + str(self.hour1['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour1['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel2.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel2.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel2.setText('\t' + str(self.hour1['rainchance']) + "% Chance of Precipitation")
                self.hourlabel3.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour2['summary']) < 8:
                    self.hourlabel3.setText(str(self.hour2['time']) + self.space1 + self.hour2['summary'] + self.space2 + str(self.hour2['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel3.setText(str(self.hour2['time']) + self.space1 + self.hour2['summary'] + self.space1 + str(self.hour2['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour2['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel4.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel4.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel4.setText('\t' + str(self.hour2['rainchance']) + " % Chance of Precipitation")
                self.hourlabel5.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour3['summary']) < 8:
                    self.hourlabel5.setText(str(self.hour3['time']) + self.space1 + self.hour3['summary'] + self.space2 + str(self.hour3['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel5.setText(str(self.hour3['time']) + self.space1 + self.hour3['summary'] + self.space1 + str(self.hour3['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour3['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel6.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel6.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel6.setText('\t' + str(self.hour3['rainchance']) + " % Chance of Precipitation")
                self.hourlabel7.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour4['summary']) < 8:
                    self.hourlabel7.setText(str(self.hour4['time']) + self.space1 + self.hour4['summary'] + self.space2 + str(self.hour4['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel7.setText(str(self.hour4['time']) + self.space1 + self.hour4['summary'] + self.space1 + str(self.hour4['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour4['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel8.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel8.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel8.setText('\t' + str(self.hour4['rainchance']) + " % Chance of Precipitation")
                self.hourlabel9.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour5['summary']) < 8:
                    self.hourlabel9.setText(str(self.hour5['time']) + self.space1 + self.hour5['summary'] + self.space2 + str(self.hour5['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel9.setText(str(self.hour5['time']) + self.space1 + self.hour5['summary'] + self.space1 + str(self.hour5['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour5['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel10.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel10.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel10.setText('\t' + str(self.hour5['rainchance']) + " % Chance of Precipitation")
                self.hourlabel11.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour6['summary']) < 8:
                    self.hourlabel11.setText(str(self.hour6['time']) + self.space1 + self.hour6['summary'] + self.space2 + str(self.hour6['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel11.setText(str(self.hour6['time']) + self.space1 + self.hour6['summary'] + self.space1 + str(self.hour6['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour6['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel12.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel12.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel12.setText('\t' + str(self.hour6['rainchance']) + " % Chance of Precipitation")
                self.hourlabel13.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour7['summary']) < 8:
                    self.hourlabel13.setText(str(self.hour7['time']) + self.space1 + self.hour7['summary'] + self.space2 + str(self.hour7['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel13.setText(str(self.hour7['time']) + self.space1 + self.hour7['summary'] + self.space1 + str(self.hour7['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour7['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel14.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel14.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel14.setText('\t' + str(self.hour7['rainchance']) + " % Chance of Precipitation")
                self.hourlabel15.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour7['summary']) < 8:
                    self.hourlabel15.setText(str(self.hour8['time']) + self.space1 + self.hour7['summary'] + self.space2 + str(self.hour8['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel15.setText(str(self.hour8['time']) + self.space1 + self.hour7['summary'] + self.space1 + str(self.hour8['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour8['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel16.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel16.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel16.setText('\t' + str(self.hour8['rainchance']) + " % Chance of Precipitation")
                self.hourlabel17.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour9['summary']) < 8:
                    self.hourlabel17.setText(str(self.hour9['time']) + self.space1 + self.hour9['summary'] + self.space2 + str(self.hour9['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel17.setText(str(self.hour9['time']) + self.space1 + self.hour9['summary'] + self.space1 + str(self.hour9['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour9['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel18.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel18.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel18.setText('\t' + str(self.hour9['rainchance']) + " % Chance of Precipitation")
                self.hourlabel19.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour10['summary']) < 8:
                    self.hourlabel19.setText(str(self.hour10['time']) + self.space1 + self.hour10['summary'] + self.space2 + str(self.hour10['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel19.setText(str(self.hour10['time']) + self.space1 + self.hour10['summary'] + self.space1 + str(self.hour10['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour10['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel20.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel20.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel20.setText('\t' + str(self.hour10['rainchance']) + " % Chance of Precipitation")
                self.hourlabel21.setStyleSheet("font-weight:bold; font-family:Purisa; color:yellow")
                self.hourlabel21.setText(str(self.hour11['time']) + '\t\t' + self.hour11['summary'] + '\t\t' + str(self.hour11['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour11['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel22.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel22.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel22.setText('\t' + str(self.hour11['rainchance']) + " % Chance of Precipitation")

            elif self.current_weather['location'] == 'Long Beach':
                self.timelabelLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.timelabelLB.setText(time.strftime("%I:%M %p"))
                self.summaryLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.summaryLB.setText(self.current_weather['Conditions'])
                self.temperatureLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.temperatureLB.setText('Temp: ' + self.current_weather['Temperature'] + u"\u00B0" + ' F')
                self.feelslikeLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.feelslikeLB.setText('Feels like: ' + self.current_weather['FeelsLike'] + u"\u00B0" + ' F')
                self.dewpointLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.dewpointLB.setText('Dew Point: ' + self.current_weather['DewPoint'] + u"\u00B0" + ' F')
                self.humidityLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.humidityLB.setText('Humidity: ' + self.current_weather['Humidity'])
                self.windLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.windLB.setText('Wind: ' + self.current_weather['Wind'])
                self.chanceofrainLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.chanceofrainLB.setText(self.current_weather['ChanceofRain'] + ' Chance of Rain')
                self.hightempLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.hightempLB.setText("Today's High: " + self.current_weather['HighTemp'] + u"\u00B0" + ' F')
                self.lowtempLB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightsteelblue")
                self.lowtempLB.setText("Today's Low: " + self.current_weather['LowTemp'] + u"\u00B0" + ' F')
                self.hourlabel1LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour1['summary']) < 8:
                    self.hourlabel1LB.setText(str(self.hour1['time']) + self.space1 + self.hour1['summary'] + self.space2 + str(self.hour1['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel1LB.setText(str(self.hour1['time']) + self.space1 + self.hour1['summary'] + self.space1 + str(self.hour1['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour1['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel2LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel2LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel2LB.setText('\t' + str(self.hour1['rainchance']) + " % Chance of Precipitation")
                self.hourlabel3LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour2['summary']) < 8:
                    self.hourlabel3LB.setText(str(self.hour2['time']) + self.space1 + self.hour2['summary'] + self.space2 + str(self.hour2['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel3LB.setText(str(self.hour2['time']) + self.space1 + self.hour2['summary'] + self.space1 + str(self.hour2['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour2['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel4LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel4LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel4LB.setText('\t' + str(self.hour2['rainchance']) + " % Chance of Precipitation")
                self.hourlabel5LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour3['summary']) < 8:
                    self.hourlabel5LB.setText(str(self.hour3['time']) + self.space1 + self.hour3['summary'] + self.space2 + str(self.hour3['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel5LB.setText(str(self.hour3['time']) + self.space1 + self.hour3['summary'] + self.space1 + str(self.hour3['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour3['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel6LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel6LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel6LB.setText('\t' + str(self.hour3['rainchance']) + " % Chance of Precipitation")
                self.hourlabel7LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour4['summary']) < 8:
                    self.hourlabel7LB.setText(str(self.hour4['time']) + self.space1 + self.hour4['summary'] + self.space2 + str(self.hour4['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel7LB.setText(str(self.hour4['time']) + self.space1 + self.hour4['summary'] + self.space1 + str(self.hour4['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour4['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel8LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel8LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel8LB.setText('\t' + str(self.hour4['rainchance']) + " % Chance of Precipitation")
                self.hourlabel9LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour5['summary']) < 8:
                    self.hourlabel9LB.setText(str(self.hour5['time']) + self.space1 + self.hour5['summary'] + self.space2 + str(self.hour5['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel9LB.setText(str(self.hour5['time']) + self.space1 + self.hour5['summary'] + self.space1 + str(self.hour5['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour5['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel10LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel10LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel10LB.setText('\t' + str(self.hour5['rainchance']) + " % Chance of Precipitation")
                self.hourlabel11LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour6['summary']) < 8:
                    self.hourlabel11LB.setText(str(self.hour6['time']) + self.space1 + self.hour6['summary'] + self.space2 + str(self.hour6['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel11LB.setText(str(self.hour6['time']) + self.space1 + self.hour6['summary'] + self.space1 + str(self.hour6['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour6['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel12LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel12LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel12LB.setText('\t' + str(self.hour6['rainchance']) + " % Chance of Precipitation")
                self.hourlabel13LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour7['summary']) < 8:
                    self.hourlabel13LB.setText(str(self.hour7['time']) + self.space1 + self.hour7['summary'] + self.space2 + str(self.hour7['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel13LB.setText(str(self.hour7['time']) + self.space1 + self.hour7['summary'] + self.space1 + str(self.hour7['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour7['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel14LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel14LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel14LB.setText('\t' + str(self.hour7['rainchance']) + " % Chance of Precipitation")
                self.hourlabel15LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour8['summary']) < 8:
                    self.hourlabel15LB.setText(str(self.hour8['time']) + self.space1 + self.hour8['summary'] + self.space2 + str(self.hour8['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel15LB.setText(str(self.hour8['time']) + self.space1 + self.hour8['summary'] + self.space1 + str(self.hour8['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour8['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel16LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel16LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel16LB.setText('\t' + str(self.hour8['rainchance']) + " % Chance of Precipitation")
                self.hourlabel17LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                if len(self.hour9['summary']) < 8:
                    self.hourlabel17LB.setText(str(self.hour9['time']) + self.space1 + self.hour9['summary'] + self.space2 + str(self.hour9['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel17LB.setText(str(self.hour9['time']) + self.space1 + self.hour9['summary'] + self.space1 + str(self.hour9['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour9['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel18LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel18LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel18LB.setText('\t' + str(self.hour9['rainchance']) + " % Chance of Precipitation")
                self.hourlabel19LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:lightgoldenrodyellow")
                if len(self.hour10['summary']) < 8:
                    self.hourlabel19LB.setText(str(self.hour10['time']) + self.space1 + self.hour10['summary'] + self.space2 + str(self.hour10['temperature']) + u"\u00B0" + ' F')
                else:
                    self.hourlabel19LB.setText(str(self.hour1['time']) + self.space1 + self.hour10['summary'] + self.space1 + str(self.hour10['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour10['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel20LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel20LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel20LB.setText('\t' + str(self.hour10['rainchance']) + " % Chance of Precipitation")
                self.hourlabel21LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:darkorchid")
                self.hourlabel21LB.setText(str(self.hour11['time']) + '\t\t' + self.hour11['summary'] + '\t\t' + str(self.hour11['temperature']) + u"\u00B0" + ' F')
                num = float(self.hour11['rainchance'] / 2)
                color = colors[int(math.ceil(num))]
                self.hourlabel22LB.setStyleSheet("font-weight:bold; font-family:Purisa; color:{}".format(color))
                self.hourlabel22LB.setAlignment(QtCore.Qt.AlignLeft)
                self.hourlabel22LB.setText('\t' + str(self.hour11['rainchance']) + " % Chance of Precipitation")
            QtGui.QApplication.processEvents()
コード例 #41
0
            "#4f3ad1",
            "#3f4cca",
            "#2e5ec2",
            "#1f6fbb",
            "#1678b6",
            "#1489bd",
            "#159ac7",
            "#16a5cd",
            "#16abd1",
            "#17b8d8",]

red = Color(rgb=(230/255, 124/255, 115/255))
yellow = Color(rgb=(1, 214/255, 102/255))
green = Color(rgb=(87/255, 187/255, 138/255))

ry = red.range_to(yellow, 12)
yg = yellow.range_to(green, 12)
hprographics = [x.hex for x in ry] + [x.hex for x in yg]

themes = {
    "hprographics": hprographics,
    "deepblue": deepblue,
    "sunburst": sunburst
}


def findColor(low, high, val, theme):
    spread = high - low
    ratio = (val - low) / spread
    index = int(ratio * len(themes[theme]))
    if index < 0:
コード例 #42
0
from avy_gis.lib.topo_db import topo_db
from colour import Color
import numpy as np
import scipy.misc as smp

db = topo_db()

r = Color('red')
p = Color('purple')
gradient = list(r.range_to(p, 91))

def getColorIndex(rad):
	minA = -1
	maxA = 6.28319
	if(rad < minA):
		rad = minA
	if(rad > maxA):
		rad = maxA
	return int(round(((rad)/(maxA)) * 90))

def color_to_rgb(c):
	return map(lambda x:int(round(x * 255)), [c.get_red(),c.get_green(),c.get_blue(), 1])

bbox = {'sw': {'lat': 46.797337,'lon': -121.847628},'ne': {'lat': 46.913387,'lon': -121.676930}}
topo_data = db.get_bbox(bbox, ['aspect'])
aspects = topo_data['aspect']

img_data = []
for row in aspects:
	img_data.insert(0,[])
	for col in row:
コード例 #43
0
from colour import Color

colors = ['#D24D57', '#DB0A5B', '#663399', '#4183D7', '#87D37C', '#E87E04']
gradient_colors = []

def group(it, n):
    return zip(*[iter(it)]*n)
    
for color_a, color_b in group(colors, 2):
    ca = Color(color_a)
    gradient_colors.extend(list(ca.range_to(Color(color_b), 10)))
    
for gc in gradient_colors:
    print(gc)
コード例 #44
0
 def get_color_ranges(self):
     min_col = Color(self.min_color)
     max_col = Color(self.max_color)
     return [c.hex for c in list(min_col.range_to(max_col, self.intervals))]
コード例 #45
0
def colorPicker(fcolor, lcolor, count):
    start = Color(fcolor)
    color_list = list(start.range_to(Color(lcolor), count))
    return color_list
コード例 #46
0
ファイル: Mapper.py プロジェクト: electoralstats/articles
  for c in range(0,len(colors)):
    style = "stop-color:%(color)s;stop-opacity:1" %{"color":colors[c]}
    offset = str(ranges[c])
    stop = mapSoup.new_tag("stop", style=style, offset=offset)
    gradient.append(stop)
  rect = mapSoup.find(id="gradrect")
  rectX = float(rect['x'])
  rectW = float(rect['width'])
  rectY = float(rect['y'])
  rectH = float(rect['height'])
  disp = 5
  labelPos = np.linspace(0.0, rectH, 5)
  labels = np.linspace(7.25, 15.00, 5)[::-1]
  for i in range(0,len(labelPos)):
    label = mapSoup.new_tag("text", x=rectX + rectW + disp, y=rectY + labelPos[i])
    label['font-family'] = "sans"
    label['font-size'] = 12
    label.string = "${0:.2f}".format(labels[i])
    mapSoup.svg.append(label)
  outputFile = open(fileName, "w")
  outputFile.write(mapSoup.prettify())
  outputFile.close()

wages = getWages()
wageOfConcern = [float(w[wageColumn]) for w in wages]
colorRanges = np.linspace(7.25, 15.00, 30)
green = Color("blue")
red = Color("#FF0000")
colors = list(green.range_to(red, len(colorRanges)+1))
map2 = produceMap(wages, wageColumn, "countiesWage_living.svg", colors)
コード例 #47
0
from colour import Color

colors = ['#D24D57', '#DB0A5B', '#663399', '#4183D7', '#87D37C', '#E87E04']
gradient_colors = []


def group(it, n):
    return zip(*[iter(it)] * n)


for color_a, color_b in group(colors, 2):
    ca = Color(color_a)
    gradient_colors.extend(list(ca.range_to(Color(color_b), 10)))

for gc in gradient_colors:
    print(gc)
コード例 #48
0
 def plotGraph(self, graph, nodesCommMembership, node_to_token_dic, figFilePath):            
     edges = []
     for edge in graph.es():
         if nodesCommMembership[edge.tuple[0]] != nodesCommMembership[edge.tuple[1]]:
             edges.append(edge)
     graph.delete_edges(edges)
     
     '''
     Creating gradient color scheme for the graph edges. Green edges
     have the minimum found weight and red edges the maximum.
     '''
     n_colors = 20
     green = Color("green")
     colors = list(green.range_to(Color("red"), n_colors))
     weights = graph.es['weight']
     maxW = max(weights)
     minW = min(weights)
     binSize = (maxW - minW)/n_colors
     edgeColors = []
     for w in weights:
         colorBin = int(ceil((w-minW)/binSize)-1)
         if colorBin == -1:
             colorBin = 0
         color = colors[colorBin]
         edgeColors.append(color.get_rgb())
         
     if os.path.isfile(figFilePath):
         os.remove(figFilePath)
     fig = pyplot.figure(figsize=(15, 15))
     axplot = fig.add_axes([0.15, 0.07, 0.7, 0.06], label='Edge weight value')
     cmap = mpl.colors.ListedColormap([color.get_rgb() for color in colors])
     norm = mpl.colors.Normalize(vmin=minW, vmax=maxW)
     colorBar = mpl.colorbar.ColorbarBase(axplot, cmap=cmap,
                                norm=norm,
                                orientation='horizontal')
     colorBar.set_label('Edge weight value')
     ax = colorBar.ax
     text = ax.xaxis.label
     font = mpl.font_manager.FontProperties(size=18)
     text.set_font_properties(font)
     
     degrees = graph.degree()
     #nodeLabels = [self.token_to_word[node_to_token_dic[nodeIndex]] + " (" + str(degree) + ")"  for nodeIndex, degree in enumerate(degrees)]
     nodeLabels = [self.token_to_word[node_to_token_dic[nodeIndex]]  for nodeIndex, degree in enumerate(degrees)]
     visual_style = {}
     
     
     bins = np.linspace(0, max(degrees), n_colors)  
     digitized_degrees =  np.digitize(degrees, bins)
     graph.vs["color"] = [colors[x-1] for x in digitized_degrees]
     N = graph.vcount()
     #visual_style["layout"] = graph.layout_fruchterman_reingold(weights=graph.es["weight"], maxiter=4000, area=N**3, repulserad=N**3)
     visual_style["layout"] = graph.layout("kk")
     
     visual_style["vertex_label"] = nodeLabels
     visual_style["vertex_label_size"] = 12
     visual_style["vertex_size"] = 6
     color_list = ['red',  'blue', 'cyan', 'purple', 'white', 'black']
     vertex_color = [color_list[x] for x in nodesCommMembership]
     visual_style["vertex_color"] = vertex_color
     
     color_count = {}
     for vertex in vertex_color:
         if not vertex in color_count:
             color_count[vertex] = 0
         color_count[vertex] += 1
     index = 0
     for color in color_count:
         tempIndex = color_count[color]
         color_count[color] = index
         index += tempIndex
     vertexOrder = []
     for vertex in vertex_color:
         vertexOrder.append(color_count[vertex])
         color_count[vertex] += 1
     #visual_style["vertex_order"] = vertexOrder
     
     visual_style["vertex_label_dist"] = 1
     visual_style["edge_color"] = edgeColors
     plot(graph, figFilePath, margin = 40, **visual_style)
     img = mpimg.imread(figFilePath)
     axplot = fig.add_axes([0.01, 0.15, 1, 0.8])
     axplot.axis('off')
     axplot.imshow(img)
     fig.savefig(figFilePath)
コード例 #49
0
from enrichr import enrichr_query
import matplotlib.pyplot as plt
import numpy as np
import pickle

genes = set(pickle.load(open("../data/pam50_mrnas.pkl", "rb")))
pam50_genes = set(open("../data/PAM50_genes.txt").read().split('\n'))

library = "GO_Biological_Process_2018"
library = "KEGG_2019_Human"
data = enrichr_query(list(genes), library)
p_values = list()
enrichment = list()
cut = 10
start_colour = Color("turquoise")
colors = list(start_colour.range_to(Color("deepskyblue"), cut))
colors = [color.rgb for color in colors]

plt.figure(figsize=(10, 10), constrained_layout=True)
for result in data[library][::-1]:
    enrichment.append(result[1])
    p_values.append(-np.log10(result[2]))
enrichment = enrichment[-cut:]
p_values = p_values[-cut:]
y_pos = np.arange(len(enrichment))
print(y_pos)
print(p_values)
plt.barh(y_pos, p_values, color=colors)
plt.yticks(y_pos, enrichment)
plt.xlabel("-log10(p-value)")
plt.title("Top 10 KEGG pathways related to the selected genes")
コード例 #50
0
ファイル: wpcColourExample.py プロジェクト: achekroud/brexit
TODO: make it a chloropleth UK map, (at the moment this would be possible but the number of data points is too large to handle i think)
'''
geoDataLoc = open('wpc.json')
refjson = geoDataLoc.read()
json_data = geojson.loads(refjson)
x=[]
y=[]
location = raw_input('Search your consituency: ').replace(' ','').replace(' ','').lower()
maxValue, minValue = maxminValue('euReferendum.json')
currentVal = float(constitValue(location, 'euReferendum.json'))

colourNo = int(ceil((currentVal/maxValue)*632))

red = Color("red")
white = Color("white")
colouring = list(white.range_to(red, 632))
mapCol= str(colouring[colourNo])

currentValue = constitValue(location, 'euReferendum.json')
nameToCoords={}

for x in range(len(json_data['features'])):
		if location == json_data['features'][x]['properties']['PCON13NM'].replace(',','').replace(' ','').lower():
			nameToCoords[location]=json_data['features'][x]['geometry']['coordinates']

coords= nameToCoords[location]
x=[i for i,j in coords[0]]
y=[j for i,j in coords[0]]
fig = plt.figure()
ax = fig.gca() 
ax.plot(x,y)
コード例 #51
0
	# and set it as tree outgroup
	t.set_outgroup(R)

	def save_obj(obj, name ):
	    with open( name + '.pkl', 'wb') as f:
	        pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)

	def load_obj(name ):
	    with open( name + '.pkl', 'r') as f:
	        return pickle.load(f)

	genedict = load_obj('genedict')
	speciescolors = load_obj('colors')
	red = Color('red')
	blue = Color('blue')
	colorvec = list(red.range_to(blue, len(genedict)))
	colormap = {}
	columnmap = {}
	for i,fasta in enumerate(genedict):
		columnmap[fasta] = i
		colormap[fasta] = colorvec[i].hex
	annotated = [] 
	print speciescolors
	for fasta in genedict:
		for leaf in t.get_leaves():

			nst = NodeStyle()
			nst["size"] = 0
			nst["fgcolor"] = 'black'
			nst["hz_line_width"] = 2
			nst["vt_line_width"]= 2
コード例 #52
0
ファイル: xi_p.py プロジェクト: marcantoinedor/halomodel_mcmc
# qs = [0.707]
# ps = [0.3]

qs = [0.6, 0.65, 0.707, 0.75, 0.8, 0.9]
ps = [0., 0.1, 0.2, 0.25, 0.3, 0.35, 0.4]
l_max = 5000000
clean = False

thetasCFHT = get.get_theta_CFHT()
xipCFHT = get.get_xip_CFHT()
ximCFHT = get.get_xim_CFHT()
sigmCFHT = get.get_sigm_CFHT()
sigpCFHT = get.get_sigp_CFHT()

begin_color = Color("blue")
colors = list(begin_color.range_to(Color("green"), len(ps)))

for q in qs:
    for p in ps:
        if clean:
            os.system(
                'mv -f data/q={0}p={1}/xi1.dat data/q={0}p={1}/xi1_old.dat'.
                format(*[q, p]))
            os.system(
                'mv -f data/q={0}p={1}/xi3.dat data/q={0}p={1}/xi3_old.dat'.
                format(*[q, p]))

        if not os.path.isfile('data/q={0}p={1}/xi1.dat'.format(*[q, p])):
            print("Creating data {0}".format(p))
            os.system(
                './bin/halo_model_plotxi {0} {1} {2}'.format(*[q, p, l_max]))
コード例 #53
0
from colour import Color

# Created by: Bang Pham Huu

brown_from = Color("#FFF201")
brown_colors = list(brown_from.range_to(Color("#FD3D00"), 155))

green_from = Color("#80B107")
green_colors = list(green_from.range_to(Color("#036200"), 100))

colors = brown_colors + green_colors

rgb_colors = []

for color in colors:
    value = color.hex

    if len(color.hex) == 4:
        tmp = color.hex[1:]
        red = tmp[0] + tmp[0]
        green = tmp[1] + tmp[1]
        blue = tmp[2] + tmp[2]
        value = "#" + red + green + blue

    rgb_color = str(tuple(bytearray.fromhex(value.replace("#", "")))).replace(
        "(", "[").replace(")", "]").replace(", ", ",")
    rgb_colors.append(rgb_color.replace("]", ",255]"))

rgb_colors.append("[255,255,255,255]")

print '"{\\\"colorPalette\\\":{\\\"colorTable\\\":[ ' + ",".join(
コード例 #54
0
ファイル: tm_tools.py プロジェクト: nudtchengqing/time-maps
def make_time_map(times, times_tot_mins, sep_array, Ncolors):

	print 'rendering normal time map ...'
	
	## set up color list
	
	red=Color("red")
	blue=Color("blue")
	color_list = list(red.range_to(blue, Ncolors)) # range of colors evenly speced on the spectrum between red and blue. Each element is a colour object
	color_list = [c.hex for c in color_list] # give hex version
		
	fig=plt.figure()
	ax =fig.add_subplot(111)
	
	plt.rc('text',usetex=True)
	plt.rc('font',family='serif')
	
	colormap = plt.cm.get_cmap('rainbow')  # see color maps at http://matplotlib.org/users/colormaps.html
	
	order=np.argsort(times_tot_mins[1:-1]) # so that the red dots are on top
#	order=np.arange(1,len(times_tot_mins)-2) # dots are unsorted

	# taken from http://stackoverflow.com/questions/6063876/matplotlib-colorbar-for-scatter
	
	sc= ax.scatter(sep_array[:,0][order],sep_array[:,1][order],c=times_tot_mins[1:-1][order],vmin=0,vmax=24*60,s=25,cmap=colormap,marker='o',edgecolors='none')
	
	color_bar=fig.colorbar(sc,ticks=[0,24*15,24*30,24*45,24*60],orientation='horizontal',shrink=0.5)
	color_bar.ax.set_xticklabels(['Midnight','18:00','Noon','6:00','Midnight'])
	color_bar.ax.invert_xaxis()
	color_bar.ax.tick_params(labelsize=16)
	
	ax.set_yscale('log') # logarithmic axes
	ax.set_xscale('log')
	
	plt.minorticks_off()
	
	pure_ticks = np.array([1e-3,1,10,60*10,2*3600,1*24*3600, 7*24*3600]) # where the tick marks will be placed, in units of seconds.
	labels = ['1 msec','1 sec','10 sec','10 min','2 hr','1 day','1 week']  # tick labels
	
	max_val = np.max([np.max(sep_array[:,0]), np.max(sep_array[:,1])])
	
	ticks = np.hstack((pure_ticks, max_val))
	
	min_val = np.min([np.min(sep_array[:,0]), np.min(sep_array[:,1])])
	
	plt.xticks(ticks,labels,fontsize=16)
	plt.yticks(ticks,labels,fontsize=16)
	
	plt.xlabel('Time Before Tweet',fontsize=18)
	plt.ylabel('Time After Tweet',fontsize=18)
	
	plt.xlim((min_val, max_val))
	plt.ylim((min_val, max_val))
	
	ax.set_aspect('equal')
	
	plt.tight_layout()
	
	plt.show()

	return None
コード例 #55
0
def folium_mapp(idd,idPost=None,limit=0,price_ratio=0.5,radius=2000, price_update = 0.0):
  client = pymongo.MongoClient("mongodb+srv://thuan:[email protected]/atomic?authSource=admin&replicaSet=atlas-1i0fgy-shard-0&w=majority&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true")
  db = client.atomicbds
  update_price_db = db.update_price
  def get_df(idd = idd,distance_radius=radius):
    client = pymongo.MongoClient("mongodb+srv://thuan:[email protected]/atomic?authSource=admin&replicaSet=atlas-1i0fgy-shard-0&w=majority&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true")
    db = client.atomicbds
    collection = db.data_post3
    df = pd.DataFrame(list(collection.find()))
    df['id'] = df['id'].astype(int)
    df['gglat'] = df['gglat'].astype(float)
    df['gglong'] = df['gglong'].astype(float)
    df['address_city'] = df['address_city'].astype(float).astype(int)
    df['position_street'] = df['position_street'].astype(float).astype(int)
    df = df[df['area_cal'].apply(float)>1.0]
    df = df[df["address_city"] == 1] # HCM
    df = df[df['price_m2_old']>0.0][df['price_m2_old']<2000000000.0]
    idPost = df[df["id"] == int(idd)].iloc[0]
    center_latlong = [idPost.gglat,idPost.gglong]
    distance_from_center = lambda row: geopy.distance.geodesic(center_latlong,[row['gglat'],row['gglong']]).m
    df['distance_from_center']=df.apply(distance_from_center,axis=1)
    return df[df.distance_from_center<float(distance_radius)],idd,idPost
  
  data_district = pd.read_csv("district.csv")
  labeled = [595347,197574,595347,728022,539702,133762,595347,648824,151611,585779,90505,193579,90505,295901,90505,316913,90505,113096,614411,430301,539702,405019,320512,409878,652053,732480,614411,63428,303680,109919,303680,441339,539702,80248,652053,468045,299557,144908,539702,536729,595347,664312,614411,568236,614411,398661,303680,307731,435447,503553,595347,622751,652053,526136,652053,526136,75320,430195,75320,685946,151611,690287,721528,288939,621291,317757,539702,63818,652053,309152,652053,57550,652053,673630,122845,596146,721528,732288,577544,763033,595347,508729,122845,605561,320512,169733,151611,717646,151611,616848,621291,727332,435447,724328,151611,336802,303680,407222,614411,305266,303680,290332,621291,622003,577544,169279,621291,94057,299557,116847,503553,47888,614411,719986,539702,327366,122845,294564,539702,581740,75320,303817,721528,643041,303680,601918,614411,566384,503553,655052,614411,617461,503553,127978,539702,535122,721528,132468,539702,322154,721528,585622,577544,588940,539702,603657,122845,535670,435447,725757,122845,390904,90505,639116,721528,80300,503553,435447,595347,320682,621291,343055,621291,107399,577544,725366,503553,452345,595347,201498,621291,442576,539702,587892,320512,308147,621291,555167,90505,59078,539702,464764,721528,688220,75320,730348,90505,112705,320512,169733,122845,50954,539702,585667,577544,78046,299557,738857,652053,471501,151611,105324,614411,548107,90505,566362,122845,735541,299557,473644,614411,506172,503553,180465,122845,629412,614411,112692,614411,299384,303680,311072,614411,509482,621291,544250,614411,178290,90505,308169,577544,588940,539702,459370,90505,739050,320512,118873,621291,497351,75320,73580,539702,454142,320512,535680]
  construct_price={'Tiết Kiệm':4500000.0,'Cơ Bản':5100000.0,'Trung Bình':5500000.0,'Khá':5850000.0,'Cao Cấp':8300000.0}
  
  def cal_land_price_per_m2(row,construct_type='Cơ Bản'):
    try:
      return (float(row.price_sell) - float(row.floor)*construct_price[construct_type])/float(row.area_cal)
    except:
      return 0.0
      # return (float(row.price_sell) - float(row.floor)*construct_price[construct_type])/float(1.0)

  def cal_house_price(row, land_price_per_m2=0.0,construct_type='Cơ Bản'):
    # print('area_call:{},land_price_per_m2:{}'.format(str(row.area_cal),str(land_price_per_m2)))
    try:
      return float(row.floor)*construct_price[construct_type] + float(land_price_per_m2)*float(row.area_cal)
    except:
      return float(row.floor)*construct_price[construct_type] + float(land_price_per_m2)*float(1.0)

  def get_price_ratio_of_a_point_with_deep(price_ratio,deep):
    return 1 + price_ratio/math.pow(1.1,(int(deep)/100))

  def size_a_point(row):
    if int(row['id']) == center_id:
      return 30
    if int(row['id']) in labeled:
      if int(row['id']) in arr_dist[0]:
        return 20
      else:
        return 15
    elif int(row['id']) in arr_dist[0]:
      return 7
    else:
      return 3

  def color_a_point(row):
    color="#0375B4" # blue
    # if int(row['id']) == center_id:
    #   return color
    
    # for i in range(0, len(arr)):
    for i in arr_dist:
      # if int(row['id']) in labeled:
      #   color = white
      # else:
      if int(row['id']) in arr_dist[i]:
        color = colors[i].get_hex()
      if int(row['id']) in arr_dist[0]:
        color = "#FFCE00" # orange
    return color

  def draw_folium_map(data_post):
      i = j = k = 0
      # generate a new map
      folium_map = folium.Map(location=[idPost['gglat'], idPost['gglong']],
                              zoom_start=15,
                              max_zoom=25,
                              tiles="CartoDB positron",
                              # tiles="CartoDB dark_matter",
                              width='50%')
      folium.CircleMarker(location=(idPost['gglat'], idPost['gglong']),
                              radius=35,
                              color="#0000FF",
                              fill=False).add_to(folium_map)
      # for each row in the data, add a cicle marker
      if(limit==0):
        lim = len(data_post)
      else:
        lim = limit

      pd_data = []
      mongo_price = []
      for index, row in data_post.iterrows():
        # if(index > limit or limit = 0):
        # if(index > lim):
        #   break
        # else:

        # # calculate net departures
        # net_departures = (row["Departure Count"]-row["Arrival Count"])
        
        # generate the popup message that is shown on click.
        i = 0
        # for i in range(0, len(arr)):
        #   if int(row['id']) in arr[i]:
        #     break
        for i in arr_dist:
          if int(row['id']) in arr_dist[i]:
            break
        
        
        ks = ['ID', 'Address Street', 'Address Ward', 'Address District', 'Position Street', 'Area', 'Deep', 'Labeled',  'Old Price/m2', 'New Price/m2', 'Ratio','Distance From Center','label']
        popup_text = """
                ID: {}<br> 
                Address Street: {}<br> 
                Address Ward: {}<br> 
                Address District: {}<br> 
                Position Street: {}<br>
                Area: {}<br>
                Deep: {}<br>
                Labeled: {}<br>
                Old Price/m2: {}<br>
                New Price/m2: {}<br>
                Ratio: {}<br>
                Price History: {}<br>
                """
        # new_price_m2 = get_price_m2_of_a_point_with_deep(price_m2,i)
        # if(i >= 100):
        #   new_ratio = get_price_ratio_of_a_point_with_deep(price_ratio,i)
        #   new_price_m2 = cal_land_price_per_m2(row)*float(new_ratio)
        # else:
        #   new_price_m2 = price_update * (EXPERT_RATE - float(i)/1000) + cal_land_price_per_m2(row) * (1 - EXPERT_RATE + float(i)/1000)
        #   new_ratio = new_price_m2/cal_land_price_per_m2(row)
        new_ratio = get_price_ratio_of_a_point_with_deep(price_ratio,i)
        new_price_m2 = cal_land_price_per_m2(row)*float(new_ratio)
        mongo_price.append({'id':str(row["id"]),\
          'positionStreet':pos_street_name(str(row["position_street"])),\
          'District': str(row["district_name"]),\
          'oldPrice':'{:,.2f}'.format(cal_land_price_per_m2(row)),\
          'newPrice':str(new_price_m2),\
          'distanceFromCenter':str(row["distance_from_center"]),\
          'deep': str(i),\
          'centerId':str(idPost["id"]),\
          'centerPrice':str(price_update),\
          'centerDistrict': str(idPost["district_name"]),\
          'centerPositionStreet': pos_street_name(str(idPost["position_street"])),\
          "date": datetime.datetime.utcnow()})
          
        pd_data.append([row["id"],
                unidecode(str(row["address_street"])),
                unidecode(str(row["address_ward"])),
                unidecode(str(row["district_name"])),
                row["position_street"],
                row['area_cal'],
                i,
                int(row["id"]) in labeled,
                '{:,.2f}'.format(cal_land_price_per_m2(row)),
                '{:,.2f}'.format(new_price_m2),
                new_ratio,
                '{:,.2f}'.format(row["distance_from_center"]),
                ''])
        popup_text = popup_text.format(
                row["id"],
                unidecode(str(row["address_street"])),
                unidecode(str(row["address_ward"])),
                unidecode(str(row["district_name"])),
                row["position_street"],
                row['area_cal'],
                i,
                int(row["id"]) in labeled,
                '{:,.2f}'.format(cal_land_price_per_m2(row)),
                '{:,.2f}'.format(new_price_m2),
                new_ratio,
                '<a href="http://0.0.0.0:5000/price_history?id={id}">{id}</a>'.format(id=row["id"])
                )
        # print(popup_text)
        # # radius of circles
        # radius = net_departures/20
        
        # # choose the color of the marker
        # if net_departures>0:
        #     # color="#FFCE00" # orange
        #     # color="#007849" # green
        #     color="#E37222" # tangerine
        # else:
        #     # color="#0375B4" # blue
        #     # color="#FFCE00" # yellow            
        #     color="#0A8A9F" # teal
        
        # add marker to the map
        if color_a_point(row) != "#0375B4":
          folium.CircleMarker(location=(row["gglat"], row["gglong"]),
                            radius=size_a_point(row),
                            color=color_a_point(row),
                            popup=popup_text,
                            fill=True).add_to(folium_map)
        
          if color_a_point(row) == "#007849":
            i += 1
          if color_a_point(row) == "#FFCE00":
            j += 1
        elif color_a_point(row) == "#0375B4":
          folium.CircleMarker(location=(row["gglat"], row["gglong"]),
                            radius=1,
                            color=color_a_point(row),
                            popup=popup_text,
                            fill=True).add_to(folium_map)
          k += 1
      update_price_db.insert_many(mongo_price)
      df_save = pd.DataFrame(pd_data, columns = ks)
      
      # df_save.to_csv(str(center_id)+'_'+str(price_ratio)+'.csv')
      
      if not os.path.exists('Results'):
        os.makedirs('Results')
      df_save = df_save.sort_values(by='Deep',axis=0)
      df_save.to_csv('Results/ID_{}_{}_{}.csv'.format(str(center_id),str(price_ratio),'{:,.2f}'.format(float(idPost["price_m2_old"])*float(new_ratio))))
      print("green: %s, orange: %s, blue: %s" % (i, j, k))
      return folium_map

  def get_direction(deep):
    if(deep == 0):
        return [[0,0]]
    if(deep > 0):
        lst = []
        for x in range(-deep,deep+1):
            for y in range(-deep,deep+1):
                if x == deep or y == deep or x == -deep or y == -deep:
                    lst.append([x,y])
        return lst

  def getSurroundings(matrix,x,y,deep):
    res = []
    for direction in get_direction(deep):
      cx = x + direction[0]
      cy = y + direction[1]
      if(cy >=0 and cy < len(matrix)):
        if(cx >=0 and cx < len(matrix[cy])):
          res.append(matrix[cy][cx])
    return res

  def closest_node(data, t, map, m_rows, m_cols):
    # (row,col) of map node closest to data[t]
    result = (0,0)
    small_dist = 1.0e20
    for i in range(m_rows):
      for j in range(m_cols):
        # ed = euc_dist(map[i][j], data[t])
        
        ed = latlong_posstreet(map[i][j], data[t])
        if ed < small_dist:
          small_dist = ed
          result = (i, j)
    return result

  def latlong_posstreet(v1, v2):
    # print(v1)
    # print(v2)
    distance_latlong = np.linalg.norm(v1[:2] - v2[:2]) * 1000 # lấy 2 giá trị đầu tính latlong

    delta = np.linalg.norm(v1[2] - v2[2]) 
    distance_district_latlong = np.linalg.norm(v1[3:5] - v2[3:5]) * 1000 / 2
    # distance_street = np.linalg.norm(v1[5:7] - v2[5:7])

    # distance = sigma + alpha * delta + abs(beta * distance_latlong) + gamma * distance_district_latlong + abs(omega * street)
    distance = sigma + alpha * delta + abs(beta * distance_latlong) + gamma * distance_district_latlong 
    return distance
  
  def score_pos_street(id_pos_street): # convert id pos_street to score
    id_pos_street = int(float(id_pos_street))
    if id_pos_street == 1:
      return c[0]
    if id_pos_street == 2:
      return c[1]
    if id_pos_street == 3:
      return c[2]
    if id_pos_street == 4:
      return c[3]
    if id_pos_street == 5:
      return c[4]
    if id_pos_street == 6:
      return c[5]
    return id_pos_street

  def pos_street_name(id_pos_street): # convert id pos_street to score
    id_pos_street = int(float(id_pos_street))
    if id_pos_street == 1:
      return 'Mặt tiền'
    if id_pos_street == 2:
      return 'Góc 2 mặt tiền'
    if id_pos_street == 3:
      return 'Hẻm 1 sẹc'
    if id_pos_street == 4:
      return 'Hẻm 2 sẹc trở lên'
    if id_pos_street == 5:
      return '2 mặt tiền hẻm'
    if id_pos_street == 6:
      return 'Hẻm'
    return 'Mặt tiền'

  def euc_dist(v1, v2):
    return np.linalg.norm(v1 - v2) 

  def manhattan_dist(r1, c1, r2, c2):
    return np.abs(r1-r2) + np.abs(c1-c2)

  def most_common(lst, n):
    # lst is a list of values 0 . . n
    if len(lst) == 0: return -1
    counts = np.zeros(shape=n, dtype=np.int)
    for i in range(len(lst)):
      counts[lst[i]] += 1
    return np.argmax(counts)
  # Get datapost

  data_post,center_id,idPost = get_df()
  print(len(data_post))
  price_m2 = cal_land_price_per_m2(idPost)

  # Initial variables for model
  # Initial variables for logic distance
  # Initial data_x, data_y, name
  
  [alpha, beta, gamma, omega, sigma, c] = [3.12506638, -9.00115707,  4.35316446, -97.95369439, -6.64789365, [-16.16039254, -12.96374504, -21.42898834, -16.06295894, -16.23441444, -18.69862314]]
  nrows = len(data_post.index)
  data_x = []
  data_x_dictrict = []
  data_x_street = []
  for i in range(0, nrows):
    data_x.append(data_post["latlongpos"].iloc[i])
    data_x_dictrict.append([data_post["district_lat"].iloc[i], data_post["district_long"].iloc[i]])
    # data_x_street.append(data_post["latlong_street"].iloc[i])

  data_x = [x[:2]+[score_pos_street(x[2])] for x in data_x]

  for i in range(0, nrows):
    data_x[i].extend(data_x_dictrict[i])
    # data_x[i].extend(data_x_street[i])
  # print(data_x)
  data_y = []
  for i in range(0, nrows):
    data_y.append(data_post["id"].iloc[i])
    
  name = []
  for index, row in data_post.iterrows():
    name.append((row.id))  

  np.random.seed(1)
  Dim = len(data_x[0])
  Rows = 100; Cols = 100
  RangeMax = Rows + Cols
  LearnMax = 0.5            # 0.5
  StepsMax = 15000          # 20000
  
  # Load K-SOM map
  map = np.load('Ver.04/map_GAKSOM3.npy', allow_pickle=True)
  mapping = np.load('Ver.04/mapping_GAKSOM3.npy', allow_pickle=True)
  label_map = np.load('Ver.04/label_map_new_GAKSOM2.npy', allow_pickle=True)
  label_map_new = np.load('Ver.04/label_map_new_GAKSOM3.npy', allow_pickle=True)
  label_map_district = np.load('Ver.04/label_map_district_new_GAKSOM2.npy', allow_pickle=True)
  # Find Closest Node
  v1_x = data_x[data_y.index(idd)]
  LOL = np.array([v1_x])
  predict_idx = closest_node(LOL, 0, map, Rows, Cols)
  arr_dist = {}
  arr_dist[0]=[idd]
  count = 0
  for i in range(0, 100):
    for index in getSurroundings(label_map_new, predict_idx[1],predict_idx[0], i):
      pred_idx=index
      if (pred_idx != -1):
        idPost_coordinate = np.array([idPost['gglat'], idPost['gglong']])
        for idd in pred_idx:
          try:
            pred_idd = np.array([data_post[data_post["id"] == idd].iloc[0]['gglat'],data_post[data_post["id"] == idd].iloc[0]['gglong']])
            try:
              arr_dist[i*10+(int(euc_dist(pred_idd,idPost_coordinate)*100)%10)].append(idd)
            except:
              arr_dist[i*10+(int(euc_dist(pred_idd,idPost_coordinate)*100)%10)]=[idd]
            count +=1
            
          except Exception as e:
            # print(str(e) + ' id: ' + str(idd))
            pass
  red = Color("#FE0000")
  green = Color ("#008000")
  blue = Color("#0000FF")
  white = Color("#FFFFFF")
  colors = list(red.range_to(green, 1000))

  # draw_folium_map(data_post)
  mymapp = draw_folium_map(data_post)
  return mymapp


# folium_mapp(539702)
コード例 #56
0
ファイル: rpi_thermal_cam.py プロジェクト: eiselekd/hw
#initialize the sensor
sensor = adafruit_amg88xx.AMG88XX(i2c_bus)

# pylint: disable=invalid-slice-index
points = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
grid_x, grid_y = np.mgrid[0:7:32j, 0:7:32j]
# pylint: enable=invalid-slice-index

#sensor is an 8x8 grid so lets do a square
height = 240
width = 240

#the list of colors we can choose from
blue = Color("indigo")
colors = list(blue.range_to(Color("red"), COLORDEPTH))

#create the array of colors
colors = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255)) for c in colors]

displayPixelWidth = width / 30
displayPixelHeight = height / 30

lcd = pygame.display.set_mode((width, height))

lcd.fill((255, 0, 0))

pygame.display.update()
pygame.mouse.set_visible(False)

lcd.fill((0, 0, 0))
コード例 #57
0
ファイル: monthmoney.py プロジェクト: RafisSomeone/statistics
set_option('display.max_rows', 500)
figure(figsize=(30, 18), dpi=200)
start = df.launched
start = [x.split(" ")[0] for x in start]
month = []
date_format = "%Y-%m-%d"
for i in range(len(start)):
    date = datetime.strptime(start[i], date_format)
    month.append(date.month)

df3 = DataFrame({"month": month, "usd_pledged_real": df.usd_pledged_real})

categories = df3.groupby('month')['month'].sum()

red = Color("gold")
colors = list(red.range_to(Color("blue"), len(categories) + 10))
colors = [x.get_hex() for x in colors if len(x.get_hex()) == 7]
colors = colors[2:]

ax = categories.plot(
    kind='bar',
    color=colors,
    title='Money collected by projects started in particular months',
    fontsize=20)
ax.set_xlabel("Months", fontsize=25)
ax.set_ylabel("Collected money [USD]", fontsize=25)
ax.title.set_size(40)

plt.savefig('monthmoney.png')

plt.clf()
コード例 #58
0
COLORDEPTH = 1024

client = mqtt.Client()
os.putenv('SDL_FBDEV', '/dev/fb1')
pygame.init()

points = [(math.floor(ix / 8), (ix % 8)) for ix in range(0, 64)]
grid_x, grid_y = np.mgrid[0:7:32j, 0:7:32j]

#sensor is an 8x8 grid so lets do a square
height = 240
width = 240

#the list of colors we can choose from
blue = Color("indigo")
colors = list(blue.range_to(Color("red"), COLORDEPTH))

#create the array of colors
colors = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255)) for c in colors]

displayPixelWidth = width / 30
displayPixelHeight = height / 30

lcd = pygame.display.set_mode((width, height))

lcd.fill((255,0,0))
pygame.display.set_caption('AMG88xx')
#pygame.display.update()
pygame.display.flip()
pygame.mouse.set_visible(False)
コード例 #59
0
from colour import Color
import math
import sys

N_POINTS = 255
MAXVAL = 255

red = Color("red")
colors = list(red.range_to(Color("blue"),N_POINTS))

for i in range(1,N_POINTS):
    sys.stdout.write("%d" % (math.floor(colors[i].red*MAXVAL)))
    sys.stdout.write(',')
    sys.stdout.write("%d" % (math.floor(colors[i].green*MAXVAL)))
    sys.stdout.write(',')
    sys.stdout.write("%d" % (math.floor(colors[i].blue*MAXVAL)))
    sys.stdout.write(',')