2019年2月27日水曜日

NetLogo関連のブログ記事

ある必要に迫られて、小生がNetLogo(エージェントベーストモデリング向け)の利用に関して、これまでに書いたブログの記事をまとめてみました。

他の方にはほとんど役に立たないかも知れませんが、小生自身が再度エージェント指向モデリングをやる場合の資料的価値はありそうです。

ブログ記事は、一般的に言って、他の人に迷惑にならなければ、参考になる場合があるかも知れません。



「このブログ(sparse-dense byFoYo)」に掲載の記事

◎卒研のレベルを高める手がかり:Multi-level Models In NetLogo 6(その2)
  http://sparse-dense.blogspot.com/2017/02/multi-level-models-in-netlogo-6_22.html
◎クリスマスプレゼントか、NetLogo 6.0リリース(日本語に恩恵)
  https://sparse-dense.blogspot.com/2016/12/netlogo-60.html
◎スマホでマルチエージェントモデリング!
  https://sparse-dense.blogspot.com/2017/07/blog-post.html
◎卒研のレベルを高める手がかり:Multi-level Models In NetLogo 6
  https://sparse-dense.blogspot.com/2017/02/multi-level-models-in-netlogo-6.html
◎Deep Learningのビジュアライゼーション
  https://sparse-dense.blogspot.com/2016/11/deep-learning_18.html
◎マルチエージェントでDeep Learningの基礎
  https://sparse-dense.blogspot.com/2016/12/deep-learning.html
◎Construct a neural network (multilayer perceptrons) using micro:bit
  https://sparse-dense.blogspot.com/2018/06/microbittwo-layer-perceptronxor.html
◎Java 8 ラムダ式の初歩(続き1)
  https://sparse-dense.blogspot.com/2017/05/java-8_81.html  
◎NetLogo
  https://sparse-dense.blogspot.com/2016/11/netlogo.html
◎マルチエージェントシステム NetLogo3D
  https://sparse-dense.blogspot.com/2017/03/netlogo3d.html
◎KAITシンポジウム2016で「現実感のある」エージェント指向モデリングを展示
  https://sparse-dense.blogspot.com/2016/12/kait2016.html

「神奈川工科大学 情報工学科 ブログ」に掲載の記事

◎NetLogoのネットワーク(社会的/電子的)
  http://blog.cs.kanagawa-it.ac.jp/2013/02/netlogo.html
◎Android端末をリモコンとして活用!
  http://blog.cs.kanagawa-it.ac.jp/2012/06/android.html
◎ホタルの季節です
  http://blog.cs.kanagawa-it.ac.jp/2015/06/blog-post_21.html
◎NetLogoの3D機能で再びサボテンを観察する
  http://blog.cs.kanagawa-it.ac.jp/2013/02/netlogod.html
◎情報学部棟(12階建て)からの階段による避難
  http://blog.cs.kanagawa-it.ac.jp/2012/06/blog-post_16.html
◎平成27年度第1回のi-Androidの会が開催されました[5/27]
  http://blog.cs.kanagawa-it.ac.jp/2015/05/271i-android527.html
◎春休みにWebでお勉強(複雑系)
  http://blog.cs.kanagawa-it.ac.jp/2014/03/web.html
◎百円ショップで買ったサボテンにフィボナッチ数列を見る
  http://blog.cs.kanagawa-it.ac.jp/2013/01/blog-post_14.html
◎(続)NetLogoプログラミングのススメ
  http://blog.cs.kanagawa-it.ac.jp/2012/06/netlogo.html
◎NetLogoプログラミングのススメ
  http://blog.cs.kanagawa-it.ac.jp/2012/05/netlogo.html
◎多忙にも余裕を、硬派にも癒しを
  http://blog.cs.kanagawa-it.ac.jp/2012/05/blog-post_04.html
◎i-Androidの会が開催されました(12/24)
  http://blog.cs.kanagawa-it.ac.jp/2015/01/i-android1224.html
◎蝶の山越え:3年セミナーの一場面
  http://blog.cs.kanagawa-it.ac.jp/2014/01/blog-post_30.html
◎(続)6月9日オープンキャンパス研究室公開
  http://blog.cs.kanagawa-it.ac.jp/2013/06/blog-post_10.html
◎通算20回目の情報工学科アンドロイドの会が行われました
  http://blog.cs.kanagawa-it.ac.jp/2013/06/blog-post_5.html
◎段階的に「交通シミュレータ」
  http://blog.cs.kanagawa-it.ac.jp/2013/05/blog-post_24.html

追記:小生による「NetLogoのチュートリアル」は以下にあります:

