SlideShare a Scribd company logo
1 of 20
GRASS×SQLiteでベクタを扱ってみる
北海道大学 大学院環境科学院 福田 陽一朗
2014/06/27
FOSS4G 2014 Hokkaido
私?
大学院生です。
バイオマス資源の分布量の検討等をやっています。
FOSS4Gを知らない頃...
⇒GISは高額で難しい! と思ってました。
スキャンした地図を他の地図に重ねたい!
⇒お絵かきソフトでなんちゃって幾何補正 みたいなことをして悦に入ってました
ふとしたきっかけでQGISを知る
⇒Georeferencerに衝撃を受けました。
⇒まだ日本語化の際に特殊な環境設定をしなければならない頃…
FOSS4G HKD 2012に参加
⇒その後、GRASS GISを使ってエネルギーの試算などやりました。
⇒日射量(r.sun)
小水力発電の適地検討(r.watershed etc.)
今
⇒GRASSでベクタネットワーク解析などをやっています。
GRASS GIS?
・種々のラスタ解析/ベクタ解析ツールが使える! (ベクタの概念はちょっと独特)
・座標系・領域の設定あたりを乗り越えるとすごく便利!
・QGISのGRASSプラグイン/プロセシングからも利用できる!(ただし機能限定)
・外部から直接モジュールを介した処理が行える!(Pythonで)
・たまに返事をしなくなる!(大抵はこちらが悪い)
http://grass.osgeo.org/
grass: db/drivers Directory Reference http://fossies.org/dox/grass-6.4.3/dir_ef3632b5d5f243c151344966da52edc4.html
○ GRASSは各種のデータベースと接続することができます。
SQLite?
・オープンソースのRDBMS(リレーショナルデータベースマネジメントシステム)
・SQL(データベース言語)が使える!
・データベースの本体が単一の独立したファイル
・完全にローカルで動作するので、サーバーの設定が要らない。 ⇒お手軽!
こんなアプリケーションでも使われています。
http://www.sqlite.org/
こんな環境でやってます。
ラスタモジュール
・
・
・
ベクタモジュール
データベースモジュール
データの選択・抽出
データの更新
データの挿入
db.connect
v.db.connect
v.db.addcol
v.db.renamecol
v.db.dropcol
etc.
ベクタデータ
ESRI SHAPE
SQLite(SpatiaLite)
etc.
v.in.ogr db.in.ogr
バッチ処理には
import grass.script as grass
grass.run_command()
grass.parse_command()
grass.write_command()
import sqlite3
sqlite3.connect()
db.execute()
cursor.execute()
SELECT FROM
UPDATE SET
INSERT INTO
(db.*, v.db.*)
(v.*)
(r.*)
・
・
・
表データ
csv
テーブルの管理、SQLによる操作は管理ソフト
(SQLiteSpy)を使ってます。
GRASS
Database
Location Mapset Geometry & attribute data
/grassdata /HKD_J2K
/HKD_TKY
/HKD_J2Ku54
/sapporo
/PERMANENT
/map_1
/map_2
/cats
/cell
/cellhd
/cell_misc
/colr
/fcell
/hist
/vector
/dbf
/landuse
/cityborder
/ncensus
coor
dbin
hist
sidx
topo
・
・
・
/landuse.dbf
/cityborder.dbf
/ncensus.dbf
・
・
・
RASTER
VECTOR
こんなファイル構造になっています。
こんなファイル構造になっています。
GRASS
Database
Location Mapset Geometry & attribute data
/grassdata /HKD_J2K
/HKD_TKY
/HKD_J2Ku54
/sapporo
/PERMANENT
/map_1
/map_2
/cats
/cell
/cellhd
/cell_misc
/colr
/fcell
/hist
/vector /landuse
/cityborder
/ncensus
coor
dbin
hist
sidx
topo
・
・
・
RASTER
VECTOR
/sqlite.db landuse
cityborder
ncensus
・
・
・ SQLite
GRASSをSQLiteと接続する!
GRASS 6.4.3 (HKD_J2K)> db.connect –p
driver:dbf
database:'$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/'
schema:
group:
> db.connect driver=sqlite database=$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db
driver:sqlite
database:$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db
schema:
group:
詳しくはこちら。GRASS-SQLite driver http://grass.osgeo.org/grass64/manuals/grass-sqlite.html
http://grass.osgeo.org/grass64/manuals/db.connect.html
データベースファイルsqlite.db ⇒ベクタデータを生成した際に自動的に生成されます
○GRASSを立ち上げて、db.connect コマンドで接続します。
・GRASS6のデフォルトデータベースはDBASE(.dbf)です。
・databaseのパスはローカルのどこでも良いですが、下記がデフォルトです。
デフォルトフォルダ:$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite.db
(ちなみに、v.db.connect コマンドを使えば、レイヤごとに別々のデータベースファイルを指定することもできます。)
現在のコネクションを表示
テーブルの操作
操作 GRASS SQLite
列の追加 v.db.addcol ALTER TABLE … ADD COLUMN…
列名の変更 v.db.renamecol 非対応*
列の削除 db.dropcol / v.db.dropcol 非対応*
テーブル名の変更 g.rename ALTER TABLE … RENAME TO …
テーブルの削除 g.remove DROP TABLE …
*やろうと思えばできる(新テーブル作成⇒データのコピー⇒元テーブル削除⇒テーブル名の変更)
テーブルの操作は、GRASSコマンドとSQLite(SQL文)のどちらからでもできます。
列名の変更と列の削除はSQLiteでサポートしていないので、何かと便利です。
リファレンスにも書いてあります。
db.dropcol is a front-end to db.execute to allow easier usage
with a special workaround for the SQLite driver to support column drop.
http://grass.osgeo.org/grass64/manuals/db.dropcol.html
GRASSで扱う上で、レイヤ名(テーブル名)や列名の制限がいくつかあります。
・半角英数字とアンダーバーのみサポート
・最初の文字はアルファベット
・レイヤ名の字数は、198文字までは大丈夫でした。
・SQLの構文で使用する語句は使用できません。 例)SELECT
・列名には大文字と小文字の区別がありません。(NAME=name)
SQLiteの型
データ型 種類 GRASSの型
NULL 空文字 null
INTGER 整数(8~64ビット) integer
REAL 浮動小数点数(64ビット) double precision
TEXT テキスト型(UTF-8 / UTF-16BE / UTF-16LE) varchar(n)
BLOB バイナリ型 -
型の名前は、一般的な名称なら理解してくれます。( INT, FLOAT, DOUBLE, VARCHAR etc.)
...型の定義はGRASSに合わせるのが吉です。
SQLiteに格納される値のデータ型は5種類。
なお、BLOB型はGRASS GISで扱えないので、
この型の列を含むテーブルをGRASSで操作するとエラーが出ます。
GRASS 6.4.3 (HKD_J2K)> v.db.renamecol map=hoge column=old_column,new_column
WARNING: SQLite driver: unable to parse decltype: blob
WARNING: SQLite driver: column 'blob', SQLite type 4 is not supported
Datatypes In SQLite Version 3 http://www.sqlite.org/datatype3.html
UPDATE hoge
SET int = 0, real = 0, text = 0;
UPDATE hoge
SET
int = 2014/6/27,
real = 2014/6/27,
text = 2014/6/27;
UPDATE hoge
SET
int = 2014/6/27,
real = 1.0*2014/6/27,
text = '2014/6/27';
SQLiteの型
列毎にデフォルトの型を定義することができますが、それぞれのセルには
独立した型のデータを格納することができてしまいます。
一応、列の定義に応じた型で格納されていますが、、、
型ごちゃまぜでもSQLite的には問題ありません。
SQLを介して演算をする場合は、文字列でも数値とみなして計算しようとします。
整数のみの演算の場合、整数型にも注意が必要です。
何ができる?
SQL文を使って高度なデータ選択、抽出、それを元にしたデータの更新ができます。
○条件による絞込み(WHERE)
・LIKE演算子でのパターンマッチング 例)WHERE city_name LIKE “%上%”
(正規表現でのマッチング(REGEXP演算子)はデフォルトでは使えない)
○データのグループ化(GROUP BY)
・同じ条件の行を一つにまとめて集計する 例)GROUP BY city_name
SELECT * FROM cityborder
WHERE city_name LIKE "%上%"
SELECT
'○○'||substr(city_name,-1) AS city_type,
count(city_name) AS count
FROM cityborder
GROUP BY city_type
例)市区町村の最後の一文字でグループ化して数を集計
例)名称に「上」を含む市区町村を抽出
○他のテーブルとの結合(LEFT JOIN, INNER JOIN)
SELECT *
FROM nationalcensus_mesh
LEFT JOIN landuse_mesh
ON landuse_mesh.meshID = nationalcensus_mesh.key_code;
例)メッシュデータの結合(国勢調査と土地利用)
LEFT JOIN
国勢調査メッシュデータ 土地利用メッシュデータ
SQLiteで利用できる結合はLEFT、INNER、CROSS、NATURALの四種類です。
⇒RIGHT JOIN,FULL OUTER JOINには対応していないので、結合の順序に注意が必要です。
何ができる?
SQLite
Features 地物データ
GRASS GIS
結合を利用したSELECTは、重層的に使うことができます。
何ができる?
Table CTable BTable A
Table E Table D
cat
cat
key_1 key_2
key_3
○選択結果の利用(サブクエリ)
ALTER TABLE landuse_mesh
ADD COLUMN Population integer; --列を追加
UPDATE landuse_mesh
SET Population =
(SELECT Population
FROM nationalcensus_mesh
WHERE landuse_mesh.meshID = nationalcensus_mesh.key_code
);
例)属性データに他のテーブルのデータを挿入(データの更新:UPDATEステートメント)
・・・
CREATE INDEX landuse_mesh_meshID ON landuse_mesh (meshID);
CREATE INDEX nationalcensus_mesh_key_code ON nationalcensus_mesh (key_code);
○インデックスの設定
・SQLiteでは、各カラムにインデックスを設定することができます。
これによって、結合やサブクエリを介した更新などが劇的に早くなる場合があります。
例)上記のUPDATE例の場合(landuse_mesh:114,100行 nationalcensus_mesh:180,222行)
処理時間 インデックス作成前:約2時間15分 ⇒インデックス作成後:1.18秒
⇒ユニークインデックス作成(CREATE UNIQUE INDEX)後:1.08秒
何ができる?
v.db.addcol
map=cityborder
column="flg integer"
ちょっと応用:日本語を含むデータを扱う 例)日本語データを条件にした抽出
v.extract
map=cityborder
where=“city_name like '%村'”
UPDATE cityborder
SET flg = 1
WHERE city_name LIKE '%村';
v.extract
map=cityborder
where=“flg = 1”
where条件を指定できるGRASSモジュールは多いので、重宝します。
何ができる?
flg列を追加
SQLでflg列を更新!
地物を抽出!
直接地物の抽出ができない。。
ちょっと応用:GROUP BYを使ってディゾルブする(4次メッシュデータ⇒3次メッシュデータ)
64415129
3
64415129
4
64415220
3
64415220
4
64415129
1
64415129
2
64415220
1
64415220
2
64415119
3
64415119
4
64415210
3
64415210
4
64415119
1
64415119
2
64415210
1
64415210
2
SELECT
substr(meshID_4th,1,8) AS meshID_3rd,
sum(Population) AS Population_3rd,
sum(Household) AS Household_3rd
FROM census_4thmeth
GROUP BY meshID_3rd;
64415129 64415220
64415119 64415210
3次メッシュの地物データは別途用意ということで…(^^;
あとは、meshID_3rdをキーにして地物データにJOIN
大量のデータを含む属性を条件にしたディゾルブの場合は、
テーブルと地物を別立てで扱うのは良い方法かも。
4次メッシュデータ
3次メッシュデータ
何ができる?
厄介なこと、追補・おまけ
○cat列
・GRASSベクタ地物と属性データを接続しています。いじると結合関係がおかしくなります。
・cat列には自動的にインデックスが生成されています。
たまにcat列が生成されない場合もありますが、v.categoryというモジュールで生成できます。
⇒これがいわゆる「空間インデックス」というものなのかどうかは・・・わかりません。
○日本語(マルチバイト文字)対応
・属性テーブル内のデータにマルチバイト文字 ⇒OK
SQLite ⇒ OK(ただしUTF-8) GRASS GIS ⇒ OK(ただし選択条件などコマンド中には使えない)
・列名にマルチバイト文字 ⇒NG
SQLite ⇒ OK GRASS GIS ⇒ NG
○トランザクション
・処理を確定(コミット)するまでは、処理実行前の状態まで戻すこと(ロールバック)ができます。
・明示的に使うことで、データの更新等の処理が早くなることもあるそうです。(実感なし)
・しかし、GRASSの処理では自動でコミットされてロールバックできないので、あまり恩恵はないかも。
○外部ソフトの使用
・GRASS内でもSQLを使用した選択(db.select)や更新(v.db.update)、その他のSQL処理
(db.execute)ができますが、外部アプリケーションを使用したほうが楽!
⇒SQLiteManager、SQLiteSpy etc.
○もっとサブクエリ!
・GRASSモジュールのwhereの部分にもサブクエリが使えます。複雑な選択条件を指定できます。
例)v.extract ... where=“cat IN (SELECT cat FROM hoge WHERE area < 1000 LIMIT 100)”
○dbfの方がいいことも・・・
・v.mkgrid(グリッドの生成)で多量のグリッドデータを作成するのに、どえらい時間がかかりました。
⇒一旦dbfで作成してから、改めてSQLiteに接続し直したらすんなりできました。
これからと、まとめ
お世話になりました(なっています)
○GRASS7では、SQLiteが標準の属性データフォーマットになります。
GRASS GIS Manual: SQL support in GRASS GIS http://grass.osgeo.org/grass70/manuals/sql.html
⇒GRASS6でデフォルトだったDBASE(.dbf)は、「非推奨」に。
○さらにRとの連携をやってみたい。
○まとめ
・SQLは便利です。もっと使いこなせばきっともっと便利な予感。
・SQLでGRASSのベクタ機能はもっと便利になります。
・SQLiteはサーバーがいらないので、とりあえず使ってみるのは割と楽です。
・日本語の資料が身近にあればもっといいのに。(MySQL、PostgreSQLにはたくさんあるみたい。)
・MySQL、PostgreSQLと較べてどうなの? ⇒わかりません。知りたい!
・SQLite入門 –DBOnline-
http://www.dbonline.jp/sqlite/
・Query Language Understood by SQLite(SQLite本家のリファレンス)
http://www.sqlite.org/lang.html
・オープンソースGIS グラスアプローチ 第3版
・GRASS GIS 6.4.4svn Reference Manual
http://grass.osgeo.org/grass64/manuals/
・その他Google先生が案内してくれたたくさんのSQL使用例を載せてくれた方々
ありがとうございました。
ご助言、ご意見は yoh.fukuda at gmail.com
2014/06/27
FOSS4G 2014 Hokkaido

More Related Content

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

GRASS × SQLite でベクタを扱ってみる