Esempio n. 1
0
    def query (self, text):
        c = None

        if isinstance (text, tuple):
            tt = (int (text [2]) / 255, int (text[1]) / 255, int (text[0]) / 255)
            c = Color (rgb = tt)

        elif isinstance (text, str):
            try:
                if text [0] == '#':
                    c = Color (text)
                elif text [0] == '(':
                    t = text [1:-1].split (',')
                    tt = (int (t [2]) / 255, int (t[1]) / 255, int (t[0]) / 255)
                    c = Color (rgb = tt)
                else:
                    #raise NotImplementedError ('color {} not understood!'.format (text))
                    return False
            except Exception as e:
                #print (e)
                return False
        
        if c is None:
            return False
        else:
            return c.get_web () [0] != '#'
Esempio n. 2
0
    def startSubdiagram(id, label, **kwargs):
        attrs = kwargs
        attrs.setdefault('label', label)
        attrs['id'] = id or Helper.cluster_counter
        Helper.cluster_counter += 1

        attrs.setdefault('fillcolor', '#FFFFFF')

        fillcolor_dark = Color(attrs.get('fillcolor'))

        fillcolor_dark.set_luminance(fillcolor_dark.get_luminance() * 0.5)

        attrs.setdefault('fillcolor_dark', fillcolor_dark.get_web())

        #TODO: support fillcolor and other attributes
        return """
	<node id="sub_{id}" yfiles.foldertype="group">
      <data key="d0">
        <y:ProxyAutoBoundsNode>
          <y:Realizers active="0">
            <y:GroupNode>
              <y:Geometry height="289.6015625" width="240.0" x="1170.0" y="-1579.6015625"/>
              <y:Fill color="{fillcolor}" transparent="false"/>
              <y:BorderStyle color="#000000" type="line" width="1.0"/>
              <y:NodeLabel alignment="center" autoSizePolicy="node_width" backgroundColor="{fillcolor_dark}" borderDistance="0.0" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="23.6015625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#FFFFFF" verticalTextPosition="bottom" visible="true" width="240.0" x="0.0" xml:space="preserve" y="0.0">{label}</y:NodeLabel>
              <y:Shape type="rectangle3d"/>
              <y:State closed="false" closedHeight="90.0" closedWidth="180.0" innerGraphDisplayEnabled="true"/>
              <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
              <y:BorderInsets bottom="28" bottomF="28.298828125" left="29" leftF="29.2978515625" right="29" rightF="29.2978515625" top="24" topF="24.298828125"/>
            </y:GroupNode>
            <y:GroupNode>
              <y:Geometry height="90.0" width="180.0" x="1170.0" y="-1579.6015625"/>
              <y:Fill color="{fillcolor}" transparent="false"/>
              <y:BorderStyle color="#000000" type="line" width="1.0"/>
              <y:NodeLabel alignment="center" autoSizePolicy="node_width" backgroundColor="{fillcolor_dark}" borderDistance="0.0" fontFamily="Dialog" fontSize="16" fontStyle="plain" hasLineColor="false" height="23.6015625" horizontalTextPosition="center" iconTextGap="4" modelName="internal" modelPosition="t" textColor="#FFFFFF" verticalTextPosition="bottom" visible="true" width="100.0" x="0.0" xml:space="preserve" y="0.0">{label}</y:NodeLabel>
              <y:Shape type="rectangle3d"/>
              <y:State closed="true" closedHeight="90.0" closedWidth="180.0" innerGraphDisplayEnabled="true"/>
              <y:Insets bottom="15" bottomF="15.0" left="15" leftF="15.0" right="15" rightF="15.0" top="15" topF="15.0"/>
              <y:BorderInsets bottom="0" bottomF="0.0" left="0" leftF="0.0" right="0" rightF="0.0" top="0" topF="0.0"/>
            </y:GroupNode>
          </y:Realizers>
        </y:ProxyAutoBoundsNode>
      </data>	    
      <graph id="{id}"  edgedefault="directed" >
""".format(**attrs)
Esempio n. 3
0
def box_plot( periods, stat, swing, imperial_units ):
    mi2km = 1.609344
    box_per_axis = 14
    max_boxes = box_per_axis * 2
    box_fill = SWING_COLORS[swing]
    color = Color(box_fill)
    color.set_luminance(max(0.,color.get_luminance()-0.2))
    box_border = color.get_web()
    color = Color(box_fill)
    color.set_luminance(max(0.,color.get_luminance()-0.3))
    box_median = color.get_web()

    data = []
    data_labels = []
    upperLabels = []
    ngroups = periods.count()
    if ngroups > max_boxes:
        all_periods = periods.all()[ngroups-max_boxes:]
        ngroups = max_boxes
    else:
        all_periods = periods.all()
    for period in all_periods:
        vals = period.shots.filter(data__swing_type=swing).values_list('data__'+stat)
        #vals = np.zeros(50)
        vals = np.array(vals).flatten()
        if stat in ['swing_speed', 'ball_speed'] and imperial_units:
            vals /= mi2km
        data_labels.append(str(period))
        data.append(np.abs(vals))
        upperLabels.append('({})'.format(len(vals)))

    naxes = ngroups//box_per_axis + (ngroups%box_per_axis > 0)
    fig, axes = plt.subplots(nrows=naxes, ncols=1, squeeze=False,figsize=(6,4*naxes))
    #fig.subplots_adjust(hspace=0.4)
    y_min = 20
    y_max = 160
    if imperial_units:
        y_min = 10
        y_max = 100
    if swing == 'SE':
        if imperial_units:
            y_min = 50
            y_max = 140
        else:
            y_min = 80
            y_max = 220
    if stat == 'swing_speed':
        if imperial_units:
            y_label = 'Swing Speed (mi/h)'
        else:
            y_label = 'Swing Speed (km/h)'
    elif stat == 'ball_speed':
        if imperial_units:
            y_label = 'Ball Speed (mi/h)'
        else:
            y_label = 'Ball Speed (km/h)'
    elif stat == 'ball_spin':
        y_label = 'Ball Spin (abs)'
        y_min = 0
        y_max = 10
    y_lim = (y_min,y_max)
    y_pos = y_min+0.05*(y_max-y_min)

    for iax, ax in enumerate(axes.flatten()):
        igroup = iax*box_per_axis
        if iax==0:
            pass
            #ax.set_title(title_)
        bp = ax.boxplot(data[igroup:min(ngroups,igroup+box_per_axis)],
                   labels=data_labels[igroup:min(ngroups,igroup+box_per_axis)],
                   patch_artist=True)
        ax.set_ylim(y_lim)
        ax.set_ylabel(y_label)
        ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',
           alpha=0.75)
        plt.setp(ax.get_xticklabels(), rotation=30, fontsize=9, ha='right')
        if naxes > 1:
            ax.set_xlim(0.5,box_per_axis+0.5)

        pos = np.arange(box_per_axis) + 1
        weights = 'semibold'
        for tick, label in enumerate(ax.get_xticklabels()):
            k = tick % 2
            ax.text(pos[tick], y_pos, upperLabels[tick],
                     horizontalalignment='center', size='x-small')#, weight=weights)

        for box in bp['boxes']:
            box.set(color=box_border, linewidth=1.5)
            box.set(facecolor=box_fill)
        for whisker in bp['whiskers']:
            whisker.set(color=box_border, linewidth=1.5)
        for cap in bp['caps']:
            cap.set(color=box_border, linewidth=1.5)
        for median in bp['medians']:
            median.set(color=box_median, linewidth=1.5)
        for flier in bp['fliers']:
            flier.set(marker='o', alpha=0.25)
            flier.set_markersize(5)
            flier.set_markeredgecolor(box_fill)
            flier.set_markerfacecolor(box_fill)


    fig.tight_layout()
    tmp=io.BytesIO()
    fig.savefig(tmp,format='svg')
    #return base64.b64encode(tmp.getvalue()).decode("utf-8")
    #return tmp.getvalue().decode("utf-8")
    return base64.b64encode(tmp.getvalue())
