• Skip to main content
  • Skip to primary sidebar

学習記録

プログラミング

前の値を参照しつつ次の値を追加

2018年9月1日 by 河副 太智 Leave a Comment

以下のように過去のlistに対し、新たな値を追加していきます。

自作関数add_value()を3回実行すればlistの過去の値に対し
新たなデータが次々と追加されていきます。
まさにブロックチェーンの基礎ですね

1
2
3
4
5
6
7
8
9
blockchain=[[1]]
 
def add_value():
    blockchain.append([blockchain[-1],6])
    print(blockchain)
 
add_value()
add_value()
add_value()

>>>[[1], [[1], 6]]
>>>[[1], [[1], 6], [[[1], 6], 6]]
>>>[[1], [[1], 6], [[[1], 6], 6], [[[[1], 6], 6], 6]]

Filed Under: ブロックチェーン

Blockchainプログラミング基礎:自作関数でリスト作成

2018年9月1日 by 河副 太智 Leave a Comment

自作関数を使って変数blockchainに値を追加
まず最初にblockchain=[1]としてリストの値を1のみにして
そこに色々足してみます。

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append(0)
    print(blockchain)
 
add_value()

>>[1, 0]
リストに0が追加されました。

 

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append(blockchain[0])
    print(blockchain)
 
add_value()

>[1, 1]
blockchain[0]の値と同じものを追加するという意味なので
1が追加される

 

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append([blockchain[0],5.3])
    print(blockchain)
 
add_value()

>[1, [1, 5.3]]
ちょっとややこしいけど[]で囲まれている場合は
blockchain[0]の値と同じものと5.3を別の[]に入れて、
元の値1のカンマで区切った次の位置に追加している。

 

1
2
3
4
5
6
7
blockchain=[1]
 
def add_value():
    blockchain.append(blockchain[-1])
    print(blockchain)
 
add_value()

[1, 1]
blockchain[-1]と指定するとlistの値の一番最後の値を意味する
ブロックチェーンでは最後の値にどんどん新たな情報を追加していくので
この[-1]の概念は非常に重要です。

Filed Under: ブロックチェーン

国連apiによるhs統計

2018年8月23日 by 河副 太智 Leave a Comment

パラメーター

中国からアメリカ向け輸出
※2019/3/7の時点で国連から該当2018年度データはまだ入手できていないと返信

1
https://comtrade.un.org/api/get?type=C&freq=A&px=HS&ps=2018&r=156&rg=2

 

中国から全国向け輸出

1
https://comtrade.un.org/api/get?type=C&freq=M&px=HS&ps=201012&r=156&rg=2&cc=382490&fmt=csv

 

1
2
http://comtrade.un.org/api/get?
max=50000&type=C&freq=A&px=HS&ps=2013&r=156&p=0&rg=all&cc=382490&fmt=csv

pxがhsの年度
ccがhsコード
psが年月
rがレポート国(国コード検索:中国は156 イギリスは826アメリカは842)

 

各国データの個別詳細(FOB,CIF等)はExplanatory Notesを参照

 

 

■コード全体

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import pandas as pd
import plotly.offline as pyo
import plotly.graph_objs as go
import urllib.request
 
 
 
#パラメーターの作成
#trade data type C Commodities S Services
datatype = "type=C"
#china=156,UK=826,US=842,jp=392or all
reporting_area = "&r=156"
#Annual=A,Monthly=M
frequency = "&freq=A"
#YYYY or YYYYMM or now or recent
time_period = "&ps=recent"
# Harmonized System (HS)
classification = "&px=H4"
#china=156,UK=826,US=842,or all
partner_area = "&p=all"
# 1 (imports) and 2 (exports),
import_or_export = "&rg=2"
#HS CODE
classification_code = "&cc=630532"
#csv or json
fmt = "&fmt=csv"
url = ("https://comtrade.un.org/api/get?"+datatype + reporting_area+frequency+time_period+classification+partner_area+
      import_or_export+classification_code+fmt)
 
 
#csvをdfに入れる
 
res = urllib.request.urlopen(url)
df = pd.read_csv(res)
 
#最新年を取得
newest = (df["Year"].max())
 
#最新年のデータのみを取得
df_n = df[df["Year"] == newest]
 
#valueが高い順に並べ替え
df_s = df_n.sort_values('Trade Value (US$)', ascending=False)
 
