File: field_creation.rst

package info (click to toggle)
cf-python 1.3.2+dfsg1-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, stretch
  • size: 7,996 kB
  • sloc: python: 51,733; ansic: 2,736; makefile: 78; sh: 2
file content (394 lines) | stat: -rw-r--r-- 14,919 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
.. currentmodule:: cf
.. default-role:: obj

.. _field_creation:
 
Creating `cf.Field` objects
===========================

A new field may be created by initializing a new `cf.Field`
instance. Data and metadata are provided with the following keyword
parameters, all of which are optional:

=======================  =============================================================
Keyword                  Description
=======================  =============================================================
``ancillary_variables``  Provide the new field with ancillary variable fields in a
                         `cf.AncillaryVariables` object
``attributes``           Provide the new field with attributes in a dictionary
``data``                 Provide the new field with a data array in a `cf.Data` object
``dimensions``           Provide the new field with a data array dimensions
``domain``               Provide the new field with a coordinate system in a
			 `cf.Domain` object
``flags``                Provide the new field with self-describing flag values in a
                         `cf.Flags` object
``properties``           Provide the new field with CF properties in a dictionary
=======================  =============================================================

.. _domain-creation:

Domain creation
---------------

Creating a domain possibly comprises the largest part of field
creation, because the domain itself is composed of many interrelated
items (dimension and auxiliary coordinate, cell measure and coordinate
reference objects). It is not, however, difficult and is essentially a
methodical assembly of components. Domain initialization is fully
described in the documention of the `cf.Domain` object.

Each component of the field's domain has an internal identifier
(unique strings such as ``'dim1'``, ``'aux0'``, ``'msr2'`` and
``'ref0'``), but for many field initializations, there is no need to
provide, nor have any knowledge of these. However, they are easy to
set if required (which may be the case if, for example, two
multidimensional auxiliary coordinates span the same dimensions but in
different orders) or if desired for clarity.

.. _inserting-and-removing-components:

Inserting and removing components 
---------------------------------

Inserting field components after initialization is done with the
following methods:

.. autosummary::
   :nosignatures:
   :template: method.rst

   cf.Field.insert_aux
   cf.Field.insert_axis
   cf.Field.insert_data
   cf.Field.insert_dim
   cf.Field.insert_measure
   cf.Field.insert_ref

For example:

>>> coord
<CF DimensionCoordinate: time(12) days since 2003-12-1>
>>> f.domain.insert_dim(coord)

Note that inserting domain items during field initialization is likely
to be faster than using the insertion methods afterwards.

Removing field components is done with the following methods:

.. autosummary::
   :nosignatures:
   :template: method.rst

   cf.Field.remove_axis
   cf.Field.remove_axes
   cf.Field.remove_data
   cf.Field.remove_item
   cf.Field.remove_items

For example:

>>> f.domain.remove_item('forecast_reference_time')


.. _field-creation_examples:

Examples
--------

To improve readability, it is recommended that the construction of a
field is done by first creating the components separately (data,
coordinates, properties, *etc.*), and then combining them to make the
field (as in :ref:`example 3 <fc-example3>` and :ref:`example 4
<fc-example4>`), although this may not be necessary for very simple
fields (as in :ref:`example 1 <fc-example1>` and :ref:`example 2
<fc-example2>`).

.. _fc-example1:

Example 1
~~~~~~~~~

An empty field:

>>> f = cf.Field()
>>> print f
 field summary
--------------

.. _fc-example2:

Example 2
~~~~~~~~~

A field with just CF properties:

>>> f = cf.Field(properties={'standard_name': 'air_temperature',
...                          'long_name': 'temperature of air'})
...
>>> print f
air_temperature field summary
-----------------------------

.. _fc-example3:

Example 3
~~~~~~~~~

A field with a simple domain. Note that in this example the data and
coordinates are generated using :py:obj:`range` and `numpy.arange`
simply for the sake of having some numbers to play with. In practice
it is likely the values would have been read from a file in some
arbitrary format:

>>> import numpy
>>> data = cf.Data(numpy.arange(90.).reshape(10, 9), 'm s-1')
>>> properties = {'standard_name': 'eastward_wind'}
>>> dim0 = cf.DimensionCoordinate(data=cf.Data(range(10), 'degrees_north'),
...                               properties={'standard_name': 'latitude'})
...
>>> dim1 = cf.DimensionCoordinate(data=cf.Data(range(9), 'degrees_east'))
>>> dim1.standard_name = 'longitude'
>>> domain = cf.Domain(dim=[dim0, dim1])
>>> f = cf.Field(properties=properties, data=data, domain=domain)
>>> print f
eastward_wind field summary
---------------------------
Data            : eastward_wind(latitude(10), longitude(9)) m s-1
Dimensions      : latitude(10) = [0, ..., 9] degrees_north
                : longitude(9) = [0, ..., 8] degrees_east