https://sites.google.com/site/yamlabnetlogo/home


2019年2月20日水曜日

JavaのCompletableFutureによる並行処理

 Javaでは当初から、平行プログラミングが重視されてきました。近年のコンピュータはマルチコア化(メニコア化)が進んでいるので、マルチスレッドによる並列化はさらに重要性を増しています。最近のJavaは、強固なコンカレントパッケージを提供していて、高レベルで、スレッドセーフなコレクションや、スレッドプールを利用できます。これによって、ユーザは、明示的にスレッドを開始することもなく、またロックを使用することもなく、並列プログラムを書くことができるようになってきました。

 ここでは、これらのうちで、FutureクラスとCompletableFutureクラスを取り上げます。下記のJava書籍[1]の第12章には、「マルチスレッドと平行処理」が詳しく解説されています。その中にある例題を参考にして検討します。例えば、以下の図1ような図を描くとします。まず、5角形と8角形をそれぞれ別のスレッドで並行してして描きます。それら両方の描画が完了するのを待って、次に外側に4角形を描きます。この四角形の一辺の長さは、図に示したように、5角形と8角形を描き終わった後に決まるとしています。(短いビデオもご覧ください。)


図1 5角形と8角形を並列に描いた後に、外側に四角形を描く

これらの多角形を描くメソッドpolyDとpolyVを以下のように定義します。
 double polyD(int x, int y, int n, int s)
 void polyV(int x, int y, int n, int s)
  x, yは多角形描画の開始点の座標
  nは頂点の数
  sは一辺の長さ
  polyDは、n * sの値を返します。

 まず、ExecutorとFutureを使ったプログラム(リスト1)を以下に示します。ExecutorService(スレッドプール)を使って、2つの多角形の描画を別々のスレッドへsubmitします。(line 21-23)すると、Futureオプジェクトx1, x2が直ちに返ってきます。したがって、描画を待たずに、両方の多角形の周の長さの和を求める計算(line 25)の開始に向かいます。しかし、ここで、x1.get()とx2.get()が呼び出されていることに注意しましょう。すなわち、このget()は、それぞれの多角形の描画の完了を待つことを意味します。それが終わった後に、外側の四角形が描かれます。(line 26)

リスト1 ExecutorとFutureによる、並列描画+逐次描画

 次に、文献[2]などを参考にして、CompletableFutureを使ったプログラム(リスト2)を以下に示します。これは、上記のExecutorとFutureを使ったプログラムと完全に同じ動作をします。しかし、注目すべきは、これが1ステートメントで完結していることです。Threadプールの利用も、2つの多角形描画の待ちも明示されていません。5角形と8角形の描画のための2つのCompletableFutureが、.thenCombineAsynによって連結され、さらにその後に起こる、四角形の描画も.thenAcceptで連結されています。並行処理部分があるのに、すべてが一気にパイプライン連結されています。なお、line 34は、両方の多角形描画の後に得られる、周の長さの和を計算するラムダ式です。

リスト2 CompletableFutureによる、並列描画+逐次描画
(全体が1ステートメントで完結)

 リスト1も十分明快ではありますが、このリスト2の方が、さらに洗練されたエレガントなプログラムであると言えるのではないでしょうか!別の言い方をすると、リスト1は、「ここで待て。そこで計算して、その結果を使って次の描画をせよ。」という命令的なのに比べて、リスト2は「2つの並行処理が終ったらその結果を使って次の描画を行う。」という仕様的記述だとも言えます。もちろん、状況により、使い分けることになるでしょう。

 リスト1とリスト2の両方に言えることですが、Java8で導入されたLambda Expressionsが重要な役割を果たしていることも再認識できると思います。

 さらに複雑な図2のような並列描画プログラムも、このCompletableFutureを使って書いてみます。これは、図1の描画を2つ横に並べて同時に描かせます。すなわち、さらに多重の並列プログラムになっています。

図2 上記の図1の並列描画をさらに2つ同時に描く

具体的なやり方は色々あるでしょうが、ここではリスト3のように、図1相当のものを2つ、.thenCombineAsyncで連結しました。なお、図1の描画に相当するプログラムは、メソッドCPF(ss)として設定しました。ここで、引数ssは、各図の描画を開始位置を決めるためのシフト量です。(なお、line 43のラムダ式(x,y)->y-xは、念のため、外側の図の開始位置の差を確認し、その値をline 44で表示していますが、特別な意味はありません。)

リスト3 図2を描くためのCompletableFutureを使ったプログラム
リスト3 図2を描くためのCompletableFutureを使ったプログラム(続)

