12A猫で学んだこと-Memoir-

...What are you learning now?

2019年7月の夏休み

Happy! Summer Vacation!

こんにちは、StudentSです。 充実した夏休みをお過ごしでしょうか。
色々なことがありつつも、何とかかんとか生きております。
夏休みの宿題をやりつつ、ゲームをしたり。川辺で遊んだり...
小学生や中学生のころとは変わりましたが、まだ、自分に夏休みはあるはず...

夏...というには湿度が高かった本日、こんなことを考えました。
「思いこみって、大事になる時があるのかなー」
間違っているかあっているかは分からないけれど、 何かを信じて一貫性をもって行動する。 それが大多数に理解されるかどうかは分からないし、 共有できる見込みもないけれど、 一途な姿勢が人間の心を動かすときは必ずある...と。

... 人狼で遊んだり、現実世界を生きると、時々そんなことを考えるときってありませんか?
もちろん、「決め打ちが激しい...人外だから、幅広い可能性を考えることを放棄しているのですね」
というような批判はありますし、思い込みが他者と共有できるというのは幻想です。
それでも、幾ばくかの人の心を動かすことができれば、
人狼においても現実世界においても"勝ち"なのではないか...
なーんて、寝ぼけた頭で思ったのです。

夏休みの日記の宿題に困った日みたいなページになりましたが、
今月のエントリはこれでいきましょうー

暑いので体に気をつけていきたいですね...
来月がいい1か月になりますように!

Powepoint + Python でスライドに色相環を配置してみる

こんにちは、StudentSです。
今月もレポート提出最終日のぎりぎりです。
これは、いけない習慣になっていますねー このままでは、 いつか単位を落としてしまいそう... 生活の見直しが必要です。

今月は、少しPowerpointで遊んでみました。

お題

comtypes のライブラリを使って 書いてみたコードが以下になります。

スクリプト

import os
import colorsys
import math
from comtypes import client


def make_hue_circle(seed_color, n_color=5):
    """ Make ``Hue Circle`` with ``seed``.
    Args:
        seed_color: 3-length tuple. (R, G, B) 
        n_color: the number of color.

    Returns:
        ``list`` of colors.
    """
    r, g, b = map(lambda x: x / 255, seed_color)
    h, l, s = colorsys.rgb_to_hls(r, g, b)
    hs = [(h + d / n_color) % 1.0 for d in range(n_color)]
    colors = [colorsys.hls_to_rgb(h, l, s) for h in hs]
    colors = [tuple(map(lambda x: round(x * 255), color)) for color in colors]
    return colors

""" Below, powerpoint specific functions.
"""

def _to_int(color):
    assert len(color) == 3
    value = sum((v << (i * 8)) for i, v in enumerate((color)))
    return value


def _get_application(path=None):
    app = client.CreateObject("Powerpoint.Application")
    app.Visible = True
    if path:
        app.open(os.path.abspath(path))
    return app

def _draw_circle(slide, cx, cy, radius, color):

    # https://docs.microsoft.com/en-us/office/vba/api/office.msoautoshapetype
    msoShapeOval = 9
    shape = slide.Shapes.AddShape(msoShapeOval,
                                  Left=cx - radius,
                                  Top=cy - radius,
                                  Width=2 * radius,
                                  Height=2 * radius)
    shape.Line.Visible = True
    shape.Fill.ForeColor.RGB = _to_int(color)
    return shape

def _draw_hue_circle(slide, cx, cy, radius, base_color, n_color, ring_radius=None):
    def _infer_ring_radius(radius, delta_theta):
        """ Based on the golden ratio, determine 
        the radius of small circle.
        """
        return radius * delta_theta * 2 / (5 + math.sqrt(5))

    colors = make_hue_circle(base_color, n_color)
    d_theta = 2 * math.pi / n_color
    if ring_radius is None:
        ring_radius = _infer_ring_radius(radius, d_theta)
    for i, color in enumerate(colors):
        x = cx + radius * math.sin(d_theta * i)
        y = cy - radius * math.cos(d_theta * i)
        _draw_circle(slide, x, y, ring_radius, color)
    return slide

if __name__ == "__main__":
    color = (0, 114, 114) # base color of ring.
    n_color = 12
    application = _get_application()
    presentation = application.ActivePresentation
    # Depending on the configuration, specify it.
    custom_layout = 9
    slide = presentation.Slides.Add(1, custom_layout)
    slide_height, slide_width = presentation.PageSetup.SlideHeight, presentation.PageSetup.SlideWidth
    cy, cx = slide_height / 2, slide_width / 2 
    _draw_hue_circle(slide, cx, cy, cy * 0.6, color, n_color)
  • 結果の例は以下の図のような感じです。

