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 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
|
import tempfile
import os
import sys
import numpy
import cf
#cf.CONSTANTS['FM_THRESHOLD'] = 100000000000000000000
import atexit
'''
Tests for the cf package.
'''
tmpfile = tempfile.mktemp('.nc')
tmpfile2 = tempfile.mktemp('.nca')
tmpfiles = [tmpfile, tmpfile2]
def _remove_tmpfiles():
'''
'''
for f in tmpfiles:
try:
os.remove(f)
except OSError:
pass
#--- End: def
atexit.register(_remove_tmpfiles)
print '\n--------------------------------------------------------------------'
print 'TEST: Set chunk size:'
# Save original chunksize
original_chunksize = cf.CHUNKSIZE()
cf.CHUNKSIZE(60)
print 'CHUNKSIZE reset to',cf.CHUNKSIZE()
print '\n--------------------------------------------------------------------'
print "TEST: Create a field:"
# Dimension coordinates
dim0 = cf.Coordinate(data=cf.Data(numpy.arange(10.), 'degrees'))
dim0.standard_name = 'grid_latitude'
dim1 = cf.Coordinate(data=cf.Data(numpy.arange(9.) + 20, 'degrees'))
dim1.standard_name = 'grid_longitude'
dim1.Data[-1] += 5
bounds = cf.Data(numpy.array([dim1.Data.array-0.5, dim1.Data.array+0.5]).transpose((1,0)))
bounds[-2,1] = 30
bounds[-1,:] = [30, 36]
dim1.insert_bounds(cf.CoordinateBounds(data=bounds))
dim2 = cf.Coordinate(data=cf.Data(1.5), bounds=cf.Data([1, 2.]))
dim2.standard_name = 'atmosphere_hybrid_height_coordinate'
# Auxiliary coordinates
aux0 = cf.Coordinate(data=cf.Data(10., 'm'))
aux0.id = 'atmosphere_hybrid_height_coordinate_ak'
aux0.insert_bounds(cf.Data([5, 15.], aux0.Units))
aux1 = cf.Coordinate(data=cf.Data(20.))
aux1.id = 'atmosphere_hybrid_height_coordinate_bk'
aux1.insert_bounds(cf.Data([14, 26.]))
aux2 = cf.Coordinate(data=cf.Data(numpy.arange(-45, 45, dtype='int32').reshape(10, 9),
units='degree_N'))
aux2.standard_name = 'latitude'
aux3 = cf.Coordinate(
data=cf.Data(numpy.arange(60, 150, dtype='int32').reshape(9, 10),
units='degreesE'))
aux3.standard_name = 'longitude'
# Cell measures
cm0 = cf.CellMeasure(data=cf.Data(numpy.arange(90.).reshape(9, 10)*1234, 'km 2'))
cm0.measure = 'area'
# Transforms
trans0 = cf.Transform(name='rotated_latitude_longitude',
grid_north_pole_latitude=38.0,
grid_north_pole_longitude=190.0)
# Data
data = cf.Data(numpy.arange(90.).reshape(10, 9), 'm s-1')
# Domain
domain = cf.Domain(dim=(dim0, dim1, dim2),
aux=[aux0, aux1, aux2, aux3],
cm={'cm0': cm0},
trans=(trans0,),
assign_axes={'aux0': ['dim2'],
'aux1': ['dim2'],
'aux3': ['dim1', 'dim0'],
'cm0' : ['dim1', 'dim0']})
properties = {'standard_name': 'eastward_wind'}
f = cf.Field(properties=properties, domain=domain, data=data)
orog = f.copy()
orog.standard_name = 'surface_altitude'
orog.insert_data(cf.Data(f.array*2, 'm'))
#orog.Data = cf.Data(f.array*2, 'm')
orog.squeeze()
#orog.domain.squeeze('dim2')
orog.remove_axes('dim2')
orog.transpose([1, 0], i=True)
#orog.finalize()
t = cf.Transform(name='atmosphere_hybrid_height_coordinate',
a='aux0', b='aux1', orog=orog,
coord_terms=('a', 'b'))
print t.inspect
assert(t.equals(t, traceback=True))
#if not t.equals(t, traceback=True):
# raise RuntimeError("Transform is not equal to itself")
#else:
# print '\nTransform is equal to itself'
f.domain.insert_transform(t)
rt = f.item('atmosphere_hybrid_height_coordinate', role='t')
print rt.inspect()
print "f.item('atmosphere_hybrid_height_coordinate', role='t').coords=",rt.coords
print f.Data.dumpd()
f.dump(complete=1)
print '\nf.items() =',f.items()
print '\nf.axes() =',f.axes()
#print (f.array == 9)
# Ancillary variables
tmp = f.copy()
print str(f)
print '+++++++++'
print repr(tmp.item('atmosphere_hybrid_height_coordinate', exact=True))
#del tmp.item('atmosphere_hybrid_height_coordinate', exact=True).transforms
tmp.remove_items(role='t') #transforms()
tmp.remove_item('aux0') #aux('aux0')
tmp.remove_item('atmosphere_hybrid_height_coordinate_bk')
f.ancillary_variables = cf.AncillaryVariables()
print 'ANCILLARY 0'
g = tmp.copy()
g.transpose([1,0], i=True)
g.standard_name = 'ancillary0'
g *= 0.01
g.remove_axes(g.axes().difference(g.data_axes()))
f.ancillary_variables.append(g)
print g
print 'ANCILLARY 1'
g = tmp.copy()
#g.domain.squeeze('dim2')
print g
#g.remove_axes('dim2')
g.standard_name = 'ancillary1'
g *= 0.01
print g
g.remove_axes(g.axes().difference(g.data_axes()))
g.remove_item('atmosphere_hybrid_height_coordinate', role='t')
f.ancillary_variables.append(g)
g.dump(complete=1)
#sys.exit(0)
print 'ANCILLARY 2'
g = tmp.copy()
print g
print g.domain.dimension_sizes, g.domain.dimensions
g = g.subspace[0]
print g.domain.dimension_sizes, g.domain.dimensions
print g.items()
g.squeeze(i=True)
print g.domain.dimension_sizes, g.domain.dimensions
print
g.standard_name = 'ancillary2'
g *= 0.001
g.remove_axes(g.axes().difference(g.data_axes()))
f.ancillary_variables.append(g)
print g
print g.Data
print g.items()
print 'ANCILLARY 3'
g = tmp.copy()
g = g.subspace[..., 0]
g.squeeze(i=True)
g.standard_name = 'ancillary3'
g *= 0.001
g.remove_axes(g.axes().difference(g.data_axes()))
f.ancillary_variables.append(g)
print g
f.flag_values = [1,2,4]
f.flag_meanings = ['a', 'bb', 'ccc']
print '||||||||||||||||'
print f.domain.dimension_sizes
print f.domain.dimensions
print
f.dump(complete=1)
print '--------------------------------------------||||||||||||||||'
print '\n--------------------------------------------------------------------'
print 'TEST: Print a dump of the field:'
print repr(f)
f.dump()
print '\n--------------------------------------------------------------------'
print 'TEST: Print CF properties:'
print f.properties
print '\n--------------------------------------------------------------------'
print "TEST: Shape of the partition array:"
print '(pndim, psize, pshape) =', (f.Data.partitions.ndim,
f.Data.partitions.size,
f.Data.partitions.shape)
f.cell_methods = cf.CellMethods('grid_longitude: mean grid_latitude: max')
print '\n--------------------------------------------------------------------'
print 'TEST: Write the field to disk:'
print 'tmpfile=', tmpfile
f.dump(complete=1)
f.dump()
print f
cf.write(f, tmpfile)
print 'tmpfile=', tmpfile
f.dump(complete=1)
print 'tmpfile=', tmpfile
print '\n--------------------------------------------------------------------'
print 'TEST: Read the field from disk:'
print f
g = cf.read(tmpfile, squeeze=True)[0]
print g
print 'tmpfile=', tmpfile
try:
del g.history
except AttributeError:
pass
g.dump()
print '\n-------------------------------------------------------------------'
print '\nComparison (set)'
c = cf.Comparison('set', [0,3,4,5])
print c
a = (f == c)
print repr(a)
print a.array
print '\n--------------------------------------------------------------------'
print "TEST: Check the equality function:"
assert(cf.equals(g, g.copy(), traceback=True))
print "Field is equal to a copy of itself"
print f
print g
print 'tmpfile=', tmpfile
print f.ancillary_variables[1]
print g.ancillary_variables[1]
f.dump(complete=1)
assert(cf.equals(f, g, traceback=True))
print "Field is equal to itself read back in"
print '\n--------------------------------------------------------------------'
# +, -, *, /, **
h = g.copy()
h **= 2
h **= 0.5
h *= 10
h /= 10.
h += 100
h -= 100
h = h ** 3
h = h ** (1/3.)
h = h * 1000
h = h / 1000.
h = h + 10000
h = h - 10000
assert(cf.equals(g, h, traceback=True))
print "Field +, -, *, / and ** passed"
print '\n--------------------------------------------------------------------'
print "TEST: Operators on a field list:"
h = g.copy()
h.override_units('m')
gl = cf.FieldList([h.copy(), h.copy()])
gl += 2
print ' ', gl[1].datum(-1)
x = 2 #.0
y = gl + x
print ' +',x,':', y[1].datum(-1)
y = gl * x
print ' *',x,':', y[1].datum(-1)
y = gl - x
print ' -',x,':', y[1].datum(-1)
y = gl / x
print ' /',x,':', y[1].datum(-1)
y = gl // x
print ' //',x,':', y[1].datum(-1)
y = gl ** int(x)
print ' **',int(x),':', y[1].datum(-1)
y = x + gl
print x, ' +',':', y[1].datum(-1)
y = x * gl
print x, ' *',':', y[1].datum(-1)
y = x - gl
print x, ' -',':', y[1].datum(-1)
y = x / gl
print x, ' /',':', y[1].datum(-1)
y = x // gl
print x, ' //',':', y[1].datum(-1)
#y = x ** gl
#print x, ' **',':', y[1].datum(-1)
y = gl.copy()
y += x
print ' +=',x,':', y[1].datum(-1)
y = gl.copy()
y *= x
print ' *=',x,':', y[1].datum(-1)
y = gl.copy()
y -= x
print ' -=',x,':', y[1].datum(-1)
y = gl.copy()
y /= x
print ' /=',x,':', y[1].datum(-1)
y = gl.copy()
y //= x
print '//=',x,':', y[1].datum(-1)
y = gl.copy()
y **= int(x)
print '**=',int(x),':', y[1].datum(-1)
y = gl.__truediv__(x)
print ' __truediv__(',x,'):', y[1].datum(-1)
y = gl.__rtruediv__(x)
print '__rtruediv__(',x,'):', y[1].datum(-1)
y = gl.copy()
y.__itruediv__(x)
print '__itruediv__(',x,'):', y[1].datum(-1)
y = gl > x
print ' >',x,':', y[1].datum(-1)
y = gl >= x
print ' >=',x,':', y[1].datum(-1)
y = gl < x
print ' <',x,':', y[1].datum(-1)
y = gl <= x
print ' <=',x,':', y[1].datum(-1)
y = gl == x
print ' ==',x,':', y[1].datum(-1)
y = gl != int(x)
print ' !=',int(x),':', y[1].datum(-1)
y = abs(gl)
print 'abs',' :', y[1].datum(-1)
y = -gl
print ' -',' :', y[1].datum(-1)
y = +gl
print ' +',' :', y[1].datum(-1)
#y = ~gl
#print ' ~',' :', y[1].datum(-1)
gl.dtype = int
y = gl & x
print ' &',int(x),':', y[1].datum(-1)
y = gl | x
print ' |',int(x),':', y[1].datum(-1)
y = gl ^ x
print ' ^',int(x),':', y[1].datum(-1)
y = gl << x
print ' <<',int(x),':', y[1].datum(-1)
y = gl >> x
print ' >>',int(x),':', y[1].datum(-1)
y = x & gl
print int(x),' &',':', y[1].datum(-1)
y = x | gl
print int(x),' |',':', y[1].datum(-1)
y = x ^ gl
print int(x),' ^',':', y[1].datum(-1)
y = x << gl
print int(x),' <<',':', y[1].datum(-1)
y = x >> gl
print int(x),' >>',':', y[1].datum(-1)
y = gl.copy()
y &= x
print ' &=',int(x),':', y[1].datum(-1)
y = gl.copy()
y |= x
print ' |=',int(x),':', y[1].datum(-1)
y = gl.copy()
y ^= x
print ' ^=',int(x),':', y[1].datum(-1)
#sys.exit(0)
print '\n--------------------------------------------------------------------'
print "TEST: tranpose, flip, expand_dims, squeeze and remove_axes:"
h = g.copy()
h.transpose((1, 0), i=True)
h.transpose((1, 0), i=True)
h.transpose(('grid_longitude', 'grid_latitude'), i=True)
h.transpose(('grid_latitude', 'grid_longitude'), i=True)
assert(cf.equals(g, h, traceback=True))
print "Tranpose of field passed"
h.flip((1, 0), i=True)
h.flip((1, 0), i=True)
h.flip(0, i=True)
h.flip(1, i=True)
h.flip([0, 1], i=True)
assert(cf.equals(g, h, traceback=True))
print "Flipping field axes passed"
#axisA = h.expand_dims()
#axisB = h.expand_dims()
#h.remove_axes([axisA, axisB])
#assert(cf.equals(g, h, traceback=True))
#print "Field expand_dims, squeeze and remove_axes passed"
print '\n--------------------------------------------------------------------'
print "TEST: Access the field's data as a numpy array:"
print g.array
print '\n--------------------------------------------------------------------'
print "TEST: Access the field's coordinates' data arrays:"
print 'grid_latitude :', g.item('lat').array
print 'grid_longitude:', g.item('lon').array
print '\n--------------------------------------------------------------------'
print 'TEST: Subspace the field (1):'
print g.subspace[..., 2:5].array
print '\n--------------------------------------------------------------------'
print 'TEST: Subspace the field (2):'
print g.subspace[9::-4, ...].array
print '\n--------------------------------------------------------------------'
print 'TEST: Subspace the field (3):'
h = g.subspace[(slice(None, None, -1),) * g.ndim]
print '\n\n\n\@AND BACK\n\n\n\n'
h.dump(complete=1)
h = h.subspace[(slice(None, None, -1),) * h.ndim]
print g
print h
g.dump(complete=1)
assert(g.equals(h, traceback=True))
print '\n--------------------------------------------------------------------'
print 'TEST: Indices for a subspace defined by coordinates:'
print f.indices()
print f.indices(grid_lat=cf.lt(5), grid_lon=27)
print f.indices('exact',
grid_latitude=cf.lt(5), grid_longitude=27,
atmosphere_hybrid_height_coordinate=1.5)
print '\n--------------------------------------------------------------------'
print 'TEST: Subspace the field:'
print g.subspace(grid_latitude=cf.lt(5), grid_longitude=27, atmosphere_hybrid_height_coordinate=1.5)
print '\n--------------------------------------------------------------------'
print 'TEST: Create list of fields:'
fl = cf.FieldList([g, g, g, g])
print '\n--------------------------------------------------------------------'
print 'TEST: Write a list of fields to disk:'
cf.write((f, fl), tmpfile)
cf.write(fl, tmpfile)
print '\n--------------------------------------------------------------------'
print 'TEST: Read a list of fields from disk:'
fl = cf.read(tmpfile, squeeze=True)
try:
fl.delattr('history')
except AttributeError:
pass
print repr(fl)
print '\n--------------------------------------------------------------------'
print 'TEST: Print all fields in the list:'
print fl
print '\n--------------------------------------------------------------------'
print 'TEST: Print the last field in the list:'
print fl[-1]
print '\n--------------------------------------------------------------------'
print 'TEST: Print the data of the last field in the list:'
print fl[-1].array
print '\n--------------------------------------------------------------------'
print 'TEST: Modify the last field in the list:'
fl[-1] *= -1
print fl[-1].array
print '\n--------------------------------------------------------------------'
print 'TEST: Changing units\n:'
fl[-1].units = 'mm.s-1'
print fl[-1].array
print '\n--------------------------------------------------------------------'
print 'TEST: Combine fields not in place:'
g = fl[-1] - fl[-1]
print g.array
print '\n--------------------------------------------------------------------'
print 'TEST: Combine field with a size 1 Data object:'
g += cf.Data([[[[[1.5]]]]], 'cm.s-1')
print g.array
g.dump()
print '\n--------------------------------------------------------------------'
print "TEST: Setting data array elements to a scalar with subspace[]:"
g.subspace[...] = 0
print g
g.subspace[3:7, 2:5] = -1
print g.array,'\n'
g.subspace[6:2:-1, 4:1:-1] = numpy.array(-1)
print g.array,'\n'
g.subspace[[0, 3, 8], [1, 7, 8]] = numpy.array([[[[-2]]]])
print g.array,'\n'
g.subspace[[8, 3, 0], [8, 7, 1]] = cf.Data(-3, None)
print g.array,'\n'
g.subspace[[7, 4, 1], slice(6, 8)] = [-4]
print g.array
print '\n--------------------------------------------------------------------'
print "TEST: Setting of (un)masked elements with setdata():"
g.subspace[::2, 1::2] = numpy.ma.masked
print g.array,'\n'
g.Data.to_memory(1)
print g.Data.partitions[0][1].subarray
g.setdata(99, None)
print g.array,'\n'
g.Data.to_memory(1)
print g.Data.partitions[0][1].subarray
g.setdata(2, None, g.mask) # Softern?
print g.array,'\n'
g.Data.to_memory(1)
print g.Data.partitions[0][1].subarray
print '\n--------------'
g.subspace[slice(None, None, 2), slice(1, None, 2)] = cf.masked
print g.array,'\n'
g.Data.to_memory(1)
print g.Data.partitions[0][1].subarray
g.setdata([[-1]], None, g.mask)
print g.array,'\n'
g.Data.to_memory(1)
print g.Data.partitions[0][1].subarray
g.setdata(cf.Data(0, None), None)
print g.array,'\n'
g.Data.to_memory(1)
print g.Data.partitions[0][1].subarray
h = g.subspace[:3, :4]
h.setdata(-1, None)
h.subspace[0, 2] = 2
h.dump()
print h.array
h.transpose([1, 0], i=True)
print h.array
h.flip([1, 0], i=True)
print h.array, h.shape
print h
print g.subspace[slice(None, 3), slice(None, 4)], g.subspace[slice(None, 3), slice(None, 4)].shape
print 'AA', g.shape, g.subspace[slice(None, 3), slice(None, 4)].shape
g.subspace[slice(None, 3), slice(None, 4)] = h
h = g.subspace[:3, :4]
h.subspace[...] = -1
h.subspace[0, 2] = 2
g.subspace[slice(None, 3), slice(None, 4)] = h
print g.array
print '\n--------------------------------------------------------------------'
print "TEST: Make sure all partitions' data are in temporary files:"
g.Data.to_disk()
print g.Data.partitions
#sys.exit(0)
print '\n--------------------------------------------------------------------'
print "TEST: Push partitions' data from temporary files into memory:"
g.Data.to_memory(regardless=True)
print g.Data.partitions
print '\n--------------------------------------------------------------------'
print g.Data.partitions
print "TEST: Push partitions' data from memory to temporary files:"
g.Data.to_disk()
print g.Data.partitions
print '\n--------------------------------------------------------------------'
print "TEST: Iterate through array values:"
for x in f.Data.flat():
print x,
print
print '\n--------------------------------------------------------------------'
print 'TEST: Reset chunk size:'
cf.CHUNKSIZE(original_chunksize)
print 'CHUNKSIZE reset to',cf.CHUNKSIZE()
print '\n--------------------------------------------------------------------'
print 'TEST: Move Data partitions to disk:'
f.Data.to_disk()
print f.Data.dumpd()
print '\n--------------------------------------------------------------------'
print 'TEST: Create a CFA file ('+tmpfile2+'):'
cf.write(f, tmpfile2, fmt='CFA4')
cf.write(f, tmpfile2, fmt='CFA3')
print 'OK'
print '\n--------------------------------------------------------------------'
print 'TEST: Read the CFA file ('+tmpfile2+'):'
n = cf.read(tmpfile2, squeeze=True)[0]
print repr(n)
if not cf.equals(f, n, traceback=True):
raise RuntimeError("Field is not equal to itself read back in from CFA file")
print 'OK'
cf.CHUNKSIZE(original_chunksize)
print f
f.transpose(i=True)
f.flip(i=True)
print f.Data.dumpd()
cf.write(f, 'delme.nc')
print f
f = cf.read('delme.nc')[0]
print f
print '########################################'
print f.Data.dumpd()
cf.write(f, 'delme.nca', fmt='CFA4')
g = cf.read('delme.nca')[0]
print g
f.aux('aux0').id = 'atmosphere_hybrid_height_coordinate_ak'
f.aux('aux1').id = 'atmosphere_hybrid_height_coordinate_bk'
b = f.subspace[:,0:6,:]
c = f.subspace[:,6:,:]
print '-----------------------'
print f
print b
print c
d = cf.aggregate([b, c], info=1)[0]
print d
print '\n--------------------------------------------------------------------'
print "TEST: Remove temporary files:"
cf.data.partition._remove_temporary_files()
cf.CHUNKSIZE(original_chunksize)
f.dump(complete=1)
|