Note that the default dimension order of ``['dim0', 'dim1']`` is
applicable to the field's data array.

Adding an auxiliary coordinate to the "latitude" axis and a cell
method may be done with the :ref:`relevant method
<inserting-and-removing-components>` and by simple assignment
respectively (note that these coordinate values are just for
illustration):

>>> aux = cf.AuxiliaryCoordinate(data=cf.Data(['alpha','beta','gamma','delta','epsilon',
...                                             'zeta','eta','theta','iota','kappa']))
...				       
>>> aux.long_name = 'extra'
>>> print f.items()
{'dim0': <CF DimensionCoordinate: latitude(10) degrees_north>,
 'dim1': <CF DimensionCoordinate: longitude(9) degrees_east>}
>>> f.insert_aux(aux, axes=['dim0'])
'aux0'
>>> f.cell_methods = cf.CellMethods('latitude: point')
>>> f.long_name = 'wind'
>>> print f
eastward_wind field summary
---------------------------
Data            : eastward_wind(latitude(10), longitude(9)) m s-1
Cell methods    : latitude: point
Dimensions      : latitude(10) = [0, ..., 9] degrees_north
                : longitude(9) = [0, ..., 8] degrees_east
Auxiliary coords: long_name:extra(latitude(10)) = ['alpha', ..., 'kappa'] 

Removing the auxiliary coordinate and the cell method that were just
added is also done with the :ref:`relevant method
<inserting-and-removing-components>` and by simple deletion
respectively:

>>> f.remove_item({'long_name': 'extra'})
<CF AuxiliaryCoordinate: long_name:extra(10)>
>>> del f.cell_methods
>>> print f
eastward_wind field summary
---------------------------
Data            : eastward_wind(latitude(10), longitude(9)) m s-1
Dimensions      : latitude(10) = [0, ..., 9] degrees_north
                : longitude(9) = [0, ..., 8] degrees_east

.. _fc-example4:

Example 4
~~~~~~~~~

.. highlight:: guess

A more complicated field is created by the following script. Note that
in this example the data and coordinates are generated using
`numpy.arange` simply for the sake of having some numbers to play
with. In practice it is likely the values would have been read from a
file in some arbitrary format::

   import cf
   import numpy
   
   #---------------------------------------------------------------------
   # 1. CREATE the field's domain items
   #---------------------------------------------------------------------
   # Create a grid_latitude dimension coordinate
   Y = cf.DimensionCoordinate(properties={'standard_name': 'grid_latitude'},
                                 data=cf.Data(numpy.arange(10.), 'degrees'))
   
   # Create a grid_longitude dimension coordinate
   X = cf.DimensionCoordinate(data=cf.Data(numpy.arange(9.), 'degrees'))
   X.standard_name = 'grid_longitude'
   
   # Create a time dimension coordinate (with bounds)
   bounds = cf.CoordinateBounds(
       data=cf.Data([0.5, 1.5], cf.Units('days since 2000-1-1', calendar='noleap')))
   T = cf.DimensionCoordinate(properties=dict(standard_name='time'),
                              data=cf.Data(1, cf.Units('days since 2000-1-1',
                                                       calendar='noleap')),
                              bounds=bounds)
   
   # Create a longitude auxiliary coordinate
   lat = cf.AuxiliaryCoordinate(data=cf.Data(numpy.arange(90).reshape(10, 9),
                                             'degrees_north'))
   lat.standard_name = 'latitude'
   
   # Create a latitude auxiliary coordinate
   lon = cf.AuxiliaryCoordinate(properties=dict(standard_name='longitude'),
                                data=cf.Data(numpy.arange(1, 91).reshape(9, 10),
                                             'degrees_east'))
   
   # Create a rotated_latitude_longitude grid mapping coordinate reference
   grid_mapping = cf.CoordinateReference('rotated_latitude_longitude',
                                         grid_north_pole_latitude=38.0,
                                         grid_north_pole_longitude=190.0)
   
   # --------------------------------------------------------------------
   # 2. Create the field's domain from the previously created items
   # --------------------------------------------------------------------
   domain = cf.Domain(dim=[T, Y, X],
                      aux=[lat, lon],
                      ref=grid_mapping)

   #---------------------------------------------------------------------
   # 3. Create the field
   #---------------------------------------------------------------------
   # Create CF properties
   properties = {'standard_name': 'eastward_wind',
                 'long_name'    : 'East Wind',
                 'cell_methods' : cf.CellMethods('latitude: point')}
   
   # Create the field's data array
   data = cf.Data(numpy.arange(90.).reshape(9, 10), 'm s-1')
   
   # Finally, create the field
   f = cf.Field(properties=properties,
                domain=domain,
                data=data)
    
   print "The new field:\n"
   print f