Esempio n. 4
0
    score_html += '</td></tr></table><p>'

    # 文章の重み付け
    word_html = '<table width="800pt" border=1 class="t1"><tr><td>'
    for word in word_summary:
        model_score = model[word[2]] * 10000.0
        if model_score > 500:
            model_score2 = 500
        elif model_score < -500:
            model_score2 = -500
        else:
            model_score2 = model_score
        model_color = (1 - (model_score2 + 500) / 1000) * 0.7
        c = Color(hsl=(model_color, 0.7, 0.5))
        # if model_score>100 or model_score<-100:
        word_html += '<font color="' + c.get_web() + '">' + word[0] + "</font>"

    word_html += "</td></tr></table>"

    # 単語毎のスコア表示
    word_html += '<table width="800pt" border=1 class="t1">'
    word_html += "<tr><th>検出語</th><th>正規化語</th><th>インデックス番号</th><th>スコア</th></tr>"
    model_sum = 0
    # bias = -1
    for word in word_summary:
        model_sum += model[word[2]]
        model_score = model[word[2]] * 10000.0
        if model_score > 500:
            model_score2 = 500
        elif model_score < -500:
            model_score2 = -500
Esempio n. 5
0
    def __init__(self, config):
        tk.Tk.__init__(self)
        self.title('BClock')
        self.className = 'tkbclock'
        self.handles = {}
        if os.name == 'posix':
            self.wm_attributes('-type', 'normal')
        if config['noTitle']:
            self.wm_overrideredirect(True)
        self.resizable(False, False)
        self.wm_attributes('-alpha',
                           config['alpha'] if 'alpha' in config else 0.5)
        self.wm_attributes('-topmost', True)
        self.radius = config['radius'] if 'radius' in config else 60
        self.x_offset = config['xyoffset'] if 'xyoffset' in config else 2
        self.y_offset = config['xyoffset'] if 'xyoffset' in config else 2
        self.xcentre = self.x_offset + self.radius
        self.ycentre = self.y_offset + self.radius
        self.center_dot_radius = 5
        canvasWidth = 2 * self.radius + 2 * self.x_offset
        canvasHeight = 2 * self.radius + 2 * self.y_offset
        windowlocation = config[
            'windowlocation'] if 'windowlocation' in config else "+0+0"
        self.geometry(
            str(canvasWidth) + "x" + str(canvasHeight) + windowlocation)
        self.w = tk.Canvas(self,
                           width=canvasWidth,
                           height=canvasHeight,
                           bg=config['backgroundColor']
                           if 'backgroundColor' in config else 'Cyan')
        self.w.pack()
        # Main circle
        self.w.create_oval(self.x_offset, self.y_offset,
                           2 * self.radius + self.x_offset,
                           2 * self.radius + self.y_offset)
        self.w.pack()
        # Centre Dot
        self.w.create_oval(
            self.x_offset + self.radius - self.center_dot_radius,
            self.y_offset + self.radius - self.center_dot_radius,
            self.x_offset + self.radius + self.center_dot_radius,
            self.y_offset + self.radius + self.center_dot_radius,
            fill='Black')
        self.w.pack()
        # Second Hand
        # self.w.create_line(0, 0, 0, 0, fill='Blue', width=1, tags='seconds')
        # Minute Hand
        # self.w.create_line(0, 0, 0, 0, fill='Blue', width=2, tags='minute')
        # Hour Hand

        # Drawing hour markings
        hourMarkLength = config[
            'hourMarkLength'] if 'hourMarkLength' in config else 0.1
        hourMarkLength = 1 - hourMarkLength
        hourMarkColor = config[
            'hourMarkColor'] if 'hourMarkColor' in config else 'Red'
        hourMarkWidth = config[
            'hourMarkWidth'] if 'hourMarkWidth' in config else 6
        for i in range(0, 12):
            self.degree = i * 30
            self.w.create_line((self.radius * cos(
                (self.degree * pi) / 180)) + self.xcentre, (self.radius * sin(
                    (self.degree * pi) / 180)) + self.ycentre,
                               ((self.radius * hourMarkLength) * cos(
                                   (self.degree * pi) / 180)) + self.xcentre,
                               ((self.radius * hourMarkLength) * sin(
                                   (self.degree * pi) / 180)) + self.ycentre,
                               fill=hourMarkColor,
                               width=hourMarkWidth)

        # for i in range(0, 60):
        #     # Drawing minute co-orninates
        #     self.degree = i*6
        #     self.w.create_line((self.radius * cos((self.degree*pi)/180)) + 270, (self.radius * sin((self.degree*pi)/180)
        #                                                                          ) + 270, (240 * cos((self.degree*pi)/180)) + 270, (240 * sin((self.degree*pi)/180)) + 270)

        # Draw hour handles
        for i, c in enumerate(config['handles']):
            tag = c['label'] + '_' + str(i)
            self.handles[tag] = c
            self.w.create_line(0,
                               0,
                               0,
                               0,
                               fill=c['colour'],
                               width=c['width'] if 'width' in c else 4,
                               tags=tag)
            color = Color(c['colour'])
            color.set_saturation(0.5)
            self.w.create_line(0,
                               0,
                               0,
                               0,
                               fill=color.get_web(),
                               width=2,
                               tags=tag + '_minute')
            self.w.create_text(self.radius / 5,
                               2 * (i + 1) * 10,
                               text=c['label'],
                               fill=c['colour'],
                               font=('Times New Roman', 10),
                               tags=tag + '_TEXT')
            self.change_clock(tag)