0
# Configuration and Utilities
1
2
System configuration, session management, and utility functions for customizing GMT behavior, managing resources, and accessing system information.
3
4
## Capabilities
5
6
### GMT Configuration
7
8
Configure GMT default settings and behavior.
9
10
```python { .api }
11
def config(**kwargs) -> None:
12
"""
13
Modify individual GMT default settings.
14
15
Parameters (via kwargs):
16
- MAP_FRAME_TYPE: Frame type ("plain", "fancy")
17
- MAP_FRAME_WIDTH: Frame width (e.g., "5p")
18
- MAP_FRAME_PEN: Frame pen attributes (e.g., "1p,black")
19
- MAP_GRID_PEN_PRIMARY: Primary grid pen (e.g., "0.5p,gray")
20
- MAP_GRID_PEN_SECONDARY: Secondary grid pen (e.g., "0.25p,lightgray")
21
- MAP_TICK_LENGTH_PRIMARY: Primary tick length (e.g., "8p")
22
- MAP_TICK_LENGTH_SECONDARY: Secondary tick length (e.g., "4p")
23
- MAP_ANNOT_FONT_PRIMARY: Primary annotation font (e.g., "12p,Helvetica")
24
- MAP_ANNOT_FONT_SECONDARY: Secondary annotation font (e.g., "10p,Helvetica")
25
- MAP_LABEL_FONT: Axis label font (e.g., "14p,Helvetica-Bold")
26
- MAP_TITLE_FONT: Title font (e.g., "16p,Helvetica-Bold")
27
- COLOR_BACKGROUND: Background color (e.g., "white")
28
- COLOR_FOREGROUND: Foreground color (e.g., "black")
29
- COLOR_MODEL: Color model ("RGB", "HSV", "CMYK")
30
- PS_MEDIA: Paper size ("A4", "Letter", "Custom")
31
- PS_PAGE_ORIENTATION: Page orientation ("portrait", "landscape")
32
- FORMAT_GEO_OUT: Geographic output format (e.g., "ddd:mm:ss")
33
- FORMAT_DATE_OUT: Date output format (e.g., "yyyy-mm-dd")
34
- FORMAT_TIME_OUT: Time output format (e.g., "hh:mm:ss")
35
- PROJ_LENGTH_UNIT: Default length unit ("cm", "inch", "point")
36
- GMT_VERBOSE: Verbosity level ("quiet", "normal", "verbose", "debug")
37
- GMT_INTERPOLANT: Default interpolation ("linear", "akima", "cubic", "none")
38
39
Notes:
40
- Settings persist for the current GMT session
41
- Use GMT parameter names exactly as documented
42
- String values should be quoted appropriately
43
"""
44
```
45
46
### System Information
47
48
Access information about PyGMT, GMT, and system configuration.
49
50
```python { .api }
51
def show_versions() -> None:
52
"""
53
Show versions of PyGMT and dependencies.
54
55
Displays:
56
- PyGMT version and commit hash
57
- GMT version and library path
58
- Python version and platform
59
- NumPy, pandas, xarray versions
60
- Ghostscript version
61
- GDAL/OGR version
62
- System information
63
"""
64
65
def info(data: PathLike | TableLike, **kwargs) -> str:
66
"""
67
Get information about data tables.
68
69
Parameters:
70
- data: Input data file or table
71
- verbose: Show detailed statistics (bool)
72
- per_column: Report statistics per column (bool)
73
- spacing_guess: Guess grid spacing from data (bool)
74
- force_scan: Force reading entire dataset (bool)
75
76
Returns:
77
str: Data information string including:
78
- Number of records and columns
79
- Data extent and ranges
80
- Missing values count
81
- Data type information
82
"""
83
84
def which(fname: str, **kwargs) -> str:
85
"""
86
Find full path to specified files.
87
88
Parameters:
89
- fname: File name to locate
90
- show_all: Show all matching files (bool)
91
- download: Download file if not found locally (bool)
92
93
Returns:
94
str: Full path to file, or empty string if not found
95
96
Searches:
97
- Current directory
98
- GMT data directories
99
- GMT cache directories
100
- System PATH (for executables)
101
"""
102
```
103
104
### Display Configuration
105
106
Configure how figures are displayed in different environments.
107
108
```python { .api }
109
def set_display(method: Literal["external", "notebook", "none"] | None = None) -> None:
110
"""
111
Set Figure display method for show().
112
113
Parameters:
114
- method: Display method
115
- "external": Launch external image viewer
116
- "notebook": Display inline in Jupyter notebooks
117
- "none": No display (useful for batch processing)
118
- None: Use default based on environment
119
120
Notes:
121
- Setting persists for current Python session
122
- Jupyter notebooks default to "notebook"
123
- Other environments default to "external"
124
- Use "none" for headless servers or batch jobs
125
"""
126
```
127
128
### Session Management
129
130
Functions for managing GMT modern mode sessions (typically handled automatically).
131
132
```python { .api }
133
def begin() -> None:
134
"""
135
Initiate a new GMT modern mode session.
136
137
Notes:
138
- Called automatically when importing PyGMT
139
- Creates global GMT session for all operations
140
- Sets GMT compatibility mode to version 6
141
- Handles platform-specific session naming
142
"""
143
144
def end() -> None:
145
"""
146
Terminate the GMT modern mode session.
147
148
Notes:
149
- Called automatically at Python exit
150
- Cleans up temporary files and session directory
151
- Should only be called explicitly in special cases
152
"""
153
```
154
155
### Helper Utilities
156
157
Utility functions for data validation, type checking, and file management.
158
159
```python { .api }
160
def unique_name() -> str:
161
"""
162
Generate unique names for temporary files and figures.
163
164
Returns:
165
str: Unique identifier string
166
"""
167
168
class GMTTempFile:
169
"""
170
Context manager for creating temporary files with GMT-compatible names.
171
172
Usage:
173
with GMTTempFile() as tmpfile:
174
# Use tmpfile.name for file operations
175
data.to_csv(tmpfile.name)
176
result = pygmt.info(tmpfile.name)
177
# File automatically cleaned up
178
"""
179
180
def __init__(self, suffix: str = ".txt") -> None:
181
"""
182
Initialize temporary file.
183
184
Parameters:
185
- suffix: File extension (e.g., ".txt", ".grd", ".cpt")
186
"""
187
188
def __enter__(self) -> "GMTTempFile":
189
"""Enter context manager and create temporary file."""
190
191
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
192
"""Exit context manager and clean up temporary file."""
193
194
def tempfile_from_geojson(geojson_dict: dict) -> GMTTempFile:
195
"""
196
Create temporary file from GeoJSON data.
197
198
Parameters:
199
- geojson_dict: GeoJSON data as dictionary
200
201
Returns:
202
GMTTempFile: Temporary file containing GeoJSON data
203
"""
204
205
def tempfile_from_image(image: np.ndarray) -> GMTTempFile:
206
"""
207
Create temporary file from image array.
208
209
Parameters:
210
- image: Image data as numpy array
211
212
Returns:
213
GMTTempFile: Temporary file containing image data
214
"""
215
216
def launch_external_viewer(fname: str) -> None:
217
"""
218
Launch external image viewer for file.
219
220
Parameters:
221
- fname: Image file path
222
223
Notes:
224
- Uses system default image viewer
225
- Platform-specific implementation
226
- Non-blocking call (viewer runs independently)
227
"""
228
```
229
230
### Data Validation
231
232
Functions for validating and checking data inputs.
233
234
```python { .api }
235
def data_kind(data: any) -> str:
236
"""
237
Determine data type/kind for GMT processing.
238
239
Parameters:
240
- data: Input data (file path, array, DataFrame, etc.)
241
242
Returns:
243
str: Data kind ("file", "matrix", "vectors", "grid", etc.)
244
"""
245
246
def is_nonstr_iter(obj: any) -> bool:
247
"""
248
Check if object is non-string iterable.
249
250
Parameters:
251
- obj: Object to check
252
253
Returns:
254
bool: True if iterable but not string
255
"""
256
257
def args_in_kwargs(args: list, kwargs: dict) -> list:
258
"""
259
Check if arguments are present in kwargs.
260
261
Parameters:
262
- args: List of argument names to check
263
- kwargs: Keyword arguments dictionary
264
265
Returns:
266
list: Arguments found in kwargs
267
"""
268
269
def build_arg_list(kwargs: dict) -> list:
270
"""
271
Build GMT argument list from kwargs.
272
273
Parameters:
274
- kwargs: Keyword arguments with GMT parameters
275
276
Returns:
277
list: GMT command-line arguments
278
"""
279
```
280
281
### String and Encoding Utilities
282
283
Functions for handling text encoding and character conversion.
284
285
```python { .api }
286
def non_ascii_to_octal(text: str) -> str:
287
"""
288
Convert non-ASCII characters to octal representation.
289
290
Parameters:
291
- text: Input text with potential non-ASCII characters
292
293
Returns:
294
str: Text with non-ASCII characters converted to octal codes
295
296
Notes:
297
- Required for GMT text processing with special characters
298
- Handles Unicode characters in plot labels and annotations
299
"""
300
301
def sequence_join(sequence: list, separator: str = " ") -> str:
302
"""
303
Join sequences with specified separator.
304
305
Parameters:
306
- sequence: List or array to join
307
- separator: String separator between elements
308
309
Returns:
310
str: Joined string
311
"""
312
```
313
314
### XArray Integration
315
316
PyGMT extends xarray with GMT-specific functionality for grids and backend support.
317
318
```python { .api }
319
class GMTDataArrayAccessor:
320
"""
321
GMT accessor for xarray.DataArray providing .gmt attribute.
322
323
Automatically registered as xarray.DataArray.gmt accessor.
324
Provides GMT-specific metadata for grids and images.
325
326
Properties:
327
- registration: Grid registration type (GridRegistration.GRIDLINE or GridRegistration.PIXEL)
328
- gtype: Grid coordinate system (GridType.CARTESIAN or GridType.GEOGRAPHIC)
329
330
Usage:
331
data_array.gmt.registration # Access grid registration
332
data_array.gmt.gtype # Access grid coordinate type
333
"""
334
335
class GMTBackendEntrypoint:
336
"""
337
XArray backend for reading GMT netCDF files.
338
339
Automatically registered as xarray backend for GMT files.
340
Enables direct loading of GMT grids with proper metadata.
341
342
Usage:
343
xr.open_dataarray("file.grd", engine="gmt")
344
"""
345
346
def load_dataarray(filename_or_obj: str, **kwargs) -> xr.DataArray:
347
"""
348
Load GMT grid file as xarray.DataArray with GMT metadata.
349
350
Parameters:
351
- filename_or_obj: Path to GMT grid file
352
- **kwargs: Additional arguments passed to xarray.open_dataarray
353
354
Returns:
355
xr.DataArray: Grid data with GMT-specific metadata via .gmt accessor
356
357
Notes:
358
- Deprecated: Will be removed in PyGMT v0.20.0
359
- Use xr.open_dataarray() with engine="gmt" instead
360
- Loads data into memory and closes file automatically
361
"""
362
```
363
364
## Usage Examples
365
366
### Basic Configuration
367
368
```python
369
import pygmt
370
371
# Configure map appearance
372
pygmt.config(
373
MAP_FRAME_TYPE="fancy",
374
MAP_FRAME_WIDTH="8p",
375
MAP_GRID_PEN_PRIMARY="0.5p,gray",
376
MAP_ANNOT_FONT_PRIMARY="12p,Helvetica",
377
COLOR_BACKGROUND="lightblue"
378
)
379
380
# Create a map with custom settings
381
fig = pygmt.Figure()
382
fig.basemap(region=[0, 10, 0, 10], projection="X10c", frame="a2f1")
383
fig.show()
384
385
# Reset to defaults (by restarting session or setting explicitly)
386
pygmt.config(
387
MAP_FRAME_TYPE="plain",
388
COLOR_BACKGROUND="white"
389
)
390
```
391
392
### System Information
393
394
```python
395
import pygmt
396
397
# Display comprehensive version information
398
pygmt.show_versions()
399
400
# Get information about a data file
401
data_info = pygmt.info("@earth_relief_01d_g")
402
print("Earth relief data info:")
403
print(data_info)
404
405
# Locate GMT data files
406
relief_path = pygmt.which("@earth_relief_01d_g")
407
print(f"Earth relief grid location: {relief_path}")
408
409
# Check if a file exists in GMT data directories
410
hotspots_path = pygmt.which("@hotspots.txt")
411
if hotspots_path:
412
print(f"Hotspots data found at: {hotspots_path}")
413
else:
414
print("Hotspots data not found")
415
```
416
417
### Display Configuration
418
419
```python
420
import pygmt
421
422
# Configure for different environments
423
# For Jupyter notebooks (usually automatic)
424
pygmt.set_display(method="notebook")
425
426
# For headless servers or batch processing
427
pygmt.set_display(method="none")
428
429
# For desktop environments
430
pygmt.set_display(method="external")
431
432
# Create and display figure (behavior depends on display method)
433
fig = pygmt.Figure()
434
fig.basemap(region="global", projection="W15c", frame=True)
435
fig.coast(shorelines=True)
436
fig.show() # Display method determined by set_display()
437
```
438
439
### Temporary File Management
440
441
```python
442
import pygmt
443
import pandas as pd
444
445
# Create temporary file for data processing
446
data = pd.DataFrame({
447
'x': [1, 2, 3, 4, 5],
448
'y': [2, 4, 6, 8, 10],
449
'z': [1, 4, 9, 16, 25]
450
})
451
452
# Use context manager for automatic cleanup
453
with pygmt.helpers.GMTTempFile(suffix=".txt") as tmpfile:
454
# Save data to temporary file
455
data.to_csv(tmpfile.name, sep='\t', index=False)
456
457
# Use temporary file with GMT functions
458
info_str = pygmt.info(tmpfile.name)
459
print("Temporary data info:", info_str)
460
461
# Process with GMT
462
grid = pygmt.surface(
463
data=tmpfile.name,
464
region=[0, 6, 0, 12],
465
spacing=0.5
466
)
467
# Temporary file automatically deleted here
468
469
print(f"Generated grid shape: {grid.shape}")
470
```
471
472
### Advanced Configuration
473
474
```python
475
import pygmt
476
477
# Set up custom plotting defaults
478
pygmt.config(
479
# Font settings
480
MAP_ANNOT_FONT_PRIMARY="10p,Times-Roman",
481
MAP_LABEL_FONT="12p,Times-Bold",
482
MAP_TITLE_FONT="16p,Times-Bold",
483
484
# Grid and frame settings
485
MAP_FRAME_PEN="1.5p,black",
486
MAP_GRID_PEN_PRIMARY="0.5p,gray50",
487
MAP_GRID_PEN_SECONDARY="0.25p,gray75",
488
MAP_TICK_LENGTH_PRIMARY="6p",
489
490
# Format settings
491
FORMAT_GEO_OUT="ddd:mm:ss",
492
FORMAT_DATE_OUT="yyyy-mm-dd",
493
494
# Paper and color settings
495
PS_MEDIA="A4",
496
COLOR_MODEL="RGB",
497
GMT_VERBOSE="normal"
498
)
499
500
# Create publication-quality figure
501
fig = pygmt.Figure()
502
fig.basemap(
503
region=[-10, 10, -5, 5],
504
projection="M15c",
505
frame=["xa2f1+lLongitude", "ya1f0.5+lLatitude", "WSen+tCustom Map Title"]
506
)
507
fig.coast(shorelines="1p,black", land="lightgray", water="lightblue")
508
509
# Add grid
510
fig.basemap(frame=["xa2f1", "ya1f0.5", "g"])
511
512
fig.show()
513
```
514
515
### Data Processing Pipeline with Utilities
516
517
```python
518
import pygmt
519
import numpy as np
520
521
# Generate sample data
522
np.random.seed(42)
523
x = np.random.uniform(-5, 5, 50)
524
y = np.random.uniform(-5, 5, 50)
525
z = np.exp(-(x**2 + y**2)/10) + 0.1 * np.random.randn(50)
526
527
# Create data table
528
import pandas as pd
529
data = pd.DataFrame({'x': x, 'y': y, 'z': z})
530
531
# Get data information
532
print("Data summary:")
533
with pygmt.helpers.GMTTempFile() as tmpfile:
534
data.to_csv(tmpfile.name, sep='\t', index=False)
535
info_str = pygmt.info(tmpfile.name, verbose=True)
536
print(info_str)
537
538
# Process data with custom configuration
539
pygmt.config(GMT_VERBOSE="verbose") # Enable verbose output
540
541
# Grid the data
542
grid = pygmt.surface(
543
data=data,
544
region=[-6, 6, -6, 6],
545
spacing=0.2,
546
tension=0.25
547
)
548
549
# Get grid information
550
grid_info = pygmt.grdinfo(grid)
551
print("\nGrid information:")
552
print(grid_info)
553
554
# Create visualization
555
fig = pygmt.Figure()
556
fig.grdimage(grid=grid, cmap="hot", projection="X12c")
557
fig.colorbar(frame='a0.2+l"Z values"')
558
fig.plot(x=x, y=y, style="c0.1c", fill="white", pen="0.5p,black")
559
fig.show()
560
```
561
562
### Error Handling and Debugging
563
564
```python
565
import pygmt
566
567
# Enable verbose output for debugging
568
pygmt.config(GMT_VERBOSE="debug")
569
570
try:
571
# This might fail - let's see detailed error info
572
fig = pygmt.Figure()
573
fig.basemap(region=[0, 10, 0, 10], projection="InvalidProjection")
574
575
except pygmt.exceptions.GMTCLibError as e:
576
print(f"GMT Library Error: {e}")
577
# Check system information for debugging
578
pygmt.show_versions()
579
580
except pygmt.exceptions.GMTInvalidInput as e:
581
print(f"Invalid Input Error: {e}")
582
583
finally:
584
# Reset verbosity
585
pygmt.config(GMT_VERBOSE="normal")
586
```
587
588
## Configuration Reference
589
590
### Common GMT Parameters
591
592
**Map Frame and Annotation:**
593
- `MAP_FRAME_TYPE`: "plain" or "fancy"
594
- `MAP_FRAME_WIDTH`: Frame width (e.g., "5p")
595
- `MAP_ANNOT_FONT_PRIMARY`: Primary annotation font
596
- `MAP_TICK_LENGTH_PRIMARY`: Primary tick length
597
598
**Grid and Lines:**
599
- `MAP_GRID_PEN_PRIMARY`: Primary grid pen
600
- `MAP_DEFAULT_PEN`: Default pen for lines
601
- `MAP_VECTOR_SHAPE`: Vector head shape
602
603
**Colors:**
604
- `COLOR_BACKGROUND`: Background color
605
- `COLOR_FOREGROUND`: Foreground color
606
- `COLOR_NAN`: Color for NaN values
607
- `COLOR_MODEL`: "RGB", "HSV", or "CMYK"
608
609
**Paper and Output:**
610
- `PS_MEDIA`: Paper size ("A4", "Letter", etc.)
611
- `PS_PAGE_ORIENTATION`: "portrait" or "landscape"
612
- `GMT_VERBOSE`: "quiet", "normal", "verbose", "debug"
613
614
**Format:**
615
- `FORMAT_GEO_OUT`: Geographic coordinate format
616
- `FORMAT_DATE_OUT`: Date format
617
- `FORMAT_TIME_OUT`: Time format
618
- `FORMAT_FLOAT_OUT`: Floating point format
619
620
All parameters use GMT's standard names and values. Refer to GMT documentation for complete parameter reference.