■参考書籍
[1]立木秀樹、有賀妙子著「すべての人のためのJavaプログラミング 第3版」、共立出版
[2]C.S. Horstmann(柴田芳樹訳)「Java SE 8 実戦プログラミング」、インプレス

2019年2月15日金曜日

Reactive Programming with Java 9

In Java 9 and later, a function called Flow API is provided. With this, it is possible to perform Reactive Programming with only the Java JDK. As a result, it is possible to appropriately control events occurring asynchronously in a distributed system or multithread, without performing low level programming. I found a nice commentary on this. It is as follows:

“The Reactive Magazine Publisher” by Moisés Macero

This is an easy-to-understand explanation using meaningful examples that actually operate, and there are many values ​​to learn. For example, consider a magazine delivery system consisting of Publisher and Customers (Subscribers, Consumers). There, some customers receive magazines very slowly. Then, since the delivery box of Publisher overflows, the next magazine will need to be dropped from that box. In this way, Publisher will react according to the Subscriber's situation.

There are several ways to create such a system or simulator. However, here it is meaningful to high level programming using the Publisher-Subscriber pattern in the above Java JDK. This example allows you to observe the behavior of the system when parameters such as Subscribers' receipt speed, Publisher's box capacity, etc. are changed. If the subscriber is slower than the publisher, it functions like a pull-based system. Conversely, if the subscriber is fast it will be like a push-based system.

I made a visualization to make the behavior of this example easier to understand. The results are shown below. One turtle shown in the figure means one magazine. Please see the execution progress by matching the output text with the figure!
(also see the short video below.)



Please enlarge and see the diagram.






As a conclusion of this article, the author says:
“You shouldn’t be in a rush of applying this pattern in a real project, but it’s great when you know it since it might happen in future that you find a problem for which Reactive Programming fits perfectly: then you’ll gain a lot. “

I agree with this. Thanks again to Moisés Macero!

2019年2月7日木曜日

週刊誌に掲載された 「数学する」歓び

滅多に買わない週刊紙であるが、先日、あることから、一冊の週刊誌(週刊新潮 2019年2月14日梅見増大号)を近くのコンビニで購入した。その中に、ちょっと目を疑うようなタイトルの記事が掲載されていた。"「数学する」歓び"という題の特別読物である。若き独立(数学)研究者による4ページの随筆である。

大衆向け週刊誌で、タイトルに"数学"という用語が含まれる記事は、これは滅多に出現しないであろう。だから驚いた。その記事は、「機械を使った人間の知能の模倣」と「人間の思考を機械に似せること」、そして、「無意味の世界」と「意味を見出そうとすること」などについて一定の説得力で書かれていた。「人工知能」がこれだけ注目されているこの現代に、もっと深く考えさせられることがあるのかも。

2019年1月30日水曜日

Java Rubik's Cube

On the Thunkable site, "Thunkable App of the Month - July 2018" had been announced. It is an application to explain the solution of Rubik's Cube. I have a special Rubik's cube called Java Rubik's Cube. It was distributed as a souvenir at Sun Tech Days 2007 in Tokyo more than 10 years ago. I completely forgot the solution, but this app should lead me well.


Rubik’s Cube Solving Guide by Winston Riggs

Java Rubik's Cube (on the left)

Java Rubik' Cube is somewhat more difficult than general Rubik's Cubes in the first stage. When a surface is filled with the same images, they must be arranged in the same direction as in the following figure. However, after overcoming this constraint, the latter half of the solution might become rather easy.


2019年1月24日木曜日

卒研論文提出が間近のようです

一般的な私立大学では、今頃(1月下旬ころ)はそろそろ卒研の論文提出期限のようです。以下の写真は、近くにある大学の情報学部棟を今夜22:00(2019年1月24日)に撮影したのものです。まわりはほぼ真っ暗ですが、この棟(12階建て)だけは、かなり灯りが灯っています。

おそらく、卒論纏めに徹夜する学生も多いのでしょう。やるべき時にはそのくらいやってほしい。ああ懐かしい、学生時代。



 情報学部棟の南側と東側が見えています。デジカメでめいっぱいのズームアップで撮ったのであまり鮮明ではありませんが、もう少し良いカメラなら、明かりの灯っている研究室を特定できそうです!?

卒研生のみなさん、指導教員の皆様、がんばって下さい。

2019年1月19日土曜日

A JSON Decoding Extension for App Inventor (2)

[Dec.6, 2019] For your convenience, another example is shown below:
https://sparse-dense.blogspot.com/2019/12/another-example-using-json-decoding.html

In the previous article, I introduced a JSON Decode Extension to easily extract the necessary information from the JSON file received from a Web service. This time, in order to test this Extension, I created a simple book search application. There are many applications of this type, but the concern here is how easy it is to decode JSON files.


