コード例 #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
ファイル: models.py プロジェクト: urfonline/website
    def generate_branding_style_secondary(self):
      styles = dict();

      if self.has_accent_color:
        accent = Color(self.safe_accent_color)
        accent.luminance = accent.luminance * 0.9 if accent.luminance * 0.9 >= 0 else 0;
        accent.saturation = accent.saturation * 1.1 if accent.saturation * 1.1 <= 1 else 1
        styles['background-color'] = accent.hex

      return self.css_style(styles);
コード例 #8
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))
コード例 #9
0
ファイル: main.py プロジェクト: PMunch/i3ColourChanger
def colourChanged(e, oldColour):
    if type(e) == str:
        return e
    elif type(e) == Color:
        nc = [e.red * 255, e.green * 255, e.blue * 255]
    else:
        nc = e.GetColour()
    if type(oldColour) is not Color:
        oldColour = Color()
    oldColour.red = nc[0] / 255
    oldColour.green = nc[1] / 255
    oldColour.blue = nc[2] / 255
    return oldColour
コード例 #10
0
ファイル: robot.py プロジェクト: IlyaSukhanov/morseapi
def color_byte_array(color_value):
    """
    convert color into a 3 byte bytearray

    :param color_value: 6-digit (e.g. #fa3b2c), 3-digit (e.g. #fbb),
    fully spelled color (e.g. white)
    """
    color = Color(color_value)
    return bytearray([
        int(round(color.get_red()*255)),
        int(round(color.get_green()*255)),
        int(round(color.get_blue()*255)),
    ])
コード例 #11
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
コード例 #12
0
ファイル: views.py プロジェクト: cuducos/findaconf
def poster():

    # randon backgorund color
    rand_rgb = tuple([(randrange(97, 160) / 255.0) for i in range(3)])
    bg = Color(rgb=rand_rgb)

    # get foreground
    fg = Color(bg.hex)
    variation = randrange(15, 60)
    fg.hue = choice([variation, variation * -1])

    # random alpha
    alpha = randrange(4, 7) / 10.0

    # create image
    svg = render_template('poster.svg', bg=bg.hex, fg=fg.hex, alpha=alpha)
    return Response(svg2png(bytestring=svg), mimetype='image/png')
コード例 #13
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}
コード例 #14
0
ファイル: geopatterns.py プロジェクト: digvan/geopatterns
    def generate_background(self):
        hue_offset = promap(int(self.hash[14:][:3], 16), 0, 4095, 0, 359)
        sat_offset = int(self.hash[17:][:1], 16)
        base_color = Color(hsl=(0, .42, .41))
        base_color.hue = base_color.hue - hue_offset

        if sat_offset % 2:
            base_color.saturation = base_color.saturation + sat_offset / 100
        else:
            base_color.saturation = base_color.saturation - sat_offset / 100

        rgb = base_color.rgb
        r = int(round(rgb[0] * 255))
        g = int(round(rgb[1] * 255))
        b = int(round(rgb[2] * 255))
        return self.svg.rect(0, 0, '100%', '100%', **{
            'fill': 'rgb({}, {}, {})'.format(r, g, b)
        })
コード例 #15
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()
コード例 #16
0
ファイル: custom.py プロジェクト: menthas/prmd
    def _visualize_beacon(self, data, beacon):
        if beacon == self.LEFT_BEACON:
            prefix = 'left_'
        else:
            prefix = 'right_'

        if not self.is_active_on_spectrum(data, prefix):
            return self.layout.set_beacon(beacon, self.layout._off)

        color = Color(rgb=self.container.get_conf(prefix + 'color'))
        color.luminance = self.container.get_conf(prefix + 'lum') / 100.0
        if self.config[beacon]['Luminance'] == 'Beat':
            color = self.beat_lum(data, color, prefix, beacon)
        elif self.config[beacon]['Luminance'] == 'Energy':
            color = self.energy_lum(data, color, prefix, beacon)
        elif self.config[beacon]['Luminance'] == 'Onset':
            color = self.onset_lum(data, color, prefix, beacon)

        if self.config[beacon]['Color'] == 'Beat':
            color = self.beat_color(data, color, prefix, beacon)
        elif self.config[beacon]['Color'] == 'Energy':
            color = self.energy_color(data, color, prefix, beacon)
        elif self.config[beacon]['Color'] == 'Onset':
            color = self.onset_color(data, color, prefix, beacon)

        if self.config[beacon]['Side'] == 'Beat':
            self.beat_side(data, color, prefix, beacon)
        elif self.config[beacon]['Side'] == 'Energy':
            self.energy_side(data, color, prefix, beacon)
        elif self.config[beacon]['Side'] == 'Onset':
            self.onset_side(data, color, prefix, beacon)
        elif self.config[beacon]['Row'] == 'Beat':
            self.beat_row(data, color, prefix, beacon)
        elif self.config[beacon]['Row'] == 'Energy':
            self.energy_row(data, color, prefix, beacon)
        elif self.config[beacon]['Row'] == 'Energy (R)':
            self.energy_row(data, color, prefix, beacon, reverse=True)
        elif self.config[beacon]['Row'] == 'Onset':
            self.onset_row(data, color, prefix, beacon)
        else:
            self.layout.set_beacon(beacon, color)
コード例 #17
0
ファイル: mobject.py プロジェクト: mherkazandjian/manim
 def add_points(self, points, rgbs = None, color = None):
     """
     points must be a Nx3 numpy array, as must rgbs if it is not None
     """
     if not isinstance(points, np.ndarray):
         points = np.array(points)
     num_new_points = points.shape[0]
     self.points = np.append(self.points, points, axis = 0)
     if rgbs is None:
         color = Color(color) if color else self.color
         rgbs = np.array([color.get_rgb()] * num_new_points)
     elif rgbs.shape != points.shape:
         raise Exception("points and rgbs must have same shape")
     self.rgbs = np.append(self.rgbs, rgbs, axis = 0)
     if self.has_normals:
         self.unit_normals = np.append(
             self.unit_normals,
             np.apply_along_axis(self.unit_normal, 1, points),
             axis = 0
         )
     return self
コード例 #18
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)
コード例 #19
0
ファイル: mobject.py プロジェクト: nachinius/animations
 def add_points(self, points, rgbs = None, color = None):
     """
     points must be a Nx3 numpy array, as must rgbs if it is not None
     """
     points = np.array(points)
     num_new_points = points.shape[0]
     self.points = np.append(self.points, points)
     self.points = self.points.reshape((self.points.size / 3, 3))
     if rgbs is None:
         color = Color(color) if color else self.color
         rgbs = np.array([color.get_rgb()] * num_new_points)
     else:
         if rgbs.shape != points.shape:
             raise Exception("points and rgbs must have same shape")
     self.rgbs = np.append(self.rgbs, rgbs)
     self.rgbs = self.rgbs.reshape((self.rgbs.size / 3, 3))
     if self.has_normals:
         self.unit_normals = np.append(
             self.unit_normals,
             np.array([self.unit_normal(point) for point in points])
         ).reshape(self.points.shape)
     return self
コード例 #20
0
ファイル: twod.py プロジェクト: alexhagen/pyg
 def add_line(self, x, y, name='plot', xerr=None, yerr=None, linewidth=0.5,
              linestyle=None, linecolor='black', legend=True, axes=None):
     if axes is None:
         axes = self.ax
     self.plotnum = self.plotnum + 1
     if name is 'plot':
         name = 'plot%d' % (self.plotnum)
     if linestyle is None:
         _ls = self.linestyle[self.plotnum % 4]
     else:
         _ls = linestyle
     if xerr is None and yerr is None:
         line = axes.plot(x, y, label=name, color=linecolor,
                          marker=self.marker[self.plotnum % 7],
                          ls=_ls, lw=linewidth, solid_capstyle='butt',
                          clip_on=True)
         for i in range(0, len(line)):
             self.lines[name + '%d' % (i)] = (line[i])
     else:
         if linecolor == 'black':
             ecolor = '#A7A9AC'
         else:
             col = Color(linecolor)
             col.saturation = 0.5
             col.luminance = 0.75
             ecolor = col.hex
         line, caplines, barlinecols = axes.errorbar(x, y, label=name,
                                                     color=linecolor,
                                                     xerr=xerr,
                                                     yerr=yerr,
                                                     marker=self.marker[self.plotnum % 7],
                                                     ls=_ls,
                                                     ecolor=ecolor,
                                                     lw=linewidth,
                                                     clip_on=True)
         self.lines[name] = (line)
     self.markers_on()
     self.lines_off()
