@@ -638,13 +638,15 @@ function cgll2latlonz(field; DIR = "cgll2latlonz_dir", nlat = 360, nlon = 720, c
638638end
639639
640640"""
641- truncate_dataset(datafile, name , datapath_trunc, date0, t_start, t_end, comms_ctx)
641+ truncate_dataset(datafile, filename, varname , datapath_trunc, date0, t_start, t_end, comms_ctx)
642642
643- Truncates given data set, and constructs a new dataset containing only the dates that are used in the simulation
643+ Truncates given data set, and constructs a new dataset containing only
644+ the dates that are used in the simulation
644645"""
645646function truncate_dataset (
646647 datafile,
647- name,
648+ filename,
649+ varname,
648650 datapath_trunc,
649651 date0,
650652 t_start,
@@ -654,17 +656,44 @@ function truncate_dataset(
654656 date_start = date0 + Dates. Second (t_start)
655657 date_end = date0 + Dates. Second (t_start + t_end)
656658
657- file_name = replace (string (name, " _truncated_data_" , string (date_start), string (date_end), " .nc" ), r" :" => " " )
658- datafile_truncated = joinpath (datapath_trunc, file_name)
659+ filename_truncated = replace (
660+ string (lowercase (filename), " _truncated_data_" , string (date_start), string (date_end), " .nc" ),
661+ r" :" => " " ,
662+ )
663+ datafile_truncated = joinpath (datapath_trunc, filename_truncated)
659664
660665 if ClimaComms. iamroot (comms_ctx)
661666 ds = NCDatasets. NCDataset (datafile, " r" )
662667 dates = ds[" time" ][:]
663668
669+ # Find the bounding indices of the dates we need
664670 (start_id, end_id) = find_idx_bounding_dates (dates, date_start, date_end)
665671
672+ var_truncated = NCDatasets. nomissing (NCDatasets. view (ds, time = start_id: end_id)[varname])
673+
674+ # Create new dataset to fill with truncated data
666675 ds_truncated = NCDatasets. NCDataset (datafile_truncated, " c" )
667- ds_truncated = NCDatasets. write (ds_truncated, NCDatasets. view (ds, time = start_id: end_id))
676+
677+ # Keep all dimensions of original dataset (except for time, which we truncate)
678+ ds_dim_names = NCDatasets. dimnames (ds[varname])
679+ for dim_name in ds_dim_names
680+ dim_name != " time" && NCDatasets. defDim (ds_truncated, dim_name, ds. dim[dim_name])
681+ end
682+ dates_truncated = dates[start_id: end_id]
683+ NCDatasets. defDim (ds_truncated, " time" , length (dates_truncated))
684+ ds_truncated. attrib[" title" ] = ds. attrib[" title" ] * " (dates truncated)"
685+
686+ # Define dimension variables
687+ for dim_name in ds_dim_names
688+ if dim_name == " time"
689+ var = NCDatasets. defVar (ds_truncated, dim_name, dates_truncated, (dim_name,))
690+ else
691+ var = NCDatasets. defVar (ds_truncated, dim_name, ds[dim_name][:], (dim_name,))
692+ end
693+ end
694+
695+ # Create variable of interest in new dataset, and fill with input dataset values
696+ var = NCDatasets. defVar (ds_truncated, varname, var_truncated, ds_dim_names)
668697
669698 close (ds)
670699 close (ds_truncated)
0 commit comments