Results from the book search app
The created application is as shown above. It shows the search results of one English book and two Japanese books. Giving a few keywords, Google Book Search searches for books and returns the results in JSON text as shown below. In this example, I set to receive only one book out of hit books.


JSON text sent back from the web service (a part)
For example, in the first search, "Galois" and "Groups" were given as keywords. The resulting Json text is shown above. "title", "authors", "publishedDate", "thumbnail" and "description" are extracted and displayed from this data. The program is shown in the figure below. This is all of the source program. Therefore, it can be said that this is made quite compact.

Complete App Inventor source program of the book search

However, there is still room for improvement. For example, the current Extension receives the following list individually as a search instruction string.

query for title -> "items,volumeInfo,title"
query for authors -> "items,volumeInfo,authors"
query for publishedDate -> "items,volumeInfo,publishedDate"
query for thumbnail -> "items,volumeInfo,imageLinks,thumbnail"
query for description -> "items,volumeInfo,description"

This is a little inefficient. The values ​​of tags at the same hierarchical level should be collectively received as follows. In the near future, we plan to revise the extension so that we can respond to this. That way, you can make this application even easier.

query for several items -> "items,volumeInfo,[title,authors,publishedDate,description]"
query for thumbnail -> "items,volumeInfo,imageLinks,thumbnail"

2019年1月18日金曜日

A JSON Decoding Extension for App Inventor (1)

[Dec.6, 2019] For your convenience, another example is shown below:
https://sparse-dense.blogspot.com/2019/12/another-example-using-json-decoding.html

[This Extension and  its doc are available. Please see the bottom of this article.]

JSON format is commonly used when receiving data from Web services, etc. With App Inventor, JsonTextDecode in the web block can convert JSON to list structures. Then, the conversion result can be manipulated by the selectItem and lookUpInPairs of the list block. However, as Evan W Patton (MIT) pointed out in the paper [1], these list processes are generally very complicated. And he also suggested a more readable and compact Extension block to alleviate this. 

I independently developed an Extension for JSON decode based on his new block idea. This Extension might be intuitive and easy to understand because it can hierarchically acquire necessary information with the tag names (properties) without using complicated operations on nested lists. The outline is shown in the figure below. (please enlarge and see the figure.)




This Extension takes two arguments. One is JSON data that was converted into list structure. The other is a search instruction list for hierarchically specifying the value of a specific tag (property). In this example, JSON text holds the values ​​of four kinds of sensors as "healthData". In the above figure, the name of the third sensor is specified. Note that in the query list, a number such as "3" indicates the element index of the JSON array structure.

Query List : John, healthData, 3, sensor
Result : Systolic pressure

JSON data used here is a modified version of the health data published in the following document [2]. The following figure shows the part of listing up all four sensors and their values ​​using this Extension. I think that it is written concisely. Operations for complicated list processing are not appeared here.


Collecting values of the four sensors



An example of running this application is shown below. For details, please see the files shown below.


Result of the test program on Android


Within this Extension, the list structure is iteratively processed using the function of YailList [3]. I think that YailList makes somewhat relaxation of complicated data type conversion (casting)  in JAVA. This Extension is still in beta. Although some of the JSON structures have been tested, all the structures are not covered, so bugs may be included. However, it is shown below for your reference. It was tested with Nexus 6 (Android 7.1.1). This extension was created using AppyBuilder Code Editor [4].

References

[1] JSON Interoperability in MIT App Inventor
https://2018.splashcon.org/event/blocks-2018-papers-json-interoperability-in-mit-app-inventor
[2] http://georgepavlides.info/ehealth-made-simple/
[3] http://3nportal.com/AIBridge/API/com/google/appinventor/components/runtime/util/YailList.html

[4] AppyBuilder Code Editor
http://Editor.AppyBuilder.com

2019年1月2日水曜日

Make a mini calendar app for Android, celebrating the New Year

Celebrate the New Year and make a small app! As you can see from the calendar, there are several months with the same day of the week. So, let's make an application that groups months by the day of the week on the 1st day as a key.

[ For Japanese version, please click here.]

grouping months by the day of the week on the 1st day

Although this mini app is not so practical, I will make it with the following five goals:

[1] Make the application logic in Java for Android.
[2] Use lambda expressions, streams, and the new date classes provided by Java 8.
[3] Create a GUI with App Inventor and call Java from there.
[4] Create as a general-purpose framework applicable to other applications.
[5] Customize the ActivityStarter to create a new block.