コード例 #21
0
def rgb_color_picker(obj, min_luminance=None, max_luminance=None):
    """Modified version of colour.RGB_color_picker"""
    color_value = int.from_bytes(
        hashlib.md5(str(obj).encode('utf-8')).digest(),
        'little',
    ) % 0xffffff
    color = Color(f'#{color_value:06x}')
    if min_luminance and color.get_luminance() < min_luminance:
        color.set_luminance(min_luminance)
    elif max_luminance and color.get_luminance() > max_luminance:
        color.set_luminance(max_luminance)
    return color
コード例 #22
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 ""
コード例 #23
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,
コード例 #24
0
from colour import Color
from flask import url_for
import numpy as np
from flask import Flask
from flask import render_template
from flask import request, redirect, jsonify
from flask_cors import CORS, cross_origin
from collections import OrderedDict
from pprint import pprint
from rule_matching import do_for_sent
from flask_sslify import SSLify

# pip3.6 install -U flask-cors
# pip3.6  install Flask-SSLify

white           = Color("white")
yellow_colors   = list(white.range_to(Color("yellow"), 101))
yellow_colors   = [c.get_hex_l() for c in yellow_colors]
blue_colors     = list(white.range_to(Color("blue"), 101))
blue_colors     = [c.get_hex_l() for c in blue_colors]
green_colors    = list(white.range_to(Color("green"), 101))
green_colors    = [c.get_hex_l() for c in green_colors]

app = Flask(__name__)
sslify = SSLify(app)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
# CORS(app)

