Introduction to GIS : Basics of Using GRASS GIS Karl Kent Benedict, Ph.D. Earth Data Analysis Center University of New Mexico Introduction

2 Class Goals

• Provide foundation knowledge about Geographic Information Systems (GIS)

• Provide hands-on experience with open-source mapping technologies: GRASS and other tools

• Provide specific knowledge required to import, integrate with other geospatial data, and visualize output of the DREAM system

Introduction 3 Class Organization

Introduction GIS Fundamentals Introduction to Building GRASS Data Acquisition and Preprocessing Data Import/Export Data Management Manipulation and Analyisis Product Generation - Visualization Product Generation - Cartography Automation Advanced Topics Recap and Review

Introduction 4 GIS Fundamentals

5 GIS Fundamentals

A basic understanding of the principles of Geographic Information Systems is required to effectively take advantage of GIS technologies in data management, analysis and visualization applications. This section provides a brief introduction to GIS consisting of the following topics:

• What is a GIS?

• Key GIS Concepts – Projection – Scale – Resolution

• Data Fundamentals – Variable Types – Layer Types

• Elements of the GIS Process – Data Acquisition – Preprocessing – Data Management – Manipulation and Management – Product Generation

GIS Fundamentals 6 What is a GIS?

• A system for managing geographic data. – Information about the shapes of objects. – Information about attributes of those objects. – Spatial variation of measurements across space without reference to specific boundaries – continuous fields of measurements.

• A system for analyzing and modeling spatial relationships. – Spatial statistics – Aggregation and reclassification of observation data – Statistical or process model development and implementation

• A system for presenting geographic information graphically and in summary – Maps – Tables – Graphs – 2D and 3D animations

GIS Fundamentals 7 Key GIS Concepts

• Projections and coordinate systems – Define units of measurement (e.g. spherical coordinates [lat-lon], projected coordinates [UTM meters]) – Translate spherical coordinates to cartesian coordinates – Projections may be optimized to retain direction, distance, or area, leading to a need to consider the application in choosing an appropriate projection for a project

• Scale – The map scale at which data retain acceptable precision

• Resolution – In raster datasets, the size of the pixels in the quantized data representation – Object size, model sensitivity, resolution of source data influence choice of resolution

GIS Fundamentals 8 Key GIS Concepts

Geographic (Unprojected representation of the analysis region)

Transverse Mercator Projection of the same region

What projection(s) are commonly used for your area?

GIS Fundamentals 9 Data Fundamentals

• Data types – Nominal: categories without an inherent order – Ordinal: ordered values without even intervals – Interval: ordered values with even intervals but no well defined zero value (e.g. degrees Celsius) – Ratio: ordered values with even intervals having a well defined zero value (e.g. degrees Kelvin, cm)

• Layer types – Vector (point, line, polygon) – Raster (pixels in a regular grid)

• Topology – Defines the relationship between spatial objects (e.g. adjacency, direction)

GIS Fundamentals 10 Data Fundamentals

Samples of Raster Data Elevation Data:

Excerpt from a global MODIS Mosaic:

GIS Fundamentals 11 Data Fundamentals

Samples of Vector Data Cities (Point):

European Drainage Network (Line):

GIS Fundamentals 12 Data Fundamentals

Vector Data Samples (cont.) Country Boundaries (Polygon):

Individual data layers are necessary for presenting data to the user, but carefully selected combinations of data layers and supplemental cartographic information provide information to the user. Geographic Information Systems provide the tools for managing data and combining those data into informational displays that enhance the user’s understanding of the phenomena being examined.

GIS Fundamentals 13 Elements of the GIS Process

• Data Acquisition

• Preprocessing

• Data Management

• Manipulation and Analysis

• Product Generation

GIS Fundamentals 14 Elements of the GIS Process

Data acquisition is often the most expensive and time consuming part of any GIS project It may require:

• Purchasing data from commercial vendors

• Acquisition of data through field collection – Aerial photography – Satellite imagery – GPS – Ground survey – Manual digitizing, either with a digitizing tablet or on-screen

• Download from government or other sources

What types of data do you want to display? How are spatial data encoded into these data?

GIS Fundamentals 15 Elements of the GIS Process

Data preprocessing is required to modify obtained data for appropriate use in the GIS. This may include

• Reprojection

• Reformatting/Conversion

• Subsetting

• Checking for errors

• Orthorectification

What are the formats of the spatial data available to you? What coordinate systems are used for those data?

GIS Fundamentals 16 Elements of the GIS Process

Data management consists of a broad range of activities within the GIS that relate to the organization, processing, and storage of geospatial data. Activities included in data management include:

• Importation of external data

• Conversion from one data type to another within the GIS

• Movement of data from one GIS workspace to another

• Building topology

• Reprojecting data

• Joining attribute data with spatial data

Do you have non-spatial data that you would like to map? If so, how might they be joined to available spatial data?

GIS Fundamentals 17 Elements of the GIS Process

Manipulation and analysis within the GIS might be seen to overlap with management, with the primary distinction being that manipulation and analysis results in:

• New datasets based upon other datasets. For example: – Slope and aspect derived from a digital elevation model – The results of a model run that combines geospatial data and predefined processes – Reclassification of data into new representations of those data

• Information about datasets as opposed to the datasets themselves (e.g. statistical information)

What derived data do you want to generate? What types of statistical analyses do you need to perform?

GIS Fundamentals 18 Elements of the GIS Process

Product generation encompasses the set of activities that result in end products coming out of the GIS. These products include:

• Hard copy maps

• Digital representations of GIS data (e.g. TIFF, JPEG, GIF, and PNG files representing mapped data)

• Tabular summary data derived from geospatial data or processes employed in the GIS (e.g. model output, or summary statistical data)

• Exported geospatial data

• Exported databases

What information do you need to present in your maps? What standards does your organization use?

GIS Fundamentals 19 Introduction to Linux

20 Introduction to Linux

The GNU/Linux and applications suite provide the foundation for the GRASS GIS application environment in the course. These tools consist of a robust collection of capabilities that must be understood to gain maximum benefit from the GIS environment. Areas to be discussed:

• Logging in & setting a password

• Interacting with the system

• File system

• Users and groups

• Permissions

• Installing Applications

• Getting help

Introduction to Linux 21 Logging In • Logging into the local system – Username & password: Generally, only the first 8 characters of the username and password are significant – Graphical login versus command prompt • Changing your password – Password best practices ∗ 8 Alphanumeric characters, mixed case ∗ Include punctuation marks ∗ NO: dictionary words, personal information, ∗ Change regularly • May be performed both from the command prompt and from a GUI interface • Login to a remote system – Telnet ∗ Commonly used to establish a connection to a remote system ∗ Insecure - username, password, and network traffic transfered in clear text – RSH ∗ Occasionally used to establish a remote connection. ∗ Insecure - username, password, and network traffic transferred in clear text – SSH ∗ Increasingly used for establishing connections to

Introduction to Linux 22 Logging In

remote systems. ∗ Secure - username, password, and network traffic exchanged in an encrypted mode. ∗ May be used for establishing a variety of connections, including: · Shell (ssh) · File Transfer Protocol (sftp) · File Copy (scp) · X-Windows Applications (ssh -X) ∗ It is good to get into a habit of using secure connections when possible

Introduction to Linux 23 Logging In

SSH Examples: ssh [-afgknqstvxACNTX1246] [-b bindAddress] [- cipherSpec] [-e escapeChar] [-i identityFile] [-l loginName] [-m macSpec] [-o option] [-p port] [-F configfile] [-L port:host:hostport] [- port:host:hostport] [-D port] hostname | user@hostname [command]

• Connecting to a remote shell

ssh -l kbene philostrate.unm.edu

• Connecting to a remote system for interactive file trasfer

sftp [email protected]