First, I will talk about [1] and [2]. With the recent Android, we can use Java 8 features. So, I'm going to write this app as concisely as possible using lambda expressions and streams. The logic part is as follows. The essential part is only one assignment statement to a Map object named "mp". The element of this object is a pair of "day of the week" and "a list of months whose first day matches that day of the week".


Next is [3] and [4]. Java programs like the above can be called using App Inventor 's Activity Starter function (block). I will use it, but in order to make it a general-purpose framework, I prepared a template for both the App Inventor side and the Java side. On the Java side, I prepared an input processing part and an output processing part beforehand so that users can complete it by rewriting only the application logic. Also, the App Inventor side has been designed to be applicable to many other applications as shown below. 

A generic App Inventor application that calls Java programs

With regard to the last item [5], I wanted to slightly change the input data and parameters passing to Activity Starter, as a result of considering the versatility as described above. So, I customized ActivityStarter and created new blocks shown below, using AppyBuilder Code Editor. I / O with the Java side was designed to do via a text file. Regarding the input, I provide two ways, passing the path of the input file and passing the text data directly. The boolean parameter "isFile" in the Setup block blow makes this selection possible.


Newly created App Inventor block (customized version of Activity Starter)

The entire App Inventor program created using this new block is as follows.


App Inventor program with newly created block

[Note] About Android and Java 8
Under Android 5.0 (API level 22), it is Java 7 compliant and Java 8 cannot be used. Android 6.0 (API level 23) can use part of lambda expressions etc., but seems to require Android 8.0 (API level 26) or higher in order to use full functions including streams.

2019年1月1日火曜日

新年にちなんでAndroidでカレンダーアプリを作る

みなさま、明けましておめでとうございます。

今年も、拙文ですが、ここに話題を書いて行こうと思っています。新年にちなんで、何か小さなアプリを作ってみたいと思います。カレンダーを眺めていたら、日にちの曜日が同一となっている月が幾つかあります。そこで、月初めの曜日をキーとして、月をグループ化するアプリを作ってみます。
【英語版はこちらにあります】

月初めの曜日が同じ月をグループ化する

実用性には乏しいミニアプリなのですが、以下の5つの「こだわり」を持って作ります。

【1】Android用に、アプリのロジックは、Javaで作る。
【2】Java8のラムダ式とストリーム、改訂日付クラスを用いる。
【3】GUIはApp Inventorで作り、そこからJavaを起動する。
【4】他のアプリにも適用できる汎用的な枠組みとする。
【5】ActivityStarterをカスタマイズして新規ブロックを作る。

まず、【1】と【2】ですが、最近のAndroidでは、Java8の機能が使えることが分かりました。そこで、ラムダ式とストリームを使って、できるだけ簡潔にこのアプリを書いたつもりです。そのロジック部は、以下の通りです。曜日や月の名前は英語ではなく、日本語にすることもできました。本質的な部分は、Mapオブジェクトmpへの代入文1つだけで済んでいます。このmpの要素は、 [曜日, 初日がその曜日である月のリスト]のペアとなります。


次に、【3】と【4】です。上記のようなJavaプログラムは、App InventorのActivity Starter機能(ブロック)を使って、App Inventorから呼び出すことができます。ここでも、それを使うのですが、できるだけ、汎用的な枠組みにするため、App Inventor側とJava側の両方のひな形を用意しました。Java側には、入力処理部と出力処理部を予め備えておき、上図のようなロジックの記述部だけを書き換えるだけで、ほぼ済むようにしました。また、App Inventor側も、下図のような、他の多くのアプリにも適用できるデザインにしました。

Javaプログラムを呼び出す汎用的なApp Inventorアプリ

最後の【5】ですが、上記の汎用性を考えたことにより、Activity Starterに対して、入力データやパラメータの受け渡しを多少変えたくなりました。そこで、それらに関するカスタマイズを行い、新たなブロックを作りました。以下がそれらのブロックです。Java側との入出力は、テキストファイルを介して行うことにしていますが、入力関しては、入力ファイルのパスを渡す場合と、テキストデータを直接渡す場合の2とおりを選べるようにしました。以下にあるSetupブロックの"isFile"でその選択ができます。

新規作成App Inventorブロック(Activity Starterのカスタマイズ版)
この新規ブロックを使って作ったApp Inventorのプログラムの全体は以下のとおりです。

新規作成ブロックを使ったApp Inventorプログラム

【注】AndroidのJava8対応について
Android 5.0(APIレベル22)以下では、Java7対応であり、Java8は使えません。Android 6.0(APIレベル23)ではラムダ式の一部などは使えますが、ストリームも含めたフル機能を使うには、Android 8.0(APIレベル26)以上が必要のようです。