babel: linking back to the index page
[Worg.git] / org-contrib / babel / uses.org
1 #+OPTIONS:    H:3 num:nil toc:1 \n:nil @:t ::t |:t ^:{} -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+OPTIONS:    H:3 num:nil toc:1 \n:nil @:t ::t |:t ^:{} -:t f:t *:t TeX:t LaTeX:nil skip:nil d:(HIDE) tags:not-in-toc
3 #+STARTUP:    align fold nodlcheck hidestars oddeven lognotestate hideblocks
4 #+SEQ_TODO:   TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
5 #+TAGS:       Write(w) Update(u) Fix(f) Check(c) 
6 #+TITLE:      Org-babel: Uses
7 #+AUTHOR:     Thomas S. Dye
8 #+EMAIL:      tsd at tsdye dot com
9 #+LANGUAGE:   en
10 #+STYLE:      <style type="text/css">#outline-container-introduction{ clear:both; }</style>
11
12 [[file:index.org][{Back to Babel's index}]]
13
14 * Introduction
15   Org-babel might be described as a literate meta-language programming
16   environment for Emacs.  It leverages Org-mode for its user interface
17   and its ability to export directly to HTML and LaTeX.  It extends
18   Org-mode source code blocks by making them executable, with several
19   options for handling the results of execution.  Org-babel is
20   described by one of its authors as language agnostic; the source
21   code blocks in a document can be written in a growing list of
22   supported languages.  A document can contain source code blocks in
23   as many languages as are needed to complete the task at hand, and
24   the results of a source code block in one language can be passed to
25   a source code block in another language.  All of this is
26   accomplished with a simple syntax and a few easily mastered options.
27
28   This combination of attributes opens up so many use options that the
29   possibilities sometimes seem endless.  This document sets out some
30   scenarios of Org-babel use.  It is designed to explore a few
31   dimensions of Org-babel's use-space, with the hope that others might
32   be inspired to explore and share other dimensions of that space.
33
34   The following sections each describe a particular use scenario: the
35   problem that it was designed to solve; its software requirements;
36   its advantages and disadvantages compared to alternative approaches;
37   and a toy example meant to illustrate the structure of the Org-mode
38   file and Org-babel's place within it, and not to emulate a
39   real-world application.  The initial examples were written primarily
40   to explore the uses of LaTeX source code blocks in Org-babel, but a
41   multi-language example that mixes LaTeX and R is also included.
42   Hopefully, Org-babel users who write in other supported languages
43   can supply examples of other work-flows.
44   
45
46 * Data Collection and Analysis
47   This example uses Org-babel to automate a repeated data-collection
48   and analysis task.  A Ruby code block is used to scrape data from
49   the output of a computational experiment.  This data is then written
50   to an Org-mode table.  A block of R code reads from this table and
51   calculates lines of fit.  Finally a block of gnuplot code is used to
52   graph the results of both the raw data and the R analysis.  By
53   performing all of these steps within an Org-mode document working
54   notes, discussion, and TODOs can be naturally interspersed with the
55   code, and the results can easily be published to HTML or PDF for
56   distribution.
57
58 ** Requirement
59    - A working [[http://www.ruby-lang.org/en/][Ruby]] installation
60    - A working [[http://www.r-project.org/][R]] installation
61    - A working [[http://www.gnuplot.info/][gnuplot]] installation
62
63 ** Advantages
64    - Org-babel handles passing the data between different programming
65      languages
66    - Raw data persists in tables in the Org-mode file
67    - Working notes can be collocated with the code/results to which
68      they refer
69    - Tasks can be saved and updated from within the same file in which
70      the work is being performed
71    - Org-mode exporting facilities can be used to export the results
72      to HTML or PDF for distribution
73
74 ** Disadvantages
75    - This approach can allow the experimenter to use whatever language
76      is most comfortable for each sub-task, sometimes resulting in an
77      overly complicated work flow.  For example, in the example below I
78      did not have to learn how to calculate the mean and standard
79      deviation in R since it was easier for me to do so in Ruby even
80      though a full R solution would have been more efficient.
81
82 ** Example
83
84 *** Code for running experiment and collecting the results
85
86     This portion will not be repeatable as it would require the
87     entire experimental setup.  It is provided for demonstration.
88
89     *Ruby* run-timer-test: Runs the actual experiment.  This is
90     tangled to an external file and run on the command line -- since
91     these runs can take several days, I prefer to run them 
92     outside of Emacs (normally using [[http://www.gnu.org/software/screen/][screen]]).
93 #+srcname: run-timer-test
94 #+begin_src ruby :results silent :tangle timer :exports code
95   DEFAULT_CMDLINE = "--swap 0 --del 0 --mut 0.1 example.c "
96   
97   def run_and_package(cmdline, package)
98     puts "#{package}: ../modify #{cmdline}"
99     start_time = Time.now
100     %x{../modify #{cmdline}}
101     total_time = Time.now - start_time
102     %x{echo "wall clock #{total_time}" >> gcd.c-.debug}
103     %x{rake package[#{package}]}
104   end
105   
106   100.times do |n|
107     # run with default options
108     run_and_package(DEFAULT_CMDLINE, "normal_#{n}")
109     run_and_package("--pll_fit 2 "+DEFAULT_CMDLINE, "pll_2_#{n}")
110     run_and_package("--pll_fit 3 "+DEFAULT_CMDLINE, "pll_3_#{n}")
111     run_and_package("--pll_fit 4 "+DEFAULT_CMDLINE, "pll_4_#{n}")
112     run_and_package("--pll_fit 5 "+DEFAULT_CMDLINE, "pll_5_#{n}")
113     run_and_package("--pll_fit 6 "+DEFAULT_CMDLINE, "pll_6_#{n}")
114     run_and_package("--pll_fit 7 "+DEFAULT_CMDLINE, "pll_7_#{n}")
115     run_and_package("--pll_fit 8 "+DEFAULT_CMDLINE, "pll_8_#{n}")
116   end
117 #+end_src
118
119     *Ruby* parse-output: The execution of =run-timer-test= leaves
120     results distributed across many text log files.  The following
121     Ruby source code block is
122     used to collect results from these files and dump them into an
123     Org-mode file as a table.
124 #+srcname: parse-output
125 #+begin_src ruby :results output raw :exports code
126   def look(path)
127     processors = if path.match(/normal/)
128                    "1"
129                  elsif path.match(/pll_(\d+)_/)
130                    $1
131                  else
132                    0
133                  end
134     results = File.read(File.join(path, "gcd.c-.debug"))
135     generations =  results.match(/^Generations to solution: (\d+)/) ? Integer($1) : -1
136     total = results.match(/^ +TOTAL +([\d\.]+) /) ? Float($1) : -1
137     wall = results.match(/^wall clock ([\d\.]+)/) ? Float($1) : -1
138     fitness = results.match(/^ +fitness +([\d\.]+) +([\d\.]+) /) ? Float($2) : -1
139     mutation = results.match(/^ +mutation +([\d\.]+) +([\d\.]+) /) ? Float($2) : -1
140     [path, processors, total, wall, good_test, bad_test, compile, fitness, generations]
141   end
142   
143   # puts "| path | processors | total | wall | fitness | mutation | generations |"
144   # puts "|-----------"
145   
146   Dir.entries('./').select{|e| e.match(/[normalpll]+[_\d]+/)}.
147     map{|e| look(e)}.each{|row| puts "| "+row.join(" | ")+" |"}
148 #+end_src
149
150 *** Data
151     Here is fake example output from the =parse-output= Ruby source
152     code block above.
153
154 #+tblname: example-data
155 | normal_0  | 1 | 150.264 | 150.631066 | 163.0 | 1 |
156 | pll_2_0   | 2 |  40.025 |  40.698944 |  39.0 | 3 |
157 | pll_3_0   | 3 |   2.504 |  31.214553 |   2.0 | 1 |
158 | normal_5  | 1 |   1.499 |   1.866362 |   2.0 | 2 |
159 | pll_2_16  | 2 |    1.43 |   1.985152 |   1.0 | 1 |
160 | normal_31 | 1 |   1.501 |   1.867453 |   2.0 | 1 |
161 | pll_2_29  | 2 |   1.431 |   1.978312 |   1.0 | 1 |
162 | normal_22 | 1 |   4.562 |   4.929897 |   3.0 | 3 |
163 | pll_4_5   | 4 |   3.609 |   6.953026 |   4.0 | 1 |
164 | normal_4  | 1 | 161.097 | 161.464041 | 181.0 | 1 |
165 | pll_3_3   | 3 |   1.751 |  33.819836 |   2.0 | 1 |
166 | pll_4_2   | 4 |  99.546 |  102.20237 |  72.0 | 2 |
167 | pll_4_1   | 4 |   5.502 |  19.875383 |   3.0 | 1 |
168 | pll_3_1   | 3 |   1.976 |   3.540565 |   2.0 | 2 |
169 | pll_3_6   | 3 |   1.433 |   2.018572 |   1.0 | 1 |
170
171 *** Analysis
172     The code blocks in this section will be repeatable as they rely on
173     the fake data given above.
174
175     *Ruby* calculate mean and standard deviation over the second column
176 #+srcname: stddev
177 #+begin_src ruby :var raw=example-data :results raw output :exports code
178   by_procs = {}
179   raw.each do |row|
180     by_procs[row[1]] ||= []
181     by_procs[row[1]] << row[3]
182   end
183
184   by_procs.each do |key, vals|
185     mean = vals.inject(0){|sum, n| sum + n} / vals.size
186     stddev = Math.sqrt(vals.inject(0){|sum, n| sum + ((n - mean).abs * (n - mean).abs)} / vals.size)
187     puts "| #{key} | #{mean} | #{stddev} |"
188   end
189 #+end_src
190
191 #+results: example-stddev
192 | 1 |       64.1517638 | 75.1190856698136 |
193 | 2 | 14.8874693333333 | 18.2514689828405 |
194 | 3 |       17.6483815 | 14.9070317402304 |
195 | 4 | 43.0102596666667 | 42.1863032424348 |
196
197     *R* find the curve that best fits these data
198 #+begin_src R :session R :exports code :var data=example-stddev :results output
199   procs <- data$V1
200   times <- data$V2
201   df <- data.frame(procs, times)
202   nlsfit <- nls(times~c0 + (load/procs), data=df, start=list(load = 100, c0 = 20))
203   summary(nlsfit)
204 #+end_src
205
206 #+results:
207 #+begin_example
208 Formula: times ~ c0 + (load/procs)
209
210 Parameters:
211      Estimate Std. Error t value Pr(>|t|)
212 load    45.70      36.71   1.245    0.339
213 c0      11.12      21.90   0.508    0.662
214
215 Residual standard error: 21.36 on 2 degrees of freedom
216
217 Number of iterations to convergence: 1 
218 Achieved convergence tolerance: 3.924e-08
219 #+end_example
220
221     *gnuplot* plot the raw data, along with the error bars and the best
222     fit curve
223 #+begin_src gnuplot :var data=example-data :var mydata=example-stddev :exports code
224   set xrange [0.5:5]
225   set yrange [0:]
226   set ylabel "seconds"
227   set xlabel "processes"
228   plot data using 2:4 with points title 'raw' linecolor 8
229   replot mydata using 1:2:3 with errorbars title 'error' linecolor 1
230   replot 11.12 + 45.70/x title 'fit'
231 #+end_src
232
233     Which produces the following [[file:../../images/babel/example-graph.png]]
234
235 *** Distribution
236     Using Org-mode's exporting capabilities it is easy to publish the
237     entire working file including source-code and raw data, to share
238     sections using `org-narrow-to-subtree', or even to share
239     individual tables or graphs.
240
241
242 * A LaTeX Form
243   This example uses Org-babel as a user interface for a LaTeX form
244   that might be used by the members of an organization.  It uses the
245   literate programming facility of Org-babel to isolate the user from
246   the sometimes arcane LaTeX constructs needed to create a
247   highly-structured form.  Org-babel can tangle multiple documents in
248   a single Org-mode file, and this ability is used to create a
249   distribution version of the form separate from one designed for the
250   file cabinet.
251
252 ** Requirement
253    - A working LaTeX installation.
254
255 ** Advantages
256    - User is isolated from the LaTeX code and thus less likely to
257      alter it inadvertently.
258    - Multiple versions of the document are created automatically.
259    - Org-mode keywords can help track data entry progress.
260
261 ** Disadvantages
262    - This approach is somewhat dated.  A modern organization might
263      accomplish this more cleanly with a web-based interface to a database.
264
265 ** Example
266
267 *** TODO Your name
268     - Enter your full name on the open line below.
269 #+srcname: your-name
270 #+begin_src latex
271 Tom Dye
272 #+end_src
273
274 *** TODO Your email address
275     - Enter your email address on the open line below.
276 #+srcname: your-email
277 #+begin_src latex
278 tsd at tsdye dot com
279 #+end_src
280
281 *** No data entry below this line
282     - The two source blocks here each produce a LaTeX document after
283       they are tangled with a call to =org-babel-tangle=.
284
285 #+begin_src latex :noweb :tangle dist-form.tex 
286   \documentclass[12pt]{article}
287   \begin{document}
288   \section{Distribution Form}
289   \begin{description}
290   \item[Name] <<your-name>>
291   \item[Email] <<your-email>>
292   \end{description}
293   \end{document}
294 #+end_src
295
296 #+begin_src latex :noweb :tangle file-form.tex 
297   \documentclass[10pt]{article}
298   \begin{document}
299   \section{File Form}
300   <<your-name>> can be reached at <<your-email>>.
301   \end{document}
302 #+end_src
303
304
305 * A Standardized Short Report
306   This example is similar to the previous one, but here the users are
307   expected to write substantial content.  This type of workflow might
308   be used by a small organization whose employees regularly produce
309   standard documents and where the writing tasks for any one document
310   are divided among the authors.  
311
312   The HTML export facility of Org-mode is used to produce a guide to
313   writing the standardized short report.  This HTML file can be used
314   to train new authors.  The Org-mode content also supplies
315   substantial direction to experienced authors as they write.
316   Org-mode keywords and tags are used to keep track of writing
317   assignments and progress.  Org-babel's literate programming facility
318   makes it possible to present writing tasks to the authors in an order
319   different from which they appear in the report.
320
321 ** Requirement
322    - A working LaTeX installation.
323
324 ** Advantages
325    - The integration of training material with in-file instruction can
326      be quite effective.
327    - Many authors find it easy to work from the bottom up, or from the
328      particular to the general, rather than the usual sequence of
329      general-particular-general found in reports.
330
331 ** Disadvantages
332    - Some features of reftex are not yet integrated into the source
333      code block editor, so writing and editing are sometimes less
334      convenient than writing to the LaTeX document directly.
335
336 ** Example
337    - This report must satisfy the requirements set out in [[http://hawaii.gov/dlnr/hpd/pdfs/revproc_har/275_284/pdfs/278.pdf][the Historic
338      Preservation Division rule]].
339    - Complete each of the TODO items.
340    - Mark each item DONE when you have completed it.
341    - =C-c a t= will make an agenda of items left to do in this
342      document.
343    - =C-c a m= YOURNAME will make an agenda of writing tasks assigned
344      to you.
345    
346 *** TODO Field Methods
347 **** TODO Include the following information: [1/7]
348       - [X] When the fieldwork was carried out.
349       - [ ] Who directed the fieldwork.
350       - [ ] The names and qualifications of crew members.
351       - [ ] Establishment of site datum and grid.
352       - [ ] Excavation tools.
353       - [ ] Assignment of contexts.
354       - [ ] Bag list.
355 **** DONE Include a citation to the project plan.
356      :LOGBOOK:
357      - State "DONE"       from "TODO"       [2009-11-25 Wed 09:53]
358      :END:
359
360 #+srcname: field-methods
361 #+begin_src latex
362   \section{Field Methods}
363   \label{sec:field-methods}
364   
365   % Enter text below this line.
366
367   Fieldwork for the project was carried out between December 26, 2008
368   and February 3, 2009 following an approved plan \cite{plan}.
369 #+end_src   
370
371 *** TODO Results
372     - Note the use of Org-mode tags to assign sections to authors Veronica and Eric.
373     - Discuss the artifacts and midden recovered during excavation.
374
375
376 **** TODO Artifacts                                                :Veronica:
377      :LOGBOOK:
378      - State "TODO"       from "DONE"       [2009-11-25 Wed 09:44]
379      - State "DONE"       from "TODO"       [2009-11-25 Wed 09:44]
380      :END:
381      - Use Sinoto's classification of one-piece fishhooks.
382      - Cite Anell when describing two-piece fishhooks.
383      - Use Emory's classification of adzes when describing
384        cross-section.
385 #+srcname: artifacts
386 #+begin_src latex
387   \subsection{Description of Artifacts}
388   \label{sec:artifact-description}
389   
390   % Enter text below this line
391 #+end_src
392
393 **** TODO Midden                                                       :Eric:
394      - Use Kay for identifying and naming marine shells
395      - Cite Ziegler for information on fish habitats
396 #+srcname: midden
397 #+begin_src latex
398   \subsection{Midden}
399   \label{sec:midden}
400   
401   % Enter text below this line
402 #+end_src
403
404 **** No data entry beyond this line
405
406 #+srcname: results
407 #+begin_src latex :noweb
408   \section{Results}
409   \label{sec:results}
410   
411   This section presents the results of excavation.
412   
413   <<artifacts>>
414   
415   <<midden>>
416 #+end_src
417
418
419 *** TODO Introduction
420     - Give the reader a brief overview of the project and its results.
421
422 #+srcname: intro
423 #+begin_src latex
424   \section{Introduction}
425   \label{sec:introduction}
426   
427   % Text below this line
428 #+end_src
429 *** No data entry beyond this line
430     - The LaTeX code here sets up the environment and inserts the
431       defined source code blocks in their report order.
432     - A call to =org-babel-tangle= produces the LaTeX report document.
433
434 #+begin_src latex :noweb :tangle report.tex
435   \documentclass{article}
436   \begin{document}
437   <<intro>>
438   <<field-methods>>
439   <<results>>
440   \bibliographystyle{apa} 
441   \bibliography{mybib}
442   \end{document}
443 #+end_src
444
445
446
447
448 * A Research Project
449   It is outrageous to think that an entire research project might fit
450   in a single computer file.  Practically speaking, it probably isn't
451   possible.  But the combination of Org-mode and Org-babel does make
452   it possible for one file to hold many, many things useful to the researcher:
453      - the project schedule; 
454      - a daily log; 
455      - notes; 
456      - a facility to track data acquisition graphically; 
457      - a complete specification of the steps taken in data analysis; 
458      - the two presentation products typically produced by researchers---an article
459        for print publication and a digital slide show; 
460      - comments; 
461      - metadata;
462      - etc.
463   
464   When the project is finished and the Org-mode file is complete, one
465   call to =org-babel-tangle= produces the LaTeX source files for the
466   print publication and the Beamer slide show.  Exporting the Org-mode
467   file, say with =C-c, C-e h=, produces an HTML file that meets most,
468   if not all, the requirements for a piece of reproducible research.
469
470   Equally outrageous---the one Org-mode file is easy to
471   set-up, use, and maintain.  A modicum of organization, along with some
472   judicious use of keywords and tags, and perhaps a custom agenda item
473   or two, makes it easy to keep track of progress and to get where you
474   want to be with no hassle.
475
476   More outrageous---the project data can be augmented or
477   corrected at any point and these changes will be reflected
478   everywhere---in the graphics, the slides, the text of the article,
479   the metadata, etc.  One can work with great confidence, knowing that
480   mistakes of logic, analysis, and execution are very likely to be
481   recorded in the Org-mode file.  Fixing an error where it occurs, and
482   only there, propagates the fix throughout the project.  As a result,
483   the researcher spends time thinking about the research, rather than
484   its organization across multiple directories, files, and
485   applications.  What fun!
486
487 ** Requirements
488    - A working LaTeX installation.
489    - A working R installation.
490    - Note that this example is an illustration only.  It is not fully
491      functional as it stands.
492
493 ** Advantages
494    - Easier and more efficient error checking and correction.
495    - On-the-fly production of reproducible research document.
496    - Comprehensive log of data analysis.
497
498 ** Disadvantages
499    - Some features of reftex are not yet integrated into the source
500      code block editor, so writing and editing are sometimes less
501      convenient than writing to the LaTeX document directly.
502
503 ** Example
504    This example shows snippets from an on-going project.  It
505    represents a first attempt to integrate Org-babel with a research
506    project. 
507
508    The schedule and daily log use Org-mode functionality in a fairly
509    simple way.  More sophisticated setups are certainly possible and
510    probably useful.
511
512    Org-babel is used to monitor data acquisition and in particular to
513    catch data entry errors as they happen.  It is also used
514    extensively in the data analysis, which provides a simple example
515    of how it might be used.
516
517 *** Schedule
518    
519
520 **** DONE Meet Jenny to measure adzes
521      DEADLINE: <2009-11-25 Wed 14:00>
522      :LOGBOOK:
523      - State "DONE"       from "TODO"       [2009-11-25 Wed 20:18]
524      :END:
525
526
527 **** TODO Regress edge width on weight 
528      DEADLINE: <2009-11-27 Fri>
529
530 *** Daily Log
531 **** 09/11/25
532      - Measured adzes in trays 2 and 3.  
533      - Reworked measurement protocol for shoulder thickness on untanged adzes.
534
535 **** 09/11/26
536      - Checked shoulder thickness measures on untanged adzes.  All OK now.
537
538 *** Data Acquisition
539
540     - This section illustrates the use of Org-babel to track data
541       acquisition.  Queries are designed to expose unlikely data
542       values likely to be the result of data entry errors.  These
543       queries are collected in a source code block that establishes an
544       R session, reads data from the database, and creates R data
545       objects and graphics that can be used diagnostically.
546
547 **** Queries
548     - Source code block r-bad-interior-landmarks checks for data entry
549       errors in the presence/absence of landmarks.  Note that if the
550       edge is present and the poll is present that the shoulder and
551       chin must be present, as well.  This query assumes that the
552       observations on chin and poll have been entered correctly.
553
554 #+srcname: r-bad-interior-landmarks
555 #+begin_src R
556       bad.landmarks <- dbGetQuery(con, "select * from adze where
557       edge_present = 'true' AND poll_present = 'true' AND (shoulder_present
558       = 'false' OR chin_present = 'false')")
559 #+end_src
560       
561       - Plot weight to look for unusual weights.  In practice any
562         diagnostic plot that isolates outliers can be used to check
563         for possible data entry errors.
564
565 #+srcname: r-complete-weight-histogram
566 #+begin_src R 
567   adze.wt <- ggplot(whole.adze, aes(weight))
568   adze.wt + geom_histogram(fill="white",color="black") +
569   scale_x_log10()
570   ggsave(file = "adze_wt_log.pdf", width = 5, height = 3)
571 #+end_src
572
573 #+resname: r-complete-weight-histogram
574 [[http://www.tsdye2.com/org-babel/adze_wt_log.pdf][file:adze_wt_log.pdf]]
575
576  
577 **** Set-up Session
578
579      - Run r-data-acquisition to refresh the output of the data
580        acquisition queries.  This is the highest-level source code
581        block.  It establishes an R session named acquire, loads
582        various R libraries, and populates the session with data
583        objects based on database queries.  The source code block
584        =<<r-complete-2>>= is defined in the following section to
585        create an R data frame of all the complete adzes in the database.
586        Then, the two source code blocks defined above are run on that
587        data frame to produce (hopefully) useful diagnostics.
588
589 #+src_name r-data-acquisition
590 #+begin_src R :session acquire :noweb
591   library(ggplot2)
592   library(xtable)
593   <<r-connect>>
594   <<r-complete-2>>
595   <<r-bad-interior-landmarks>>
596   <<r-complete-weight-histogram>>
597 #+end_src
598
599   - The r-connect source code block can be used by other source code
600     blocks.  It is used in r-data-acquisition (above) and in
601     r-data-analysis (below).  The fictitious code shown here
602     illustrates an R connection to a database server.
603 #+srcname: r-connect
604 #+begin_src R
605   library(RMySQL)
606   con <- dbConnect(MySQL(), user="me", password="mine", dbname="adze", host="localhost")
607 #+end_src
608
609 *** Data Analysis
610     - This section illustrates how queries can be documented and
611       revised.  A simple table is developed for use in the print
612       publication and the Beamer slide show.
613
614 **** Querying for Complete Adzes
615    - The first try was r-complete, which relies on a single field, *complete*, in
616      the data table.  In practice, an adze blade that is substantially
617      complete, but whose edge has been chipped away, would be
618      classified as complete because all of the attributes typically
619      recorded are present.  For certain measures, such as length, this
620      might introduce a bit of bias.
621
622 #+srcname: r-complete
623 #+begin_src R
624  complete.adze <- dbGetQuery(con, "select * from adze where complete = 'complete'")
625 #+end_src
626
627  - A second try is somewhat more satisfying because it relies on
628    direct observation that the edge is present along with the poll.
629    For length measurements, for instance, it is a direct statement to
630    the effect that the full length of the blade was measured.
631
632 #+srcname: r-complete-2
633 #+begin_src R
634  whole.adze <- dbGetQuery(con, "select * from adze where edge_present = 'true' AND poll_present = 'true'")
635 #+end_src
636
637 **** Making a Table
638
639      - Here, the xtable package is used to return a LaTeX table of
640        values corresponding to the range, median, and 0.25 quantiles
641        of the adze blade weights.  This can be inserted directly into
642        a LaTeX source block, or it can be saved to a file with the
643        xtable print() function.  The file solution is attractive
644        because the table can be tweaked after it is written and
645        subsequent tangles, if necessary, will not overwrite it.  On
646        the other hand, it might be best to tweak the table after the
647        document is completely stable and doesn't need re-tangling.
648        The output of xtable is certainly useful in draft documents.
649        The R source block r-weight-quantile is designed to insert its
650        results directly in the LaTeX file.  The source block can be
651        debugged by checking that its :results output latex is a valid
652        LaTeX construct.
653
654 #+srcname: r-weight-quantile
655 #+begin_src R :session adze :results output
656    weight <- quantile(whole.adze$weight)
657    weight.xtable <- xtable(as.data.frame(weight))
658    caption(weight.xtable) <- 'Weights of complete adzes in the Bishop
659    Museum collection.'
660    label(weight.xtable) <- 'tab:weight_xtable'
661    print(weight.xtable, file="weight_xtable.tex", table.placement =
662    "htb!", caption.placement = "top")
663 #+end_src
664
665 #+resname: r-weight-quantile
666 % latex table generated in R 2.9.2 by xtable 1.5-5 package
667 % Wed Nov  4 08:21:58 2009
668 \begin{table}[htb!]
669 \begin{center}
670 \caption{Weights of complete adzes in the Bishop
671 Museum collection.}
672 \label{tab:weight_xtable}
673 \begin{tabular}{rr}
674   \hline
675  & weight \\ 
676   \hline
677 0\% &   0 \\ 
678   25\% &  22 \\ 
679   50\% &  34 \\ 
680   75\% &  83 \\ 
681   100\% & 2580 \\ 
682    \hline
683 \end{tabular}
684 \end{center}
685 \end{table}
686
687 *** Presentation of Results
688
689     - Org-babel and Org-mode make it convenient to develop a slide
690       show and a print publication side-by-side.  The literate
691       programming facility of Org-babel makes it easy to divide each
692       of the presentations up into small chunks.  Sometimes, writing
693       the slide helps the mind focus on what should appear in the
694       print publication.  Other times, writing out the print
695       publication helps define what should appear in the slide.
696
697 **** Introduction
698
699  The introduction needs to set up the problem: adzes have been
700   classified according to putatively culture-historical
701   characteristics, the goal of which is to create classes of artifact
702   that have distinctive space-time distributions. In Dunnell's terms,
703   these must be stylistic classes. But, Turner's work in NZ has
704   shown that the classes thus formed are actually functional.  Thus,
705   they aren't appropriate for culture history.  The problem is that
706   they are poorly specified for functional studies.  We want to
707   develop a specifically functional classification.
708
709   - The LaTeX introduction.  Compare this with the introductory Beamer
710     slide below.
711 #+srcname: latex-introduction
712 #+begin_src latex :exports code
713   \section{Introduction}
714   \label{sec:introduction}
715   
716   The traditional archaeological classification of Polynesian stone
717   adzes, based on the work of
718   \citet{duff56:_moa_hunter_period_of_maori_cultur}, no longer serves a
719   useful purpose.  Duff's classification, based on the shape of the
720   cross-section, was designed for culture historical study:
721   
722   \begin{quote} the peculiarities in the distribution of adze types
723     over the scattered island groups of Polynesia are due less to the
724     nature or needs of the environment than to the successive growth,
725     diffusion, and replacement of cultural patterns.  The practical
726     layman, contrasting a `hog-backed' with a `side-hafted' adze,
727     might object that each was so shaped for specific purpose, and
728     that their distribution must be due to that purpose.  These two
729     ...
730    \endquote 
731 #+end_src
732
733   - The introductory Beamer slide.
734 #+srcname: beamer-introduction
735 #+begin_src latex :exports code
736   \section{Introduction}
737   \label{sec:introduction}
738   
739   \begin{frame}
740     \frametitle{Duff Types Have No Practical Use}
741     \begin{itemize}
742     \item Duff Classification Based on Cross-section
743       \begin{itemize}
744       \item Used for culture history
745       \item Attributes must be stylistic
746       \end{itemize}
747     \item Turner's Experimental Work
748       \begin{itemize}
749       \item Duff's classes are broadly functional
750       \end{itemize}
751     \item Conclusion
752       \begin{itemize}
753       \item Duff's classes not useful for culture history
754       \item Cross-section not the best attribute for studying function
755       \end{itemize}
756     \end{itemize}
757   \end{frame}
758 #+end_src  
759
760 **** Results
761  In this section a table and a graphic generated earlier are inserted
762  into the LaTeX document.  The table is
763  inserted directly, while the graphic is inserted using its pdf file
764  representation.
765
766  - The LaTeX results source code block.  Note the references to the
767    <<r-weight-quantile>> table and to the adz_wt_log.pdf file created
768    above. 
769
770 #+srcname: latex-results
771 #+begin_src latex :noweb
772   The distribution of complete adze weights is summarized in
773   Table~\ref{tab:weight_xtable} and displayed graphically in
774   Figure~\ref{fig:complete-weight}.
775   
776     <<r-weight-quantile>>
777   
778     \begin{figure}[htb!]
779       \centering
780       \includegraphics[width=5in]{adze_wt_log}
781       \caption[Weight of complete adzes]{Weight of complete adzes on a
782         logarithmic scale.}
783       \label{fig:complete-weight}
784     \end{figure}
785 #+end_src
786
787
788 **** Setup
789
790      - This section contains the source code blocks that set up the
791        LaTeX and Beamer environments.
792
793         - Set up the LaTeX source file.
794 #+srcname: latex-preamble
795 #+begin_src latex :exports code
796 \documentclass[minion,glossaries]{tsdarticle}
797 \author{Thomas S. Dye and Jenny Kahn}
798 \title{Notes on Adze Classification}
799 \newcommand{\attr}[1]{\textbf{#1}}
800
801 \begin{document}
802
803 \maketitle
804 #+end_src
805
806       - Set up the Beamer source file.
807 #+srcname: beamer-preamble
808 #+begin_src latex :exports code
809 \documentclass{beamer}
810 \mode<presentation>
811 {
812  \usetheme{Malmoe}
813  \usecolortheme{tsdye}
814 }
815 \usepackage[english]{babel}
816 \usepackage[latin1]{inputenc}
817 \usepackage{times} 
818 \usepackage[T1]{fontenc}
819 \institute{T. S. Dye \& Colleagues \\ B.P. Bishop Museum}          
820 \subject{Adze Classification}
821 \beamerdefaultoverlayspecification{<+->}
822 \usepackage{booktabs}
823 % \pgfdeclareimage[height=0.5cm]{logo}{tsd_logo}
824 % \logo{\pgfuseimage{logo}}
825 % \setbeameroption{show only notes}
826 \let\latin\textit
827
828 \title{Functional Classification of Hawaiian Adzes}
829 \author{Tom Dye and Jenny Kahn}
830
831 \begin{document}
832
833 \maketitle
834
835 #+end_src
836
837    - Close up the LaTeX source file.
838 #+srcname: latex-ending
839 #+begin_src latex :exports code
840 % Comment or uncomment as needed
841 % style=altlist another possibility
842 \printglossary[type=main, style=tsdlist]
843 \printglossary[type=hawaiian, style=tsdlist]
844 % \printglossary[type=polynesian, style=tsdlist]
845 % \printglossary[type=gazetteer, style=tsdlist]
846 % \printglossary[type=acronym, style=tsdlist]
847 % \printglossary[type=oldenglish, style=tsdlist]
848 % \printglossary[type=bio, style=tsdlist]
849
850 \addcontentsline{toc}{section}{Bibliography}
851 \bibliographystyle{chicago}
852
853 % Comment or uncomment as needed
854 \bibliography{tsd}
855 %\bibliography{tsd,local}
856
857 \end{document}
858
859 #+end_src
860
861    - Close up the Beamer source file.
862
863 #+srcname: beamer-ending
864 #+begin_src latex :exports code
865 \end{document}
866 #+end_src
867
868 **** Master Documents
869
870    - The two source blocks here are the masters for the print document
871      and the beamer slide show.  Running =org-babel-tangle= generates
872      both the print document and the beamer slide show.
873      
874      - The master LaTeX document.  Note the ease with which it is
875        possible to rearrange the parts of the document.
876  
877 #+srcname: latex-document
878 #+begin_src latex :tangle adz_print.tex
879      <<latex-preamble>>
880      <<latex-introduction>>
881      <<latex-results>>
882      ...
883      <<latex-ending>>
884 #+end_src
885
886      - The master Beamer document.  Note the ease with which
887        individual slides can be rearranged.
888
889 #+srcname: beamer-document
890 #+begin_src latex :tangle adz_beamer.tex
891   <<beamer-preamble>>
892   <<beamer-introduction>>
893   ...
894   <<beamer-ending>>
895 #+end_src
896