• Transferring files from one system to another scp [email protected]:/home/kbene/testfile.txt [email protected]:/home/kbene/testfileNew.txt • Running X-windows applications on a remote system

ssh -X -l kbene philostrate.unm.edu grass5

Introduction to Linux 24 Command Line vs.

The execution of commands may often be accomplished via both the command prompt and via the system’s graphical user interface (GUI). Pros and Cons of GUIs

• The GUI often provides access to complex functionality that would require the input of long commands.

• GUIs are very difficult to script, making it hard to develop automated and replicable processes and procedures.

• Some GUIs do not provide access to all of the options available through the same command executed from the command prompt.

Introduction to Linux 25 Command Line vs. Graphical User Interface

Pros and Cons of working at the command prompt

• Typing commands at the command prompt introduces the possibility of making errors in command syntax resulting in failure to execute a command or the execution of a command in an unexpected manner.

• Commands executed from the command prompt are easily integrated into automated proccessed and procedures through a variety of scripting languages.

Introduction to Linux 26 Command Line vs. Graphical User Interface

GRASS Command Line Interface

GRASS GUI

Introduction to Linux 27 File System

In working with GRASS there are several important locations within the file system that any GRASS user should be aware of:

• Home Directory: Each user has a home directory /home/userName within which they may store their personal files. This directory typically contains the GRASS data files that are associated with GIS projects.

• Location of Executable Files (programs): Programs are typically installed within several directories, depending upon their role within the system. Base system programs are typically installed in /bin and /sbin. Additional programs are usually installed within the /usr directory tree which includes /usr/bin, /usr/sbin, /usr/local/bin, and /usr/local/sbin. Some applications are also installed directly within the /usr/local directory in their own directories (e.g. postgresql). GRASS uses a combination of these directories, installing the grass5 executable into /usr/local/bin and all of the GRASS support programs into /usr/local/grass5.

Introduction to Linux 28 Users, Groups and Permissions

Permission to access files and directories on the computer is determined by the rights assigned to the owner, group, and in the case of users that are neither the owner nor a member of the assigned group, to others. The access permissions for a directory or file may be viewed by executing the Linux ls -l command. This command will result in a listing of files and directories contained within the current directory in the following format:

This listing provides information about the read, write and execute permissions for the owner, group and others for each listed file or directory. The listing also indicates whether the listed item is a plain file or a directory (- or d in the first column of the listing), the file or directory’s size, modification date, and name.

Introduction to Linux 29 Users, Groups and Permissions

Three Linux commands may be executed to change the ownership, group assignment, and permissions assigned to file and directory owners, groups, and others:

• chown. This command changes the ownership of a file or directory.

• chgrp. This command changes the group assignemnt for a file or directory.

• chmod. This command changes the permissions for the owner, group, or others for a specified file or directory.

Shared access to GRASS GIS data is facilitated through file system permissions on the GRASS data directories and the files that they contain. GRASS has an internal interactive command (g.access) that sets permissions on the current mapset for access by other users and groups.

Introduction to Linux 30 Installing Applications

Application installation on a RedHat Linux system may be accomplished by following two distinct installation procedures:

• The RedHat Package Manager (rpm).

• Installation from source code.

The RedHat Package Manager (rpm) provides a command line interface that installs precompiled versions of applications that are configured for execution within particular RedHat Linux versions. The package file also contains information about the prerequisite libraries and their versions. In cases where there are no RPMs available for the application to be installed (as is often the case for GRASS GIS), or instances where you wish to customize how the application is built, bulding the application from source code is the preferred approach.

Introduction to Linux 31 Installing Applications from Source Code

While individual application build procedures may vary in their details (always check the directory containing the source code for README and INSTALL files for additional instructions), the common procedure for building an application from source is:

1. Download the source code (often as a tar.gz,a tgz,ora bz2 file).

2. Unpack the archive: • tar zxvf archivename for tar.gz and tgz files. • bunzip2 archivename for bz2 files.

3. Create localized makefile: ./configure

4. Compile the source code: make

5. Install the compiled application (as root): make install

6. Rebuild the library cache (if needed, as root): /sbin/ldconfig

Introduction to Linux 32 Getting Help

The Linux operating system has a variety of built-in help tools. One of the most commonly used text-based help system is the man (short for manual) page system. Information about the syntax and a brief description of a command are available at the command prompt by executing the man command: man command name All of the GRASS commands have man pages and documentation for the commands may be accessed from the GRASS command prompt by executing the above man command. System commands and keywords associated with those commands may be searched using the apropos command. Execution of the apropos command results in a lising of commands that match the provided search string: apropos search string

Online Linux documentation may be obtained from the Linux Documentation Project: http://www.tldp.org/

Introduction to Linux 33 Exercises – Preliminary Materials

34 Install GRASS and Supporting Applications