@app.route("/")
def get_news():
コード例 #25
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() 
コード例 #26
0
def folium_mappd(idd, idPost=None, limit=0, price_ratio=0.5, radius=5000):
    def get_df(idd=idd, distance_radius=5000):
        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

        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):
        return 3

    def color_a_point(row):
        color = "#0375B4"  # blue
        # if int(row['id']) == center_id:
        #   return color
        try:
            color = mapping_color[row['id']]
        except:
            pass
        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 = []
        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', '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>
                """
            # new_price_m2 = get_price_m2_of_a_point_with_deep(price_m2,i)
            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)
            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, ''
            ])
            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,
            )
            # 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
        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 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
    mapping_color = {}
    red = Color("#FE0000")
    green = Color("#008000")
    colors = list(red.range_to(green, 10000))
    for i_x, x in enumerate(label_map_new):
        for i_y, y in enumerate(x):
            if isinstance(y, list):
                # mapping_color[100*i_y+i_x]=y
                for item in y:
                    mapping_color[item] = colors[100 * i_y + i_x].get_hex()

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


# folium_mapp(539702)
コード例 #27
0
    cells = dict(
        values=[cols] + [l],
        line_color='darkslategray',
    )
    header = dict(values=['Round', 'Points'], line_color='darkslategray')
    fig = go.Figure(data=[go.Table(header=header, cells=cells)])
    fig.update_layout(margin=dict(l=0, r=0, t=0, b=0))
    file_name = f"Write_Up/img/{team.replace(' ', '_').replace(',','')}_Week_{week}_Breakdown.html"
    fig.write_html(file_name)


weeks = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
trivia = Trivia(weeks)

s_col = Color("#fa8575")
colors = list(s_col.range_to(Color("#009c50"), 10))
#Overall
make_standings_table(trivia)  # -> to HTML
make_records(trivia)  # -> local var
make_cats(trivia)  # -> to HTML
#Individual
teams = trivia.teams
for team in teams:
    print(f'Making Team: {team}')
    print('.....Overall')
    team_weeks = [x[0] for x in trivia.team_weeks[team]]
    make_butterfly(trivia, team)
    make_season_plots(trivia, team)
    make_season_all(trivia, team)
    ##        make_cats_team(trivia, team)
コード例 #28
0
ファイル: timebox.py プロジェクト: vosmont/timebox
def temp(ctx, color, f):
    if(color):
        c = color_convert(Color(color).get_rgb())
        ctx.obj['dev'].send(set_temp_color(c[0],c[1],c[2],0xff,f))
    else:
        ctx.obj['dev'].send(switch_view("temp"))
コード例 #29
0
class VirtualLedModel:
    """
    Simulates the LED cube in different configurations in OpenGL.
    You have to provide a json dictionary at instantiation, this should refer to a json file.
    You also have to provide a pointer to the array of led colors.
    After this, use the refresh function to update the LEDs.
    The current shader supports up to 300 LEDS, update the shader variable if more is needed.
    """

    model = None
    program = None
    debug_program = None
    visualizer_thread = None
    led_colors = None

    vao = None

    led_enclosure_buffer = None
    led_enclosure_buffer_id = None
    attrib_position_id = None
    attrib_normal_id = None

    led_color_buffer = None
    led_color_buffer_id = None
    attrib_led_color_id = None

    led_position_buffer = None
    led_position_buffer_id = None
    attrib_led_position_id = None

    camera_horizontal_angle = pi / 4
    camera_vertical_angle = pi / 4
    attrib_cam_pos_id = None
    cam_pos = [0.0, 0.0, 0.0]

    zoom_factor = 0.0
    zoom_start_distance = 1.0
    zoom_last_distance = 1.0
    zoom_animation_speed = 0.1

    key_down_left_mouse = False

    mouse_drag_speed = 0.01
    mouse_scroll_speed = 0.1
    mouse_last_x = -1.0
    mouse_last_y = -1.0

    refresh_queued = False
    shutdown_requested = False
    delta_time = None
    last_time = None
    n_leds = None

    hdr = [1.0, 0.0]
    hdr_goal = [1.0, 0.0]
    hdr_change_rate = 0.05
    attrib_hdr_id = None

    clear_color = Color('gray')
    debug = False
    active_debug = False
    fov = 45.0
    close = 0.01
    far = 1000
    fps = 60
    window_width = 800
    window_height = 600
    window_title = b'LED Visualizer'

    def __init__(self, model):
        self.model = model
        self.n_leds = len(self.model['led-strip'])
        self.last_time = time.time()
        self.led_colors = [0] * (self.n_leds * 3)

        def thread_func():
            self._init_glut()
            self._init_opengl()
            glutMainLoop()

        self.visualizer_thread = Thread(name='visualizer', target=thread_func)

        self.visualizer_thread.start()

    def _init_opengl(self):
        glClearColor(self.clear_color.get_red(), self.clear_color.get_green(),
                     self.clear_color.get_blue(), 1.0)
        glClearDepth(1.0)
        glDepthFunc(GL_LEQUAL)
        glShadeModel(GL_SMOOTH)
        glEnable(GL_POLYGON_SMOOTH)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_CULL_FACE)
        #glEnable(GL_VERTEX_ARRAY)
        #glEnable(GL_BLEND)
        #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        if not glUseProgram:
            raise EnvironmentError('Missing shader objects')

        # Open shader files
        vert_file = open('neural_presenters/virtual/shaders/enclosure.vert')
        frag_file = open('neural_presenters/virtual/shaders/enclosure.frag')

        # Compile
        self.program = compileProgram(
            compileShader(vert_file.read(), GL_VERTEX_SHADER),
            compileShader(frag_file.read(), GL_FRAGMENT_SHADER))

        # Close files
        vert_file.close()
        frag_file.close()

        # Open shader files
        vert_file = open('neural_presenters/virtual/shaders/debug.vert')
        frag_file = open('neural_presenters/virtual/shaders/debug.frag')

        self.debug_program = compileProgram(
            compileShader(vert_file.read(), GL_VERTEX_SHADER),
            compileShader(frag_file.read(), GL_FRAGMENT_SHADER))

        # Close files
        vert_file.close()
        frag_file.close()

        glUseProgram(self.program)

        # Fill LED buffers
        led_positions = self.model['led-strip']
        self.led_color_buffer = (GLfloat *
                                 (4 * self.n_leds))(*ones(4 * self.n_leds))
        self.led_position_buffer = (GLfloat *
                                    (4 * self.n_leds))(*ones(4 * self.n_leds))
        for i in range(self.n_leds):
            for j in range(3):
                self.led_color_buffer[i * 4 + j] = 0.0
                self.led_position_buffer[i * 4 + j] = led_positions[i][j]

        # Fill enclosure buffer
        led_enclosure = self.model['led-enclosure']
        self.led_enclosure_buffer = (GLfloat * (3 * 8 * len(led_enclosure)))(
            *ones(3 * 8 * len(led_enclosure)))
        for i in range(len(led_enclosure)):
            # Calculate normal for the next three vertices
            v1 = array(led_enclosure[i][0])
            v2 = array(led_enclosure[i][1])
            v3 = array(led_enclosure[i][2])
            edge1 = v2 - v1
            edge2 = v3 - v1
            normal = cross(edge1, edge2)
            normal = normal / sqrt(normal[0]**2 + normal[1]**2 + normal[2]**2)
            for j in range(3):
                for k in range(3):
                    self.led_enclosure_buffer[i * 8 * 3 + j * 8 +
                                              k] = led_enclosure[i][j][k]
                for k in range(3):
                    self.led_enclosure_buffer[i * 8 * 3 + j * 8 + k +
                                              4] = normal[k]

        # Generate vertex array and bind
        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)

        # Not the best way, but works for now
        self.attrib_led_color_id = glGetUniformLocation(
            self.program, 'led_colors')
        self.attrib_led_position_id = glGetUniformLocation(
            self.program, 'led_positions')
        self.attrib_hdr_id = glGetUniformLocation(self.program, 'hdr')
        self.attrib_cam_pos_id = glGetUniformLocation(self.program, 'cam_pos')
        self._bind_uniforms()
        """
        # Setup LED color buffer
        self.led_color_buffer_id = glGenBuffers(1)
        glBindBuffer(GL_UNIFORM_BUFFER, self.led_color_buffer_id)
        glBufferData(GL_UNIFORM_BUFFER, len(self.led_color_buffer) * sizeof(GLfloat),
                     self.led_color_buffer, GL_STREAM_DRAW)

        self.attrib_led_color_id = glGetUniformLocation(self.program, 'led_colors')
        glBindBufferRange(GL_UNIFORM_BUFFER, 0, self.led_color_buffer_id, 0, len(self.led_color_buffer_id))

        # Setup LED position buffer
        self.led_position_buffer_id = glGenBuffers(1)
        glBindBuffer(GL_UNIFORM_BUFFER, self.led_position_buffer_id)
        glBufferData(GL_UNIFORM_BUFFER, len(self.led_position_buffer) * sizeof(GLfloat),
                     self.led_position_buffer, GL_STATIC_DRAW)

        self.attrib_led_position_id = glGetUniformLocation(self.program, 'led_positions')
        glBindBufferBase(GL_UNIFORM_BUFFER, 1, self.led_position_buffer_id)
        glUniformBlockBinding(self.program, self.attrib_led_position_id, 1)

        glBindBuffer(GL_UNIFORM_BUFFER, 0)
        """

        # Setup enclosure vertex buffer
        self.led_enclosure_buffer_id = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, self.led_enclosure_buffer_id)
        glBufferData(GL_ARRAY_BUFFER,
                     len(self.led_enclosure_buffer) * sizeof(GLfloat),
                     self.led_enclosure_buffer, GL_STATIC_DRAW)

        self.attrib_position_id = glGetAttribLocation(self.program, 'position')
        self.attrib_normal_id = glGetAttribLocation(self.program, 'normal')
        glVertexAttribPointer(self.attrib_position_id, 4, GL_FLOAT, GL_FALSE,
                              8 * sizeof(GLfloat), GLvoid)
        glEnableVertexAttribArray(self.attrib_position_id)
        glVertexAttribPointer(self.attrib_normal_id, 4, GL_FLOAT,
                              GL_FALSE, 8 * sizeof(GLfloat),
                              GLvoidp(4 * sizeof(GLfloat)))
        glEnableVertexAttribArray(self.attrib_normal_id)

        glBindBuffer(GL_ARRAY_BUFFER, 0)

        glBindVertexArray(0)

        glUseProgram(0)

    def _init_glut(self):
        glutInit()
        glutInitDisplayMode(GLUT_DEPTH | GLUT_SINGLE | GLUT_RGB)
        glutInitWindowSize(self.window_width, self.window_height)
        glutCreateWindow(self.window_title)
        glutDisplayFunc(self._render)
        glutIdleFunc(self._render)
        glutMouseFunc(self._mouse_used)
        glutMouseWheelFunc(self._mouse_scroll_used)
        glutKeyboardFunc(self._keyboard_used)
        glutMotionFunc(self._motion)
        glutReshapeFunc(self._resize)

    def _update_hdr(self):
        for i in range(2):
            if abs(self.hdr_goal[i] -
                   self.hdr[i]) <= self.hdr_change_rate * self.delta_time:
                self.hdr[i] = self.hdr_goal[i]
            else:
                self.hdr[i] += self.hdr_change_rate * self.delta_time * sign(
                    self.hdr_goal[i] - self.hdr[i])

        if not self.active_debug:
            glClearColor(
                self.clear_color.get_red() / self.hdr[0] - self.hdr[1],
                self.clear_color.get_green() / self.hdr[0] - self.hdr[1],
                self.clear_color.get_blue() / self.hdr[0] - self.hdr[1], 1.0)
            glUniform2f(self.attrib_hdr_id, GLfloat(self.hdr[0]),
                        GLfloat(self.hdr[1]))
        else:
            glClearColor(self.clear_color.get_red(),
                         self.clear_color.get_green(),
                         self.clear_color.get_blue(), 1.0)

    def _resize(self, width, height):
        if height == 0:
            height = 1

        glViewport(0, 0, width, height)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        gluPerspective(self.fov,
                       float(width) / float(height), self.close, self.far)
        glMatrixMode(GL_MODELVIEW)

    def _update_camera(self):
        zoom_distance_goal = pow(2.0,
                                 self.zoom_factor) * self.zoom_start_distance
        self.zoom_last_distance += (
            zoom_distance_goal -
            self.zoom_last_distance) * self.zoom_animation_speed

        self.cam_pos[0] = self.zoom_last_distance * cos(
            self.camera_horizontal_angle) * sin(self.camera_vertical_angle)
        self.cam_pos[1] = self.zoom_last_distance * sin(
            self.camera_horizontal_angle) * sin(self.camera_vertical_angle)
        self.cam_pos[2] = self.zoom_last_distance * cos(
            self.camera_vertical_angle)

        gluLookAt(self.cam_pos[0], self.cam_pos[1], self.cam_pos[2], 0, 0, 0,
                  0, 0, 1)

        if not self.active_debug:
            glUniform3f(self.attrib_cam_pos_id, GLfloat(self.cam_pos[0]),
                        GLfloat(self.cam_pos[1]), GLfloat(self.cam_pos[2]))

    def _draw_model(self):
        glBindVertexArray(self.vao)
        glDrawArrays(GL_TRIANGLES, 0, len(self.led_enclosure_buffer))
        glBindVertexArray(0)

    def _draw_debug(self):
        # This is horrible, mixing opengl versions, using fixed pipeline... Oh well, only for debug

        # Grid
        glBegin(GL_LINES)
        glColor(0.2, 0.2, 0.2)

        for x in arange(-1, 1.1, 0.1):
            glVertex(x, 1, 0)
            glVertex(x, -1, 0)

        for y in arange(-1, 1.1, 0.1):
            glVertex(1, y, 0)
            glVertex(-1, y, 0)

        glEnd()

        # Origin marker
        glBegin(GL_LINES)

        # X - axis
        glColor(1, 0, 0)
        glVertex(0, 0, 0)
        glColor(1, 0, 0)
        glVertex(0.1, 0, 0)

        # Y - axis
        glColor(0, 1, 0)
        glVertex(0, 0, 0)
        glColor(0, 1, 0)
        glVertex(0, 0.1, 0)

        # Z - axis
        glColor(0, 0, 1)
        glVertex(0, 0, 0)
        glColor(0, 0, 1)
        glVertex(0, 0, 0.1)

        glEnd()

        # LEDs
        glPointSize(5)
        glBegin(GL_LINES)
        trans = linspace(0, 1, self.n_leds)
        for led in range(self.n_leds - 1):
            glColor(1, trans[led], 1 - trans[led])
            glVertex(self.led_position_buffer[led * 4],
                     self.led_position_buffer[led * 4 + 1],
                     self.led_position_buffer[led * 4 + 2])
            glColor(1, trans[led + 1], 1 - trans[led + 1])
            glVertex(self.led_position_buffer[(led + 1) * 4],
                     self.led_position_buffer[(led + 1) * 4 + 1],
                     self.led_position_buffer[(led + 1) * 4 + 2])
        glEnd()

        glBegin(GL_POINTS)
        for led in range(self.n_leds):
            glColor(self.led_color_buffer[led * 4],
                    self.led_color_buffer[led * 4 + 1],
                    self.led_color_buffer[led * 4 + 2])
            glVertex(self.led_position_buffer[led * 4],
                     self.led_position_buffer[led * 4 + 1],
                     self.led_position_buffer[led * 4 + 2])
        glEnd()

        # Enclosure
        for poly in self.model['led-enclosure']:
            glBegin(GL_LINE_LOOP)
            glColor(0, 1, 1)
            for vert in poly:
                glVertex(vert[0], vert[1], vert[2])
            glEnd()

    def _render(self):
        if self.shutdown_requested:
            glutLeaveMainLoop()
            return

        now_time = time.time()
        self.delta_time = now_time - self.last_time
        self.last_time = now_time

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glLoadIdentity()

        debug_state = self.debug

        if debug_state:
            glUseProgram(self.debug_program)
        else:
            glUseProgram(self.program)

        if self.active_debug != debug_state:
            self.active_debug = debug_state
            #self._bind_uniforms()

        if self.refresh_queued:
            light_intensity = 0.0
            for i in range(self.n_leds):
                led_intensity = 0.0
                for j in range(3):
                    led = self.led_colors[i * 3 + j] / 255.0
                    led_intensity += led / 3.0
                    self.led_color_buffer[i * 4 + j] = led
                self.led_color_buffer[i * 4 + 3] = 1.0
                light_intensity += led_intensity
            light_intensity /= self.n_leds
            self.hdr_goal[1] = light_intensity * 0.5
            if not debug_state:
                glUniform4fv(self.attrib_led_color_id, self.n_leds,
                             self.led_color_buffer)
            """
            glBindBuffer(GL_UNIFORM_BUFFER, self.led_buffer_color_index)
            glBufferSubData(GL_UNIFORM_BUFFER,
                            0,
                            len(self.led_buffer_colors)*sizeof(c_float),
                            self.led_buffer_colors)
            glBindBuffer(GL_UNIFORM_BUFFER, 0)
            """

            self.refresh_queued = False

        self._update_hdr()
        self._update_camera()

        if debug_state:
            self._draw_debug()
        else:
            self._draw_model()

        glutSwapBuffers()

        glUseProgram(0)

        time_taken = time.time() - now_time
        sync_time = 1. / self.fps - time_taken
        if sync_time < 0:
            #print('Virtual model can\'t keep up')
            sync_time = 0
        time.sleep(sync_time)

    def refresh(self, led_color_array):
        for i in range(self.n_leds):
            for j in range(3):
                self.led_colors[i * 3 + j] = led_color_array[i * 3 + j]
        self.refresh_queued = True

    def running(self):
        return self.visualizer_thread.is_alive()

    def shutdown(self):
        self.shutdown_requested = True

    def _keyboard_used(self, key, x, y):
        if key == b'd':
            self.debug = not self.debug

    def _bind_uniforms(self):
        glUniform4fv(self.attrib_led_position_id, self.n_leds,
                     self.led_position_buffer)
        glUniform4fv(self.attrib_led_color_id, self.n_leds,
                     self.led_color_buffer)

    def _mouse_used(self, button, state, x, y):
        if button == GLUT_LEFT_BUTTON:
            if state == GLUT_UP:
                self.key_down_left_mouse = False
                self.mouse_last_x = -1.0
                self.mouse_last_y = -1.0
            else:
                self.key_down_left_mouse = True

    def _mouse_scroll_used(self, wheel, direction, x, y):
        self.zoom_factor -= direction * self.mouse_scroll_speed

    def _motion(self, x, y):
        if self.key_down_left_mouse:
            if self.mouse_last_x == -1.0:
                self.mouse_last_x = x
                self.mouse_last_y = y
            self.camera_horizontal_angle -= (
                x - self.mouse_last_x) * self.mouse_drag_speed
            self.camera_horizontal_angle = self.camera_horizontal_angle % (2 *
                                                                           pi)
            temp = self.camera_vertical_angle - (
                y - self.mouse_last_y) * self.mouse_drag_speed
            self.camera_vertical_angle = clip(temp, 0.001, pi - 0.001)
            self.mouse_last_x = x
            self.mouse_last_y = y
コード例 #30
0
def colourRange(n):
    blue = Color('blue')
    return list(blue.range_to(Color("green"), n))
コード例 #31
0
    def draw(self, qp):
        pen = QPen(Qt.black, 1, Qt.SolidLine)
        qp.setPen(pen)

        # draw current arc expansion
        if self.status == "arc-expand":
            pen.setColor(Qt.yellow)
            qp.setPen(pen)
            for pixel in self.pixelsToColorInExpansion:
                qp.drawPoint(pixel[0], pixel[1])
            pen.setColor(Qt.red)
            qp.setPen(pen)
            for pixel in self.boundaryPixelsToColorInExpansion:
                qp.drawPoint(pixel[0], pixel[1])

        # paint completed arcs
        if self.status != 'spine-search' and self.status != 'spine-map' and self.status != 'spine-extension' and self.status != 'done':
            pen.setColor(Qt.green)
            qp.setPen(pen)
            for arcNum in self.arcsCompletedInArcExpansion:  # all pixels
                for pixel in self.ah.getArcPixels(arcNum):
                    qp.drawPoint(pixel[0], pixel[1])
            pen.setColor(Qt.red)
            qp.setPen(pen)
            for arcNum in self.arcsCompletedInArcExpansion:  # boundary pixels
                for pixel in self.ah.getArcPixels(arcNum, boundary=True):
                    qp.drawPoint(pixel[0], pixel[1])

        # draw our arc search pixel on top
        if hasattr(
                self, 'currPixelInArcSearch'
        ) and self.currPixelInArcSearch is not None:  # first time it'll be None
            pen.setColor(Qt.black)
            qp.setPen(pen)
            qp.drawPoint(self.currPixelInArcSearch[0],
                         self.currPixelInArcSearch[1])

        # draw our spine search pixel on top
        if hasattr(self, 'currPixelInSpineSearch'
                   ) and self.currPixelInSpineSearch is not None:
            pen.setColor(Qt.white)
            qp.setPen(pen)
            qp.drawPoint(self.currPixelInSpineSearch[0],
                         self.currPixelInSpineSearch[1])

        # draw current spine mapping
        if hasattr(self, 'pixelsVisitedInSpineMapping'
                   ) and self.pixelsVisitedInSpineMapping is not None:
            for pixel in self.pixelsVisitedInSpineMapping:
                pen.setColor(Qt.red)
                qp.setPen(pen)
                qp.drawPoint(pixel[0], pixel[1])

        # draw gradient between endpoints of completed spines
        if self.status != "done" and len(self.arcsCompletedInSpineMapping) > 0:
            for arcNum in self.arcsCompletedInSpineMapping:
                pixels, colors = self.ah.getSpinePaintMap(arcNum)
                for i in range(len(pixels)):
                    pixel = pixels[i]
                    color = colors[i]
                    pen.setColor(QColor(color[0], color[1], color[2]))
                    qp.setPen(pen)
                    qp.drawPoint(pixel[0], pixel[1])

        # draw paths extended from endpoints
        if self.status == "spine-extension":
            for endPoint, stepped in self.spineExtensionStepped.items():
                for pixel in stepped:
                    if self.ah.getEndPointPair(endPoint) is None:
                        pen.setColor(Qt.white)
                    else:
                        pen.setColor(QColor(50, 205, 50))  # is connected
                    qp.setPen(pen)
                    qp.drawPoint(pixel[0], pixel[1])

        # draw color gradient over entire knot
        if self.status == "done":
            # get rgb values for as many pixels as we need
            red = Color("red")
            blue = Color("blue")
            colors = list(
                red.range_to(blue, int(len(self.knotEnumeration) / 2)))
            colors.extend(
                list(blue.range_to(red,
                                   int(len(self.knotEnumeration) / 2) + 1)))
            rgbs = [color.rgb for color in colors]
            scaledRgbs = [(r * 255, g * 255, b * 255) for (r, g, b) in rgbs]
            i = 0
            source = list(self.knotEnumeration.keys())[0]
            currPixel = source
            while True:
                color = scaledRgbs[i]
                pen.setColor(QColor(color[0], color[1], color[2]))
                qp.setPen(pen)
                qp.drawPoint(currPixel[0], currPixel[1])  # ignore error
                currPixel = self.knotEnumeration[currPixel]['next']
                i += 1
                if currPixel == source:
                    break

        if self.status == "done":
            pass
コード例 #32
0
ファイル: cable.py プロジェクト: cable-robots/cdpyr
    def color(self, color: Union[AnyStr, Color]):
        if not isinstance(color, Color):
            color = Color(color)

        self._color = color
コード例 #33
0
width  = 480

pixels_size_height = height /pixels_colum
pixels_size_width = width /pixels_row

num_color = (0,0,0)

resolution = (height,width )
num_size = height / pixels_row /2

max_temp = 31
min_temp = 26

color_resolution = 100

blue = Color("blue")
#list() turn the tuple to list.
colors = list(blue.range_to(Color("red"), color_resolution))
colors = [(int(c.red * 255), int(c.green * 255), int(c.blue * 255)) for c in colors]
#print colors

def select_color(val):
    if (val< min_temp):
        return 0
    return int((float(val)-min_temp)/(max_temp-min_temp) *color_resolution -1)
    

def conver_val_to_str(value):
    val_str=str(value)
    val_str=val_str[0:4]
    return val_str
コード例 #34
0
 def get_stroke_colors(self, background=False):
     return [
         Color(rgb=rgba[:3]) for rgba in self.get_stroke_rgbas(background)
     ]
コード例 #35
0
 def get_fill_colors(self):
     return [Color(rgb=rgba[:3]) for rgba in self.get_fill_rgbas()]
コード例 #36
0
import plotly.express as px
import pandas as pd
from dash.dependencies import Input, Output
from dash.exceptions import PreventUpdate
import json

###
## To Do:
## Show name of node on hover
##

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

from colour import Color
red = Color("blue")
colors = list(red.range_to(Color("green"), 36))

# Create color gradient for groups
group_stylesheet = [{
    "selector": '[group = {}]'.format(group + 1),
    'style': {
        "opacity": .50,
        'z-index': 9999,
        'background-color': colors[group].hex
    }
} for group in range(36)]

default_cyto_stylesheet = group_stylesheet + [
    # Instantiate with the first node highlight white as a prompt
    {
コード例 #37
0
ファイル: active_data.py プロジェクト: davehunt/fxtest-report
 def _get_color(self, value, _max, _min=0):
     spectrum = list(Color("lime").range_to(Color("red"), 100))
     percent = ((value - _min) / (_max - _min)) * 100
     index = int(max(0, min(99, percent)))
     return spectrum[index].hex
コード例 #38
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
コード例 #39
0
ファイル: rpi_thermal_cam.py プロジェクト: eiselekd/hw
pygame.init()

#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)
コード例 #40
0
def main5(argv):
    pygame.init()
    pygame.midi.init()
    fenetre = pygame.display.set_mode((1470, 750), DOUBLEBUF)

    fenetre.set_alpha(None)
    fond = pygame.image.load("Images/fond3.png").convert_alpha()

    clavier = pygame.image.load("Images/clavier7.png").convert_alpha()
    touche = pygame.image.load("Images/db.png").convert()
    touchen = pygame.image.load("Images/dn.png").convert()
    touche_n = pygame.image.load("Images/gb.png").convert()
    terrain = pygame.image.load("Images/terrain.png").convert()

    fond1 = pygame.image.load("Images/fond.png").convert()

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

    midiOut = pygame.midi.Output(0)

    class Test():
        def __init__(self,
                     touche,
                     time_pos,
                     time,
                     octave,
                     posy=0,
                     posx=0,
                     val=0,
                     nature='ok',
                     increment=0):
            self.touche = touche
            self.time_pos = time_pos
            self.time = time
            self.octave = octave
            self.posy = posy
            self.posx = posx
            self.val = val
            self.nature = nature
            self.increment = increment

    class conv():
        def __init__(self, type, note, time):
            self.type = type
            self.note = note
            self.time = time

    path = "fichier_midi/"
    Fpath = path + argv
    mid = MidiFile(Fpath)

    conversion = []
    conversion2 = []
    partition = []
    partition2 = []

    compteur = 0

    fichier = open("midi.txt", "w")

    for i, j in enumerate(mid.tracks):
        for msg in j:
            fichier.write("%s %s %s\n" % (msg.type, msg.bytes()[1], msg.time))

    p1 = 0
    ok = 0
    ligne = 0
    for i, j in enumerate(mid.tracks):
        for msg in j:
            if (msg.type == 'note_on'
                    or msg.type == 'note_off') and (p1 == 0 or p1 == 2):
                conversion.append(
                    conv(msg.type,
                         msg.bytes()[1], int(msg.time * 1.7)))
                #print("%s, %s, %s" % (msg.type, msg.bytes()[1], msg.time))
            if msg.type == 'end_of_track' and len(conversion) == 0:
                p1 = 2
            elif msg.type == 'end_of_track' and len(conversion) > 0:
                p1 = 1
            if (msg.type == 'note_on' or msg.type == 'note_off') and p1 == 1:
                conversion2.append(
                    conv(msg.type,
                         msg.bytes()[1], int(msg.time * 1.7)))
                #print("Droite : %s, %s, %s" % (msg.type, msg.bytes()[1], msg.time))

    taille = len(conversion)
    taille2 = len(conversion2)
    print(taille2)
    tempo = 0

    def _render_region(image, rect, color, rad):
        """Helper function for round_rect."""
        corners = rect.inflate(-2 * rad, -2 * rad)
        for attribute in ("topleft", "topright", "bottomleft", "bottomright"):
            pg.draw.circle(image, color, getattr(corners, attribute), rad)
        image.fill(color, rect.inflate(-2 * rad, 0))
        image.fill(color, rect.inflate(0, -2 * rad))

    def round_rect(surface,
                   rect,
                   color,
                   rad=20,
                   border=0,
                   inside=(0, 0, 0, 0)):
        """
        Draw a rect with rounded corners to surface.  Argument rad can be specified
        to adjust curvature of edges (given in pixels).  An optional border
        width can also be supplied; if not provided the rect will be filled.
        Both the color and optional interior color (the inside argument) support
        alpha.
        """
        rect = pg.Rect(rect)
        zeroed_rect = rect.copy()
        zeroed_rect.topleft = 0, 0
        image = pg.Surface(rect.size).convert_alpha()
        image.fill((0, 0, 0, 0))
        _render_region(image, zeroed_rect, color, rad)
        if border:
            zeroed_rect.inflate_ip(-2 * border, -2 * border)
            _render_region(image, zeroed_rect, inside, rad)
        surface.blit(image, rect)

    def verif_note_on(nb):
        for i in range(nb):
            if conversion[i].type != 'note_on':
                return False
        return True

    if verif_note_on(10):
        for i in range(len(conversion)):
            if conversion[i].type == 'note_on':
                cp = 1
                if conversion[i].note == conversion[i + cp].note:
                    conversion[i + cp].type = 'note_off'
                while conversion[i].note != conversion[i + cp].note:
                    cp += 1
                if cp != 1:
                    conversion[i + cp].type = 'note_off'
        for i in range(len(conversion2)):
            if conversion2[i].type == 'note_on':
                cp = 1
                if conversion2[i].note == conversion2[i + cp].note:
                    conversion2[i + cp].type = 'note_off'
                while conversion2[i].note != conversion2[i + cp].note:
                    cp += 1
                if cp != 1:
                    conversion2[i + cp].type = 'note_off'

    #for obj in conversion:
    #    print(obj.type, obj.note, obj.time)

    def verif_blanc(touche):
        if (int(touche) % 12 < 5):
            if ((int(touche) % 12) % 2 == 0):
                return True
            else:
                return False
        else:
            if ((int(touche) % 12) % 2 == 1):
                return True
            else:
                return False

    for i in range(len(conversion)):
        if conversion[i].type == 'note_on':
            cp = 1
            time_on = int(conversion[i].time)
            time_off = 0
            while conversion[i].note != conversion[i + cp].note:
                time_off += int(conversion[i + cp].time)
                cp += 1
            time_off += int(conversion[i + cp].time)
            tempo += int(conversion[i].time)
            note_centre = int(conversion[i].note) % 12
            if note_centre < 5:
                if note_centre % 2 == 0:
                    note_place = (note_centre / 2) * 30
                else:
                    note_place = 19 + (note_centre / 2) * 30
            else:
                if note_centre % 2 == 1:
                    note_place = ((
                        (conversion[i].note - 5) % 12) / 2) * 30 + 3 * 30
                else:
                    note_place = ((
                        (conversion[i].note - 6) % 12) / 2) * 30 + 108
            nb_octave_px = (int(conversion[i].note / 12) - 2) * 210
            if verif_blanc(conversion[i].note):
                partition.append(
                    Test(conversion[i].note, int(tempo / 10),
                         int(time_off / 10),
                         int(conversion[i].note) / 12, -int(time_off / 10),
                         note_place + nb_octave_px, 0, 'blanc'))
            else:
                partition.append(
                    Test(conversion[i].note, int(tempo / 10),
                         int(time_off / 10),
                         int(conversion[i].note) / 12, -int(time_off / 10),
                         note_place + nb_octave_px, 0, 'noir'))
        else:
            tempo += int(conversion[i].time)

    tempo = 0

    for i in range(len(conversion2)):
        if conversion2[i].type == 'note_on':
            cp = 1
            time_on = int(conversion2[i].time)
            time_off = 0
            while conversion2[i].note != conversion2[i + cp].note:
                time_off += int(conversion2[i + cp].time)
                cp += 1
            time_off += int(conversion2[i + cp].time)
            tempo += int(conversion2[i].time)
            note_centre = int(conversion2[i].note) % 12
            if note_centre < 5:
                if note_centre % 2 == 0:
                    note_place = (note_centre / 2) * 30
                else:
                    note_place = 19 + (note_centre / 2) * 30
            else:
                if note_centre % 2 == 1:
                    note_place = ((
                        (conversion2[i].note - 5) % 12) / 2) * 30 + 3 * 30
                else:
                    note_place = ((
                        (conversion2[i].note - 6) % 12) / 2) * 30 + 108
            nb_octave_px = (int(conversion2[i].note / 12) - 2) * 210
            if verif_blanc(conversion2[i].note):
                partition2.append(
                    Test(conversion2[i].note, int(tempo / 10),
                         int(time_off / 10),
                         int(conversion2[i].note) / 12, -int(time_off / 10),
                         note_place + nb_octave_px, 0, 'blanc'))
            else:
                partition2.append(
                    Test(conversion2[i].note, int(tempo / 10),
                         int(time_off / 10),
                         int(conversion2[i].note) / 12, -int(time_off / 10),
                         note_place + nb_octave_px, 0, 'noir'))
        else:
            tempo += int(conversion2[i].time)

    for obj in partition:
        print(obj.touche, obj.time_pos, obj.time, obj.posx, obj.posy)

    posx = 0
    posy = 0

    haut = bas = gauche = droite = 0

    font = pygame.font.SysFont("gameovercre", 30)
    continuer = 1
    c = 0
    score = 0

    touche_actuelle = []
    touche_actuelle2 = []

    touche_actuelle.append(partition2[0])
    index2 = 0

    if (len(partition2) != 0):
        touche_actuelle2.append(partition2[0])

    index = 0

    while partition2[index].time_pos == partition2[index + 1].time_pos:
        touche_actuelle.append(partition2[index + 1])
        index += 1

    #touche_actuelle = [partition[0],partition[1]]

    #print(len(touche_actuelle))

    tps_actuel = tps_precedent = 0
    start = 1
    stop = 0

    fenetre.blit(fond, (0, 0))

    index = 0

    class vecColor:
        def __init__(self, r, g, b):
            self.R = r
            self.G = g
            self.B = b

    def computeVarColor(first, second, shades):
        toReturn = vecColor(0.0, 0.0, 0.0)

        toReturn.R = abs(first.R - second.R) / shades
        if first.R > second.R:
            toReturn.R = -1 * toReturn.R
        toReturn.G = abs(first.G - second.G) / shades
        if first.G > second.G:
            toReturn.G = -1 * toReturn.G
        toReturn.B = abs(first.B - second.B) / shades
        if first.B > second.B:
            toReturn.B = -1 * toReturn.B

        return toReturn

    color1 = vecColor(132, 176, 217)
    color2 = vecColor(33, 112, 187)

    colorvars = computeVarColor(color1, color2, 200)

    # for i in range(300):
    #     print("%d %d %d" % (color1.R + i*colorvars.R, color1.G + i*colorvars.G, color1.B + i*colorvars.B))

    inp = pygame.midi.Input(1)
    clock = pygame.time.Clock()

    while continuer:
        dt = clock.tick(161)
        if inp.poll():
            for items in inp.read(1000):
                midi_value = items[0][0:3]

                if midi_value[0] == 144:
                    midiOut.note_on(midi_value[1], 127)
                elif midi_value[0] != 144:
                    midiOut.note_off(midi_value[1], 127)

                print(midi_value)
                if len(touche_actuelle) == 1 and touche_actuelle[
                        0].posy + touche_actuelle[0].time >= 531:
                    #if midi_value[0] == int(touche_actuelle[0].touche) and midi_value[1] != 0:
                    if midi_value[1] == int(
                            touche_actuelle[0].touche
                    ) and midi_value[0] == 144 and midi_value[2] != 0:
                        touche_actuelle[0].val = 1
                        index += 1
                        del touche_actuelle[:]

                        plus = 0

                        touche_actuelle.append(partition2[index])

                        while partition2[index + plus].time_pos == partition2[
                                index + 1 + plus].time_pos:
                            touche_actuelle.append(partition2[index + 1 +
                                                              plus])
                            plus += 1
                    '''else:
                        touche_actuelle[0].val =2
                        index+=1
                        del touche_actuelle[:]
                        if partition[index].time_pos == partition[index+1].time_pos:
                            touche_actuelle.append(partition[index])
                            touche_actuelle.append(partition[index+1])
                        else:
                            touche_actuelle.append(partition[index])'''
                else:
                    for elem in touche_actuelle:
                        if elem.posy + elem.time >= 531:
                            #if midi_value[0] == int(elem.touche) and midi_value[1] != 0:
                            if midi_value[1] == int(
                                    elem.touche
                            ) and midi_value[0] == 144 and midi_value[2] != 0:
                                elem.val = 1
                    ok = 1
                    for elem in touche_actuelle:
                        if elem.val == 1 or elem.val == 2:
                            ok *= 1
                        else:
                            ok *= 0
                    if ok == 1:
                        index += len(touche_actuelle)
                        del touche_actuelle[:]
                        plus = 0

                        touche_actuelle.append(partition2[index])

                        while partition2[index + plus].time_pos == partition2[
                                index + 1 + plus].time_pos:
                            touche_actuelle.append(partition2[index + 1 +
                                                              plus])
                            plus += 1

        for event in pygame.event.get():
            if event.type == QUIT:
                continuer = 0
            if event.type == KEYDOWN:
                if event.key == K_DOWN:
                    bas = 1
                if event.key == K_UP:
                    haut = 1
                if event.key == K_RIGHT:
                    droite = 1
                    '''if touche_actuelle.posy+touche_actuelle.time>=531:
                        score=1'''
                if event.key == K_LEFT:
                    gauche = 1
            if event.type == KEYUP:
                if event.key == K_DOWN:
                    bas = 0
                if event.key == K_UP:
                    haut = 0
                if event.key == K_RIGHT:
                    droite = 0
                    #score=0
                if event.key == K_LEFT:
                    gauche = 0
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    posx = event.pos[0]
                    posy = event.pos[1]
        if droite == 1:
            posx += 1
        if gauche == 1:
            posx -= 1
        if haut == 1:
            posy -= 1
        if bas == 1:
            posy += 1
        '''
        c+=1
        for i in range(int(taille/2)):
            if i == 0:
                if partition[0].posy+int(partition[0].time)<fenetre.get_height()- clavier.get_height() and partition[0].val==0:
                    partition[0].posy+=1
                elif partition[0].val == 1:
                    partition[0].posy+=1
            elif partition[i].posy+int(partition[i].time)<=partition[i-1].posy and partition[i].val == 0 and partition[i].posy+int(partition[i].time)<fenetre.get_height()- clavier.get_height():
                partition[i].posy+=1
            elif partition[i].posy+int(partition[i].time)<=partition[i-1].posy and partition[i].val == 1:
                partition[i].posy+=1'''

        tps_actuel = pygame.time.get_ticks()

        if start == 1:
            c += 1

        if len(touche_actuelle) == 1:
            if touche_actuelle[0].posy + int(touche_actuelle[
                    0].time) < fenetre.get_height() - clavier.get_height():
                start = 1
            elif touche_actuelle[0].posy + int(touche_actuelle[
                    0].time) >= fenetre.get_height() - clavier.get_height():
                start = 0
        else:
            ok = 1
            for elem in touche_actuelle:
                if elem.posy + int(elem.time) < fenetre.get_height(
                ) - clavier.get_height():
                    ok *= 1
                    #tps_precedent=tps_actuel
                elif elem.posy + int(elem.time) >= fenetre.get_height(
                ) - clavier.get_height():
                    ok *= 0
                    #tps_precedent=tps_actuel
            if ok == 1:
                start = 1
            else:
                start = 0

        #fenetre.blit(fond, (0,0))

        for i in range(int(taille2 / 2)):
            cropped = pygame.Surface([44, partition2[i].time], pygame.SRCALPHA,
                                     32)
            cropped.blit(fond, (0, 0), (partition2[i].posx, partition2[i].posy,
                                        44, partition2[i].time))
            fenetre.blit(cropped, (partition2[i].posx, partition2[i].posy))
            if c >= partition2[i].time_pos and start == 1:
                partition2[i].posy += 1
        '''for i in range(int(taille/2)):
            if i == 0:
                if partition[0].val == 0 and score == 1:
                    #partition[0].val=1
                    del touche_actuelle[:]
                    touche_actuelle.append(partition[1])
                    score=0
                    break
            else:
                if partition[i-1].val == 1 and score == 1 and partition[i].val == 0:
                    #partition[i].val =1
                    if partition[i].time_pos == partition[i+1].time_pos:
                        del touche_actuelle[:]
                        touche_actuelle.append(partition[i])
                        touche_actuelle.append(partition[i+1])
                    score=0'''

        for i in range(int(taille2 / 2)):
            '''if c>=partition[i].time_pos and partition[i].posy+partition[i].time-1 == fenetre.get_height()- clavier.get_height():
                midiOut.note_on(partition[i].touche,127)
                
            if c>=partition[i].time_pos and partition[i].posy == fenetre.get_height()- clavier.get_height():
                midiOut.note_off(partition[i].touche,127)'''

            if c >= partition2[i].time_pos and partition2[
                    i].posy < fenetre.get_height() - clavier.get_height():
                if partition2[i].val == 1:
                    if partition2[i].nature == 'blanc':
                        round_rect(fenetre,
                                   (partition2[i].posx, partition2[i].posy, 30,
                                    partition2[i].time), pg.Color("blue"), 8,
                                   2, (132, 0, 217, 255))
                    else:
                        round_rect(fenetre,
                                   (partition2[i].posx, partition2[i].posy, 19,
                                    partition2[i].time), pg.Color("blue"), 5,
                                   2, (33, 0, 187, 255))
                elif partition2[i].val == 0:
                    if partition2[i].nature == 'blanc':
                        round_rect(fenetre,
                                   (partition2[i].posx, partition2[i].posy, 30,
                                    partition2[i].time), pg.Color("white"), 8,
                                   2, (132, 0, 217, 255))
                    else:
                        round_rect(fenetre,
                                   (partition2[i].posx, partition2[i].posy, 19,
                                    partition2[i].time), pg.Color("white"), 5,
                                   2, (33, 0, 187, 255))
                else:
                    if partition2[i].nature == 'blanc':
                        round_rect(fenetre,
                                   (partition2[i].posx, partition2[i].posy, 30,
                                    partition2[i].time), pg.Color("red"), 8, 2,
                                   (132, 0, 217, 255))
                    else:
                        round_rect(fenetre,
                                   (partition2[i].posx, partition2[i].posy, 19,
                                    partition2[i].time), pg.Color("red"), 5, 2,
                                   (33, 0, 187, 255))

                #fenetre.blit(touches[i], (partition[i].posx, partition[i].posy))
        fenetre.blit(clavier, (0, fenetre.get_height() - clavier.get_height()))

        #write = "COUCOU %d s, score : %d,  : %d, test ; %d %d %d" % (int(c/100),osu, score, partition[0].val,partition[1].val,partition[2].val)
        write = "Compteur : %d Start : %d" % (c, start)
        #texte = font.render(write, 1, (0,0,0))
        texte = font.render(" ", 1, (0, 0, 0))
        fenetre.blit(texte, (0, 0))

        #round_rect(fenetre, (500,250,44,200), pg.Color("black"), 10,3, (0,0,0,0))

        pygame.display.flip()
    '''    
    for obj in partition:
        print(obj.touche, obj.time_pos, obj.time, obj.octave)'''
    '''
    index=0
    for i,j in enumerate(mid.tracks):
        for msg in j:
            print(index, msg)
            index +=1
     '''
    '''def getNoteRangeAndTicks(files_dir, res_factor=1):
        ticks = []
        notes = []
        for file_dir in files_dir:
            file_path = "%s" %(file_dir)
            mid = MidiFile(file_path)                   
            
            for track in mid.tracks: #preprocessing: Checking range of notes and total number of ticks
                num_ticks = 0           
                for message in track:
                    if not isinstance(message, MetaMessage):
                        notes.append(message.note)
                        num_ticks += int(message.time/res_factor)
                ticks.append(num_ticks)
                        
        return min(notes), max(notes), max(ticks) '''

    #print(mid.ticks_per_beat)
    '''continuer = 1
    i = 0
    clock = pygame.time.Clock()
    
    while continuer:
        for event in pygame.event.get():  
            if event.type == QUIT:     
                continuer = 0
        i+=1
        if i == 7:
            i=0
        fenetre.blit(logo_a[i], (0,0))
        pygame.display.flip()
        clock.tick(10)'''

    inp.close()
    pygame.display.quit()
コード例 #41
0
def createGrad(startColor=Color("#FFA13D"), endColor=Color("#0D1D3B")):
	#Create the color gradient
	colorGrad = list(startColor.range_to(endColor, 30))

	#Adjust the color gradient to be returned in a form that pyplot can accept
	return list(map(lambda x: x.hex, colorGrad))
コード例 #42
0
def main():

    # argument parsing

    parser = argparse.ArgumentParser()
    parser.add_argument("color_depth",
                        help="integer number of colors to use to draw temps",
                        type=int)
    parser.add_argument('--headless',
                        help='run the pygame headlessly',
                        action='store_true')
    args = parser.parse_args()

    MAXTEMP = 31  # initial max temperature
    COLORDEPTH = args.color_depth  # how many color values we can have
    AMBIENT_OFFSET = 9  # value to offset ambient temperature by to get rolling MAXTEMP
    AMBIENT_TIME = 3000  # length of ambient temperature collecting intervals in seconds

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

    # empty the images folder
    for filename in os.listdir(get_filepath('../img/')):
        if filename.endswith('.jpeg'):
            os.unlink(get_filepath('../img/') + filename)

    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
    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))
    pygame.display.update()

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

    # # Change thresholds
    params.minThreshold = 10
    params.maxThreshold = 255

    # # Filter by Area.
    params.filterByArea = True
    params.minArea = 250

    # # Filter by Circularity
    params.filterByCircularity = True
    params.minCircularity = 0.1

    # # Filter by Convexity
    params.filterByConvexity = False
    params.minConvexity = 0.87

    # # Filter by Inertia
    params.filterByInertia = False
    params.minInertiaRatio = 0.01

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

    # initialize centroid tracker
    ct = CentroidTracker()

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

    # press key to exit
    screencap = True

    # json dump
    data = {}
    data['sensor_readings'] = []

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

    print('sensor started!')

    start_time = time.time()

    while (screencap):
        start = time.time()
        date = datetime.now()
        # read the pixels
        pixels = []
        for row in sensor.pixels:
            pixels = pixels + row

        data['sensor_readings'].append({
            'time': datetime.now().isoformat(),
            'temps': pixels,
            'count': ct.get_count()
        })
        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
        MAXTEMP = float(np.mean(mode_list)) + AMBIENT_OFFSET
        pixels = [
            map_value(p,
                      np.mean(mode_list) + 2, MAXTEMP, 0, COLORDEPTH - 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, COLORDEPTH - 1)],
                        (displayPixelHeight * ix, displayPixelWidth * jx,
                         displayPixelHeight, displayPixelWidth))
                except:
                    print("Caught drawing error")
        pygame.display.update()

        surface = pygame.display.get_surface()

        # frame saving
        folder = get_filepath('../img/')
        filename = str(date) + '.jpeg'
        pygame.image.save(surface, folder + filename)

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

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

        # Detect blobs.
        keypoints = detector.detect(img)

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

            # print little circle
            pygame.draw.circle(lcd, (200, 0, 0), (int(x), int(y)), 7, 3)

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

        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))

    # write raw sensor data to file
    data_index = 0
    while os.path.exists(
            get_filepath('../data/') + 'data%s.json' % data_index):
        data_index += 1
    data_path = str(get_filepath('../data/') + 'data%s.json' % data_index)

    with open(data_path, 'w+') as outfile:
        json.dump(data, outfile, indent=4)

    # stitch the frames together
    dir_path = get_filepath('../img/')
    ext = '.jpeg'

    out_index = 0
    while os.path.exists(
            get_filepath('../video/') + 'output%s.avi' % out_index):
        out_index += 1
    output = str(get_filepath('../video/') + 'output%s.avi' % out_index)

    framerate = 10

    # get files from directory
    images = []
    for f in os.listdir(dir_path):
        if f.endswith(ext):
            images.append(f)

    # sort files
    images = sorted(images,
                    key=lambda x: datetime.strptime(
                        x.split('.j')[0], '%Y-%m-%d %H:%M:%S.%f'))
    # determine width and height from first image
    image_path = os.path.join(dir_path, images[0])
    frame = cv2.imread(image_path)
    if not args.headless:
        cv2.imshow('video', frame)
    height, width, channels = frame.shape

    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')  # Be sure to use lower case
    out = cv2.VideoWriter(output, fourcc, framerate, (width, height))

    for image in images:

        image_path = os.path.join(dir_path, image)
        frame = cv2.imread(image_path)

        out.write(frame)  # Write out frame to video

        if not args.headless:
            cv2.imshow('video', frame)
            if (cv2.waitKey(1) & 0xFF) == ord('q'):  # Hit `q` to exit
                break

    print('video created!')
    # Release everything if job is finished
    out.release()
    cv2.destroyAllWindows()
コード例 #43
0
ファイル: mapBoxMapDisplay.py プロジェクト: ykv001/pixiedust
 def _getColorList(self, color1, color2, nColors):
     colorList = []
     colorRange = Color(color1).range_to(Color(color2), nColors)
     for color in list(colorRange):
         colorList.append(color.hex_l)
     return colorList
コード例 #44
0
ファイル: lifxaway.py プロジェクト: caj380/lifxaway
    return lazylights.Bulb(b'LIFXV2',
                           binascii.unhexlify(macString.replace(':', '')),
                           (ip, port))


#------------------------------------------------------------------------------------------------------------

myBulb1 = createBulb('10.0.0.X',
                     'XX:XX:XX:XX:XX:XX')  #Bulb for right side of screen
#lazylights requires a 'set' of bulbs as input so I put each one in its own set
bulbs1 = [myBulb1]
while True:
    target_name = "Pixel XL"
    target_address = None
    nearby_devices = bluetooth.discover_devices()

    for bdaddr in nearby_devices:
        if target_name == bluetooth.lookup_name(bdaddr):
            target_address = bdaddr
            break

    if target_address is not None:
        c = Color("green")
        print "***True"
        lazylights.set_state(bulbs1, c.hue * 360, (c.saturation), c.luminance,
                             3500, (500), False)
    else:
        c = Color("yellow")
        print "***False"
        lazylights.set_state(bulbs1, c.hue * 360, (c.saturation), c.luminance,
                             3500, (500), False)
コード例 #45
0
ファイル: timebox.py プロジェクト: vosmont/timebox
def clock(ctx, color, ampm):
    if(color):
        c = color_convert(Color(color).get_rgb())
        ctx.obj['dev'].send(set_time_color(c[0],c[1],c[2],0xff,not ampm))
    else:
        ctx.obj['dev'].send(switch_view("clock"))
コード例 #46
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] != '[]':
コード例 #47
0
import pandas as pd
import datetime
from colour import Color
import datetime
import random

app = Flask(__name__)

# set up api and caching
api = Api(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})

with app.app_context():
    MAX_DECIMALS = 3
    # get color range for station status and bike angels
    red = Color("red")
    green = Color("green")
    colors = list(green.range_to(red, 101))
    months = [
        'January', 'February', 'March', 'April', 'May', 'June', 'July',
        'August', 'September', 'October', 'November', 'December'
    ]

    ## get current status and merge that with stations
    sa_data_url = "https://github.com/cdepeuter/dsi-waterquality-data/raw/master/flask-app/data/south_africa_data.csv"
    x = requests.get(url=sa_data_url).content
    sa_data = pd.read_csv(io.StringIO(x.decode('utf8')))
    print("sa data columns", sa_data.columns)
    ## local for testing
    #sa_data = pd.read_csv("data/south_africa_data.csv")
コード例 #48
0
 def set_color(self, color):
     self.highlight(color)
     self.color = Color(color)
     return self
コード例 #49
0
ファイル: darken.py プロジェクト: mungojelly/7by7grid
from colour import Color

input = []
while (len(input) < 49):
    input.extend(raw_input().split())

output = []
for color_text in input:
    c = Color(color_text)
    c.luminance = c.luminance / 2
    output.append(c.hex_l)

for _ in range(7):
    for _ in range(7):
        print output.pop(0) + " ",
    print
コード例 #50
0
ファイル: app_q1.py プロジェクト: jonygeta/CUNY-DATA608
# -*- coding: utf-8 -*-
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import datetime
from colour import Color

app = dash.Dash()
server = app.server

# Variables
text_style = dict(color='#444', fontFamily='sans-serif', fontWeight=300)
colors = list(Color('#68ff68').range_to(Color('#ff6868'),14))
           
# Import data and adjust entero count                    
df = pd.read_csv('https://raw.githubusercontent.com/ilyakats/'
                 'CUNY-DATA608/master/hw4/'
                 'riverkeeper_data_2013.csv', 
                 parse_dates=['Date'])
df['EnteroNo'] = df['EnteroCount']
df['EnteroNo'] = df['EnteroCount'].map(lambda x: x.lstrip('<>')).astype(int)

# Format output table
def generate_table(dataframe):
    rows = []
    for i in range(len(dataframe)):
        row = []
        for col in dataframe.columns:
            value = dataframe.iloc[i][col]
            if col=='Site':
コード例 #51
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)
コード例 #52
0
    zurich_lat, zurich_long = 47.36667, 8.55

    travel_time.append(cities.iloc[idx]['Travel time'])

# save the data as csv
cities.to_csv('all_cities_CH_time_geo.cvs', sep=',', encoding='utf-8')

# Normalize travel time for the coloring scheme
travel_time = np.array(travel_time)

# Remove a few outliers above 14000 s
travel_time[travel_time > 14000] = 14000
travel_time = normalize_list(travel_time)
unique_times = np.unique(np.array(travel_time))
red = Color("green")
colors = list(red.range_to(Color("red"), cities_shape[0]))

cities.to_csv('new_data2.csv', encoding='utf-8')

# print(travel_time)

# Generate map
gmap1 = gmplot.GoogleMapPlotter(46.8181877, 8.2275124, 9, apikey=API)

for idx, lat_ in enumerate(lat_list):
    frac = idx / len(lat_list)
    if travel_time[idx] != 0:
        color_value = colors[int(travel_time[idx] * cities_shape[0] -
                                 1)].get_hex()
コード例 #53
0
 def __init__(self, iterations):
     self.steps = int(iterations)
     blue = Color('blue')
     green = Color('green')
     self.grad = list(blue.range_to(green, self.steps))
     self.grad += list(green.range_to(blue, self.steps))
コード例 #54
0
ファイル: test_svg_mobject.py プロジェクト: rootonchair/manim
def test_set_color_sets_fill_and_stroke():
    expected_color = "#EEE777"
    svg = SVGMobject(get_svg_resource("heart.svg"), color=expected_color)
    assert svg.color == Color(expected_color)
    assert svg.fill_color == Color(expected_color)
    assert svg.stroke_color == Color(expected_color)
コード例 #55
0
ファイル: camera.py プロジェクト: yosemitebandit/setbot
  image = image.resize((width, height), resample=Image.ANTIALIAS)
  rendered_card_data[name] = np.array(image)
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])
コード例 #56
0
 def hexcolor (cls, color) :
     return Color(color).hex_l
コード例 #57
0
 def setPalette(self, plist):
     self.palette = []
     for item in plist:
         self.palette.append(Color(item))
コード例 #58
0
ファイル: pymunk_physics.py プロジェクト: jvitku/torchsim
 def to_color(self):
     return Color(self.name)
コード例 #59
0
os.putenv('SDL_FBDEV', '/dev/fb1')
pygame.init()

#initialize the sensor
sensor = Adafruit_AMG88xx()

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.update()
pygame.mouse.set_visible(False)
コード例 #60
0
if len(sys.argv) == 2:
    clean = (sys.argv[1] == 'clean')

SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 20

plt.rc('font', size=BIGGER_SIZE)  # controls default text sizes
plt.rc('axes', titlesize=BIGGER_SIZE)  # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE)  # fontsize of the x and y labels

a_s = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

q_st = 0.707
p_st = 0.3
begin_color = Color("blue")
colors = list(begin_color.range_to(Color("green"), len(a_s)))

plt.figure(1).set_size_inches((8, 8), forward=False)
i = 0
for a in a_s:

    create.multiplicity_function(q_st, p_st, a, clean=clean)

    x_axis = dat.get_x_axis_multiplicity_function(q_st, p_st, a)
    column = dat.get_column_multiplicity_function(q_st, p_st, a)

    plt.plot(x_axis, column, color=colors[i].rgb, label="a={0}".format(a))
    i += 1

plt.xscale('log')