#上位10件を取得してリスト化
partner = []
for var in range(1, 5):
    partner.append(df_s.iat[var, 12])
 
 
data = []
for i in partner:
    df2 = df[df["Partner"] == i]
    trace = go.Scatter(x=df2["Year"],
                       y=df2["Trade Value (US$)"],
                       mode="lines",
                       name = i)
    data.append(trace)
 
pyo.plot(data)

■必要なカラム一覧
[ Year]
[ Trade Flow]
[ Reporter]
[ Partner]
[ Commodity Code]
[ Commodity]
[ Qty Unit]
[ Alt Qty Unit]
[Netweight (kg)]
[Trade Value (US$)]

Filed Under: プログラミング

さくらvpsにflaskを入れてwebapp作成

2018年8月10日 by 河副 太智 Leave a Comment

rootログイン

FTPでのファイル転送はrootで行う為に以下のサイトを参考

Ubuntu 16.04: rootでログインする

ソフトウェアのインストール

– Go to the server root directory with “cd /”
– yumでInstall required software with
“yum install python-virtualenv nginx gunicorn supervisor python-pip”

– apt-getでInstall required software with “
apt-get install python-virtualenv nginx gunicorn supervisor python-pip

 

ディレクトリの作成

– Create a new directory for the virtual environment with
“mkdir /opt/envs”

– Create a virtual environment with virtualenv
“virtualenv /opt/envs/virtual”

– Activate the virtual environment
“. /opt/envs/virtual/bin/activate”

– Install Python dependencies
“pip install bokeh”
“pip install flask”
“pip install gunicorn”

– Create a new directory inside the nginx server
“mkdir /var/log/nginx/flask”

– Create a new directory for uploading app files
“mkdir /opt/webapps” “mkdir /opt/webapps/bokehflask”

 

configuration filesの作成

– Make sure you have your configuration files ready
which are bokeh_serve.conf, flask.conf and default.

 

FTPアップロード

– Locate your local project directory on the left panel and select your
Python files and the templates directory or any other associated local directory,
but not configuration files

– Locate and select the server directory on the right panel and click Upload
/opt/webapps/bokehflaskにapp.pyとrandom_generator.pyをアップする

 

– Upload the file named “default” to
/etc/nginx/sites-available
using the same procedure

– Upload files
“bokeh_serve.conf”
and
“flask.conf”
to /etc/supervisor/conf.d using the same procedure

サーバー上での調整

–  app.py を編集

以下のコマンドで開く
“nano /opt/webapps/bokehflask/app.py”

– インポート文を追加
“from werkzeug.contrib.fixers import ProxyFix”
to the remote app.py file.

– Modify the index function as follows:

1
2
3
4
5
def index():
    url="http://104.236.40.212:5006"
    session=pull_session(url=url,app_path="/random_generator")
    bokeh_script=autoload_server(None,app_path="/random_generator",session_id=session.id, url=url)
    return render_template("index.html", bokeh_script=bokeh_script)

– Add “app.wsgi_app = ProxyFix(app.wsgi_app)” to the remote app.py file after the index function.
– Save the file by pressing Control-X, then type y and then hit Enter.

–  bokeh_serve.confを編集

以下のコマンドで開く
“nano /etc/supervisor/conf.d/bokeh_serve.conf”
and put your IP for –allow-websocket-origin and your IP and port 5006 for –host

 

実行

– Start the nginx webserver with
“service nginx restart”

– Start supervisor with
“service supervisor restart”

– Start flask with
“supervisorctl restart flask”

– Start bokeh server with
“supervisorctl restart bokeh_serve”

– Visit your app in the browswer at http://160.16.225.109 (put your own IP)

Filed Under: Bokeh, flask

Bokehサーバーで使用したコマンドライン

2018年7月22日 by 河副 太智 Leave a Comment

pyファイルを実行
※http://localhost:5006/widgetsと表示されるのでブラウザからアクセス

1
C:\Users\Myname\Myfolder>python -m bokeh serve 〇〇.py

1
C:\Users\Myname\Myfolder>bokeh serve 〇〇.py

ポート番号を指定して実行
※5007の部分は任意で指定できる

1
C:\Users\Myname\jupyter_notebook>bokeh serve widgets.py --port 5007

 

実行したコマンドラインの停止は ctrl + C

Filed Under: Bokeh, プログラミング

Bokehサーバーでインタラクティブなグラフアプリを作る

2018年7月20日 by 河副 太智 Leave a Comment