Bright Color Tone

Dark Color Tone

あとがき

  • pep8flake8も忘れていましたー
  • 強引にやったという感じがありますー

おまけ

ブログのネタを考えていたら、頭の中で生み出された妄想会話を残しておきます。

Conversationi

遅れてしまった2019年5月の日記

駄目じゃん! 5月のブログを書くことを忘れていました...

何か書こうと思っても、急に出てくる題材はなく...
自らの引き出しの少なさを感じます...

あーでも、最近、少しずつですが英語の勉強はしていますー
まだまだ日本語を読むのと同じようにできないですが...
少しずつ、少しずつ...

5月はダンガンロンパV3というゲームの英語版を遊びましたー
総じて楽しませていただきました! ネタバレはないですが、
ほんのちょこっとだけ(ネガティブな要素もある)感想を書かせていただきます。
無知なのに、知ったかぶりをする人狼PLのような文章になります。

ゲームプレー後に感じたのは、
「物語を楽しむときには、前提の世界観がはっきりしていないと厳しい」
ということでした。

「何かをやりたいという熱意があり、そして、細部も作りこんでいるのだけれど、空回りしている感じがある。」
という点をゲーム終了後に感じてしまったのです。

その自分の中で感じた違和感を突き詰めると、「物語における前提の世界観の明確化」に落ち着きました。

例えば、トムとジェリーの世界では銃を打っても誰も死にませんが、
現実世界で銃が貫通すると当然人は死にます。
2つの世界ではルールが異なっていて、物語は、そのストーリーが成立する世界の中で楽しむものだと思っています。

もちろん、そのルールをひっくり返すプロットを導入している作品もあります。
ダンガンロンパV3で遊ばせていただいた直後の感想は「最後、このゲームがどんなルールに基づいていたかが分からない」でした。
物語の世界が成立している前提を明確化できると、違和感を感じない作品になった気がします。
ルールがあいまいなものになると、「なんでもあり」となってしまって、考察するのが非常に難しくなってしまうのです。
(この点は人狼に似ていますね。)

少なくとも、このゲームは色々考えさせられたゲームです。
すごく楽しませていただいたことは間違いありません。
そして、英語を聞いたり、読んだりする力も上がっているといいなぁ...

来月は(もう今月だけど...)ガンバロー!

個人的なことしか書いていない、2019年4月の日記

人狼

上記村の3日目夜の占い先はまずかったねー 内訳はきちんと整理しないといけないねー

18A猫とかも楽しませていただけるといいなーと思うけれど、あんまり参加させていただけていないなぁ...

人狼との付き合い方はマイペース。 気負うことなくかかわっていきたいなぁ...

PyCheckIO

上の問題の回答は個人的に頑張ったという記憶...

Diary

In Japan,one specific name is given to an era, over which a certain emperor resides.
At the beginning of May 1st, the new era, 令和(Reiwa) is about to begin.
To be honest, I cannot feel importance of the change of name itself, though, I can imagine, abdication and enthronement of the Emperors have much effects, especially, on those who are related to politics.

Some companies commercially use this opportunity as some kind of festivals.

Although I'm unfamiliar with movements of society, I'd like to use this atmosphere to recall some memories in recent years.

Have a nice month each other!

折れ線グラフのAxesからデータを復元したい

状況

matplotlib, plot関数を使用して折れ線グラフを作成した。
plot関数の対象となったAxes オブジェクトから、折れ線グラフの作成に使われた データを抽出したい。

""" ## Purpose   
This is a problem related to [matplotlib](https://matplotlib.org/)
As you know, you can make a figure of line graph with such as the following functions.  

> fig, (ax) = plt.subplots(1, 1)  
> ax.plot([1, 2, 3], [4, 5, 6])

Here, I'd like the function to read the representation of the data 
from given ``Axes`` class. 


### Environment  
* matplotlib==3.0.3    
* pandas==0.24.2    

"""

import warnings
from collections import defaultdict 
import random

import matplotlib
import matplotlib.pyplot as plt 
from matplotlib.axes._axes import Axes
import pandas as pd

