...

Mathematica データ入出力について解説

by user

on
Category: Documents
34

views

Report

Comments

Transcript

Mathematica データ入出力について解説
Mathematica データ入出力について解説
(c)Symbolic Systems 2009.8.26
http://www.symboilcs.jp/lecturenotes.html
デモプログラムについて.特に断りがないもの以外は,すべて自前で用意したものか,Mathematica ドキュメントか
ら利用しています.
In[3]:=
Clear@"Globals`"D
ファイル操作関数
ref, guide  DirectoriesAndDirectoryOperations
In[4]:=
Out[4]=
In[5]:=
Out[5]=
$Path
8ApplicationsMathematica.appSystemFilesLinks,
UsersmatsudaLibraryMathematicaKernel, UsersmatsudaLibraryMathematicaAutoload,
UsersmatsudaLibraryMathematicaApplications, LibraryMathematicaKernel,
LibraryMathematicaAutoload, LibraryMathematicaApplications,
., Usersmatsuda, ApplicationsMathematica.appAddOnsPackages,
ApplicationsMathematica.appAddOnsLegacyPackages,
ApplicationsMathematica.appSystemFilesAutoload,
ApplicationsMathematica.appAddOnsAutoload,
ApplicationsMathematica.appAddOnsApplications,
ApplicationsMathematica.appAddOnsExtraPackages,
ApplicationsMathematica.appSystemFilesKernelPackages,
ApplicationsMathematica.appDocumentationEnglishSystem<
$TopDirectory
ApplicationsMathematica.app
In[6]:=
$HomeDirectory
Out[6]=
Usersmatsuda
In[7]:=
Out[7]=
In[8]:=
Out[8]=
In[9]:=
$TemporaryDirectory
tmp
Directory@D H* current directory *L
Usersmatsuda
SetDirectory@FileNameJoin@8$HomeDirectory, "Apps"<DD
H* ファイルパス名はシステム依存.明示的に記述せず,ここに記すようにディレクトリ名の列で書くことが望ましい *L
Out[9]=
UsersmatsudaApps
In[10]:=
CreateDirectory@"test"D
Out[10]=
UsersmatsudaAppstest
2
MahtematicaDataIO.nb
In[11]:=
SetDirectory@%D H* change directory *L
Out[11]=
UsersmatsudaAppstest
In[12]:=
FileNames@D
Out[12]=
8a, about.html, ca.avi, clip.avi, data.xls, demofiles, .DS_Store,
exp.tex, ffile, ffile.mx, HTMLFiles, HTMLLinks, j.txt, M.csv, M.dat,
M.dump, out1, sin.eps, s.wav, temp, temp2, test.c, test.mc, tmp, tri.avi<
In[13]:=
Expand@Hx + yL ^ 3D >> tmp H* Put the result to the file "tmp" *L
In[14]:=
FileNames@D
Out[14]=
8a, about.html, ca.avi, clip.avi, data.xls, demofiles, .DS_Store,
exp.tex, ffile, ffile.mx, HTMLFiles, HTMLLinks, j.txt, M.csv, M.dat,
M.dump, out1, sin.eps, s.wav, temp, temp2, test.c, test.mc, tmp, tri.avi<
In[15]:=
FilePrint@"tmp"D
x^3 + 3*x^2*y + 3*x*y^2 + y^3
In[16]:=
Function@8a<, 8FileByteCount@aD, FileDate@aD, FileType@aD<D@"tmp"D
Out[16]=
830, 82009, 9, 2, 8, 14, 39.<, File<
In[17]:=
ResetDirectory@D; Directory@D H* change to $HOME *L
Out[17]=
UsersmatsudaApps
In[18]:=
SetDirectory@FileNameJoin@8$HomeDirectory, "Apps", "test"<DD
Out[18]=
UsersmatsudaAppstest
Put/Get, Save/DumpSave
Ÿ 式をテキスト形式で保存
In[19]:=
Factor@x ^ 6 - 1D >>> tmp H* PutAppend *L
In[20]:=
FilePrint@"tmp"D
x^3 + 3*x^2*y + 3*x*y^2 + y^3
(-1 + x)*(1 + x)*(1 - x + x^2)*(1 + x + x^2)
In[21]:=
<< tmp H* Get@D この時,2つの式が読み込まれているが,表示は最後の式の評価のみ *L
Out[21]=
H- 1 + xL H1 + xL I1 - x + x2 M I1 + x + x2 M
Ÿ 関数定義をテキスト形式で保存
In[22]:=
a = 2 - x^2
Out[22]=
2 - x2
In[23]:=
f@z_D := a ^ 2 - 2
In[24]:=
Save@"ffile", fD H* 関数fの定義並びに,fの定義に現れる独立変数aの定義も併せて保存される *L
MahtematicaDataIO.nb
In[25]:=
FilePrint@"ffile"D
f[z_] := a^2 - 2
a = 2 - x^2
f[z_] := a^2 - 2
a = 2 - x^2
f[z_] := a^2 - 2
a = 2 - x^2
f[z_] := a^2 - 2
a = 2 - x^2
In[26]:=
Clear@f, aD
In[27]:=
<< ffile
Out[27]=
2 - x2
In[28]:=
Definition@fD
Out[28]=
f@z_D := a2 - 2
Ÿ 関数定義をバイナリ形式で保存
In[29]:=
quickSort@m_, orderQ_D := Module@8lst, QSort<,
SetAttributes@QSort, HoldFirstD;
QSort@lst_, n0_, n1_D := lst ; n0 ³ n1;
QSort@lst_, n0_, n1_D := Module@8lm, i, j<,
lm = lstP Floor@Hn0 + n1L  2D T; i = n0; j = n1;
While@True,
While@orderQ@lstPiT, lmD , i = i + 1D;
While@orderQ@lm, lstPjTD, j = j - 1D;
If@ i ³ j, Break@D D;
8lstPiT, lstPjT< = 8lstPjT, lstPiT<;
i = i + 1; j = j - 1;
D;
QSort@ lst, n0, i - 1 D;
QSort@ lst, j + 1, n1 D;
D;
lst = m; QSort@lst, 1, Length@lstDD; lstD;
In[30]:=
DumpSave@"ffile.mx", 8f, quickSort<D
H* システム依存.このダンプファイルを他のOSに移動しても使えない. *L
Out[30]=
8f, quickSort<
In[31]:=
Clear@f, quickSortD
In[32]:=
<< ffile.mx
In[33]:=
randomData = Table@Random@Integer, 81, 100<D, 820<D;
quickSort@randomData, ð1 > ð2 &D
Out[34]=
896, 96, 96, 95, 86, 83, 81, 79, 78, 73, 71, 63, 60, 50, 47, 33, 31, 24, 16, 6<
3
4
MahtematicaDataIO.nb
Ÿ 大規模データの取り扱い
大きなデータをなんらかの形で Mathematica 内に保存,あるいは取り込んだ場合,それを後の利用のために保存して
おきたい.その場合,Dumpsave[]は有効.保存の際は多少時間がかかるが,読み込みは非常に速い.ただし,DumpSave[]は環境を保存するため,後で利用するにはなんらかの変数データを束縛させておく必要がある.
In[35]:=
M = Table@Random@D * 10 000, 81000<, 81000<D;
In[36]:=
MP2, 33T
Out[36]=
9035.63
In[37]:=
ByteCount@MD
Out[37]=
8 000 128
In[38]:=
Timing@DumpSave@"M.dump", MD;D
Out[38]=
80.149125, Null<
In[39]:=
FileByteCount@"M.dump"D
Out[39]=
8 000 268
In[40]:=
Clear@MD
In[41]:=
Timing@<< M.dump;D
Out[41]=
80.022392, Null<
In[42]:=
MP2, 33T
Out[42]=
9035.63
Export/Import
ref. guide  ImportingAndExporting
Mathematicaではこれだけのフォーマットが用意されている.
In[43]:=
$ExportFormats
Out[43]=
83DS, ACO, AIFF, AU, AVI, Base64, Binary, Bit, BMP, Byte, BYU, BZIP2, CDF, Character16,
Character8, Complex128, Complex256, Complex64, CSV, DICOM, DIF, DXF, EPS, ExpressionML,
FASTA, FITS, FLAC, FLV, GIF, Graph6, GZIP, HarwellBoeing, HDF, HDF5, HTML, Integer128,
Integer16, Integer24, Integer32, Integer64, Integer8, JPEG, JPEG2000, JVX, List, LWO,
MAT, MathML, Maya, MGF, MIDI, MOL, MOL2, MTX, MX, NB, NetCDF, NOFF, OBJ, OFF, Package,
PBM, PCX, PDB, PDF, PGM, PICT, PLY, PNG, PNM, POV, PPM, PXR, RawBitmap, Real128,
Real32, Real64, RIB, RTF, SCT, SDF, SND, Sparse6, STL, String, SVG, SWF, Table, TAR,
TerminatedString, TeX, Text, TGA, TIFF, TSV, UnsignedInteger128, UnsignedInteger16,
UnsignedInteger24, UnsignedInteger32, UnsignedInteger64, UnsignedInteger8, UUE,
VRML, WAV, Wave64, WDX, X3D, XBM, XHTML, XHTMLMathML, XLS, XML, XYZ, ZIP, ZPR<
MahtematicaDataIO.nb
In[44]:=
$ImportFormats
Out[44]=
83DS, ACO, AIFF, ApacheLog, AU, AVI, Base64, Binary, Bit, BMP, Byte, BYU, BZIP2, CDED, CDF,
Character16, Character8, Complex128, Complex256, Complex64, CSV, CUR, DBF, DICOM, DIF,
Directory, DXF, EDF, ExpressionML, FASTA, FITS, FLAC, GenBank, GeoTIFF, GIF, Graph6, GTOPO30,
GZIP, HarwellBoeing, HDF, HDF5, HTML, ICO, Integer128, Integer16, Integer24, Integer32,
Integer64, Integer8, JPEG, JPEG2000, JVX, LaTeX, List, LWO, MAT, MathML, MBOX, MDB, MGF,
MMCIF, MOL, MOL2, MPS, MTP, MTX, MX, NB, NetCDF, NOFF, OBJ, ODS, OFF, Package, PBM, PCX, PDB,
PDF, PGM, PLY, PNG, PNM, PPM, PXR, QuickTime, RawBitmap, Real128, Real32, Real64, RIB, RSS,
RTF, SCT, SDF, SDTS, SDTSDEM, SHP, SMILES, SND, SP3, Sparse6, STL, String, SXC, Table, TAR,
TerminatedString, Text, TGA, TIFF, TIGER, TSV, UnsignedInteger128, UnsignedInteger16,
UnsignedInteger24, UnsignedInteger32, UnsignedInteger64, UnsignedInteger8, USGSDEM,
UUE, VCF, WAV, Wave64, WDX, XBM, XHTML, XHTMLMathML, XLS, XML, XPORT, XYZ, ZIP<
In[45]:=
Export@"out1", 86.7, 8.5, - 5.3<, "List"D
Out[45]=
out1
In[46]:=
FilePrint@"out1"D
6.7
8.5
-5.3
Ÿ Text data(*.dat)
通常のテキストデータ.TABで区切られている.
In[47]:=
HM = Table@RandomInteger@810, 100<D, 81000<, 810<DL  Short
Out[47]//Short=
8833, 42, 43, 53, 34, 80, 96, 22, 53, 23<, †998‡, 846, 48, 100, 21, 75, 37, 61, 42, 90, 37<<
In[48]:=
ByteCount@MD
Out[48]=
40 128
In[49]:=
Timing@Export@"M.dat", MD;D
Out[49]=
80.05835, Null<
In[50]:=
FileByteCount@"M.dat"D
Out[50]=
30 099
In[51]:=
Timing@MM = Import@"M.dat"D;D
Out[51]=
80.068136, Null<
In[52]:=
MM  Short
Out[52]//Short=
8833, 42, 43, 53, 34, 80, 96, 22, 53, 23<, †998‡, 846, 48, 100, 21, 75, 37, 61, 42, 90, 37<<
Ÿ CSV data(*.csv)
こちらも通常のテキストデータ.「,」で区切られている.Excelの出力形式としてもよく使われる.
In[53]:=
Timing@Export@"M.csv", MD;D
Out[53]=
80.055354, Null<
5
6
MahtematicaDataIO.nb
In[54]:=
FileByteCount@"M.csv"D
Out[54]=
30 099
In[55]:=
Timing@MM = Import@"M.csv"D;D
Out[55]=
80.040835, Null<
In[56]:=
MM  Short
Out[56]//Short=
8833, 42, 43, 53, 34, 80, 96, 22, 53, 23<, †998‡, 846, 48, 100, 21, 75, 37, 61, 42, 90, 37<<
Ÿ Excel形式(*.xls)
In[57]:=
Out[57]=
In[58]:=
He = Import@"data.xls", "XLS"D L  Short@ð, 5D &
Out[58]//Short=
†1‡
In[59]:=
eP2T H* Sheet2 *L
Out[59]=
98, , , , , , <, 9, レート表, , , , , =, 8, , , , , , <, 9, 1ドル, 95., 円, , , =,
9,
8,
8,
8,
9,
1ユーロ, 130., 円, , , =, 8, , , , , , <, 9, 円, ドル, ユーロ, , ドル, 円=,
10 000., 105.263, 76.9231, , 100., 9500.<, 8, 20 000., 210.526, 153.846, , 200., 19 000.<,
30 000., 315.789, 230.769, , 300., 28 500.<, 8, 40 000., 421.053, 307.692, , 400., 38 000.<,
50 000., 526.316, 384.615, , 500., 47 500.<, 8, , , , , , <, 8, , , , , , <,
計算表, , , , , =, 9, 円, ドル, , ユーロ, 円, =, 8, 45 000., 473.684, , , , <=
MahtematicaDataIO.nb
7
8
MahtematicaDataIO.nb
Ÿ URL
In[60]:=
Import@"http:reference.wolfram.commathematicaExampleDataocelot.jpg"D
Out[60]=
cf. Lunchtime Playground: Fun with Mathematica
http://mathgis.blogspot.com/2008/03/learning-regular-expression.html
MahtematicaDataIO.nb
In[61]:=
9
10
MahtematicaDataIO.nb
Out[61]=
上記ページの中から表の部分だけを取り出す.
In[62]:=
url = "http:groups.google.comgroupcomp.soft-sys.math.mathematicaabout";
reg = "H?<=monthL\\d+-\\d+\">\\d+";
data = Import@url, "Source"D;
ex = StringCases@data, RegularExpression@regDD;
ds = ToExpression@StringSplit@ex, 8";", "-", "\">"<DD;
ref. Regular Expression
上記dataの中身はこのURLページのHTMLコードからなる巨大な文字列.dataを評価してみれば中身がみれる.その中
に,下記のような日付と値の記述がある.そこから,{{年,月},値}のリストを作り出す.以下のデータ例と正規表
現に関しては,上記refs先を参照のこと.
MahtematicaDataIO.nb
11
上記dataの中身はこのURLページのHTMLコードからなる巨大な文字列.dataを評価してみれば中身がみれる.その中
に,下記のような日付と値の記述がある.そこから,{{年,月},値}のリストを作り出す.以下のデータ例と正規表
現に関しては,上記refs先を参照のこと.
In[67]:=
StringCases@"month1996-06\">218<td>", RegularExpression@"H?<=monthL\\d+-\\d+\">\\d+"DD
Out[67]=
81996-06">218<
In[68]:=
ex  Short
Out[68]//Short=
81995-04">339, 1995-05">315, 1995-06">299, †167‡, 2009-06">1000, 2009-07">882, 2009-08">715<
In[69]:=
ds  Short
Out[69]//Short=
881995, 4, 339<, 81995, 5, 315<, 81995, 6, 299<,
†167‡, 82009, 6, 1000<, 82009, 7, 882<, 82009, 8, 715<<
In[70]:=
DateListPlot@Map@8Drop@ð, - 1D, Last@ðD< &, dsDD
1600
1400
1200
1000
Out[70]=
800
600
400
200
1995
2000
2005
In[71]:=
Export@"about.html", %, "HTML"D H* 上記図をHTML形式で保存 *L
Out[71]=
about.html
In[72]:=
"about.html"
Out[72]=
about.html
いま生成したHTMLファイルに対しリンクを貼る.表示名はこの場合 Archive Sample.
In[73]:=
Hyperlink@"Archive Sample", "file:" <> ToFileName@Directory@D, "about.html"DD
Out[73]=
Archive Sample
Ÿ JPEG data (*.jpg*)
Mathematicaはシステム内にサンプルデータを大量に持っている.そこから取り込んだデータ.
12
MahtematicaDataIO.nb
In[74]:=
g = Import@"ExampleDataocelot.jpg"D
Out[74]=
In[75]:=
Shallow@InputForm@gDD
Out[75]//Shallow=
Image@8<< 200 >><, "Byte", Rule@<< 2 >>D, Rule@<< 2 >>D, Rule@<< 2 >>D, Rule@<< 2 >>DD
ImageData[]はピクセル値を返す関数.
In[76]:=
Hd = ImageData@gDL  Short@ð, 2D &
Out[76]//Short=
880.909804, 0.901961, 0.894118, †194‡, 0.603922, 0.619608, 0.631373<, †198‡, 8†1‡<<
Ÿ PostScript (*.eps)
In[77]:=
Plot@Sin@xD + Sin@Sqrt@2D xD, 8x, 0, 10<D
2.0
1.5
1.0
Out[77]=
0.5
-0.5
2
4
6
8
10
-1.0
In[78]:=
Export@"sin.eps", %, ImageSize ® 200D
Out[78]=
sin.eps
In[79]:=
Import@"sin.eps"D
Out[79]=
Ÿ 音
MahtematicaDataIO.nb
音
In[80]:=
s = ExampleData@8"Sound", "Viola"<D
Out[80]=
In[81]:=
Shallow@sD
Out[81]//Shallow=
Sound@SampledSoundList@8†1‡<, 22 050DD
In[82]:=
sP1TP1T  Short
Out[82]//Short=
88- 0.000762963, - 0.00253304, †53 208‡, 0.000762963<<
In[83]:=
Export@"s.wav", sD
Out[83]=
s.wav
Ÿ
13
14
MahtematicaDataIO.nb
Ÿ アニメーション
In[84]:=
a = Import@"ExampleDataclip.mov", "Animation"D
Out[84]=
clip.movデータから1番目,8番目,16番目のフレームだけを取り出す.
MahtematicaDataIO.nb
In[85]:=
a = Import@"ExampleDataclip.mov", 8"QuickTime", "Frames", 81, 8, 16<<D
Out[85]=
:
,
,
In[86]:=
aP1T
Out[86]=
3枚の画像を動画用にAVI形式で保存.
In[87]:=
Export@"clip.avi", a, "AVI"D
Out[87]=
clip.avi
In[88]:=
Import@"clip.avi", "Animation"D
>
15
16
MahtematicaDataIO.nb
Out[88]=
MahtematicaDataIO.nb
17
18
MahtematicaDataIO.nb
以下,2つの例も同様.計算して得られた複数の画像をリストで用意し,そこからAVIファイルを作成.
In[89]:=
Table@ArrayPlot@Table@Mod@Binomial@i, jD, nD, 8i, 30<, 8j, 30<D, ImageSize ® 100D, 8n, 2, 10<D
Out[89]=
:
,
,
,
,
,
,
,
>
In[90]:=
Export@"tri.avi", %, "AVI"D
Out[90]=
tri.avi
In[91]:=
Import@"tri.avi", "Animation"D
,
Out[91]=
In[92]:=
a=
Table@ArrayPlot@First@CellularAutomaton@8746, 82, 882, 2, 2<, 82, 1, 2<, 82, 2, 2<<<, 81, 1<<,
8881, 1, 1, 1, 1, 1, 1<<, 0<, x, - 1DD, ImageSize ® 128,
Frame ® False, ColorRules ® 81 ® Hue@x  400D, 0 ® White<D, 8x, 10, 400, 10<D;
In[93]:=
Export@"ca.avi", aD
Out[93]=
ca.avi
MahtematicaDataIO.nb
In[94]:=
Import@"ca.avi", 8"Frames", 810, 30<<D
Out[94]=
:
In[95]:=
Import@"ca.avi", "Animation"D
Out[95]=
,
>
19
20
MahtematicaDataIO.nb
Ÿ Math Form: TEX, MathML
ref. MathML( XML/tutorial/MathML)
b
In[96]:=
TeXFormBHoldFormBà x â xFF
a
Out[96]//TeXForm=
\int_a^b x \, dx
In[97]:=
Export@"exp.tex", %D
Out[97]=
exp.tex
In[98]:=
FilePrint@"exp.tex"D
%% AMS-LaTeX Created by Wolfram Mathematica 7.0 : www.wolfram.com
\documentclass{article}
\usepackage{amsmath, amssymb, graphics}
\newcommand{\mathsym}[1]{{}}
\newcommand{\unicode}[1]{{}}
\begin{document}
\[\int_a^b x \, dx\]
\end{document}
b
In[99]:=
MathMLFormBHoldFormBà x â xFF  Short
a
Out[99]//Short=
<math>
<mrow>
<msubsup>
<mo>&ð8747;<mo> … i>x<mi>
<mrow>
<mrow>
<mrow>
<math>
In[100]:=
Out[100]=
ToExpression@"\\sqrt8x y<", TeXFormD
xy
Ÿ Export/ImportString
In[101]:=
Clear@a, b, xD
MahtematicaDataIO.nb
b
In[102]:=
ExportStringBà x â x, "TeX"F
a
%% AMS-LaTeX Created by Wolfram Mathematica 7.0 : www.wolfram.com
Out[102]=
\documentclass8article<
\usepackage8amsmath, amssymb, graphics<
\newcommand8\mathsym<@1D88<<
\newcommand8\unicode<@1D88<<
\begin8document<
\@-\frac8a^2<82<+\frac8b^2<82<\D
\end8document<
In[103]:=
ImportString@"3,4,6\na,b,c", "Table"D
883,4,6<, 8a,b,c<<
Out[103]=
Ÿ XML
In[104]:=
Out[104]=
ImportString@"<a><b bb='1'>ss<b><b bb='2'>ss<b><a>", "XML"D
XMLObject@DocumentD@8<,
XMLElement@a, 8<, 8XMLElement@b, 8bb ® 1<, 8ss<D, XMLElement@b, 8bb ® 2<, 8ss<D<D, 8<D
Ÿ Mathematica式のWord2007への貼付け
双方はMathML形式で互換性があるようである(推定).方法は単純.Mathematicaの式が表示されたセルをコ
ピーし,Word上で貼付けるだけ.表示はビットマップではないので,拡大縮小しても画質は劣化しない.
21
22
MahtematicaDataIO.nb
ReadList/Read
ref. tutorial  ReadingTextualData
Import[]と異なり,データをレコード(行)単位で読んだり,指定した要素数で読む時などに便利.
Ÿ Real Number
In[105]:=
FilePrint@"ExampleDatanumbers"D
11.1
22.2
33.3
44.4
55.5
66.6
In[106]:=
Import@"ExampleDatanumbers", "Table"D H* 全体として読む場合に利用 *L
Out[106]=
8811.1, 22.2, 33.3<, 844.4, 55.5, 66.6<<
In[107]:=
ReadList@"ExampleDatanumbers", NumberD
Out[107]=
In[108]:=
Out[108]=
In[109]:=
Out[109]=
811.1, 22.2, 33.3, 44.4, 55.5, 66.6<
ReadList@"ExampleDatanumbers", 8Number, Number<D
H* 元は2行3列のデータであるが,2要素ずつのリストで読む.*L
8811.1, 22.2<, 833.3, 44.4<, 855.5, 66.6<<
ReadList@"ExampleDatanumbers", Number, RecordLists -> TrueD
8811.1, 22.2, 33.3<, 844.4, 55.5, 66.6<<
Ÿ BigNum
In[110]:=
FilePrint@"ExampleDatabignum"D
4.5E-5
7.8E4
2.5E2
In[111]:=
Out[111]=
-8.9
ReadList@"ExampleDatabignum", NumberD
80.000045, 78 000., 250., - 8.9<
Ÿ 文字列
In[112]:=
FilePrint@"ExampleDatastrings"D
Here is text.
And more text.
MahtematicaDataIO.nb
In[113]:=
Out[113]=
In[114]:=
Out[114]=
In[115]:=
Out[115]=
In[116]:=
Out[116]=
In[117]:=
Out[117]=
In[118]:=
ReadList@"ExampleDatastrings", CharacterD
H* t,., , Windowsと異なり復帰と改行2つの文字が文末に存在 *L
8H, e, r, e, , i, s, , t, e, x, t, ., ,
,
, A, n, d, , m, o, r, e, , t, e, x, t, .,
,
<
ReadList@"ExampleDatastrings", ByteD
872, 101, 114, 101, 32, 105, 115, 32, 116, 101, 120, 116, 46, 32, 13,
10, 65, 110, 100, 32, 109, 111, 114, 101, 32, 116, 101, 120, 116, 46, 13, 10<
ReadList@"ExampleDatastrings", Byte, RecordLists -> TrueD
H* レコード形式で読んでいるんで復帰コード13と改行コード10は含まれない.*L
8872, 101, 114, 101, 32, 105, 115, 32, 116, 101, 120, 116, 46, 32<,
865, 110, 100, 32, 109, 111, 114, 101, 32, 116, 101, 120, 116, 46<<
ReadList@"ExampleDatastrings", WordD
8Here, is, text., And, more, text.<
ReadList@"ExampleDatastrings", Word, WordSeparators -> 8"e", "."<D
H* e と. で分離された語の単位で読み込まれる *L
8H, r, is t, xt, , And mor, t, xt<
ReadList@"ExampleDatastrings", RecordD  InputForm H* 文字列のøが入る *L
Out[118]//InputForm=
{"Here is text. ", "And more text."}
Ÿ 文 Sentence
In[119]:=
Out[119]=
In[120]:=
ReadList@"ExampleDatasentences", CharacterD
8H, e, r, e, , i, s, , t, e, x, t, ., , A, n, d, , m, o, r, e, .,
,
, A, n, d, , a, , s, e, c, o, n, d, , l, i, n, e, .,
,
<
FilePrint@"ExampleDatasentences"D
Here is text. And more.
And a second line.
In[121]:=
Out[121]=
In[122]:=
Out[122]=
ReadList@"ExampleDatasentences", Record, RecordSeparators -> 8".", "\n"<D
H* MacOSでは改行コード以外に復帰コードがあるため,,が一個余計につく. *L
8Here is text, And more,
, And a second line,
<
ReadList@"ExampleDatasentences", Word, RecordLists -> True, RecordSeparators -> 8".", "\n"<D
88Here, is, text<, 8And, more<, 8
<, 8And, a, second, line<, 8
<<
23
24
MahtematicaDataIO.nb
In[123]:=
Out[123]=
Directory@D
UsersmatsudaAppstest
Ÿ 日本語ファイルの場合
In[124]:=
Out[124]=
In[125]:=
Out[125]=
J = FromCharacterCode@ToCharacterCode@ðD, "ShiftJIS"D & ž ReadList@"j.txt", StringD
9日本語テキストの例。, うまく処理されるかな。=
StringSplitAð, 9"。", "語"=E & ž J
99日本, テキストの例=, 9うまく処理されるかな==
Ÿ command
In[126]:=
Out[126]=
ReadList@"!date", StringD
8Wed Sep
2 08:15:18 JST 2009<
Ÿ Read
ReadListよりさらに細かい制御が可能.要素一つを読み込んだり,読み飛ばしたり(Skip[]),ReadList[]と組み合わせた
り.この場合は,残り全部を読み取る.
In[127]:=
FilePrint@"ExampleDatanumbers"D
11.1
22.2
33.3
44.4
55.5
66.6
In[128]:=
snum = OpenRead@"ExampleDatanumbers"D
Out[128]=
InputStream@ExampleDatanumbers, 246D
In[129]:=
Out[129]=
In[130]:=
Out[130]=
Read@snum, NumberD H* read from the stream, not from the file *L
11.1
Read@snum, 8Number, Number<D
822.2, 33.3<
In[131]:=
Skip@snum, NumberD
In[132]:=
ReadList@snum, NumberD
Out[132]=
In[133]:=
Out[133]=
855.5, 66.6<
Close@snumD
ExampleDatanumbers
Ÿ WordData
ref. guide/LinguisticData
MahtematicaDataIO.nb
In[134]:=
Out[134]=
25
WordData@"fish", "Synonyms"D
88fish, Noun, AquaticVertebrate< ® 8<, 8fish, Noun, Food< ® 8<,
8fish, Verb, Grab< ® 8<, 8fish, Verb, Search< ® 8angle<<
Find/FindList
ref. tutorial/SearchingFiles
ReadList/Readと同じ.ただし,条件付きで読んでくる.日本語ファイルの場合,読み取る「途中」で文字コード処理
が不可能なので,いったん,全体を文字列をして読み込んで,それから文字コード変換する方法を採用.
In[135]:=
FilePrint@"ExampleDatatextfile"D
Here is the first line of text.
And the second.
And the third. Here is the end.
In[136]:=
Out[136]=
In[137]:=
Out[137]=
FindList@"ExampleDatatextfile", "is"D
8Here is the first line of text., And the third. Here is the end.<
FindList@"ExampleDatatextfile", "And", RecordSeparators -> 8"."<D
8
And the second,
And the third<
In[138]:=
Out[138]=
In[139]:=
Out[139]=
In[140]:=
Out[140]=
FindList@"ExampleDatatextfile", "Here", AnchoredSearch -> TrueD
H* at the beginning of of a record *L
8Here is the first line of text.<
FindList@"ExampleDatatextfile", "th"D
8Here is the first line of text., And the second., And the third. Here is the end.<
FindList@"ExampleDatatextfile", "th", WordSearch -> TrueD
8<
In[141]:=
FindList@8"ExampleDatatextfile", "ExampleDatatextfile"<, "third"D
Out[141]=
8And the third. Here is the end., And the third. Here is the end.<
In[142]:=
stext = OpenRead@"ExampleDatatextfile"D
Out[142]=
InputStream@ExampleDatatextfile, 287D
In[143]:=
Out[143]=
In[144]:=
Out[144]=
Find@stext, "And"D H* Read records until the first pattern appears *L
And the second.
Find@stext, "And"D
And the third. Here is the end.
26
MahtematicaDataIO.nb
In[145]:=
Out[145]=
Close@stextD
ExampleDatatextfile
In[146]:=
stext = OpenRead@"ExampleDatatextfile"D
Out[146]=
InputStream@ExampleDatatextfile, 288D
In[147]:=
Out[147]=
Read@stext, WordD
Here
In[148]:=
Skip@stext, Word, 4D
In[149]:=
Find@stext, "is"D
Out[149]=
In[150]:=
Out[150]=
And the third. Here is the end.
Close@stextD
ExampleDatatextfile
In[151]:=
stext = OpenRead@"ExampleDatatextfile"D
Out[151]=
InputStream@ExampleDatatextfile, 289D
In[152]:=
Out[152]=
In[153]:=
Out[153]=
In[154]:=
Out[154]=
In[155]:=
Out[155]=
In[156]:=
Out[156]=
In[157]:=
Out[157]=
StreamPosition@stextD
0
Read@stext, RecordD
Here is the first line of text.
StreamPosition@stextD
31
SetStreamPosition@stext, 5DH* set the position back *L
5
Read@stext, RecordD
is the first line of text.
Close@stextD
ExampleDatatextfile
BinaryRead/Write
ref. BianryData
FortranなどでUnformattedで作られたデータ,あるいはEndian(Byte order)が異なるデータを読み出す場合重要.
In[158]:=
8$ByteOrdering , $ProcessorType< H* Endian *L
Out[158]=
8- 1, x86-64<
In[159]:=
file = "temp";
サンプルとして12345を32ビット整数のバイナリ形式でファイルに保存.
MahtematicaDataIO.nb
27
サンプルとして12345を32ビット整数のバイナリ形式でファイルに保存.
In[160]:=
BinaryWrite@file, 12 345, "Integer32"D; Close@fileD;
Unix command od(octal dump)でバイナリの内容を10進数で表示,それをファイルaに保存.
In[161]:=
Out[161]=
In[162]:=
Run@"od -d temp > a"D H* -d:digit, -a:ascii, -c:character *L
0
FilePrint@"a"D
0000000
0000004
12345
0
元の数を16進数表示させてみてバイトオーダを確認.
In[163]:=
BaseForm@12 345, 16D
Out[163]//BaseForm=
303916
本来のバイトオーダで読んでみる.
In[164]:=
Out[164]=
In[165]:=
BinaryRead@file, "Integer32", ByteOrdering -> $ByteOrderingD
12 345
Close@fileD;
逆のバイトオーダで読んでみる.一見,わからないが,この数は次の式で16進表示させてみると,バイトオーダが逆
になっていることが確認できる.
In[166]:=
Out[166]=
In[167]:=
BinaryRead@file, "Integer32", ByteOrdering -> - $ByteOrderingD
959 447 040
BaseForm@%, 16D
Out[167]//BaseForm=
3930000016
そこで元に戻すために,1バイトずつに区切って,これを逆順に並べ替え,1バイトをベースに整数に戻すと確かにう
まくいく.
In[168]:=
Out[168]=
In[169]:=
Out[169]=
IntegerDigits@%, 256D H* 2^8 *L
857, 48, 0, 0<
FromDigits@Reverse@%D, 256D
12 345
In[170]:=
Close@fileD;
In[171]:=
file = "temp2";
バイナリデータを異なる形式(バイト,文字,整数)で読んでみた場合の例.
In[172]:=
BinaryWrite@file, 88, 97, 255<D; Close@fileD;
28
MahtematicaDataIO.nb
In[173]:=
Out[173]=
In[174]:=
Out[174]=
BinaryReadList@fileD
88, 97, 255<
BinaryReadList@file, 8"Byte", "Character8", "Integer8"<D
888, a, - 1<<
外部プログラムの実行
!, Run, RunThrough
Ÿ ReadList
In[175]:=
ReadList@"!ls -l", StringD  Short@ð, 10D &  TableForm
Out[175]//TableForm=
8total 22056, drwxr-xr-x
6 matsuda matsuda
204 Aug 25 19:28 HTMLFiles,
drwxr-xr-x
2 matsuda matsuda
68 Aug 25 19:28 HTMLLinks,
-rw-r--r-1 matsuda matsuda
30099 Sep 2 08:14 M.csv,
-rw-r--r-1 matsuda matsuda
30099 Sep 2 08:14 M.dat,
-rw-r--r-1 matsuda matsuda 8000268 Sep 2 08:14 M.dump,
†13‡, -rw-r--r-1 matsuda matsuda
4 Sep 2 08:15 temp,
-rw-r--r-1 matsuda matsuda
3 Sep 2 08:15 temp2,
-rw-r--r-1 matsuda matsuda
132 Aug 28 09:32 test.c,
-rw-r--r-1 matsuda matsuda
112 Aug 26 11:37 test.mc,
-rw-r--r-1 matsuda matsuda
75 Sep 2 08:14 tmp,
-rw-r--r-1 matsuda matsuda
272272 Sep 2 08:15 tri.avi<
Ÿ FindList
In[176]:=
Out[176]=
In[177]:=
Out[177]=
ReadList@"!date", StringD
8Wed Sep
2 08:15:40 JST 2009<
FindList@"!date", ":", RecordSeparators -> 8" "<D
808:15:40<
Ÿ RunTrough
ノートブックの外でMath Kernelに計算させる式を渡し,その結果をファイルに保存する例. Unevaluated[]はその後の
式を評価せずそのまま渡すために必要.
In[178]:=
Out[178]=
$CommandLine
8ApplicationsMathematica.appContentsMacOSMathKernel, -mathlink,
-linkmode, connect, -linkprotocol, SharedMemory, -linkname, f5k_shm<
In[179]:=
mathcommand = StringReplace@First@$CommandLineD, "MathKernel" ® "math"D;
outputfile = "rtout";
RunThrough@mathcommand <> " -noprompt", Unevaluated@Put@Factorial@47D, "rtout"DDD
In[182]:=
FilePrint@outputfileD
258623241511168180642964355153611979969197632389120000000000
MahtematicaDataIO.nb
In[183]:=
29
DeleteFile@outputfileD
Ÿ URL
In[184]:=
SystemOpen@"http:www.wolfram.com"D
Splice
拡張子(下記の例では mとc)をみてその言語に対応した形式に変換.以下の例では,<*....*>内の Mathematica の式
を評価し,その「結果」を該当言語の形式で書き出す.
In[185]:=
FilePrint@"test.mc"D
#include "mdefs.h"
double f(x)
double x;
{
double y;
y = <* Integrate[Sin[x]^5, x] *> ;
return(2*y - 1) ;
}
In[186]:=
Out[186]=
In[187]:=
Splice@"test.mc"D
test.mc
FilePrint@"test.c"D
#include "mdefs.h"
double f(x)
double x;
{
double y;
y = (-5*Cos(x))/8. + (5*Cos(3*x))/48. - Cos(5*x)/80. ;
return(2*y - 1) ;
}
画像処理ImageProcessing
ref. guide/ImageProcessing
信号処理Signal Processing
ref. guide/SignalProcessing
Deploy
左側の円はグラフィックスとして操作対象となってる.一方,右側の円は中のスライド以外は操作不能.
30
MahtematicaDataIO.nb
In[188]:=
Out[188]=
8Graphics@8Disk@D, Inset@Slider2D@DD<D, Deploy@Graphics@8Disk@D, Inset@Slider2D@DD<DD<
:
,
>
あらかじめ用意されている科学/技術データ
ref. guide/ScientificAndTechnicalData
Physical & Chemical Data
ElementData — bulk, atomic, chemical, etc. properties of chemical elements
ChemicalData — structural, physical and other properties of chemical compounds
IsotopeData — static and decay properties of all nuclear isotopes
MahtematicaDataIO.nb
31
IsotopeData — static and decay properties of all nuclear isotopes
ParticleData — properties of stable, unstable and resonance particles
Earth & Astronomical Data
WeatherData — full current and historical worldwide weather data
GeodesyData — data on geodetic coordinate systems, geoid shapes, etc.
CityData ä CountryData ä GeoDistance
AstronomicalData — static and dynamic properties of stars, planets and other objects
Life Science Data
GenomeData — properties of human and other genes
GenomeLookup — fast lookup of human and other genome sequences
SequenceAlignment ä SmithWatermanSimilarity ä ...
ProteinData — protein structure and function
SQL Database
Mathematica が対象とするSQL言語(あるいは想定されるデータベースの形式)については,この資料作者の理解の
範囲外.後日,判明した場合,情報を修正・追加の予定.対象となるデータベース一覧は下記リンク先のAppendixを
参照のこと.
ref. DatabaseLink/tutorial/Overview
Ÿ Using the Example Databases
ref. DatabaseLink  tutorial  UsingTheExampleDatabases
In[189]:=
Out[189]=
ToFileName@ 8$UserBaseDirectory, "DatabaseResources"<, "Examples"D
UsersmatsudaLibraryMathematicaDatabaseResourcesExamples
In[190]:=
<< DatabaseLink`DatabaseExamples`;
In[191]:=
DatabaseExamplesBuild@ D
Ÿ Loading the Package
ref. DatabaseLink/tutorial/GettingStarted
In[192]:=
Needs@"DatabaseLink`"D
Ÿ Connecting to the Database
In[193]:=
Out[193]=
conn = OpenSQLConnection@"demo"D
SQLConnection@demo, 3, Open, TransactionIsolationLevel ® ReadCommittedD
Ÿ Fetching Data
32
MahtematicaDataIO.nb
Fetching Data
In[194]:=
Out[194]=
In[195]:=
Out[195]=
In[196]:=
Out[196]=
In[197]:=
SQLTables@connD
8SQLTable@SAMPLETABLE1, TableType ® TABLED<
SQLColumns@conn, "SAMPLETABLE1"D
8SQLColumn@8SAMPLETABLE1, ENTRY<, DataTypeName ® INTEGER, Nullable ® 1, DataLength ® NullD,
SQLColumn@8SAMPLETABLE1, VALUE<, DataTypeName ® DOUBLE, Nullable ® 1, DataLength ® NullD,
SQLColumn@8SAMPLETABLE1, NAME<, DataTypeName ® VARCHAR,
Nullable ® 1, DataLength ® 2 147 483 647D<
data = SQLSelect@ conn, "SAMPLETABLE1"D
881, 5.6, Day1<, 82, 5.9, Day2<, 83, 7.2, Day3<, 84, 6.2, Day4<, 85, 6., Day5<<
ListLinePlot@data@@All, 2DD, ImageSize ® 200D
7.0
Out[197]=
6.5
1
In[198]:=
2
3
4
5
SQLSelect@ conn, "SAMPLETABLE1", "ShowColumnHeadings" ® TrueD  TableForm
Out[198]//TableForm=
ENTRY
1
2
3
4
5
In[199]:=
Out[199]=
VALUE
5.6
5.9
7.2
6.2
6.
NAME
Day1
Day2
Day3
Day4
Day5
SQLExecute@ conn, "SELECT * FROM SAMPLETABLE1"D
881, 5.6, Day1<, 82, 5.9, Day2<, 83, 7.2, Day3<, 84, 6.2, Day4<, 85, 6., Day5<<
Ÿ Inserting Data
In[200]:=
Out[200]=
In[201]:=
SQLInsert@ conn, "SAMPLETABLE1", 8"ENTRY", "VALUE", "NAME"<, 86, 8.2, "Day6"<D
1
SQLSelect@ conn, "SAMPLETABLE1", "ShowColumnHeadings" ® TrueD  TableForm
Out[201]//TableForm=
ENTRY
1
2
3
4
5
6
Ÿ
VALUE
5.6
5.9
7.2
6.2
6.
8.2
NAME
Day1
Day2
Day3
Day4
Day5
Day6
MahtematicaDataIO.nb
In[202]:=
Out[202]=
33
SQLExecute@ conn, "INSERT INTO SAMPLETABLE1HENTRY, VALUE, NAMEL VALUES H7, 6.9, 'Day7'L"D
1
通常,キー(今の場合,ENTRY, VALUE, NAME)を文字列として結合して検査に使用.その負荷を避けるため,あ
らかじめスロットを決めておくことが可能.それが(`1`, `2`, `3`).これがあるため,レコードと値の関係が容易に対応
ずけ可能となる.
In[203]:=
Out[203]=
In[204]:=
Out[204]=
SQLExecute@ conn,
"INSERT INTO SAMPLETABLE1HENTRY, VALUE, NAMEL VALUES H`1`, `2`, `3`L", 88, 10.5, "Day8"<D
1
SQLExecute@ conn, "SELECT * FROM SAMPLETABLE1"D
881, 5.6, Day1<, 82, 5.9, Day2<, 83, 7.2, Day3<, 84, 6.2, Day4<,
85, 6., Day5<, 86, 8.2, Day6<, 87, 6.9, Day7<, 88, 10.5, Day8<<
Ÿ Updating Data
In[205]:=
Out[205]=
In[206]:=
SQLUpdate@ conn, "SAMPLETABLE1", 8"VALUE"<, 87<, SQLColumn@"VALUE"D > 8D
2
SQLSelect@ conn, "SAMPLETABLE1", "ShowColumnHeadings" ® TrueD  TableForm
Out[206]//TableForm=
ENTRY
1
2
3
4
5
7
6
8
In[207]:=
Out[207]=
In[208]:=
Out[208]=
VALUE
5.6
5.9
7.2
6.2
6.
6.9
7.
7.
NAME
Day1
Day2
Day3
Day4
Day5
Day7
Day6
Day8
SQLExecute@ conn, "UPDATE SAMPLETABLE1 SET VALUE = `1` WHERE VALUE >= `2`", 87, 6<D
6
SQLExecute@ conn, "SELECT * FROM SAMPLETABLE1"D
881, 5.6, Day1<, 82, 5.9, Day2<, 83, 7., Day3<, 84, 7., Day4<,
85, 7., Day5<, 87, 7., Day7<, 86, 7., Day6<, 88, 7., Day8<<
Ÿ Deleting Data
In[209]:=
Out[209]=
In[210]:=
SQLDelete@ conn, "SAMPLETABLE1", SQLColumn@"VALUE"D ³ 7D
6
SQLSelect@ conn, "SAMPLETABLE1", "ShowColumnHeadings" ® TrueD  TableForm
Out[210]//TableForm=
ENTRY VALUE NAME
1
5.6
Day1
2
5.9
Day2
34
MahtematicaDataIO.nb
In[211]:=
Out[211]=
In[212]:=
Out[212]=
SQLExecute@ conn, "DELETE FROM SAMPLETABLE1 WHERE VALUE > 5.7"D
1
SQLExecute@ conn, "SELECT * FROM SAMPLETABLE1"D
881, 5.6, Day1<<
Ÿ Batch Commands
In[213]:=
Out[213]=
In[214]:=
Out[214]=
SQLExecute@ conn, "INSERT INTO SAMPLETABLE1HENTRY, VALUE, NAMEL VALUES H`1`, `2`, `3`L",
884, 6.2, "Day4"<, 85, 6., "Day5"<<D
81, 1<
SQLExecute@ conn, "SELECT * FROM SAMPLETABLE1"D
881, 5.6, Day1<, 84, 6.2, Day4<, 85, 6., Day5<<
Ÿ Closing the Connection
In[215]:=
In[216]:=
CloseSQLConnection@connD
Fly UP