インタラクティブなグラフをwebアプリで公開するには
Bokehサーバーを使用する必要があります。

今回はBokehサーバーを利用したweb上で表示して
ユーザーがいじる事ができるインタラクティブグラフの作成方法を紹介します。

 

まずはインポート

1
2
3
4
5
6
7
8
#アウトプットと別画面表示
from bokeh.io import output_file, show
 
#ユーザーが入力できるテキスト、ボタン、パラグラフウィジェット
from bokeh.models.widgets import TextInput, Button, Paragraph
 
#レイアウトをアレンジするオブジェクト
from bokeh.layouts import layout

 

とりあえず何かそれっぽいhtmlファイルを生成

1
2
3
4
5
6
7
8
9
10
11
12
#html出力 Bokehサーバー使用時には不要なので後で削除します。
output_file("bokehserver1.html")
 
#テキスト入力フォームとボタン
text_input=TextInput(value="ABC")
button=Button(label="ボタンText")
 
#テキスト、ボタンのウィジェットを指定
lay_out=layout([[button,text_input]])
 
#表示 こちらもBokehサーバー使用時には不要なので後で削除します。
show(lay_out)

 

実行結果
何かができました(笑)
ボタンもあればテキスト入力フォームも動いています。

 

この時点ではまだBokehサーバーにはつながっておりませんので
何も動作はしません。

上記のコードは違いを理解する為だけにありますので
実際はhtmlのアウトプットやshowメソッドは不要です。

では実際にBokehサーバーを使用して動くようにしてみます。

動的にテキストを変化させる為にcurdocオブジェクトを使用します。

1
2
#curdocをインポート
from bokeh.io import curdoc

ボタンを押した際に発生するアクションを設定

1
2
3
4
5
6
def update():
    output.text="Hello," + text_input.value
 
button.on_click(update)
 
curdoc().add_root(lay_out)

 

上記2つを元のコードに合わせると以下のようになります。

 

コード

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from bokeh.io import curdoc
from bokeh.models.widgets import TextInput, Button, Paragraph
from bokeh.layouts import layout
 
text_input=TextInput(value="AAA")
button=Button(label="Text")
output=Paragraph()
 
def update():
    output.text="Hello," + text_input.value
 
button.on_click(update)
 
# button.on_click(update)
lay_out=layout([[button,text_input],[output]])
 
curdoc().add_root(lay_out)

 

エディターで上記コードをwidget.pyという名前で保存し、
コマンドラインから実行します。

例:
C:\Users\xxxx>bokeh serve widgets.py

すると以下のようにlocalhostのアドレスが出てきます
2018-07-21 22:54:49,162 Bokeh app running at: http://localhost:5006/widgets

ブラウザにhttp://localhost:5006/widgetsを打ち込むと先ほどの動かなかった
webアプリが動くようになります。

 

 

以下は元素データから取得した元素ごとの沸点を表示するグラフのコードです。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#ライブラリーのインポート
from bokeh.plotting import figure
from bokeh.io import curdoc
from bokeh.sampledata.periodic_table import elements
from bokeh.models import Range1d, PanTool, ResetTool, HoverTool, ColumnDataSource, LabelSet, Select
from bokeh.models.annotations import Span, BoxAnnotation, Label, LabelSet
from bokeh.layouts import layout
 
#N/Aを含む行を削除する118あった行が31個まで減る
elements.dropna(inplace=True)
#辞書を使用してガスは黄色というように記憶させる
colormap={'gas':'yellow','liquid':'orange','solid':'red'}
#elementsのデータフレームに色(color)のカラムを追加しつつカラムstandard stateにある値に対する色を入れていく
elements['color']=[colormap[x] for x in elements['standard state']]
 
#データフレームのままだと柔軟に動かせないのでカラムデータソースに3つに分けて入れる
gas=ColumnDataSource(elements[elements["standard state"]=="gas"])
liquid=ColumnDataSource(elements[elements['standard state']=='liquid'])
solid=ColumnDataSource(elements[elements['standard state']=='solid'])
 
#figureオブジェクトを作成
f=figure()
 
#glyphの作成 無地のグラフに一本ずつグラフの線を追加していく
#今回は丸で表すのせcircle()を追加し、その色やサイズを指定していく
f.circle(x="atomic radius",y="boiling point",#x軸を原子のサイズ、y軸を沸点に指定
         size=[i/10 for i in gas.data["van der Waals radius"]],#sizeカラムを作り、そこに半径の1/10の数値を入れる
         fill_alpha=0.2,color="color",legend="Gas",source=gas)#colorは先程追加したカラムを参照するので""で指定、sourceはカラムデータソースの変数なので""はつかない