.. highlight:: none

Running this script produces the following output::

   The new field:

   eastward_wind field summary
   ---------------------------
   Data           : eastward_wind(grid_longitude(9), grid_latitude(10)) m s-1
   Cell methods   : latitude: point
   Axes           : time(1) = [2000-01-02 00:00:00] noleap
                  : grid_longitude(9) = [0.0, ..., 8.0] degrees
                  : grid_latitude(10) = [0.0, ..., 9.0] degrees
   Aux coords     : latitude(grid_latitude(10), grid_longitude(9)) = [[0, ..., 89]] degrees_north
                  : longitude(grid_longitude(9), grid_latitude(10)) = [[1, ..., 90]] degrees_east
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>

.. highlight:: guess

.. _fc-example5:

Example 5
~~~~~~~~~

:ref:`Example 4 <fc-example4>` would be slightly more complicated if
the ``grid_longitude`` and ``grid_latitude`` axes were to have the
same size. In this case the domain needs be told which axes, and in
which order, are spanned by the two dimensional auxiliary coordinates
(``latitude`` and ``longitude``) and the field needs to know which
axes span the data array::

   import cf
   import numpy
   

   #---------------------------------------------------------------------
   # 1. CREATE the field's domain items
   #---------------------------------------------------------------------
   # Create a grid_latitude dimension coordinate
   Y = cf.DimensionCoordinate(properties={'standard_name': 'grid_latitude'},
                                 data=cf.Data(numpy.arange(10.), 'degrees'))
   
   # Create a grid_longitude dimension coordinate
   X = cf.DimensionCoordinate(data=cf.Data(numpy.arange(10.), 'degrees'))
   X.standard_name = 'grid_longitude'
   
   # Create a time dimension coordinate (with bounds)
   bounds = cf.CoordinateBounds(
       data=cf.Data([0.5, 1.5], cf.Units('days since 2000-1-1', calendar='noleap')))
   T = cf.DimensionCoordinate(properties=dict(standard_name='time'),
                              data=cf.Data(1, cf.Units('days since 2000-1-1',
                                                       calendar='noleap')),
                              bounds=bounds)
   
   # Create a longitude auxiliary coordinate
   lat = cf.AuxiliaryCoordinate(data=cf.Data(numpy.arange(100).reshape(10, 10),
                                             'degrees_north'))
   lat.standard_name = 'latitude'
   
   # Create a latitude auxiliary coordinate
   lon = cf.AuxiliaryCoordinate(properties=dict(standard_name='longitude'),
                                data=cf.Data(numpy.arange(1, 101).reshape(10, 10),
                                             'degrees_east'))
   
   # Create a rotated_latitude_longitude grid mapping coordinate reference
   grid_mapping = cf.CoordinateReference('rotated_latitude_longitude',
                                         grid_north_pole_latitude=38.0,
                                         grid_north_pole_longitude=190.0)
   
   # --------------------------------------------------------------------
   # 2. Create the field's domain from the previously created items
   # --------------------------------------------------------------------
   domain = cf.Domain(dim=[T, Y, X],
                      aux={'aux0': lat, 'aux1': lon},
                      ref=grid_mapping,
		      assign_axes={'aux0': ['grid_latitude', 'grid_longitude'],
                          	   'aux1': ['grid_longitude', 'grid_latitude']})

   #---------------------------------------------------------------------
   # 3. Create the field
   #---------------------------------------------------------------------
   # Create CF properties
   properties = {'standard_name': 'eastward_wind',
                 'long_name'    : 'East Wind',
                 'cell_methods' : cf.CellMethods('latitude: point')}
   
   # Create the field's data array
   data = cf.Data(numpy.arange(90.).reshape(9, 10), 'm s-1')
   
   # Finally, create the field
   f = cf.Field(properties=properties,
                domain=domain,
                data=data,
                axes=['grid_latitude', 'grid_longitude'])
    
   print "The new field:\n"
   print f


.. highlight:: none

Running this script produces the following output::

   eastward_wind field summary
   ---------------------------
   Data           : eastward_wind(grid_latitude(10), grid_longitude(10)) m s-1
   Cell methods   : latitude: point
   Axes           : time(1) = [2000-01-02 00:00:00] noleap
                  : grid_longitude(10) = [0.0, ..., 9.0] degrees
                  : grid_latitude(10) = [0.0, ..., 9.0] degrees
   Aux coords     : latitude(grid_latitude(10), grid_longitude(10)) = [[0, ..., 99]] degrees_north
                  : longitude(grid_longitude(10), grid_latitude(10)) = [[1, ..., 100]] degrees_east
   Coord refs     : <CF CoordinateReference: rotated_latitude_longitude>

.. highlight:: guess