1. Download source code archives into a directory in your home directory (e.g. /home/username/grassinstall): – : Projection library (http://proj.maptools.org/ or http://www.remotesensing.org/proj) – PostgreSQL: PostgreSQL Database Server (http://www.postgresql.org/) – GDAL: Geospatial Data Abstraction Library (http://remotesensing.org/gdal/) – GRASS: GRASS GIS application (http://grass.itc.it/)

2. Decompress the downloaded archives

tar zxvf archivename

Exercises – Preliminary Materials 35 Install GRASS and Supporting Applications

3. Install proj (# indicates commands that should be executed as root)

cd archiveDirectory ./configure make # make install When building applications, the required libraries must be available for the compilation process. By default the proj libraries are installed in /usr/local/lib. For these libraries to be used in subsequent application builds, add (as root) /usr/local/lib to the /etc/ld.so.conf file. The system’s library cache must then be updated (as root): # /sbin/ldconfig

Exercises – Preliminary Materials 36 Install GRASS and Supporting Applications

4. Install PostgreSQL (# indicates commands that should be executed as root)

cd archiveDirectory ./configure make # make install By default the PostgreSQL libraries are installed in /usr/local/pgsql/lib. For these libraries to be used in subsequent application builds, add (as root) /usr/local/pgsql/lib to the /etc/ld.so.conf file. The system’s library cache must then be updated (as root): # /sbin/ldconfig These instructions allow GDAL and GRASS to compile against the PostgreSQL libraries, but additional configuration of PostgreSQL is required to run the PostgreSQL database server. The additional PostgreSQL installation instructions may be found in /usr/local/pgsql/INSTALL.

Exercises – Preliminary Materials 37 Install GRASS and Supporting Applications

5. Install GDAL (# indicates commands that should be executed as root)

cd archiveDirectory ./configure --with-pg=/usr/local/pgsql/bin/pg config make # make install By default the GDAL libraries are installed in /usr/local/lib. For these libraries to be used in subsequent application builds, add (as root) /usr/local/lib to the /etc/ld.so.conf file. The system’s library cache must then be updated (as root): # /sbin/ldconfig These build instructions compile GDAL with a basic set of supported raster and vector formats. Support for additional file formats is available through the installation of additional support libraries (e.g. HDF, DODS, ArcSDE) and the insertion of additional congiguration options for the ./configure command. These options may be viewed by executing the ./configure --help command. A listing of the currently supported raster formats may be viewed by executing the gdalinfo --formats command. A lising of the currently supported vector formats may be viewed by executing the ogrinfo --formats command.

Exercises – Preliminary Materials 38 Install GRASS and Supporting Applications

gdalinfo --formats Supported Formats: VRT (rw): Virtual Raster GTiff (rw): GeoTIFF NITF (rw): National Imagery Transmission Format HFA (rw): Erdas Imagine Images (.img) SAR CEOS (ro): CEOS SAR Image CEOS (ro): CEOS Image ELAS (rw): ELAS AIG (ro): Arc/Info Binary Grid AAIGrid (rw): Arc/Info ASCII Grid SDTS (ro): SDTS Raster DTED (rw): DTED Elevation Raster PNG (rw): Portable Network Graphics JPEG (rw): JPEG JFIF MEM (rw): In Memory Raster JDEM (ro): Japanese DEM (.mem) GIF (rw): Graphics Interchange Format (.gif)

continued ...

Exercises – Preliminary Materials 39 Install GRASS and Supporting Applications

gdalinfo --formats (continued) ESAT (ro): Envisat Image Format BSB (ro): Maptech BSB Nautical Charts XPM (rw): X11 PixMap Format BMP (rw): MS Windows Device Independent Bitmap PCIDSK (rw): PCIDSK Database File PNM (rw): Portable Pixmap Format (netpbm) DOQ1 (ro): USGS DOQ (Old Style) DOQ2 (ro): USGS DOQ (New Style) ENVI (rw): ENVI .hdr Labelled EHdr (rw): ESRI .hdr Labelled PAux (rw): PCI .aux Labelled MFF (rw): Atlantis MFF Raster MFF2 (rw): Atlantis MFF2 (HKV) Raster FujiBAS (ro): Fuji BAS Scanner Image GSC (ro): GSC Geogrid FAST (ro): EOSAT FAST Format BT (rw): VTP .bt (Binary Terrain) 1.3 Format LAN (ro): Erdas .LAN/.GIS L1B (ro): NOAA Polar Orbiter Level 1b Data Set FIT (rw): FIT Image USGSDEM (rw): USGS Optional ASCII DEM (and CDED) GXF (ro): GeoSoft Grid Exchange Format

Exercises – Preliminary Materials 40 Install GRASS and Supporting Applications

ogrinfo --formats Loaded OGR Format Drivers: -> "ESRI " (read/write) -> "UK .NTF" (readonly) -> "SDTS" (readonly) -> "TIGER" (read/write) -> "S57" (read/write) -> "MapInfo File" (read/write) -> "DGN" (read/write) -> "VRT" (readonly) -> "AVCBin" (readonly) -> "REC" (readonly) -> "Memory" (read/write) -> "GML" (read/write) -> "ODBC" (read/write) -> "PostgreSQL" (read/write)

Exercises – Preliminary Materials 41 Install GRASS and Supporting Applications

6. Install GRASS (# indicates commands that should be executed as root)

cd archiveDirectory ./configure --with-postgres-includes=/usr/local/pgsql/include --with-postgres-libs=/usr/local/pgsql/lib --with-odbc=no --with-fftw=no --with- make # make install This build of GRASS includes support for the raster and vector formats supported by GDAL (and the OGR vector library included with GDAL) and database connections to PostgreSQL databases. Support for connections to ODBC databases and Fast Fourier transforms is specifically excluded. Support for these capabilities would require the installation of additional libraries not included in the current installation.

Exercises – Preliminary Materials 42 GDAL & OGR

Query datasets using GDAL and OGR

• GDAL and OGR are libraries that provide for reading raster and vector datasets, respectively

• Use the gdalinfo and ogrinfo commands to query the datasets provided for the class for information about their projection, units, and attributes.

gdalinfo [--version] [--formats] [-mm] dataset name ogrinfo [-ro] [-q] [-where restricted where] [-spat xmin ymin xmax ymax] [-fid fid] [-sql statement] [-al] [--formats] datasourceName [layer [layer ...]]

Exercises – Preliminary Materials 43 Proj

Using proj to change the projection of data input at the command prompt. In addition to providing a project library that is used by GRASS and other geospatial applications, the proj installation also provides an application that can be executed from the command prompt. proj [-bcefiormstwW [args]][+opts [=arg]][files]

Review the man page for proj: man proj

The downloads and documentation for proj may be accessed at: http://proj.maptools.org/ Review pg. 1-10 in the proj tutorial: OF90-284. Experiment with some of the examples.

Exercises – Preliminary Materials 44 GRASS Workspace Setup

Setting up the GRASS workspace

• Run GRASS from the command prompt

%grass53 The first time you run GRASS you will be prompted for the name of the location, mapset, and database location. These values are defined as follows:

• Location defines the projection, default spatial extent, and resolution for all data in the project

• Mapset defines collections of data within a given location. Mapsets can be used to organize data of similar types or categories

• Database defines where in the file system the files for the GIS will be stored for the given location and mapset. Database needs to be set to a valid directory BEFORE a location and mapset can be defined.

Exercises – Preliminary Materials 45 GRASS Workspace Setup

Create a GRASS workspace for use in the class:

• Location: class location – Coordinate System: Latitude-Longitude – Default Coordinates: 30W-50E, 10N-50N – Geodetic Datum: wgs84 – Datum Transformation Parameters: 1 – Resolution: 0.0833 degrees (5’)

• Mapset: practice

• Database: /home//gis data

Exercises – Preliminary Materials 46 Data Acquisition and Preprocessing

47 Supported Data Formats

GRASS GIS can import and export a wide variety of standard GIS data formats. These data include: FormatName Extension DataType ESRIShapefiles .shp vectordata ArcInfoCoverages FileFolder vectordata ArcInfoGrids FileFolder rasterdata ERDASImagine .img rasterdata TIFF/GEOTIFF .tif raster GDALSupportedTypes Various raster OGRSupportedTypes Various vector Many additional file formats are supported by GRASS. The supported formats are generally accessed through the GRASS commands that begin with m.in., s.in., r.in., and v.in.. The file formats supported by the currently installed GDAL library may be obtained by executing the gdalinfo -- formats command. Likewise, OGR’s supported vector formats may be obtained by executing the ogrinfo --formats command.

Data Acquisition and Preprocessing 48 Sources of Data

Data may be both acquired and generated in support of a particular analysis/mapping project. Data Acquisition

• Search Tools: Google, FGDC Clearinghouse Gateway, etc.

• Local, Regional, National, International data clearinghouses

• Local, Regional, National government agencies

• Commercial data providers

Data Generation

• Digitize from hard-copy materials (v.digit)

• GPS data collection and management (e.g. gpsman & others)

• Scanned imagery: SANE complient scanning application

• Creation of ASCII files for import: vi, EMACS, Kate

Data Acquisition and Preprocessing 49 Preprocessing: Conversion and Subsetting

Many data need to be converted or subsetted prior to import into GRASS. This will streamline the import by reducing the amount of data that must be processed by GRASS and provide an import file format supported by GRASS.

Vector data may be converted with the ogr2ogr command: ogr2ogr [-skipfailures] [-append] [-update] [-f format name] [-select field list] [-where restricted where] [-spat xmin ymin xmax ymax] [-a srs srs def] [-t srs srs def] [-s srs srs def] [[-dsco NAME=VALUE] ...] dst datasource name src datasource name [-lco NAME=VALUE] [-nln name] [-nlt type] layer [layer ...]] More detailed information about the options for this command may be obtained by executing the ogr2ogr --help command.

Data Acquisition and Preprocessing 50 Preprocessing: Conversion and Subsetting

Raster data may be converted with the gral translate command: gdal translate [--version] [-ot Byte/Int16/UInt16/UInt32/Int32/Float32/Float64 CInt16/CInt32/CFloat32/CFloat64] [-not strict] [-of format] [-b band] [-outsize xsize[%] ysize[%]] [-scale [src min src max [dst min dst max]]] [-srcwin xoff yoff xsize ysize] [-a srs srs def] [-projwin ulx uly lrx lry] [-co "NAME=VALUE"]* [-mo "META-TAG=VALUE"]* src dataset dst dataset More detailed information about the options for this command may be obtained by executing the gdal translate --helpcommand.

Data Acquisition and Preprocessing 51 Preprocessing: Reprojection

Data that are not in the same coordinate system and projection as the GRASS location must be reprojected prior to import into the GRASS environment or a new GRASS environment that matches the coordinate system/projection of the data must be created. Several tools exist for reprojecting data prior to import into GRASS. Tabular (ASCII text) data: proj proj [ -beEfiIlormsStTvVwW [args] ] [ +opts[=arg] ] [ files ]

Vector Data: ogr2ogr (see above for syntax)

Raster Data: gdal translate (see above), gdalwarp gdalwarp [--version] [--formats] [-s srs srs def] [-t srs srs def] [-order n] [-et err threshold] [-te xmin ymin xmax ymax] [-tr xres yres] [-ts width height] [-of format] [-co "NAME=VALUE"]* srcfile dstfile

Data Acquisition and Preprocessing 52 Exercise: Acquire Data

Locate some sources of data of interest to you in your GIS analysis.

• Some good places to start might include: – Google – general Internet search – UN Web sites – Local, Regional and National Government Web Sites

• Keep in mind the formats supported by GRASS and GDAL

• Make note of metadata (information about the datasets) for the datasets you find that will be useful in identifying their coordinate system/projection, areas of coverage, units of measurement, file format, etc. This information will be needed to efficiently import the data into GRASS.

Data Acquisition and Preprocessing 53 Data Import and Export

54 Overview of GRASS Import Commands

As previously mentioned, the GRASS commands that import data into the GIS are generally of the form: m.in., s.in., r.in., and v.in.. The more commonly used commands for importing data are: Sites (point) data:

s.in.ascii s.in.dbf s.in.shape

Vector data (partial list) – run v.support after import to build topology.

v.import v.in.arc v.in.ascii v.in.dxf v.in.dxf3d v.in.poly v.in.shape

Data Import and Export 55 Overview of GRASS Import Commands

Raster data (partial list) – run r.support after import to build raster support files.

r.in.arc r.in.ascii r.in.bin r.in.doq r.in.dted r.in.gdal r.in.png r.in.poly r.in.shape r.in.tiff A full listing of import commands may be obtained from the online GRASS documentation under the miscellaneous, sites, raster, and vector categories.

Data Import and Export 56 Importing ArcGIS .e00 Files

ArcGIS .e00 files may contain either raster or vector data. These files are used to encapsulate the directory structure of ArcGIS Coverages and Grids into a single file that may easily be transferred from one system to another. The import of .e00 files is accomplished with the GRASS m.in.e00 command. m.in.e00 [-idts] input=name [mapset=name] [action=what to do] [verbose=debug level] [logfile=name] [list=name,name,name...]

• When m.in.e00 is run against a point coverage, the imported GRASS dataset is a site layer.

• When m.in.e00 is run against a line or polygon coverage, the imported layer is a vector layer. v.support must be run after import to build the topology for the imported layer.

• When m.in.e00 is run against a raster coverage, the imported layer is a GRASS raster.

Data Import and Export 57 Importing TIFF (.tif) Files

Two types of files have the .tif extension – standard TIFF graphic files that have no embedded geographic information and GeoTIFF files that have resolution, spatial extent, and projection data embedded within the file. If the file is a standard TIFF, GRASS requires a “world file” that contains the information required to place the image within space. If the file is a GeoTIFF, the r.in.gdal command may be used.

Data Import and Export 58 Importing TIFF (.tif) Files

Importing standard TIFF files using r.in.tiff.

1. Verify that a correctly formatted “world file” exists. a. The “world file” should have the same name as the related TIFF file, except it will have a “.tfw” extension instead of “.tif”. b. The file should be a text file consisting of six lines: Line 1: Cell size in the x-direction (e.g. 2.5) Line 2: Rotation in the x-direction (e.g. -0.0) Line 3: Rotation in the y-direction (e.g. -0.0) Line 4: Cell size in the y-direction (e.g. -2.5) Line 5: Easting value of the upper-left corner (e.g. 75000) Line 6: Northing value of the upper-left corner (e.g. -200000)

2. Execute the r.in.tiff command.

r.in.tiff [-v] input=name output=name

Data Import and Export 59 Importing TIFF (.tif) Files

Importing a GeoTIFF using r.in.gdal The GDAL library includes support for reading the geographic information encoded in GeoTIFF files. This allows the r.in.gdal command to directly read these files and import them into GRASS rasters. r.in.gdal [-oek] input=name [band=number] output=name [target=name] [TITLE="phrase"] [location=name]

If the input file is a multi-band image, the specified band will be imported. The default is to import all bands. If the projection information for the GeoTIFF does not match the projection of the current location, the “-o” option must be used to force the import. The “location” option will result in the creation of a new location that matches the geographic characteristics of the specified dataset.

The r.in.gdal command may be used to import any of the raster formats supported by the GDAL library.

Data Import and Export 60 Importing ESRI Shapefiles (.shp)

ESRI shapefiles may be directly imported into both vector and raster GRASS layers. Two commands provide this functionality: r.in.shape in=name out=name [cat=category column] [lab=category label column] v.in.shape[-loud] input=name [output=name] [verbose=debug level] [log- file=name] [snapdist=snap distance] [scale=orig. scale] [attribute=category number] [label=category label]

Data Import and Export 61 Importing DREAM Model Output

The most streamlined method of importing DREAM model output into GRASS is through GRASS’ ASCII text import capabilities. These capabilities allow for the import of simple to generate ASCII text files that represent the grided model output as:

• A collection of observation points that consist of an X, Y and Z value

• A rectangular matrix of values that correspond with points within a defined raster grid.

Import of model output as a collection of points would use the s.in.ascii command, while importing grided model output as a raster would use the r.in.ascii command. Site layers may also be generated directly if the formatting specifications for the ASCII text file used to encode site data are followed. The required format for the imported ASCII files is provided in the man page for each command. s.in.ascii sites=name [input=name] [d=value] [fs=character|space|tab] [date=timestamp[/timestamp]] r.in.ascii [-ifds] input=name output=name [TITLE="phrase"] [mult=multiplier]

Data Import and Export 62 Exercise: Import Data into GRASS

Import the data that you found on the Internet and the data provided for the class into the GRASS workspace that you previously created. Remember that you may have to:

• Change data formats prior to import

• Reproject to the same coordinate system as the current GRASS location

• Subset the data if the dataset is larger than your area of interest and very large.

While the imported data won’t be fully usable until the support commands presented in the next section are run, you may list the imported site, raster, and vector layers by executing the g.list sites, g.list rast, and g.list vect commands respectively.

Data Import and Export 63 Exporting Data from GRASS

Similar to the import commands, the GRASS commands that export data from the GIS are generally of the form: m.out., s.out., r.out., and v.out.. The more commonly used commands for exporting data are: Sites (point) data:

s.out.ascii s.out.e00 Vector data (partial list).

v.out.arc v.out.ascii v.out.dlg v.out.dlg.scs v.out.dxf v.out.e00 v.out.idrisi v.out.moss v.out.scsgef v.out.sdts v.out.shape

Data Import and Export 64 Exporting Data from GRASS

Raster data (partial list)

r.out.agnps r.out.arc r.out.ascii r.out.bin r.out.elas r.outgdal r.out.hdf r.out.mpeg r.out.pov r.out.ppm r.out.rlc r.out.tiff r.out.xyz A full listing of export commands may be obtained from the online GRASS documentation under the miscellaneous, sites, raster, and vector categories.

Data Import and Export 65 Exercise: Export Data from GRASS

Practice exporting different GRASS data types into different external formats. Examine the exported data using gdalinfo and ogrinfo to see what information GRASS encodes in the output files. How does this encoded data differ from the data encoded in the data files that were imported into GRASS?

Data Import and Export 66 Data Management

67 Data Management

Data management in GRASS consists of a variety of utility functions that enable manipulation of existing data and the data analysis environment. These functions include:

• Postprocessing imported data to create topology and other support files

• Changing color table(s) for imported data

• Defining and managing GRASS regions

• Defining and managing GRASS masks

• Conversion of data from one type to another (e.g. sites -> vector data)

• Changing the projection of GRASS data

Data Management 68 Postprocessing Imported Data

Most imported raster and vector datasets require some degree of postprocessing before they are usable within GRASS. Postprocessing of these files generally creates additional required information that GRASS uses to store, access, and display the imported data.

• Vector data require that topology and other support files be generated before they are usable. This is accomplished by executing the v.support command. v.support [-spr] map=name [option=name] [threshold=value] [err=name]

• Raster data require that support files be generated before use by some commands. This is accomplished by executing the interactive r.support command.

r.support [-r] map=name

Data Management 69 Postprocessing Imported Data

• Raster data may be assigned a variety of predefined or specified color schemes via the interactive r.colors command. A single color table may be associated with a raster at any given time. It is often most convenient to store a color specification in an external file and execute the r.colors command in a way that the external file is read into the command

r.colors [-wq] map=name [color=type] [rast=name] cat | r.colors map= color=rules

Data Management 70 Exercise: Generate Support Files for Imported Data

Run r.support and v.support on Imported Data.

Data Management 71 Exercise: Create a Color Table for an Imported Raster

Create a color table for one of your imported rasters and preview it on the display. Data may be viewed by executing the following commands: d.mon start=x0 d.rast

The display window may be erased by executing the d.erase command. d.erase [color=name]

Modify the color table and see how your changes are reflected in the display.

Data Management 72 GRASS Regions Regions define the boundaries and resolution of the current workspace within which GRASS commands are executed. The current region effects many GRASS commands, such as export, analysis, etc. The documentation for specific commands should be checked to determine the effect of the region on a given command. Regions have the following characteristics: • Multiple named regions may be created for each mapset. • Only one region may be active at any given time. • Regions may be used to limit the geographic scope and computational requirements of commands by limiting the area over which a command is executed and the number of pixels for which values may be calculated (by changing the resolution of the current region).

Regions are managed using the g.region command. g.region [-adgplecmu] [region=name] [raster=name] [vector=name] [sites=name] [3dview=name] [n=value] [s=value] [e=value] [w=value] [res=value] [nsres=value] [ewres=value] [zoom=name] [align=name] [save=name]

Regions may be quickly created based upon existing site, raster, and vector layers. Otherwise specific north, south, east, and west bounding values and resolution values may be provided. When working with a display monitor, the d.zoom command may be used to interactively zoom to a new region that may then be saved as a named region using the g.region command.

Data Management 73 Exercise: Create a New Region for Your Area of Interest

Define a region for your specific area of interest for use in later mapping and analysis exercises. Make note of the bounding box coordinates of your region so that they may be used in the creation of a Mercator Projection location in a later exercise.

Data Management 74 GRASS Masks

GRASS Masks provide a powerful capability of hiding areas within a map from analysis. This is different from Regions in that regions define a rectangular boundary for the current analysis region while Masks define, on a pixel-by-pixel basis, which parts of the analysis region are to be included in an analysis. A mask may be created by using the interactive r.mask command or by creating a raster called “MASK”. Areas within the mask that are assigned a value of “1” are included in the analysis while areas assigned a “0” are excluded. “MASK” rasters remain in effect for as long as they exist. “MASK” rasters may be manipulated just like all other GRASS rasters by commands such as g.copy, g.region, g.remove, g.rename, and r.mapcalc. r.mask

Data Management 75 Data Conversion Within GRASS

GRASS provides a variety of commands for transforming data from one type to another (e.g. raster to vector, sites to vector, etc.)

• site –> Vector

s.to.vect [-p] input=name output=name [cat=type,index]

• site –> Raster s.to.rast [-qs] input=name output=name size=value title="phrase" field=value findex=value string=value

• Vector –> Site v.to.sites [-acCid] input=name output=name [dmax=value]

• Vector –> Raster

v.to.rast input=name output=name

Data Management 76 Data Conversion Within GRASS

• Raster –> Site

r.to.sites [-az] input=name output=name [label=name]

• Raster –> Vector

r.line input=name output=name [type=name] r.poly [-lcb] input=name output=name r.contour [-qn] input=name output=name [levels=value,value,...,value] [minlevel=value] [maxlevel=value] [step=value] [cut=value]

Data Management 77 Exercise: Create New Sites Data and Convert to Other Formats

Experiment with creating Sites data and converting those data from one type to another.

• Create an ASCII text sites list for import and processing.

• Use s.in.ascii to import the text file as a sites map for use in analysis and data conversion.

• Convert the resulting sites data to other formats.

• How does the data change its appearance when converting from one type to another?

• If you change the resolution of the current region, does the conversion of data change?

Data Management 78 Reprojection within GRASS

Reprojection of data within GRASS is accomplished by moving data from one GRASS location to another. This requires that the data to be reprojected already be in a GRASS location and mapset and that the projection defined for that location be well defined. Once the data are in one GRASS location, they may be reprojected into another by executing one of the following four commands, depending upon the type of data to be reprojected.

• Sites data s.proj [-l] input=name location=name [mapset=name] [dbase=name] [output=name]

• Vector data v.proj [-sl] input=name location=name [dbase=name] [mapset=name] [out=name]

• Raster data r.proj [-ln] input=name location=name [output=name] [mapset=name] [dbase=name] [method=name] [resolution=value]

Data Management 79 Exercise: Create a new Mercator Projection Location and Mapset for Your Area of Interest

Create a new GRASS location and mapset based upon a Mercator projection centered upon your area of interest. Make sure you know the following:

• The projection parameters for your projection (check the proj documentation for this information)

• The coordinates of the boundaries of your area of interest.

• The resolution that you want to set the default region to.

You can use the d.mon, d.rast/d.vect, and d.zoom commands to easily identify the coordinates of a bounding box in an existing location. This information can be used in proj in the calculation of projected coordinates for your new location.

Data Management 80 Exercise: Reproject Imported Geographic Data to a Mercator Projection Location

Create a new Mercator projection location for you use and import/reproject the data you have imported into the Geographic coordinate sytem location.

• Create a new location and mapset with the new projection.

• Reproject the data you have imported into the Geographic location into your new workspace using the s.proj , v.proj , and r.proj commands.

Data Management 81 Data Manipulation and Analysis

82 Data Manipulation and Analysis

Data manipulation and analysis within GRASS consists of commands and functions that generate new data or information from existing data within the GIS. These functions include functions that:

• Calculate Statistics from the content of geographic data

• Derive new data from existing data from simple mathematical relationships (e.g slope and aspect from elevation)

• Perform map algebra in which data from one or more layers are combined mathematically to yield new data (e.g. implementation of a regression model in which mapped values play a role, calculating weighted sums of mapped data to yield a mapped distribution of sums).

• Interpolate from existing vector data to product continuous fields of values in a raster form.

• Reclassify or Modify the Classification of Raster or Vector Data

Data Manipulation and Analysis 83 Statistical Analysis

There are a variety of statistical functions available within GRASS. These functions calculate summary statistics for a map based upon the range of values within the map.

s.univar s.windavg

s.normal s.probplt

v.report

r.stats r.sum

r.average r.median

r.mode r.statistics

s.univar [-aglq] sites=name [field=value] s.windavg [-qzp] input=name attr=name [index=value] [output=name] s.normal [-q] sites=name [tests=range[,range,...]] [field=value] s.probplot [-alq] sites=name width=value [graph=name] v.report [ -ehfq] map=name type=name [units=name[,name,...]] [pl=value] [pw=value] r.stats [-1aclmqgxnNCri] input=name[,name,...] [fs=character|space] [output=name] r.sum rast=name r.average [-c] base=name cover=name output=name r.median base=name cover=name output=name r.mode base=name cover=name output=name

Data Manipulation and Analysis 84 Statistical Analysis

r.statistics r.statistics help r.statistics [-c] base=name cover=name method=name [output=name]

There are also a number of statistical functions that allow for the quantification of the relationship between two or more rasters.

r.coin r.covar

r.coin [-qw] map1=name map2=name units=name r.covar [-mrq] map=name[,name,...]

Data Manipulation and Analysis 85 Statistical Analysis

Some basic spatial analysis tools are also available for use on raster data sets.

r.buffer r.circle

r.clunp r.grow

r.neighbors

r.buffer [-q] input=name output=name distances=value[,value,...] [units=name] r.circle [-b] output=name coordinate=x,y [min=value] [max=value] [mult=value] r.clump [-q] input=name output=name [TITLE="string"] r.grow [-bq] input=name output=name r.neighbors [-aq] input=name output=name method=name size=value [TITLE="phrase"

Data Manipulation and Analysis 86 Exercise: Run Statistical Procedures on Imported Data

• How do the sites map statistical tools summarize the sites data that you previously created and imported?

• What types of information are available from the statistical tools?

• Experiment with the different statistical tools for raster data. How may these tools be used to summarize data for different regions (i.e. countries)?

• Convert a line map into a raster and try some of the spatial analysis commands on the resulting raster map. How do the different commands change how the line data are represented in the raster? Do the same thing with a vector polygon map.

Data Manipulation and Analysis 87 Mathematical Derivation: Physiography and Solar Radiation

Two examples of mathematica derivation of new data layers from existing data are the calculation of slope and aspect from digital elevation data and the calculation of incident solar radiation given elevation, slope, aspect, and optionally, cloud cover.

r.slope.aspect r.sun

r.slope.aspect [-aq] elevation=name [slope=name] [aspect=name] [format=name] [zfactor=value] [prec=name] [pcurv=name] [tcurv=name] [dx=name] [dy=name] [dxx=name] [dyy=name] [dxy=name] [min slp allowed=value] r.sun [-s] elevin=name aspin=name slopein=name [linkein=name] [lin=value] [albedo=name] [alb=value] [latin=name] [lat=value] [coefbh=name] [coefdh=name] [incidout=name] [beam rad=name] [insol time=name] [diff rad=name] [refl rad=name] day=value [step=value] [ declin=value] [ time=value] [dist=value]

Data Manipulation and Analysis 88 Exercise: Generate Physiographic and Solar Radiation Layers

Use the imported elevation data to calculate aspect and slope for the analysis region. Use these data to calculate incident solar radiation for the smaller region that you defined previously.

Data Manipulation and Analysis 89 Map Algebra and Combinining Data

The term map algebra is generally used to refer to mathematical combination of raster data to create new rasters. Vector data may also be combined, but the results of those combinations commonly are new vector maps that reflect the combined or selected characteristics of the merged maps.

v.cutter v.patch

r.combine r.mapcalc

r.patch r.weight

r.weight2

v.cutter [-o] [-l] [-a] [-q] cutter=name input=name output=name type=name v.patch input=name[,name,...] output=name r.combine < inputfile r.mapcalc [result=expression] r.patch [-qz] input=name[,name,...] output=name r.weight r.weight2 [output=option] [action=option] [color=option]

Data Manipulation and Analysis 90 Exercise: Use r.mapcalc to Perform Raster Calculations

Experiment with r.mapcalc to generate new rasters from mathematical, logical, and statistical combinations of other rasters.

Data Manipulation and Analysis 91 Interpolation and Extrapolation In general, interpolation involves the calculation of regional or continuous values from multiple point or vector data points while extrapolation involves the assignment of values from one data point to other locations. GRASS supports both interpolation and extrapolation from site and vector data. Interpolation and smoothing of raster data are also available within GRASS. These functions generally are applied in situations where raster data need to be converted to another resolution (i.e. the region resolution has been changed) or continuous raster data need to be calculated from rasterized contours. Extrapolation

s.delaunay s.voronoi

s.delaunay [-aql] sites=name vect=name s.voronoi [-aq] sites=name vect=name [catnum=no|keep|gen] [labels=no|cat|str,#|dec,#]

Interpolation

s.surf.idw s.surf.rst

r.bilinear r.neighbors

r.surf.contour r.surf.idw

r.surf.idw2

s.surf.idw [-n] input=name output=name [npoints=count] [field=number]

Data Manipulation and Analysis 92 Interpolation and Extrapolation

s.surf.rst [-d] [-t] input = name [elev = name] [field=val] [slope = name] [aspect = name] [pcurv = name] [tcurv = name] [mcurv = name] [maskmap = name] [dmin = val] [zmult = val] [tension = val] [smooth = val] [smatt=val] [segmax = val] [npmin = val] [theta = val] [scalex = val] [devi = name] [treefile = name] [overfile = name] r.bilinear [-q] input=name output=name [north=value] [south=value] r.neighbors [-aq] input=name output=name method=name size=value [TITLE="phrase"] r.surf.contour [-f] input=name output=name r.surf.idw [-e] input=name output=name [npoints=value] r.surf.idw2 input=name output=name [npoints=count]

Data Manipulation and Analysis 93 Exercise: Extrapolate and Interpolate Sites Data to Rasters and Contours

Experiment with the listed extrapolation and interpolation commands to generate rasters from the previously imported ASCII sites data. Generate contours (iso-lines) from the resulting raster files using the r.contour command.

Data Manipulation and Analysis 94 Reclassification and Class Modification

Reclassification and class modification of GIS data involves the assignment of existing spatial objects to classes of values that differ from their current ones. This may result in aggregation of individual values into classes that represent ranges of values (a frequent reclassification activity), or to qualitatively different representations (i.e assignment of floating point values to clases represented by their rounded or truncated values). Site data may have multiple attributes associated with each site, but hove not functions for reclassifying sites data. Vectors may have both categories and attributes associated with objects, while rasters may have measured or calculated values associated with each pixel in addition to categorical data.

Data Manipulation and Analysis 95 Reclassification and Class Modification

v.reclass

r.reclass r.recode

r.resample r.rescale.eq

r.infer r.mapcalc

v.reclass [-d] input=name output=name type=area, line, or site [title=name] r.reclass input=name output=name [TITLE=name] r.recode [-ad] input=name output=name [title=name] r.resample [-q] input=name output=name r.rescale.eq [-qz] input=name [from=min,max] output=name to=min,max [title="phrase"] r.infer [-vt] rulesfile=name

Data Manipulation and Analysis 96 Product Generation – Visualization

97 Product Generation – Visualization

On screen visualization of data and the generation of graphics files representing those data is the topic of this section. While closely related to the next section on cartography, the emphasis in this section is on the on screen display options of GRASS while the next section is focused on the generation of Postscript renditions of cartographic (map) products. GRASS supports a variety of display options, primarily through the d. family of commands. These commands both create and manage multiple display monitors (areas on the computer screen where data are displayed) while also selecting which data and mapping elements may be displayed within those monitors. GRASS also has “drivers” that allow the results of display commands to be written to graphics files instead of the screen, allowing for the creating of computer graphic versions of the content that would normally be displayed on the computer screen.

Product Generation – Visualization 98 Commands that Manage Display Monitors

The commands that manage display monitors create, select and erase the visible display monitors while the other display commands are effective on the currently selected monitor screen.

d.mon

d.erase d.frame

d.display nviz

d.mon [-lLprs] [start=name] [stop=name] [select=name] [unlock=name] d.erase [color=name] d.frame [-cepslD] [frame=name] [at=bottom,top,left,right] d.display nviz [-qkx] [elevation=name[,name,...]] [color=name[,name,...]] [vector=name[,name,...]] [sites=name[,name,...]] [path=name] [state=name] [script=name]

Product Generation – Visualization 99 Commands that Display Data on the Screen

The commands that display data within the current display monitor allow the user to select map data (i.e. sites, vectors, rasters, data from external databases) and map elements (i.e. bar scales, legends, titles and other text) to create on-screen map compositions.

d.his d.rgb

d.db

d.rast

d.icons p.icons

d.points d.site.labels

d.sites d.sites.qual

d.vect d.vect.labels

d.3d

Product Generation – Visualization 100 Commands that Display Data on the Screen

d.graph d.mapgraph

d.barscale d.colortable

d.grid d.legend

d.histogram d.linegraph

d.profile

d.font d.label

d.labels d.paint.labels

d.text d.title

p.icons p.labels

d.pan d.zoom

d.save

Product Generation – Visualization 101 Commands that Display Data on the Screen

d.his [-n] h map=name [i map=name] [s map=name] d.rgb [-o] red=name green=name blue=name d.db table=table name x=column name y=column name [where=SQL where clause] [color=name] [size=value] [icon=name] d.rast [-oi] map=name [catlist=list] [vallist=list] [bg=color] d.icons [-r] icon=name [color=name] [size=value] [points=name] p.icons d.points [color=name] [size=value] [type=name] [file=name] d.site.labels -m file=name [attr=string|cat|double| coords|dim] [index=number] [xref=left|center|right] [yref=top|center|bottom] [size=number] [color=colorname] [backgr=colorname] [border=colorname] [font=fontname] d.sites sitefile=name [color=name] [size=value] [type=name] d.sites.qual [-n] sitefile=name [color=name] [size=value] [type=name] [rules=name[,name,...]] [output=name] d.vect [-fv] map=name [color=name] cat=value[,value,...] d.vect.labels [-smv] map=name [attr=string|cat|coords] [size=number] [color=colorname] [backgr=colorname] [border=colorname] [font=fontname]

Product Generation – Visualization 102 Commands that Display Data on the Screen

d.3d [-lan] map=name elevation=name [from coordinate=x,y,z] [to coordinate=x,y,z] [exaggeration=value] [lines=value] [field=value] [color=name] [box=name] d.graph [input=name] [color=name] d.mapgraph [input=name] [color=name] d.barscale [-m] [-f] [-l] [-t] [bcolor=name] [tcolor=name] [at=x,y] d.colortable map=name [color=name] [lines=value] [cols=value] d.grid [-g] [-b] size=value [color=name] [origin=easting,northing] d.legend [-vcnsmf] map=name [color=name] [lines=value] [thin=value] [labelnum=value] [at=bottom,top,left,right] [use=catnum[,catnum,...]] [range=min,max] d.histogram [-qnC] map=name [color=name] [style=name] [nsteps=value] d.linegraph xfilename yfilename[,name,...] [directoryname] [ycoloroption[,option,...]] [xtitlevalue] [ytitlevalue] [titlevalue] [titlecoloroption] d.profile rast=name [drast=name] [plotfile=name] d.font font=name d.label [size=value] [backcolor=name] [textcolor=name] [font=name] d.labels d.paint.labels file=name

Product Generation – Visualization 103 Commands that Display Data on the Screen

d.text [size=value] [color=name] [line=value] d.title [-f] map=name [color=name] [size=value] p.icons p.labels d.pan [-j] [rast=name[,name,...]] [vector=name[,name,...]] [site=name[,name,...]] [zoom=value] d.zoom [-fhj] [rast=name[,name,...]] [vector=name[,name,...]][site=name[,name,...]] [zoom=value] d.save [-ca] [frame=name[,name,...]] [remove=val[,val,...]][move=from,to[,from,to,...]]

Product Generation – Visualization 104 Exercise: Create Map Compositions in the Display Monitor

Use the various display commands presented above to create an on screen map composition of the data in your database.

Product Generation – Visualization 105 Commands that Generate Graphics Files for Viewing and Printing

The commands that generate graphics files for viewing and printing enable the export of graphics (i.e. TIFF or PMG) files for export to the file system for display and printing outside of GRASS. These uses might include integration into a written report as images, display on a web page, or use in an external graphics program to product composite graphics documents. Two tools can be used to produce graphics files for external use: the CELL driver and the PNG driver.

Product Generation – Visualization 106 Commands that Generate Graphics Files for Viewing and Printing

The CELL driver allows for the creation of rasters composed of combinations of sites, vectors, rasters, and other map elements for export using r.out.tiff. The general procedure for using the CELL driver is:

• Set Environment variables

• Start the CELL Driver

• Display the map elements using the common display commands (e.g. d.sites, d.vect, d.rast, etc.)

• Stop the CELL driver

• Reset the region to match the new raster layer

• Export the raster layer using an appropriate r.out.* command.

Product Generation – Visualization 107 Commands that Generate Graphics Files for Viewing and Printing Example CELL Driver shell script #!/bin/tcsh # This script will generate a map and export the results as a tiff # file using the GRASS CELL driver # Set environment variables echo "Now setting the environment variables" setenv GRASS WIDTH 480 setenv GRASS HEIGHT 240 #Start and select the CELL Driver echo "Now starting and selecting the CELL driver" echo "" d.mon start=CELL d.mon select=CELL # Display the map elements using the common display commands (e.g. d.sites,d.vect, d.rast, etc.) echo "Now displaying the map elements" echo "" g.region region=med d.rgb red=euroworld.1 green=euroworld.2 blue=euroworld.3 d.rast -o map=fort45 vallist=0.001-100 d.vect map=countries color=black d.legend map=fort45 at=20,80,2,7 # Stop the CELL Driver echo "Now stopping the CELL driver"

Product Generation – Visualization 108 Commands that Generate Graphics Files for Viewing and Printing

echo "" d.mon stop=CELL # Reset the region to match the new raster layer g.region raster=D cell # Display the resulting raster in display monitor 'x6' d.mon start=x6 d.mon select=x6 d.rast map=D cell d.mon stop=x6

# Export the raster layer using an appropriate r.out.* command (e.g. r.out.tiff) echo "Now exporting the TIFF file" echo "" r.out.tiff input=D cell output=cell output compression=none # Reset the region to 'med' and select the 'x0' display monitor g.region region=med d.mon select=x0

Product Generation – Visualization 109 Commands that Generate Graphics Files for Viewing and Printing

The PNG driver allows for the creation of rasters composed of combinations of sites, vectors, rasters and other map elements in a .png file on the system. The process for the PNG driver is similar to that of the CELL driver, though not as complex:

• Set environment variables

• Start the PNG Driver

• Display the map elements using the common display commands (e.g. d.sites, d.vect, d.rast, etc.)

• Stop the PNG Driver

Product Generation – Visualization 110 Commands that Generate Graphics Files for Viewing and Printing Example PNG driver shell script. #!/bin/tcsh # This script will generate a map and export the results as a PNG # file using the GRASS PNG driver # Set environment variables setenv GRASS WIDTH 480 setenv GRASS HEIGHT 240 setenv GRASS PNGFILE "png output.png" setenv GRASS BACKGROUNDCOLOR 000000 setenv GRASS TRANSPARENT FALSE setenv GRASS TRUECOLOR TRUE #Start and select the PNG Driver d.mon start=PNG d.mon select=PNG # Display the map elements using the common display commands (e.g. d.sites,d.vect, d.rast, etc.) g.region region=med d.rgb red=euroworld.1 green=euroworld.2 blue=euroworld.3 d.rast -o map=fort45 vallist=0.001-100 d.vect map=countries color=black d.legend map=fort45 at=20,80,2,7 # Stop the PNG Driver d.mon stop=PNG

Product Generation – Visualization 111 Commands that Generate Graphics Files for Viewing and Printing

# Reset the region to 'med' and select the 'x0' display monitor g.region region=med d.mon select=x0

Product Generation – Visualization 112 Exercise: Create Shell Scripts to Create Graphics Files Develop shell scripts that automate the process of creating a TIFF and PNG graphics file using the CELL and PNG driver. The preceeding sample scripts may provide a useful template for the scripts that you develop. In developing your scripts, remember the following map-making best practices and concepts: • Your maps should include the following elements: – Title – Scale – North Arrow – Legend – Name of the individual or organization that produced the map – Date the map was produced – Projection information • When ordering the display of layers, rasters will normally be the first layers displayed — resulting in their display at the bottom of the stack of layers. • Text (i.e. labels, legends, notes) are usually the last elements added to a map so that they are not obscured by other map elements. • Include enough reference information for the reader to have a locational context, but not so much as to obscure the point

Product Generation – Visualization 113 Exercise: Create Shell Scripts to Create Graphics Files

being made by the map.

Product Generation – Visualization 114 Product Generation – Cartography

115 Product Generation – Cartography

While the graphics generation commands outlined in the previous section are excellent for producing maps for display on computer screens and other low-resolution media, high-resolution output (i.e. printed maps) is beter generated using a page layout language like Postscript. This allows for the generation of high-quality text and vector data that print at the resolution of the output device without degrading when scaled. This translates into higher quality output than can be obtained using the raster file generation capabilities of the CELL and PNG drivers outlined in the previous section. GRASS supports the generation of Postscript-based maps through the p. family of commands.

Product Generation – Cartography 116 GRASS Postscript Commands

There are three Postscript commands in GRASS that are used to generate output:

ps.select ps.icon

ps.map

The ps.select and ps.icon commands are preliminary commands that define the page setup (ps.select) and generate icons (ps.icon) for display, while the ps.map command generates the Postscript map representation. The ps.select command must be run before the ps.map command. While the ps.map command may be run interactively, it is most efficient to develop shell scripts that execute the series of commands required to generate a map.

The ps.map command also provides broad support for the use of encapsulated Postscript (eps) files as graphic elements within a map. Use of eps for symbols and other elements within the map will also improve the quality of the output map since these elements are described mathematically and retain their quality when scaled for display or printing.

Product Generation – Cartography 117 Sample Postscript Map Generation Script

The following map was created by the sample script that is provided below.

Product Generation – Cartography 118 Sample Postscript Map Generation Script

Sample Script:

#!/bin/tcsh

ps.select painter=diss_halfpage

ps.map input=- output=./output/ushcn_paleoprecip_map.ps << "eof" maploc 0.2 0.2 4 4 raster fs_250k_dem_m

vector projectareas color red width 0.5 label Project\nBoundary lpos 1 end

vector states color black width 0.5 label State Boundaries lpos 1 end

sites ushcn_stations_analysis color red size 0.3 eps ./symbol_concentric_circles.eps end

sites paleoprecip color red size 0.3 eps ./symbol_upsidedown_triangle.eps end

sites paleotemp color red size 0.3 eps ./symbol_plus.eps end

Product Generation – Cartography 119 Sample Postscript Map Generation Script

text 28% 23% Fort Valley ref center center width 1 size 11280 color black font Helvetica end

text 29% 28% San Francisco\nPeaks ref left center width 1 size 11280 color black font Helvetica end

text 33% 24% Flagstaff ref left center width 1 size 11280 color black font Helvetica end

text 50.5% 36% Hopi Mesa ref left center width 1 size 11280 color black font Helvetica end

text 49.5% 55% Tsegi Canyon ref left center width 1 size 11280 color black font Helvetica end

Product Generation – Cartography 120 Sample Postscript Map Generation Script

text 45% 62% Navajo Mountain ref left center width 1 size 11280 color black font Helvetica end

text 67% 43% Canyon de Chelly ref left center width 1 size 11280 color black font Helvetica end

text 82.5% 63.5% Mesa Verde ref left center width 1 size 11280 color black font Helvetica end

colortable y where 4.3 0.5 width .25 height 1.75 fontsize 8 end

eps 5% 10% epsfile ./north_arrow.eps end

mapinfo where 0.5 3.8 fontsize 4 end

Product Generation – Cartography 121 Sample Postscript Map Generation Script

rectangle 8% 10% 26.46% 10.5% color black fcolor black end

text 17.25% 11.5% 100 km ref center center width 1 size 11280 color black font Helvetica end

text 67.5% 62.5% UT ref left center width 2 size 15040 color black font Helvetica end

text 67.5% 57.5% AZ ref left center width 2 size 15040 color black font Helvetica end

text 73.5% 62.5% CO ref left center width 2 size 15040 color black font Helvetica end

Product Generation – Cartography 122 Sample Postscript Map Generation Script

text 73.5% 57.5% NM ref left center width 2 size 15040 color black font Helvetica end

text 53% 50% Project Area ref left center width 2 size 11280 color black font Helvetica end

text 118.5% 97% Elevation (m) ref center center width 3 size 15040 color black font Helvetica end

eps 106% 45% epsfile ./symbol_upsidedown_triangle.eps scale 0.3 end

text 110% 45% Prehistoric Precipitation\nLocation width 1 size 11280 color black font helvetica ref left center end

eps 106% 40% epsfile ./symbol_concentric_circles.eps scale 0.3 end

Product Generation – Cartography 123 Sample Postscript Map Generation Script

text 110% 40% USHCN Station width 1 size 11280 color black font helvetica ref left center end

eps 106% 35% epsfile ./symbol_plus.eps scale 0.3 end

text 110% 35% Prehistoric Temperature\nLocation width 1 size 11280 color black font helvetica ref left center end

comments ./analysis_elevation_map_comments fontsize 6 color black font Helvetica where 4.3 3.8 end

end "eof"

gs -r300 -sDEVICE=epswrite -dBATCH -sOutputFile=./output/ushcn_paleoprecip_map.eps ./output/ushcn_paleoprecip_map.ps

Product Generation – Cartography 124 Automation

125 Automation

GRASS processing may be integrated with other applications through scripting languages. For example, through shell scripting (i.e. bash, tcsh), Perl or Python scripts. Each command available from the GRASS command prompt may also be executed from the system command prompt if the appropriate environment variables are set. The specific commands for setting environment variables depend upon the shell or scripting environment

Automation 126 Required Environment Variables

The required environment variables include:

• GISBASE - the parent directory for the GRASS application files

• GISDBASE - the file system location for the grass data files

• GISRC - the location (often .grassrc5 in each users home directory) of the users GRASS configuration file

• LOCATION NAME - the name of the GRASS location to use in the execution of the commands

• MAPSET - the name of the GRASS mapset (within the location specified above) to use

• The PATH environment variable may also need to be modified to include the directory containing the GRASS binary files (e.g. /usr/local/grass5/bin)

Automation 127 Required Environment Variables

Sample TCSH script fragment setting the required environment variables: #!/bin/tcsh # Set environment variables for script to run outside of GRASS setenv GISBASE "/usr/local/grass5" setenv GISDBASE "/Users/karlbenedict/grass.data" setenv GISRC "/Users/karlbenedict/.grassrc5" setenv LOCATION NAME "med" setenv MAPSET "dustmodel" setenv PATH $PATH":/usr/local/grass5/bin" # Add additional GRASS commands to accomplish data import, processing, and output functions

Automation 128 Exercise: Create a Free-Standing GRASS Script

Create a copy of one of the GRASS scripts that you have already developed and modify it so that it will run outside of GRASS. This will require that you add commands to the script that set the required environment variables that enable the GRASS commands to execute properly.

Automation 129 Notes

1. http://grass.itc.it 2. http://www.opensource.org 3. The current “testing” version upon which this presentation is based is GRASS ver. 5.3 4. http://www.gnu.org

129-1