#以下もう2本のグラフを追加する
f.circle(x="atomic radius", y="boiling point",
         size=[i/10 for i in liquid.data["van der Waals radius"]],
         fill_alpha=0.2,color="color",legend='Liquid',source=liquid)
 
f.circle(x="atomic radius", y="boiling point",
         size=[i/10 for i in solid.data["van der Waals radius"]],
         fill_alpha=0.2,color="color",legend='Solid',source=solid)
 
#x軸y軸に名前を付ける
f.xaxis.axis_label="Atomic radius"
f.yaxis.axis_label="Boiling point"
 
 
#各要素(3つ分)の沸点の平均を計算する、sumでカラム内要素を足してlenで取得したカラム内項目数で割る
gas_average_boil=sum(gas.data["boiling point"])/len(gas.data["boiling point"])
liquid_average_boil=sum(liquid.data["boiling point"])/len(liquid.data["boiling point"])
solid_average_boil=sum(solid.data["boiling point"])/len(solid.data["boiling point"])
 
#沸点の最低値と最高値を取得
solid_min_boil=min(solid.data["boiling point"])
solid_max_boil=max(solid.data["boiling point"])
 
 
#各要素(3つ分)の平均値に目印となる(Spanと呼ぶ)色付きの線を設定する
#これら平均値を表す目印はユーザーの指定によって変化する
span_gas_average_boil=Span(location=gas_average_boil,dimension="width",line_color="yellow",line_width=2)
span_liquid_average_boil=Span(location=liquid_average_boil, dimension='width',line_color='orange',line_width=2)
span_solid_boil=Span(location=solid_average_boil, dimension='width',line_color='red',line_width=2)
 
#上記で設定した平均値を表す目印をfigure()オブジェクトに追加する
#無地のグラフに一本ずつグラフの線を追加していく作業を先ほど行ったのでここに更に足す形になる
f.add_layout(span_gas_average_boil)
f.add_layout(span_liquid_average_boil)
f.add_layout(span_solid_boil)
 
 
 
#span_solid_boilの位置に関する値をアップデートする自作関数を設定
#select.valueから帰ってくる値はstringとなっているのでfloatに変換する必要がある
def update_span(attr, old, new):
    span_solid_boil.location=float(select.value)
 
 
#変数optionの中にリスト形式でデータから取得した値とそれを説明する文字列をタプルのペアで入れる
#データから取得した値はstringに変換する必要がある
options=[
(str(solid_average_boil),"Solid Average Boiling Point"),
(str(solid_min_boil),"Solid Minimum Boiling Point"),
(str(solid_max_boil),"Solid Maximum Boiling Point")]
 
#選択ウィジェットを作成
select=Select(title="Select span value", options=options)
select.on_change("value",update_span)
 
 
#選択ウィジェットの配置と有効化
lay_out=layout([[select]])
curdoc().add_root(f)
curdoc(.add_root(lay_out))

 

 

Filed Under: Bokeh

  • « Go to Previous Page
  • Page 1
  • Interim pages omitted …
  • Page 8
  • Page 9
  • Page 10
  • Page 11
  • Page 12
  • Interim pages omitted …
  • Page 55
  • Go to Next Page »

Primary Sidebar

カテゴリー

  • AWS
  • Bootstrap
  • Dash
  • Django
  • flask
  • GIT(sourcetree)
  • Plotly/Dash
  • VPS
  • その他tool
  • ブログ
  • プログラミング
    • Bokeh
    • css
    • HoloViews
    • Jupyter
    • Numpy
    • Pandas
    • PosgreSQL
    • Python 基本
    • python3
      • webアプリ
    • python3解説
    • scikit-learn
    • scipy
    • vps
    • Wordpress
    • グラフ
    • コマンド
    • スクレイピング
    • チートシート
    • データクレンジング
    • ブロックチェーン
    • 作成実績
    • 時系列分析
    • 機械学習
      • 分析手法
      • 教師有り
    • 異常値検知
    • 自然言語処理
  • 一太郎
  • 数学
    • sympy
      • 対数関数(log)
      • 累乗根(n乗根)
    • 暗号学

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · Log in