def read_plot(ax, *, fill=None): 
    """ Speculate the data of plotted ``Axes``. 
    Args:
        ax(Axes): The target ``Axes`` of read.
        fill(Number): The value for empty ``X``.  

    Return: 
        ``dict`` of ``list`` format of the estimated data. 
    """

    assert isinstance(ax, Axes), "Given Object must be ``Axes`` "


    """ If ``xaxis.label`` is existent, 
    then it is regarded as label. 
    Otherwiser, ``X`` is used. 
    """
    x_text = ax.xaxis.label.get_text()
    if x_text:
        xlabel = x_text
    else:
        warnings.warn("``label`` of ``X`` is not specified. ")
        xlabel =  "X"
    
    if len(ax.lines) == 0:
        raise ValueError("There is no ``Line2D`` given ``Axes``.")

    # Construct the data dependent on ``X``.  
    x_to_data = defaultdict(dict) 

    """
    ### As for the label of ``Y``.
    * Priority 1.
    If the ``label`` is set at ``line``, 
    then it is regarded as label of ``Y``. 
    """
    labeled_lines = [line for line in ax.lines if line._label]
    if labeled_lines:
        for line in labeled_lines:
            label = line._label
            for x, y in zip(*line.get_data()):
                x_to_data[x][label] = y
    else:
        if len(ax.lines) == 1:
            """
            ### As for the label of ``Y``.
            * Priority2.
            As long as the ``label`` of ``yaxis`` exists.
            it is regarded as the column of ``Y``. 
            """
            label =  ax.yaxis.label.get_text()
            if label:
                for x, y in zip(*ax.lines[0].get_data()):
                    x_to_data[x][label] = y

    if not x_to_data:
        raise ValueError("Cannot read any semantic data.")


    listmap = []
    x_values = x_to_data.keys()
    columns = {c for x in x_values for c in x_to_data[x].keys()} 

    for x in sorted(x_to_data.keys()):
        row = dict()
        row[xlabel] = x
        for c in columns:
            row[c] = x_to_data[x].get(c, fill)
        listmap.append(row)

    return listmap


if __name__ == "__main__":
    """ Example. 
    1. Plot an artificial data to ``in_ax``. 
    2. Using ``read_plot``, the target data is given from ``in_ax``. 
    3. Read data is plotted to ``out_ax``. 
    """

    fig, (in_ax, out_ax) = plt.subplots(1, 2)
    func = lambda x: 3 * x + 1 + random.random() * 10

    x_values = range(10)
    y_values = tuple(map(func, x_values))
    in_ax.plot(x_values, y_values, "-*", color="C0", label="LINE_SAMPLE1")
    y_values = tuple(map(func, x_values))
    in_ax.plot(x_values, y_values, "-*", color="C1", label="LINE_SAMPLE2")
 
    in_ax.set_title("This is ``in_ax``. ", fontsize=16)
    in_ax.set_xlabel("X_LABEL")
    in_ax.set_ylabel("Y_LABEL")

    in_ax.legend()
    in_ax.tick_params(labelsize=12)
    

    """ Read the contents of ``in_ax``, 
    and plot to ``out_ax``. 
    """
    listmap = read_plot(in_ax)

    xlabel = in_ax.get_xlabel()
    df = pd.DataFrame.from_records(listmap)
    df.plot(ax=out_ax, x=xlabel, style="-o")

    out_ax.set_title("This is read from ``in_ax``.", fontsize=16)
    out_ax.tick_params(labelsize=12)

    fig.tight_layout()
    plt.show()  # Display


""" Comment
* Return of ``read_plot`` may be preferable if the type is ``Dataframe``.   

"""

ユースケース

見当たらない。

作成動機1

JSON, YAML, CSV なんでもいいから、テキスト形式でデータをください... 再利用可能な形でデータを提供できないのは、貴方が騙りだからですよ!」
という知人の呟きを聞いたから

作成動機2

逆変換ができることって、大切だと思うんだ。

いつでも恋人同士に戻れる夫婦はいいなーって、学校の先生が言っていたし、 別れた後も友達に戻れたカップルの先輩たちはどっちもいい人だった。

安心できるから、ちょっと怖くても一歩を踏み出せるんだよね!

レポート提出期限1時間前

from datetime import datetime

class Uncertain(NotImplementedError):
    def __init__(self, message):
        self.message = message

    def __str__(self):
        return f"UncertainException:{self.message}"

class Apathy(RuntimeError):
    def __str__(self):
        return "Apathy struck the writer."

def is_submitted(year, month):
    if (year, month) == (2019, 1):
        """ In January, 2019, there is no entry now. 
        However, if this script is to be submitted,
        then I can claim that an entry is posted.
        Hence,  ``True`` is returned.
        This is nothing but a sophistory...
        """
        return True

    """ This script is intended to write some posts,   
    with no regard to the contents in January, 2019.
    Hence, other cases is not to be implemented.
    """
    raise Uncertain("The past is fixed, but the future is to be changed.")

def write_something():
    raise Apathy()

def act():
    current_time = datetime.now()
    year = int(current_time.strftime("%Y"))
    month = int(current_time.strftime("%m"))

    """ Assured that an entry is submitted.
    """
    if not is_submitted(year, month):
        write_something()

if __name__ == "__main__":
    act()