| 30 | |
| 31 | |
| 32 | def copy_and_reduce(opts): |
| 33 | infilename = opts.filename |
| 34 | outfilename = os.path.expanduser( |
| 35 | os.path.join(opts.outdir, "ci_test_file.nc")) |
| 36 | |
| 37 | with Dataset(infilename) as infile, Dataset(outfilename, "w") as outfile: |
| 38 | |
| 39 | # Copy the global attributes |
| 40 | outfile.setncatts(infile.__dict__) |
| 41 | |
| 42 | # Copy Dimensions |
| 43 | for name, dimension in infile.dimensions.iteritems(): |
| 44 | if name in DIMS_TO_TRIM: |
| 45 | if name.find("_stag") > 0: |
| 46 | dimsize = (len(dimension) / 2 |
| 47 | if len(dimension) % 2 == 0 |
| 48 | else (len(dimension) + 1) / 2) |
| 49 | else: |
| 50 | dimsize = (len(dimension) / 2 |
| 51 | if len(dimension) % 2 == 0 |
| 52 | else (len(dimension) - 1) / 2) |
| 53 | else: |
| 54 | dimsize = len(dimension) |
| 55 | |
| 56 | outfile.createDimension(name, dimsize) |
| 57 | |
| 58 | # Copy Variables |
| 59 | for name, variable in infile.variables.iteritems(): |
| 60 | if name not in VARS_TO_KEEP: |
| 61 | continue |
| 62 | |
| 63 | outvar = outfile.createVariable(name, variable.datatype, |
| 64 | variable.dimensions, zlib=True) |
| 65 | |
| 66 | in_slices = tuple(slice(0, dimsize) for dimsize in outvar.shape) |
| 67 | |
| 68 | outvar[:] = variable[in_slices] |
| 69 | outvar.setncatts(infile.variables[name].__dict__) |
| 70 | |
| 71 | |
| 72 | def add_to_ncfile(outfile, var, varname): |