def main(radial, database=False): """ :param radial: :param database: :return: """ # Get directory and filename of radial file pathname, filename = os.path.split(radial) pathname_qc = os.path.join(pathname.split('radials')[0], 'radials_qc', filename[5:9]) filename_qc = os.path.join(pathname_qc, filename) # Create new dir from pathname if it doesn't already exist cf.create_dir(pathname_qc) # Parse the radial file with the generic codar CTF/LLUV parser located in functions/common radial_file_data = cf.parse_lluv(radial) # Create radial_data variable with alias for main datatable in radial_file_data radial_data = radial_file_data['tables']['1']['data'] # QARTOD QC Tests radial_data = qc.qc_location(radial_data) radial_data = qc.qc_speed(radial_data, 250) radial_file_data['header']['qc_qartod_radial_count'] = str(qc.qc_radial_count(radial_data, 150, 300)) # Modify any tableheader information that needs to be updated radial_file_data['tables']['1']['TableColumns'] = radial_data.shape[1] header_list = radial_data.columns.tolist() header_list.remove('%%') radial_file_data['tables']['1']['TableColumnTypes'] = ' '.join(header_list) # Generate quality controlled radial file create_ruv(radial_file_data, filename_qc)
def plot_ctdmo(data_dict, var, stdev=None): colors10 = [ 'red', 'firebrick', 'orange', 'mediumseagreen', 'blue', 'darkgreen', 'purple', 'indigo', 'slategray', 'black' ] colors16 = [ 'red', 'firebrick', 'orange', 'gold', 'mediumseagreen', 'darkcyan', 'blue', 'darkgreen', 'purple', 'lightgray', 'slategray', 'black', 'coral', 'gold', 'limegreen', 'midnightblue' ] fig, ax1 = plt.subplots() sensor_list = [] median_list = [] for i, (key, value) in enumerate(data_dict.items()): if len(data_dict) < 11: colors = colors10 else: colors = colors16 t = value['time'] y = value['yD'] if stdev != None: ind = cf.reject_outliers(value['yD'], stdev) t = t[ind] y = y[ind] refdes = str(key) sensor_list.append(refdes.split('-')[-1]) median_list.append(value['median']) plt.scatter(t, y, c=colors[i], marker='.', s=.5) if i == len(data_dict) - 1: # if the last dataset has been plotted plt.grid() plt.margins(y=.05, x=.05) # refdes on secondary y-axis only for pressure and density if var in ['ctdmo_seawater_pressure', 'density']: ax2 = ax1.twinx() ax2.set_ylim(ax1.get_ylim()) plt.yticks(median_list, sensor_list, fontsize=7.5) plt.subplots_adjust(right=.85) pf.format_date_axis(ax1, fig) pf.y_axis_disable_offset(ax1) subsite = refdes.split('-')[0] title = subsite + ' ' + ('-'.join( (value['dms'].split('-')[0], value['dms'].split('-')[1]))) ax1.set_ylabel((var + " (" + value['yunits'] + ")"), fontsize=9) ax1.set_title(title, fontsize=10) fname = '-'.join((subsite, value['dms'], var)) if stdev != None: fname = '-'.join((fname, 'outliers_rejected')) sdir = os.path.join(sDir, subsite, value['dms'].split('-')[0]) cf.create_dir(sdir) pf.save_fig(sdir, fname)
def main(sDir, url_list, preferred_only): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) ms = uu.split(rd + '-')[1].split('/')[0] if rd not in rd_list: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) subsite = r.split('-')[0] array = subsite[0:2] datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) if preferred_only == 'yes': ps_df, n_streams = cf.get_preferred_stream_info(r) fdatasets = [] for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets = cf.filter_collocated_instruments(main_sensor, fdatasets) num_data = len(fdatasets) save_dir = os.path.join(sDir, array, subsite, r, 'preferred_method_plots') cf.create_dir(save_dir) print(len(fdatasets)) if len(fdatasets) > 3: steps = list(range(3, len(fdatasets) + 3, 3)) for ii in steps: plot_velocity_variables(r, fdatasets[ii - 3:ii], 3, save_dir) else: plot_velocity_variables(r, fdatasets, 3, save_dir)
def main(files, out): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ fname, ext = os.path.splitext(files) if ext in '.nc': list_files = [files] elif ext in '.ncml': list_files = [files] else: list_files = read_file(files) stream_vars = pf.load_variable_dict(var='eng') # load engineering variables # for nc in list_files: # print nc # the engine that xarray uses can be changed as specified here # http://xarray.pydata.org/en/stable/generated/xarray.open_dataset.html#xarray.open_dataset with xr.open_mfdataset(list_files, engine='netcdf4') as ds_disk: # change dimensions from 'obs' to 'time' ds_disk = ds_disk.swap_dims({'obs': 'time'}) ds_variables = ds_disk.data_vars.keys() # List of dataset variables stream = ds_disk.stream # List stream name associated with the data title_pre = mk_str(ds_disk.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds_disk.attrs, 's') # , var, tt0, tt1, 's') save_dir = os.path.join(out, ds_disk.subsite, ds_disk.node, ds_disk.stream, 'pcolor') cf.create_dir(save_dir) # t0, t1 = cf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = t0 + t1 - (t0 / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] # time_list = [[t0, t1]] # for period in time_list: # tt0 = period[0] # tt1 = period[1] # sub_ds = ds_disk.sel(time=slice(str(tt0), str(tt1))) bins = ds_disk['bin_depths'] north = ds_disk['northward_seawater_velocity'] east = ds_disk['eastward_seawater_velocity'] # up = ds_disk['upward_seawater_velocity'] # error = ds_disk['error_velocity'] time = dict(data=ds_disk['time'].data, info=dict(label=ds_disk['time'].standard_name, units='GMT')) bins = dict(data=bins.data.T, info=dict(label=bins.long_name, units=bins.units)) north = dict(data=north.data.T, info=dict(label=north.long_name, units=north.units)) east = dict(data=east.data.T, info=dict(label=east.long_name, units=east.units)) # up = dict(data=up.data.T, info=dict(label=up.long_name, units=up.units)) # error = dict(data=error.data.T, info=dict(label=error.long_name, units=error.units)) sname = save_pre + 'ADCP' title = title_pre fig, axs = pf.adcp(time, bins, north, east, title) pf.resize(width=12, height=8.5) # Resize figure pf.save_fig(save_dir, sname, res=250) # Save figure plt.close('all')
def main(sDir, f): ff = pd.read_csv(os.path.join(sDir, f)) datasets = cf.get_nc_urls(ff['outputUrl'].tolist()) for d in datasets: print(d) fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( d) save_dir = os.path.join(sDir, subsite, refdes, deployment) cf.create_dir(save_dir) sci_vars = cf.return_science_vars(stream) colors = cm.jet(np.linspace(0, 1, len(sci_vars))) with xr.open_dataset(d, mask_and_scale=False) as ds: ds = ds.swap_dims({'obs': 'time'}) t = ds['time'].data t0 = pd.to_datetime(t.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(t.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) fig, ax = plt.subplots() axes = [ax] for i in range(len(sci_vars)): if i > 0: axes.append(ax.twinx() ) # twin the x-axis to make independent y-axes fig.subplots_adjust(right=0.6) right_additive = (0.98 - 0.6) / float(5) for i in range(len(sci_vars)): if i > 0: axes[i].spines['right'].set_position( ('axes', 1. + right_additive * i)) y = ds[sci_vars[i]] ind = cf.reject_outliers(y, 5) yD = y.data[ind] x = t[ind] #yD = y.data c = colors[i] axes[i].plot(x, yD, '.', markersize=2, color=c) axes[i].set_ylabel((y.name + " (" + y.units + ")"), color=c, fontsize=9) axes[i].tick_params(axis='y', colors=c) if i == len( sci_vars) - 1: # if the last variable has been plotted pf.format_date_axis(axes[i], fig) axes[0].set_title((title + '\n' + t0 + ' - ' + t1), fontsize=9) sfile = '_'.join((fname, 'timeseries')) pf.save_fig(save_dir, sfile)
def main(url, out): now = dt.datetime.now().strftime('%Y.%m.%dT%H.%M.00') C = Crawl(url, select=[".*ncml"]) tds = 'https://opendap.oceanobservatories.org/thredds/dodsC/' cf.create_dir(out) fopen = open(out + '/' + now + '-nc-links.txt', 'w') for dataset in C.datasets: fopen.write(tds + dataset.id + '\n') fopen.close()
def main(url, out): now = dt.datetime.now().strftime('%Y.%m.%dT%H.%M.00') C = Crawl(url, select=[".*ncml"]) tds = 'https://opendap.oceanobservatories.org/thredds/dodsC/' cf.create_dir(out) fopen = open(out+ '/' + now+'-nc-links.txt', 'w') for dataset in C.datasets: fopen.write(tds + dataset.id + '\n') fopen.close()
def main(username, token, refdes, saveDir): cf.create_dir(saveDir) sensor_inv = 'https://ooinet.oceanobservatories.org/api/m2m/12576/sensor/inv/' if not refdes: f = 'uframe_annotations_all.csv' elif ',' in refdes: f = 'uframe_annotations_multiple_refdes.csv' else: f = 'uframe_annotations_{}.csv'.format(refdes) fN = os.path.join(saveDir, f) session = requests.session( ) # open the connection and leave it open for the session with open(fN, 'a') as outfile: writer = csv.writer(outfile) writer.writerow([ 'id', 'subsite', 'node', 'sensor', 'stream', 'method', 'parameters', 'beginDate', 'endDate', 'beginDT', 'endDT', 'exclusionFlag', 'qcFlag', 'source', 'annotation' ]) if not refdes: # if no refdes specified, provide all annotations write_all_annotations(username, token, outfile, session) else: refdes_list = [] frefdes = data_request_tools.format_inputs(refdes) for i in frefdes: print(i) if len(i) == 8: url = sensor_inv + i node_info = session.get(url, auth=(username, token)) nodes = node_info.json() for n in nodes: url2 = url + '/' + n sensor_info = session.get(url2, auth=(username, token)) sensors = sensor_info.json() for s in sensors: refdes = '-'.join([i, n, s]) refdes_list.append(refdes) elif len(i) == 14: url = sensor_inv + i.split('-')[0] + '/' + i.split('-')[1] sensor_info = session.get(url, auth=(username, token)) sensors = sensor_info.json() for s in sensors: refdes = '-'.join([i, s]) refdes_list.append(refdes) elif len(i) == 27: refdes_list.append(i) refdes_unique = sorted(list(set(refdes_list))) write_refdes_annotations(username, token, refdes_unique, outfile, session)
def main(sDir, array, subsite, node, sensor, delivery_methods, begin, end, now): cf.create_dir(sDir) begin = data_request_tools.format_date(begin) end = data_request_tools.format_date(end) # basic checks that dates were specified properly if end: if not begin: raise Exception('If an end date is specified, a begin date must also be specified.') if end: if begin >= end: raise Exception('End date entered ({:s}) is not after begin date ({:s})'.format(end, begin)) dmethods = data_request_tools.define_methods(delivery_methods) gui_df_sci = gui_streams_science() gui_df = data_request_tools.filter_dataframe(gui_df_sci, array, subsite, node, sensor, dmethods) url_list = data_request_urls(gui_df, begin, end) urls = pd.DataFrame(url_list) urls.to_csv(os.path.join(sDir, 'data_request_urls_{}.csv'.format(now)), index=False, header=False) return url_list
def main(sDir, thredds_urls): server_url = 'https://opendap.oceanobservatories.org' cf.create_dir(sDir) if type(thredds_urls) == list: thredds_list = thredds_urls else: thredds_file = pd.read_csv(os.path.join(sDir, thredds_urls)) thredds_list = thredds_file['outputUrl'].tolist() for t in thredds_list: print(t) # Check that the data request has been fulfilled cf.check_request_status(t) # Create local folders and download files print('Downloading files') folder = t.split('/')[-2] subsite = folder.split('-')[1] refdes = '-'.join((subsite, folder.split('-')[2], folder.split('-')[3], folder.split('-')[4])) output_dir = os.path.join(sDir, subsite, refdes, folder) cf.create_dir(output_dir) catalog_url = t.replace('.html', '.xml') files = [] datasets = get_elements(catalog_url, 'dataset', 'urlPath') for d in datasets: if d.endswith(('_provenance.json', '_annotations.json', '.nc')): files.append(d) count = 0 for f in files: count += 1 file_url = '/'.join((server_url, 'thredds/fileServer', f)) file_name = '/'.join((output_dir, file_url.split('/')[-1])) urlretrieve(file_url, file_name)
def main(files, out, east_var, north_var, up_var, err_var): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ fname, ext = os.path.splitext(files) if ext in '.nc': list_files = [files] elif ext in '.ncml': list_files = [files] else: list_files = read_file(files) stream_vars = pf.load_variable_dict(var='eng') # load engineering variables # for nc in list_files: # print nc # the engine that xarray uses can be changed as specified here # http://xarray.pydata.org/en/stable/generated/xarray.open_dataset.html#xarray.open_dataset for nc in list_files: print nc with xr.open_dataset(nc, mask_and_scale=False) as ds_disk: #with xr.open_mfdataset(nc, engine='netcdf4') as ds_disk: # change dimensions from 'obs' to 'time' ds_disk = ds_disk.swap_dims({'obs': 'time'}) ds_variables = ds_disk.data_vars.keys() # List of dataset variables stream = ds_disk.stream # List stream name associated with the data deployment = 'D0000{}'.format(str(numpy.unique(ds_disk.deployment)[0])) title_pre = mk_str(ds_disk.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds_disk.attrs, 's') # , var, tt0, tt1, 's') save_dir = os.path.join(out, ds_disk.subsite, deployment, ds_disk.node, ds_disk.stream, 'pcolor') cf.create_dir(save_dir) # t0, t1 = cf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = t0 + t1 - (t0 / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] # time_list = [[t0, t1]] # for period in time_list: # tt0 = period[0] # tt1 = period[1] # sub_ds = ds_disk.sel(time=slice(str(tt0), str(tt1))) north = ds_disk[north_var] east = ds_disk[east_var] up = ds_disk[up_var] error = ds_disk[err_var] try: bins = ds_disk['bin_depths'] bins = dict(data=bins.data.T, info=dict(label=bins.long_name, units=bins.units)) except KeyError: # use the matrix indices to plot bins = numpy.zeros_like(east.data) for i, item in enumerate(east): for jj, xtem in enumerate(east[i]): bins[i][jj] = jj bins = numpy.reshape(bins,(bins.shape[-1],bins.shape[0])) bins = dict(data=bins, label='bin_indices', units='') # the correct way to do this is to calculate the bin_depths, for that you need: # 9 First Cell Range(meters) (rounded bin_1_distance average, m) # 73 deployment depth of the ADCP instrument (pull from asset-management, depth in m) # 21 number of bins (num_cells, m) # 4 cell length (cell_length, m) # equation with the numbers above would be: # depths = 73 - 9 - ([1:21]-1)*4; time = dict(data=ds_disk['time'].data, info=dict(label=ds_disk['time'].standard_name, units='GMT')) #bins = dict(data=bins.data.T, info=dict(label=bins.long_name, units=bins.units)) north = dict(data=north.data.T, info=dict(label=north.long_name, units=north.units)) east = dict(data=east.data.T, info=dict(label=east.long_name, units=east.units)) up = dict(data=up.data.T, info=dict(label=up.long_name, units=up.units)) error = dict(data=error.data.T, info=dict(label=error.long_name, units=error.units)) sname_ew = save_pre + 'E-W-ADCP' title = title_pre fig, axs = pf.adcp(time, bins, north, east, title) pf.resize(width=12, height=8.5) # Resize figure pf.save_fig(save_dir, sname_ew, res=250) # Save figure sname_ur = save_pre + 'U-R-ADCP' fig, axs = pf.adcp(time, bins, up, error, title) pf.resize(width=12, height=8.5) # Resize figure pf.save_fig(save_dir, sname_ur, res=250) # Save figure plt.close('all')
def main(url_list, sDir, stime, etime): if len(url_list) != 2: print('Please provide 2 reference designators for plotting') else: uu0 = url_list[0] uu1 = url_list[1] rd0 = uu0.split('/')[-2][20:47] rd1 = uu1.split('/')[-2][20:47] array = rd0[0:2] inst = rd0.split('-')[-1] datasets0 = [] datasets1 = [] for i in range(len(url_list)): udatasets = cf.get_nc_urls([url_list[i]]) if i == 0: datasets0.append(udatasets) else: datasets1.append(udatasets) datasets0 = list(itertools.chain(*datasets0)) datasets1 = list(itertools.chain(*datasets1)) main_sensor0 = rd0.split('-')[-1] main_sensor1 = rd1.split('-')[-1] fdatasets0_sel = cf.filter_collocated_instruments( main_sensor0, datasets0) fdatasets1_sel = cf.filter_collocated_instruments( main_sensor1, datasets1) deployments = [ dd.split('/')[-1].split('_')[0] for dd in fdatasets0_sel ] for d in deployments: fd0 = [x for x in fdatasets0_sel if d in x] fd1 = [x for x in fdatasets1_sel if d in x] ds0 = xr.open_dataset(fd0[0], mask_and_scale=False) ds0 = ds0.swap_dims({'obs': 'time'}) ds1 = xr.open_dataset(fd1[0], mask_and_scale=False) ds1 = ds1.swap_dims({'obs': 'time'}) if stime is not None and etime is not None: ds0 = ds0.sel(time=slice(stime, etime)) ds1 = ds1.sel(time=slice(stime, etime)) if len(ds0['time'].values) == 0: print( 'No data to plot for specified time range: ({} to {})'. format(start_time, end_time)) continue fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( fd0[0]) sci_vars = cf.return_science_vars(stream) save_dir_profile = os.path.join(sDir, array, subsite, inst, 'profile_plots', deployment) cf.create_dir(save_dir_profile) # get pressure variable pvarname, y1, y_units, press, y_fillvalue = cf.add_pressure_to_dictionary_of_sci_vars( ds0) for sv in sci_vars: print('') print(sv) if 'pressure' not in sv: fig, ax = plt.subplots() plt.margins(y=.08, x=.02) plt.grid() title = ' '.join((deployment, subsite, inst, method)) sname = '-'.join((subsite, inst, method, sv)) for i in range(len(url_list)): if i == 0: ds = ds0 else: ds = ds1 t = ds['time'].values zpressure = ds[pvarname].values z1 = ds[sv].values fv = ds[sv]._FillValue sv_units = ds[sv].units # Check if the array is all NaNs if sum(np.isnan(z1)) == len(z1): print('Array of all NaNs - skipping plot.') continue # Check if the array is all fill values elif len(z1[z1 != fv]) == 0: print('Array of all fill values - skipping plot.') continue else: # get rid of 0.0 data if sv == 'salinity': ind = z1 > 1 elif sv == 'density': ind = z1 > 1000 elif sv == 'conductivity': ind = z1 > 0.1 elif sv == 'dissolved_oxygen': ind = z1 > 160 elif sv == 'estimated_oxygen_concentration': ind = z1 > 200 else: ind = z1 > 0 # if sv == 'sci_flbbcd_chlor_units': # ind = ndata < 7.5 # elif sv == 'sci_flbbcd_cdom_units': # ind = ndata < 25 # else: # ind = ndata > 0.0 # if 'CTD' in r: # ind = zpressure > 0.0 # else: # ind = ndata > 0.0 lenzero = np.sum(~ind) dtime = t[ind] zpressure = zpressure[ind] zdata = z1[ind] if len(dtime) > 0: ax.scatter(zdata, zpressure, s=2, edgecolor='None') xlabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" ax.invert_yaxis() # plt.xlim([-0.5, 0.5]) ax.set_xlabel(xlabel, fontsize=9) ax.set_ylabel(ylabel, fontsize=9) ax.set_title(title + '\nWFP02 (blue) & WFP03 (orange)', fontsize=9) fig.tight_layout() pf.save_fig(save_dir_profile, sname)
def main(files, out): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ fname, ext = os.path.splitext(files) if ext in '.nc': list_files = [files] elif ext in '.ncml': list_files = [files] else: list_files = read_file(files) stream_vars = pf.load_variable_dict( var='eng') # load engineering variables # for nc in list_files: # print nc # the engine that xarray uses can be changed as specified here # http://xarray.pydata.org/en/stable/generated/xarray.open_dataset.html#xarray.open_dataset with xr.open_mfdataset(list_files, engine='netcdf4') as ds_disk: # change dimensions from 'obs' to 'time' ds_disk = ds_disk.swap_dims({'obs': 'time'}) ds_variables = ds_disk.data_vars.keys() # List of dataset variables stream = ds_disk.stream # List stream name associated with the data title_pre = mk_str(ds_disk.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds_disk.attrs, 's') # , var, tt0, tt1, 's') save_dir = os.path.join(out, ds_disk.subsite, ds_disk.node, ds_disk.stream, 'pcolor') cf.create_dir(save_dir) # t0, t1 = cf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = t0 + t1 - (t0 / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] # time_list = [[t0, t1]] # for period in time_list: # tt0 = period[0] # tt1 = period[1] # sub_ds = ds_disk.sel(time=slice(str(tt0), str(tt1))) bins = ds_disk['bin_depths'] north = ds_disk['northward_seawater_velocity'] east = ds_disk['eastward_seawater_velocity'] # up = ds_disk['upward_seawater_velocity'] # error = ds_disk['error_velocity'] time = dict(data=ds_disk['time'].data, info=dict(label=ds_disk['time'].standard_name, units='GMT')) bins = dict(data=bins.data.T, info=dict(label=bins.long_name, units=bins.units)) north = dict(data=north.data.T, info=dict(label=north.long_name, units=north.units)) east = dict(data=east.data.T, info=dict(label=east.long_name, units=east.units)) # up = dict(data=up.data.T, info=dict(label=up.long_name, units=up.units)) # error = dict(data=error.data.T, info=dict(label=error.long_name, units=error.units)) sname = save_pre + 'ADCP' title = title_pre fig, axs = pf.adcp(time, bins, north, east, title) pf.resize(width=12, height=8.5) # Resize figure pf.save_fig(save_dir, sname, res=250) # Save figure plt.close('all')
def main(nc, save_dir, display=False): cf.create_dir(save_dir) with xr.open_dataset(nc, mask_and_scale=False) as ds: subsite = ds.subsite node = ds.node sensor = ds.sensor stream = ds.stream deployment = 'D0000{}'.format(str(np.unique(ds.deployment)[0])) t0 = ds.time_coverage_start t1 = ds.time_coverage_end sub_dir = os.path.join(save_dir, subsite, '{}-{}-{}'.format(subsite, node, sensor), stream, deployment) cf.create_dir(sub_dir) misc = ['quality', 'string', 'timestamp', 'deployment', 'id', 'provenance', 'qc', 'time', 'mission', 'obs', 'volt', 'ref', 'sig', 'amp', 'rph', 'calphase', 'phase', 'therm'] reg_ex = re.compile(r'\b(?:%s)\b' % '|'.join(misc)) # keep variables that are not in the regular expression vars = [s for s in ds.data_vars if not reg_ex.search(s)] x = ds['time'].data for v in vars: # List of dataset variables # print v # Filter out variables that are strings, datetimes, or qc related if ds[v].dtype.kind == 'S' or ds[v].dtype == np.dtype('datetime64[ns]') or 'time' in v or 'qc_results' in v or 'qc_executed' in v: continue y = ds[v] try: y_units = y.units except AttributeError: y_units = None y_data = y.data if y_data.ndim > 1: continue source = ColumnDataSource( data=dict( x=x, y=y_data, ) ) gr = cf.get_global_ranges(subsite, node, sensor, v) output_file('{}/{}-{}-{}.html'.format(sub_dir, v, ds.time_coverage_start.replace(':', ''), ds.time_coverage_end.replace(':', ''))) p = figure(width=1200, height=800, title='{}-{}-{}: {} - {} - {}, Stream: {}'.format(subsite, node, sensor, deployment, t0, t1, stream), x_axis_label='Time (GMT)', y_axis_label='{} ({})'.format(v, y_units), x_axis_type='datetime', tools=[tools]) p.line('x', 'y', legend=v, line_width=3, source=source) p.circle('x', 'y', fill_color='white', size=4, source=source) if gr: low_box = BoxAnnotation(top=gr[0], fill_alpha=0.05, fill_color='red') mid_box = BoxAnnotation(top=gr[1], bottom=gr[0], fill_alpha=0.1, fill_color='green') high_box = BoxAnnotation(bottom=gr[1], fill_alpha=0.05, fill_color='red') p.add_layout(low_box) p.add_layout(mid_box) p.add_layout(high_box) if display: show(p) else: save(p) reset_output()
def main(url_list, sDir, deployment_num, start_time, end_time, preferred_only, n_std, inpercentile, zcell_size, zdbar): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list and 'ENG' not in rd and 'ADCP' not in rd: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join((spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments(main_sensor, fdatasets) for fd in fdatasets_sel: part_d = fd.split('/')[-1] print('\n{}'.format(part_d)) ds = xr.open_dataset(fd, mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) fname, subsite, refdes, method, stream, deployment = cf.nc_attributes(fd) array = subsite[0:2] sci_vars = cf.return_science_vars(stream) # if 'CE05MOAS' in r or 'CP05MOAS' in r: # for coastal gliders, get m_water_depth for bathymetry # eng = '-'.join((r.split('-')[0], r.split('-')[1], '00-ENG000000', method, 'glider_eng')) # eng_url = [s for s in url_list if eng in s] # if len(eng_url) == 1: # eng_datasets = cf.get_nc_urls(eng_url) # # filter out collocated datasets # eng_dataset = [j for j in eng_datasets if (eng in j.split('/')[-1] and deployment in j.split('/')[-1])] # if len(eng_dataset) > 0: # ds_eng = xr.open_dataset(eng_dataset[0], mask_and_scale=False) # t_eng = ds_eng['time'].values # m_water_depth = ds_eng['m_water_depth'].values # # # m_altitude = glider height above seafloor # # m_depth = glider depth in the water column # # m_altitude = ds_eng['m_altitude'].values # # m_depth = ds_eng['m_depth'].values # # calc_water_depth = m_altitude + m_depth # # # m_altimeter_status = 0 means a good reading (not nan or -1) # try: # eng_ind = ds_eng['m_altimeter_status'].values == 0 # except KeyError: # eng_ind = (~np.isnan(m_water_depth)) & (m_water_depth >= 0) # # m_water_depth = m_water_depth[eng_ind] # t_eng = t_eng[eng_ind] # # # get rid of any remaining nans or fill values # eng_ind2 = (~np.isnan(m_water_depth)) & (m_water_depth >= 0) # m_water_depth = m_water_depth[eng_ind2] # t_eng = t_eng[eng_ind2] # else: # print('No engineering file for deployment {}'.format(deployment)) # m_water_depth = None # t_eng = None # else: # m_water_depth = None # t_eng = None # else: # m_water_depth = None # t_eng = None if deployment_num is not None: if int(int(deployment[-4:])) is not deployment_num: print(type(int(deployment[-4:])), type(deployment_num)) continue if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print('No data to plot for specified time range: ({} to {})'.format(start_time, end_time)) continue stime = start_time.strftime('%Y-%m-%d') etime = end_time.strftime('%Y-%m-%d') ext = stime + 'to' + etime # .join((ds0_method, ds1_method save_dir_profile = os.path.join(sDir, array, subsite, refdes, 'profile_plots', deployment, ext) save_dir_xsection = os.path.join(sDir, array, subsite, refdes, 'xsection_plots', deployment, ext) save_dir_4d = os.path.join(sDir, array, subsite, refdes, 'xsection_plots_4d', deployment, ext) else: save_dir_profile = os.path.join(sDir, array, subsite, refdes, 'profile_plots', deployment) save_dir_xsection = os.path.join(sDir, array, subsite, refdes, 'xsection_plots', deployment) save_dir_4d = os.path.join(sDir, array, subsite, refdes, 'xsection_plots_4d', deployment) time1 = ds['time'].values try: ds_lat1 = ds['lat'].values except KeyError: ds_lat1 = None print('No latitude variable in file') try: ds_lon1 = ds['lon'].values except KeyError: ds_lon1 = None print('No longitude variable in file') # get pressure variable pvarname, y1, y_units, press, y_fillvalue = cf.add_pressure_to_dictionary_of_sci_vars(ds) for sv in sci_vars: print('') print(sv) if 'pressure' not in sv: if sv == 'spkir_abj_cspp_downwelling_vector': pxso.pf_xs_spkir(ds, sv, time1, y1, ds_lat1, ds_lon1, zcell_size, inpercentile, save_dir_profile, save_dir_xsection, deployment, press, y_units, n_std, zdbar) elif 'OPTAA' in r: if sv not in ['wavelength_a', 'wavelength_c']: pxso.pf_xs_optaa(ds, sv, time1, y1, ds_lat1, ds_lon1, zcell_size, inpercentile, save_dir_profile, save_dir_xsection, deployment, press, y_units, n_std, zdbar) else: z1 = ds[sv].values fv = ds[sv]._FillValue sv_units = ds[sv].units # Check if the array is all NaNs if sum(np.isnan(z1)) == len(z1): print('Array of all NaNs - skipping plot.') continue # Check if the array is all fill values elif len(z1[z1 != fv]) == 0: print('Array of all fill values - skipping plot.') continue else: # remove unreasonable pressure data (e.g. for surface piercing profilers) if zdbar: po_ind = (0 < y1) & (y1 < zdbar) tm = time1[po_ind] y = y1[po_ind] z = z1[po_ind] ds_lat = ds_lat1[po_ind] ds_lon = ds_lon1[po_ind] else: tm = time1 y = y1 z = z1 ds_lat = ds_lat1 ds_lon = ds_lon1 # reject erroneous data dtime, zpressure, ndata, lenfv, lennan, lenev, lengr, global_min, global_max, lat, lon = \ cf.reject_erroneous_data(r, sv, tm, y, z, fv, ds_lat, ds_lon) # get rid of 0.0 data if sv == 'salinity': ind = ndata > 30 elif sv == 'density': ind = ndata > 1022.5 elif sv == 'conductivity': ind = ndata > 3.45 else: ind = ndata > 0 # if sv == 'sci_flbbcd_chlor_units': # ind = ndata < 7.5 # elif sv == 'sci_flbbcd_cdom_units': # ind = ndata < 25 # else: # ind = ndata > 0.0 # if 'CTD' in r: # ind = zpressure > 0.0 # else: # ind = ndata > 0.0 lenzero = np.sum(~ind) dtime = dtime[ind] zpressure = zpressure[ind] ndata = ndata[ind] if ds_lat is not None and ds_lon is not None: lat = lat[ind] lon = lon[ind] else: lat = None lon = None if len(dtime) > 0: # reject time range from data portal file export t_portal, z_portal, y_portal, lat_portal, lon_portal = \ cf.reject_timestamps_dataportal(subsite, r, dtime, zpressure, ndata, lat, lon) print('removed {} data points using visual inspection of data'.format( len(ndata) - len(z_portal))) # create data groups if len(y_portal) > 0: columns = ['tsec', 'dbar', str(sv)] min_r = int(round(np.nanmin(y_portal) - zcell_size)) max_r = int(round(np.nanmax(y_portal) + zcell_size)) ranges = list(range(min_r, max_r, zcell_size)) groups, d_groups = gt.group_by_depth_range(t_portal, y_portal, z_portal, columns, ranges) if 'scatter' in sv: n_std = None # to use percentile else: n_std = n_std # get percentile analysis for printing on the profile plot y_avg, n_avg, n_min, n_max, n0_std, n1_std, l_arr, time_ex = cf.reject_timestamps_in_groups( groups, d_groups, n_std, inpercentile) """ Plot all data """ if len(time1) > 0: cf.create_dir(save_dir_profile) cf.create_dir(save_dir_xsection) sname = '-'.join((r, method, sv)) sfileall = '_'.join(('all_data', sname, pd.to_datetime(time1.min()).strftime('%Y%m%d'))) tm0 = pd.to_datetime(time1.min()).strftime('%Y-%m-%dT%H:%M:%S') tm1 = pd.to_datetime(time1.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) + '\n' + tm0 + ' to ' + tm1 if 'SPKIR' in r: title = title + '\nWavelength = 510 nm' ''' profile plot ''' xlabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" clabel = 'Time' fig, ax = pf.plot_profiles(z1, y1, time1, ylabel, xlabel, clabel, stdev=None) ax.set_title(title, fontsize=9) fig.tight_layout() pf.save_fig(save_dir_profile, sfileall) ''' xsection plot ''' clabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" fig, ax, bar = pf.plot_xsection(subsite, time1, y1, z1, clabel, ylabel, t_eng=None, m_water_depth=None, inpercentile=None, stdev=None) if fig: ax.set_title(title, fontsize=9) fig.tight_layout() pf.save_fig(save_dir_xsection, sfileall) """ Plot cleaned-up data """ if len(dtime) > 0: if len(y_portal) > 0: sfile = '_'.join(('rm_erroneous_data', sname, pd.to_datetime(t_portal.min()).strftime('%Y%m%d'))) t0 = pd.to_datetime(t_portal.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(t_portal.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) + '\n' + t0 + ' to ' + t1 if 'SPKIR' in r: title = title + '\nWavelength = 510 nm' ''' profile plot ''' xlabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" clabel = 'Time' fig, ax = pf.plot_profiles(z_portal, y_portal, t_portal, ylabel, xlabel, clabel, stdev=None) ax.set_title(title, fontsize=9) ax.plot(n_avg, y_avg, '-k') ax.fill_betweenx(y_avg, n0_std, n1_std, color='m', alpha=0.2) if inpercentile: leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} unreasonable values'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nexcluded {} suspect data points when inspected visually'.format( len(ndata) - len(z_portal)) + '\n(black) data average in {} dbar segments'.format(zcell_size) + '\n(magenta) {} percentile envelope in {} dbar segments'.format( int(100 - inpercentile * 2), zcell_size),) elif n_std: leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} unreasonable values'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nexcluded {} suspect data points when inspected visually'.format( len(ndata) - len(z_portal)) + '\n(black) data average in {} dbar segments'.format(zcell_size) + '\n(magenta) +/- {} SD envelope in {} dbar segments'.format( int(n_std), zcell_size),) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) fig.tight_layout() pf.save_fig(save_dir_profile, sfile) ''' xsection plot ''' clabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" # plot non-erroneous data fig, ax, bar = pf.plot_xsection(subsite, t_portal, y_portal, z_portal, clabel, ylabel, t_eng=None, m_water_depth=None, inpercentile=None, stdev=None) ax.set_title(title, fontsize=9) leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} unreasonable values'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nexcluded {} suspect data points when inspected visually'.format( len(ndata) - len(z_portal)), ) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) fig.tight_layout() pf.save_fig(save_dir_xsection, sfile) ''' 4D plot for gliders only ''' if 'MOAS' in r: if ds_lat is not None and ds_lon is not None: cf.create_dir(save_dir_4d) clabel = sv + " (" + sv_units + ")" zlabel = press[0] + " (" + y_units[0] + ")" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') sct = ax.scatter(lon_portal, lat_portal, y_portal, c=z_portal, s=2) cbar = plt.colorbar(sct, label=clabel, extend='both') cbar.ax.tick_params(labelsize=8) ax.invert_zaxis() ax.view_init(25, 32) ax.invert_xaxis() ax.invert_yaxis() ax.set_zlabel(zlabel, fontsize=9) ax.set_ylabel('Latitude', fontsize=9) ax.set_xlabel('Longitude', fontsize=9) ax.set_title(title, fontsize=9) pf.save_fig(save_dir_4d, sfile)
def main(sDir, url_list, start_time, end_time, preferred_only): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list and 'PRESF' in rd: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) for ud in udatasets: # filter out collocated data files if 'PRESF' in ud.split('/')[-1]: datasets.append(ud) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets fdatasets = np.unique(fdatasets).tolist() for fd in fdatasets: ds = xr.open_dataset(fd, mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print( 'No data to plot for specified time range: ({} to {})'. format(start_time, end_time)) continue fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( fd) sci_vars = cf.return_science_vars(stream) print('\nPlotting {} {}'.format(r, deployment)) array = subsite[0:2] filename = '_'.join(fname.split('_')[:-1]) save_dir = os.path.join(sDir, array, subsite, refdes, 'timeseries_plots', deployment) cf.create_dir(save_dir) tm = ds['time'].values t0 = pd.to_datetime(tm.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(tm.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) for var in sci_vars: print(var) if var != 'id': #if var == 'presf_wave_burst_pressure': y = ds[var] fv = y._FillValue if len(y.dims) == 1: # Check if the array is all NaNs if sum(np.isnan(y.values)) == len(y.values): print('Array of all NaNs - skipping plot.') # Check if the array is all fill values elif len(y[y != fv]) == 0: print('Array of all fill values - skipping plot.') else: # reject fill values ind = y.values != fv t = tm[ind] y = y[ind] # Plot all data fig, ax = pf.plot_timeseries(t, y, y.name, stdev=None) ax.set_title((title + '\n' + t0 + ' - ' + t1), fontsize=9) sfile = '-'.join((filename, y.name, t0[:10])) pf.save_fig(save_dir, sfile) # Plot data with outliers removed fig, ax = pf.plot_timeseries(t, y, y.name, stdev=5) ax.set_title((title + '\n' + t0 + ' - ' + t1), fontsize=9) sfile = '-'.join( (filename, y.name, t0[:10])) + '_rmoutliers' pf.save_fig(save_dir, sfile) else: v = y.values.T n_nan = np.sum(np.isnan(v)) # convert fill values to nans try: v[v == fv] = np.nan except ValueError: v = v.astype(float) v[v == fv] = np.nan n_fv = np.sum(np.isnan(v)) - n_nan # plot before global ranges are removed fig, ax = pf.plot_presf_2d(tm, v, y.name, y.units) ax.set_title((title + '\n' + t0 + ' - ' + t1), fontsize=9) sfile = '-'.join((filename, var, t0[:10])) pf.save_fig(save_dir, sfile) # reject data outside of global ranges [g_min, g_max] = cf.get_global_ranges(r, var) if g_min is not None and g_max is not None: v[v < g_min] = np.nan v[v > g_max] = np.nan n_grange = np.sum(np.isnan(v)) - n_fv - n_nan if n_grange > 0: # don't plot if the array is all nans if len(np.unique( np.isnan(v))) == 1 and np.unique( np.isnan(v))[0] == True: continue else: # plot after global ranges are removed fig, ax = pf.plot_presf_2d( tm, v, y.name, y.units) title2 = 'removed: {} global ranges [{}, {}]'.format( n_grange, g_min, g_max) ax.set_title((title + '\n' + t0 + ' - ' + t1 + '\n' + title2), fontsize=9) sfile = '-'.join( (filename, var, t0[:10], 'rmgr')) pf.save_fig(save_dir, sfile)
def main(sDir, url_list, start_time, end_time, preferred_only): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): rms = '-'.join((r, row[ii])) for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments( main_sensor, fdatasets) for fd in fdatasets_sel: with xr.open_dataset(fd, mask_and_scale=False) as ds: ds = ds.swap_dims({'obs': 'time'}) if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print( 'No data to plot for specified time range: ({} to {})' .format(start_time, end_time)) continue fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( fd) print('\nPlotting {} {}'.format(r, deployment)) array = subsite[0:2] save_dir = os.path.join(sDir, array, subsite, refdes, 'timeseries_panel_plots') filename = '_'.join(fname.split('_')[:-1]) sci_vars = cf.return_science_vars(stream) if len(sci_vars) > 1: cf.create_dir(save_dir) colors = cm.jet(np.linspace(0, 1, len(sci_vars))) t = ds['time'].values t0 = pd.to_datetime(t.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(t.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) # Plot data with outliers removed fig, ax = pf.plot_timeseries_panel(ds, t, sci_vars, colors, 5) plt.xticks(fontsize=7) ax[0].set_title((title + '\n' + t0 + ' - ' + t1), fontsize=7) sfile = '-'.join((filename, 'timeseries_panel', t0[:10])) pf.save_fig(save_dir, sfile) else: print( 'Only one science variable in file, no panel plots necessary' )
def main(url_list, sDir, plot_type, start_time, end_time, deployment_num): for i, u in enumerate(url_list): elements = u.split('/')[-2].split('-') r = '-'.join((elements[1], elements[2], elements[3], elements[4])) ms = u.split(r + '-')[1].split('/')[0] subsite = r.split('-')[0] array = subsite[0:2] main_sensor = r.split('-')[-1] datasets = cf.get_nc_urls([u]) datasets_sel = cf.filter_collocated_instruments(main_sensor, datasets) save_dir = os.path.join(sDir, array, subsite, r, plot_type) cf.create_dir(save_dir) sname = '-'.join((r, ms, 'track')) print('Appending....') sh = pd.DataFrame() deployments = [] end_times = [] for ii, d in enumerate(datasets_sel): print('\nDataset {} of {}: {}'.format(ii + 1, len(datasets_sel), d.split('/')[-1])) ds = xr.open_dataset(d, mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print( 'No data to plot for specified time range: ({} to {})'. format(start_time, end_time)) continue fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( d) if deployment_num is not None: if int(deployment.split('0')[-1]) is not deployment_num: print(type(int(deployment.split('0')[-1])), type(deployment_num)) continue # get end times of deployments ps_df, n_streams = cf.get_preferred_stream_info(r) dr_data = cf.refdes_datareview_json(r) for index, row in ps_df.iterrows(): deploy = row['deployment'] deploy_info = cf.get_deployment_information( dr_data, int(deploy[-4:])) if int(deploy[-4:]) not in deployments: deployments.append(int(deploy[-4:])) if pd.to_datetime(deploy_info['stop_date']) not in end_times: end_times.append(pd.to_datetime(deploy_info['stop_date'])) data = {'lat': ds['lat'].values, 'lon': ds['lon'].values} new_r = pd.DataFrame(data, columns=['lat', 'lon'], index=ds['time'].values) sh = sh.append(new_r) xD = sh.lon.values yD = sh.lat.values tD = sh.index.values clabel = 'Time' ylabel = 'Latitude' xlabel = 'Longitude' fig, ax = pf.plot_profiles(xD, yD, tD, ylabel, xlabel, clabel, end_times, deployments, stdev=None) ax.invert_yaxis() ax.set_title('Glider Track - ' + r + '\n' + 'x: platform location', fontsize=9) ax.set_xlim(-71.75, -69.75) ax.set_ylim(38.75, 40.75) #cbar.ax.set_yticklabels(end_times) # add Pioneer glider sampling area ax.add_patch( Rectangle((-71.5, 39.0), 1.58, 1.67, linewidth=3, edgecolor='b', facecolor='none')) ax.text(-71, 40.6, 'Pioneer Glider Sampling Area', color='blue', fontsize=8) # add Pioneer AUV sampling area # ax.add_patch(Rectangle((-71.17, 39.67), 0.92, 1.0, linewidth=3, edgecolor='m', facecolor='none')) array_loc = cf.return_array_subsites_standard_loc(array) ax.scatter(array_loc.lon, array_loc.lat, s=40, marker='x', color='k', alpha=0.3) #ax.legend(legn, array_loc.index, scatterpoints=1, loc='lower left', ncol=4, fontsize=8) pf.save_fig(save_dir, sname)
def main(sDir, url_list, start_time, end_time, preferred_only): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): rms = '-'.join((r, row[ii])) for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join((spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets for fd in fdatasets: with xr.open_dataset(fd, mask_and_scale=False) as ds: ds = ds.swap_dims({'obs': 'time'}) if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print('No data to plot for specified time range: ({} to {})'.format(start_time, end_time)) continue fname, subsite, refdes, method, stream, deployment = cf.nc_attributes(fd) print('\nPlotting {} {}'.format(r, deployment)) array = subsite[0:2] save_dir = os.path.join(sDir, array, subsite, refdes, 'ts_plots') cf.create_dir(save_dir) tme = ds['time'].values t0 = pd.to_datetime(tme.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(tme.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) filename = '-'.join(('_'.join(fname.split('_')[:-1]), 'ts', t0[:10])) ds_vars = list(ds.data_vars.keys()) raw_vars = cf.return_raw_vars(ds_vars) xvar = return_var(ds, raw_vars, 'salinity', 'Practical Salinity') sal = ds[xvar].values sal_fv = ds[xvar]._FillValue yvar = return_var(ds, raw_vars, 'temp', 'Seawater Temperature') temp = ds[yvar].values temp_fv = ds[yvar]._FillValue press = pf.pressure_var(ds, list(ds.coords.keys())) if press is None: press = pf.pressure_var(ds, list(ds.data_vars.keys())) p = ds[press].values # get rid of nans, 0.0s, fill values sind1 = (~np.isnan(sal)) & (sal != 0.0) & (sal != sal_fv) sal = sal[sind1] temp = temp[sind1] tme = tme[sind1] p = p[sind1] tind1 = (~np.isnan(temp)) & (temp != 0.0) & (temp != temp_fv) sal = sal[tind1] temp = temp[tind1] tme = tme[tind1] p = p[tind1] # reject values outside global ranges: global_min, global_max = cf.get_global_ranges(r, xvar) if any(e is None for e in [global_min, global_max]): sal = sal temp = temp tme = tme p = p else: sgr_ind = cf.reject_global_ranges(sal, global_min, global_max) sal = sal[sgr_ind] temp = temp[sgr_ind] tme = tme[sgr_ind] p = p[sgr_ind] global_min, global_max = cf.get_global_ranges(r, yvar) if any(e is None for e in [global_min, global_max]): sal = sal temp = temp tme = tme p = p else: tgr_ind = cf.reject_global_ranges(temp, global_min, global_max) sal = sal[tgr_ind] temp = temp[tgr_ind] tme = tme[tgr_ind] p = p[tgr_ind] # get rid of outliers soind = cf.reject_outliers(sal, 5) sal = sal[soind] temp = temp[soind] tme = tme[soind] p = p[soind] toind = cf.reject_outliers(temp, 5) sal = sal[toind] temp = temp[toind] tme = tme[toind] p = p[toind] if len(sal) > 0: # if there are any data to plot colors = cm.rainbow(np.linspace(0, 1, len(tme))) # Figure out boundaries (mins and maxes) #smin = sal.min() - (0.01 * sal.min()) #smax = sal.max() + (0.01 * sal.max()) if sal.max() - sal.min() < 0.2: smin = sal.min() - (0.0005 * sal.min()) smax = sal.max() + (0.0005 * sal.max()) else: smin = sal.min() - (0.001 * sal.min()) smax = sal.max() + (0.001 * sal.max()) if temp.max() - temp.min() <= 1: tmin = temp.min() - (0.01 * temp.min()) tmax = temp.max() + (0.01 * temp.max()) elif 1 < temp.max() - temp.min() < 1.5: tmin = temp.min() - (0.05 * temp.min()) tmax = temp.max() + (0.05 * temp.max()) else: tmin = temp.min() - (0.1 * temp.min()) tmax = temp.max() + (0.1 * temp.max()) # Calculate how many gridcells are needed in the x and y directions and # Create temp and sal vectors of appropriate dimensions xdim = int(round((smax-smin)/0.1 + 1, 0)) if xdim == 1: xdim = 2 si = np.linspace(0, xdim - 1, xdim) * 0.1 + smin if 1.1 <= temp.max() - temp.min() < 1.7: # if the diff between min and max temp is small ydim = int(round((tmax-tmin)/0.75 + 1, 0)) ti = np.linspace(0, ydim - 1, ydim) * 0.75 + tmin elif temp.max() - temp.min() < 1.1: ydim = int(round((tmax - tmin) / 0.1 + 1, 0)) ti = np.linspace(0, ydim - 1, ydim) * 0.1 + tmin else: ydim = int(round((tmax - tmin) + 1, 0)) ti = np.linspace(0, ydim - 1, ydim) + tmin # Create empty grid of zeros mdens = np.zeros((ydim, xdim)) # Loop to fill in grid with densities for j in range(0, ydim): for i in range(0, xdim): mdens[j, i] = gsw.density.rho(si[i], ti[j], np.median(p)) # calculate density using median pressure value fig, ax = pf.plot_ts(si, ti, mdens, sal, temp, colors) ax.set_title((title + '\n' + t0 + ' - ' + t1 + '\ncolors = time (cooler: earlier)'), fontsize=9) leg_text = ('Removed {} values (SD=5)'.format(len(ds[xvar].values) - len(sal)),) ax.legend(leg_text, loc='best', fontsize=6) pf.save_fig(save_dir, filename)
def main(files, out, time_break, depth, start, end, interactive): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ fname, ext = os.path.splitext(files) if ext in '.nc': list_files = [files] elif ext in '.ncml': list_files = [files] else: list_files = read_file(files) stream_vars = pf.load_variable_dict( var='eng') # load engineering variables for nc in list_files: print nc with xr.open_dataset(nc, mask_and_scale=False) as ds: # change dimensions from 'obs' to 'time' ds = ds.swap_dims({'obs': 'time'}) ds_variables = ds.data_vars.keys() # List of dataset variables stream = ds.stream # List stream name associated with the data title_pre = mk_str(ds.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds.attrs, 's') # , var, tt0, tt1, 's') platform = ds.subsite node = ds.node sensor = ds.sensor # save_dir = os.path.join(out,'xsection_depth_profiles') save_dir = os.path.join( out, ds.subsite, ds.subsite + '-' + ds.node + '-' + ds.sensor, ds.stream, 'xsection_depth_profiles') cf.create_dir(save_dir) misc = [ 'quality', 'string', 'timestamp', 'deployment', 'id', 'provenance', 'qc', 'time', 'mission', 'obs', 'volt', 'ref', 'sig', 'amp', 'rph', 'calphase', 'phase', 'therm', 'light' ] reg_ex = re.compile('|'.join(misc)) # keep variables that are not in the regular expression sci_vars = [s for s in ds_variables if not reg_ex.search(s)] if not time_break == None: times = np.unique(ds[time_break]) for t in times: time_ind = t == ds[time_break].data for var in sci_vars: x = dict(data=ds['time'].data[time_ind], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime( x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime( x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop( 'comment') # remove from the attributes sci = ds[var] # or else the variable won't load y = dict(data=ds[depth].data[time_ind], info=dict(label='Pressure', units='dbar', var=var, platform=platform, node=node, sensor=sensor)) try: z_lab = sci.long_name except AttributeError: z_lab = sci.standard_name z = dict(data=sci.data[time_ind], info=dict(label=z_lab, units=str(sci.units), var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.depth_glider_cross_section(x, y, z, title=title) if interactive == True: fig.canvas.mpl_connect( 'pick_event', lambda event: pf.onpick3( event, x['data'], y['data'], z['data'])) plt.show() else: pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format( platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') else: ds = ds.sel(time=slice(start, end)) for var in sci_vars: x = dict(data=ds['time'].data[:], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime( x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime( x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop( 'comment') # remove from the attributes sci = ds[var] # or else the variable won't load y = dict(data=ds[depth].data[:], info=dict(label='Pressure', units='dbar', var=var, platform=platform, node=node, sensor=sensor)) try: z_lab = sci.long_name except AttributeError: z_lab = sci.standard_name z = dict(data=sci.data[:], info=dict(label=z_lab, units=sci.units, var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.depth_glider_cross_section( x, y, z, title=title, interactive=interactive) if interactive == True: fig.canvas.mpl_connect( 'pick_event', lambda event: pf.onpick3( event, x['data'], y['data'], z['data'])) plt.show() else: pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format( platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all')
def main(url_list, sDir, mDir, zcell_size, zdbar, start_time, end_time, inpercentile): """"" URL : path to instrument data by methods sDir : path to the directory on your machine to save plots mDir : path to the directory on your machine to save data ranges zcell_size : depth cell size to group data zdbar : define depth where suspect data are identified start_time : select start date to slice timeseries end_time : select end date to slice timeseries """"" rd_list = [] ms_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) ms = uu.split(rd + '-')[1].split('/')[0] if rd not in rd_list: rd_list.append(rd) if ms not in ms_list: ms_list.append(ms) for r in rd_list: print('\n{}'.format(r)) subsite = r.split('-')[0] array = subsite[0:2] main_sensor = r.split('-')[-1] # read in the analysis file dr_data = cf.refdes_datareview_json(r) # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) # get science variable long names from the Data Review Database stream_sci_vars = cd.sci_var_long_names(r) # check if the science variable long names are the same for each stream and initialize empty arrays sci_vars_dict0 = cd.sci_var_long_names_check(stream_sci_vars) # get the list of data files and filter out collocated instruments and other streams datasets = [] for u in url_list: print(u) splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = cf.filter_collocated_instruments(main_sensor, datasets) fdatasets = cf.filter_other_streams(r, ms_list, fdatasets) # select the list of data files from the preferred dataset for each deployment fdatasets_final = [] for ii in range(len(ps_df)): for x in fdatasets: if ps_df['deployment'][ii] in x and ps_df[0][ii] in x: fdatasets_final.append(x) # build dictionary of science data from the preferred dataset for each deployment print('\nAppending data from files') sci_vars_dict, y_unit, y_name, l0 = cd.append_evaluated_science_data( sDir, ps_df, n_streams, r, fdatasets_final, sci_vars_dict0, zdbar, start_time, end_time) # get end times of deployments deployments = [] end_times = [] for index, row in ps_df.iterrows(): deploy = row['deployment'] deploy_info = cf.get_deployment_information(dr_data, int(deploy[-4:])) deployments.append(int(deploy[-4:])) end_times.append(pd.to_datetime(deploy_info['stop_date'])) # create data range output folders save_dir_stat = os.path.join(mDir, array, subsite) cf.create_dir(save_dir_stat) # create plots output folder save_fdir = os.path.join(sDir, array, subsite, r, 'data_range') cf.create_dir(save_fdir) stat_df = pd.DataFrame() """ create data ranges csv file and figures """ for m, n in sci_vars_dict.items(): for sv, vinfo in n['vars'].items(): print('\n' + vinfo['var_name']) if len(vinfo['t']) < 1: print('no variable data to plot') continue else: sv_units = vinfo['units'][0] fv = vinfo['fv'][0] t = vinfo['t'] z = vinfo['values'] y = vinfo['pressure'] # Check if the array is all NaNs if sum(np.isnan(z)) == len(z): print('Array of all NaNs - skipping plot.') continue # Check if the array is all fill values elif len(z[z != fv]) == 0: print('Array of all fill values - skipping plot.') continue else: if len(y) > 0: if m == 'common_stream_placeholder': sname = '-'.join((vinfo['var_name'], r)) else: sname = '-'.join((vinfo['var_name'], r, m)) """ create data ranges for non - pressure data only """ if 'pressure' in vinfo['var_name']: pass else: columns = ['tsec', 'dbar', str(vinfo['var_name'])] # create depth ranges min_r = int(round(min(y) - zcell_size)) max_r = int(round(max(y) + zcell_size)) ranges = list(range(min_r, max_r, zcell_size)) # group data by depth groups, d_groups = gt.group_by_depth_range(t, y, z, columns, ranges) print('writing data ranges for {}'.format(vinfo['var_name'])) stat_data = groups.describe()[vinfo['var_name']] stat_data.insert(loc=0, column='parameter', value=sv, allow_duplicates=False) t_deploy = deployments[0] for i in range(len(deployments))[1:len(deployments)]: t_deploy = '{}, {}'.format(t_deploy, deployments[i]) stat_data.insert(loc=1, column='deployments', value=t_deploy, allow_duplicates=False) stat_df = stat_df.append(stat_data, ignore_index=False) """ plot full time range free from errors and suspect data """ clabel = sv + " (" + sv_units + ")" ylabel = (y_name[0][0] + " (" + y_unit[0][0] + ")") t_eng = None m_water_depth = None # plot non-erroneous -suspect data fig, ax, bar = pf.plot_xsection(subsite, t, y, z, clabel, ylabel, t_eng, m_water_depth, inpercentile, stdev=None) title0 = 'Data colored using the upper and lower {} percentile.'.format(inpercentile) ax.set_title(r+'\n'+title0, fontsize=9) leg_text = ('{} % erroneous values removed after Human In the Loop review'.format( (len(t)/l0) * 100),) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) for ii in range(len(end_times)): ax.axvline(x=end_times[ii], color='b', linestyle='--', linewidth=.8) ax.text(end_times[ii], min(y)-5, 'End' + str(deployments[ii]), fontsize=6, style='italic', bbox=dict(boxstyle='round', ec=(0., 0.5, 0.5), fc=(1., 1., 1.), )) # fig.tight_layout() sfile = '_'.join(('data_range', sname)) pf.save_fig(save_fdir, sfile) # write stat file stat_df.to_csv('{}/{}_data_ranges.csv'.format(save_dir_stat, r), index=True, float_format='%11.6f')
def main(url_list, sDir, plot_type, deployment_num, start_time, end_time, preferred_only, glider, zdbar, n_std, inpercentile, zcell_size): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list and 'ENG' not in rd: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join((spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments(main_sensor, fdatasets) for fd in fdatasets_sel: part_d = fd.split('/')[-1] print(part_d) ds = xr.open_dataset(fd, mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) fname, subsite, refdes, method, stream, deployment = cf.nc_attributes(fd) array = subsite[0:2] sci_vars = cf.return_science_vars(stream) if 'CE05MOAS' in r or 'CP05MOAS' in r: # for coastal gliders, get m_water_depth for bathymetry eng = '-'.join((r.split('-')[0], r.split('-')[1], '00-ENG000000', method, 'glider_eng')) eng_url = [s for s in url_list if eng in s] if len(eng_url) == 1: eng_datasets = cf.get_nc_urls(eng_url) # filter out collocated datasets eng_dataset = [j for j in eng_datasets if (eng in j.split('/')[-1] and deployment in j.split('/')[-1])] if len(eng_dataset) > 0: ds_eng = xr.open_dataset(eng_dataset[0], mask_and_scale=False) t_eng = ds_eng['time'].values m_water_depth = ds_eng['m_water_depth'].values # m_altimeter_status = 0 means a good reading (not nan or -1) eng_ind = ds_eng['m_altimeter_status'].values == 0 m_water_depth = m_water_depth[eng_ind] t_eng = t_eng[eng_ind] else: print('No engineering file for deployment {}'.format(deployment)) if deployment_num is not None: if int(deployment.split('0')[-1]) is not deployment_num: print(type(int(deployment.split('0')[-1])), type(deployment_num)) continue if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print('No data to plot for specified time range: ({} to {})'.format(start_time, end_time)) continue stime = start_time.strftime('%Y-%m-%d') etime = end_time.strftime('%Y-%m-%d') ext = stime + 'to' + etime # .join((ds0_method, ds1_method save_dir = os.path.join(sDir, array, subsite, refdes, plot_type, deployment, ext) else: save_dir = os.path.join(sDir, array, subsite, refdes, plot_type, deployment) cf.create_dir(save_dir) tm = ds['time'].values # get pressure variable ds_vars = list(ds.data_vars.keys()) + [x for x in ds.coords.keys() if 'pressure' in x] y, y_units, press = cf.add_pressure_to_dictionary_of_sci_vars(ds) print(y_units, press) # press = pf.pressure_var(ds, ds_vars) # print(press) # y = ds[press].values # y_units = ds[press].units for sv in sci_vars: print(sv) if 'sci_water_pressure' not in sv: z = ds[sv].values fv = ds[sv]._FillValue z_units = ds[sv].units # Check if the array is all NaNs if sum(np.isnan(z)) == len(z): print('Array of all NaNs - skipping plot.') continue # Check if the array is all fill values elif len(z[z != fv]) == 0: print('Array of all fill values - skipping plot.') continue else: """ clean up data """ # reject erroneous data dtime, zpressure, ndata, lenfv, lennan, lenev, lengr, global_min, global_max = \ cf.reject_erroneous_data(r, sv, tm, y, z, fv) # get rid of 0.0 data if 'CTD' in r: ind = zpressure > 0.0 else: ind = ndata > 0.0 lenzero = np.sum(~ind) dtime = dtime[ind] zpressure = zpressure[ind] ndata = ndata[ind] # creating data groups columns = ['tsec', 'dbar', str(sv)] min_r = int(round(min(zpressure) - zcell_size)) max_r = int(round(max(zpressure) + zcell_size)) ranges = list(range(min_r, max_r, zcell_size)) groups, d_groups = gt.group_by_depth_range(dtime, zpressure, ndata, columns, ranges) # rejecting timestamps from percentile analysis y_avg, n_avg, n_min, n_max, n0_std, n1_std, l_arr, time_ex = cf.reject_timestamps_in_groups( groups, d_groups, n_std, inpercentile) t_nospct, z_nospct, y_nospct = cf.reject_suspect_data(dtime, zpressure, ndata, time_ex) print('removed {} data points using {} percentile of data grouped in {} dbar segments'.format( len(zpressure) - len(z_nospct), inpercentile, zcell_size)) # reject time range from data portal file export t_portal, z_portal, y_portal = cf.reject_timestamps_dataportal(subsite, r, t_nospct, y_nospct, z_nospct) print('removed {} data points using visual inspection of data'.format(len(z_nospct) - len(z_portal))) # reject data in a depth range if zdbar: y_ind = y_portal < zdbar n_zdbar = np.sum(~y_ind) t_array = t_portal[y_ind] y_array = y_portal[y_ind] z_array = z_portal[y_ind] else: n_zdbar = 0 t_array = t_portal y_array = y_portal z_array = z_portal print('{} in water depth > {} dbar'.format(n_zdbar, zdbar)) """ Plot data """ if len(dtime) > 0: sname = '-'.join((r, method, sv)) clabel = sv + " (" + z_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" if glider == 'no': t_eng = None m_water_depth = None # plot non-erroneous data fig, ax, bar = pf.plot_xsection(subsite, dtime, zpressure, ndata, clabel, ylabel, t_eng, m_water_depth, inpercentile, stdev=None) t0 = pd.to_datetime(dtime.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(dtime.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) + '\n' + t0 + ' to ' + t1 ax.set_title(title, fontsize=9) leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} zeros'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero), ) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) fig.tight_layout() sfile = '_'.join(('rm_erroneous_data', sname)) pf.save_fig(save_dir, sfile) # plots removing all suspect data if len(t_array) > 0: if len(t_array) != len(dtime): # plot bathymetry only within data time ranges if glider == 'yes': eng_ind = (t_eng >= np.min(t_array)) & (t_eng <= np.max(t_array)) t_eng = t_eng[eng_ind] m_water_depth = m_water_depth[eng_ind] fig, ax, bar = pf.plot_xsection(subsite, t_array, y_array, z_array, clabel, ylabel, t_eng, m_water_depth, inpercentile, stdev=None) t0 = pd.to_datetime(t_array.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(t_array.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) + '\n' + t0 + ' to ' + t1 ax.set_title(title, fontsize=9) if zdbar: leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} zeros'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nremoved {} in the upper and lower {}th percentile of data grouped in {} dbar segments'.format( len(zpressure) - len(z_nospct), inpercentile, zcell_size) + '\nexcluded {} suspect data points when inspected visually'.format( len(z_nospct) - len(z_portal)) + '\nexcluded {} suspect data in water depth greater than {} dbar'.format(n_zdbar, zdbar), ) else: leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} zeros'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nremoved {} in the upper and lower {}th percentile of data grouped in {} dbar segments'.format( len(zpressure) - len(z_nospct), inpercentile, zcell_size) + '\nexcluded {} suspect data points when inspected visually'.format( len(z_nospct) - len(z_portal)), ) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) fig.tight_layout() sfile = '_'.join(('rm_suspect_data', sname)) pf.save_fig(save_dir, sfile)
def main(sDir, url_list, deployment_num): reviewlist = pd.read_csv( 'https://raw.githubusercontent.com/ooi-data-lab/data-review-prep/master/review_list/data_review_list.csv') rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list: rd_list.append(rd) json_file_list = [] for r in rd_list: dependencies = [] print('\n{}'.format(r)) data = OrderedDict(deployments=OrderedDict()) save_dir = os.path.join(sDir, r.split('-')[0], r) cf.create_dir(save_dir) # Deployment location test deploy_loc_test = cf.deploy_location_check(r) data['location_comparison'] = deploy_loc_test for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) catalog_rms = '-'.join((r, splitter[-2], splitter[-1])) # complete the analysis by reference designator if rd_check == r: udatasets = cf.get_nc_urls([u]) # check for the OOI 1.0 datasets for review rl_filtered = reviewlist.loc[ (reviewlist['Reference Designator'] == r) & (reviewlist['status'] == 'for review')] review_deployments = rl_filtered['deploymentNumber'].tolist() review_deployments_int = ['deployment%04d' % int(x) for x in review_deployments] for rev_dep in review_deployments_int: if deployment_num is not None: if int(rev_dep[-4:]) is not deployment_num: print('\nskipping {}'.format(rev_dep)) continue rdatasets = [s for s in udatasets if rev_dep in s] rdatasets.sort() if len(rdatasets) > 0: datasets = [] for dss in rdatasets: # filter out collocated data files if catalog_rms == dss.split('/')[-1].split('_20')[0][15:]: datasets.append(dss) else: drd = dss.split('/')[-1].split('_20')[0][15:42] if drd not in dependencies and drd != r: dependencies.append(drd) notes = [] time_ascending = '' sci_vars_dict = {} #datasets = datasets[0:2] #### for testing for i in range(len(datasets)): ds = xr.open_dataset(datasets[i], mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) print('\nAppending data from {}: file {} of {}'.format(rev_dep, i+1, len(datasets))) # when opening multiple datasets, don't check that the timestamps are in ascending order time_ascending = 'not_tested' if i == 0: fname, subsite, refdes, method, data_stream, deployment = cf.nc_attributes(datasets[0]) fname = fname.split('_20')[0] # Get info from the data review database dr_data = cf.refdes_datareview_json(refdes) stream_vars = cf.return_stream_vars(data_stream) sci_vars = cf.return_science_vars(data_stream) node = refdes.split('-')[1] if 'cspp' in data_stream or 'WFP' in node: sci_vars.append('int_ctd_pressure') # Add pressure to the list of science variables press = pf.pressure_var(ds, list(ds.coords.keys())) if press is None: press = pf.pressure_var(ds, list(ds.data_vars.keys())) if press is not None: sci_vars.append(press) sci_vars.append('time') sci_vars = list(np.unique(sci_vars)) if 'ADCP' in r: sci_vars = [x for x in sci_vars if 'beam' not in x] for sci_var in sci_vars: if sci_var == 'time': sci_vars_dict.update( {sci_var: dict(values=np.array([], dtype=np.datetime64), units=[], fv=[])}) else: sci_vars_dict.update({sci_var: dict(values=np.array([]), units=[], fv=[])}) deploy_info = get_deployment_information(dr_data, int(deployment[-4:])) # Grab deployment Variables deploy_start = str(deploy_info['start_date']) deploy_stop = str(deploy_info['stop_date']) deploy_lon = deploy_info['longitude'] deploy_lat = deploy_info['latitude'] deploy_depth = deploy_info['deployment_depth'] # Calculate days deployed if deploy_stop != 'None': r_deploy_start = pd.to_datetime(deploy_start).replace(hour=0, minute=0, second=0) if deploy_stop.split('T')[1] == '00:00:00': r_deploy_stop = pd.to_datetime(deploy_stop) else: r_deploy_stop = (pd.to_datetime(deploy_stop) + timedelta(days=1)).replace(hour=0, minute=0, second=0) n_days_deployed = (r_deploy_stop - r_deploy_start).days else: n_days_deployed = None # Add reference designator to dictionary try: data['refdes'] except KeyError: data['refdes'] = refdes # append data for the deployment into a dictionary for s_v in sci_vars_dict.keys(): vv = ds[s_v] try: if vv.units not in sci_vars_dict[s_v]['units']: sci_vars_dict[s_v]['units'].append(vv.units) except AttributeError: print('') try: if vv._FillValue not in sci_vars_dict[s_v]['fv']: sci_vars_dict[s_v]['fv'].append(vv._FillValue) except AttributeError: print('') if len(vv.dims) == 1: if s_v in ['wavelength_a', 'wavelength_c']: # if the array is not same as the array that was already appended for these # two OPTAA variables, append. if it's already there, don't append if np.sum(vv.values == sci_vars_dict[s_v]['values']) != len(vv.values): sci_vars_dict[s_v]['values'] = np.append(sci_vars_dict[s_v]['values'], vv.values) else: sci_vars_dict[s_v]['values'] = np.append(sci_vars_dict[s_v]['values'], vv.values) elif len(vv.dims) == 2: # appending 2D datasets vD = vv.values.T if len(sci_vars_dict[s_v]['values']) == 0: sci_vars_dict[s_v]['values'] = vD else: sci_vars_dict[s_v]['values'] = np.concatenate((sci_vars_dict[s_v]['values'], vD), axis=1) deployments = data['deployments'].keys() data_start = pd.to_datetime(min(sci_vars_dict['time']['values'])).strftime('%Y-%m-%dT%H:%M:%S') data_stop = pd.to_datetime(max(sci_vars_dict['time']['values'])).strftime('%Y-%m-%dT%H:%M:%S') # Add deployment and info to dictionary and initialize delivery method sub-dictionary if deployment not in deployments: data['deployments'][deployment] = OrderedDict(deploy_start=deploy_start, deploy_stop=deploy_stop, n_days_deployed=n_days_deployed, lon=deploy_lon, lat=deploy_lat, deploy_depth=deploy_depth, method=OrderedDict()) # Add delivery methods to dictionary and initialize stream sub-dictionary methods = data['deployments'][deployment]['method'].keys() if method not in methods: data['deployments'][deployment]['method'][method] = OrderedDict( stream=OrderedDict()) # Add streams to dictionary and initialize file sub-dictionary streams = data['deployments'][deployment]['method'][method]['stream'].keys() if data_stream not in streams: data['deployments'][deployment]['method'][method]['stream'][ data_stream] = OrderedDict(file=OrderedDict()) # Get a list of data gaps >1 day time_df = pd.DataFrame(sci_vars_dict['time']['values'], columns=['time']) time_df = time_df.sort_values(by=['time']) gap_list = cf.timestamp_gap_test(time_df) # Calculate the sampling rate to the nearest second time_df['diff'] = time_df['time'].diff().astype('timedelta64[s]') rates_df = time_df.groupby(['diff']).agg(['count']) n_diff_calc = len(time_df) - 1 rates = dict(n_unique_rates=len(rates_df), common_sampling_rates=dict()) for i, row in rates_df.iterrows(): percent = (float(row['time']['count']) / float(n_diff_calc)) if percent > 0.1: rates['common_sampling_rates'].update({int(i): '{:.2%}'.format(percent)}) sampling_rt_sec = None for k, v in rates['common_sampling_rates'].items(): if float(v.strip('%')) > 50.00: sampling_rt_sec = k if not sampling_rt_sec: sampling_rt_sec = 'no consistent sampling rate: {}'.format(rates['common_sampling_rates']) # Don't do : Check that the timestamps in the file are unique time_test = '' # Count the number of days for which there is at least 1 timestamp n_days = len(np.unique(sci_vars_dict['time']['values'].astype('datetime64[D]'))) # Compare variables in file to variables in Data Review Database ds_variables = list(ds.data_vars.keys()) + list(ds.coords.keys()) ds_variables = eliminate_common_variables(ds_variables) ds_variables = [x for x in ds_variables if 'qc' not in x] [_, unmatch1] = compare_lists(stream_vars, ds_variables) [_, unmatch2] = compare_lists(ds_variables, stream_vars) # calculate mean pressure from data, excluding outliers +/- 3 SD try: pressure = sci_vars_dict[press] if len(pressure) > 1: # reject NaNs p_nonan = pressure['values'][~np.isnan(pressure['values'])] # reject fill values p_nonan_nofv = p_nonan[p_nonan != pressure['fv'][0]] # reject data outside of global ranges [pg_min, pg_max] = cf.get_global_ranges(r, press) if pg_min is not None and pg_max is not None: pgr_ind = cf.reject_global_ranges(p_nonan_nofv, pg_min, pg_max) p_nonan_nofv_gr = p_nonan_nofv[pgr_ind] else: p_nonan_nofv_gr = p_nonan_nofv if (len(p_nonan_nofv_gr) > 0): [press_outliers, pressure_mean, _, pressure_max, _, _] = cf.variable_statistics(p_nonan_nofv_gr, 3) pressure_mean = round(pressure_mean, 2) pressure_max = round(pressure_max, 2) else: press_outliers = None pressure_mean = None pressure_max = None if len(pressure) > 0 and len(p_nonan) == 0: notes.append('Pressure variable all NaNs') elif len(pressure) > 0 and len(p_nonan) > 0 and len(p_nonan_nofv) == 0: notes.append('Pressure variable all fill values') elif len(pressure) > 0 and len(p_nonan) > 0 and len(p_nonan_nofv) > 0 and len(p_nonan_nofv_gr) == 0: notes.append('Pressure variable outside of global ranges') else: # if there is only 1 data point press_outliers = 0 pressure_mean = round(ds[press].values.tolist()[0], 2) pressure_max = round(ds[press].values.tolist()[0], 2) try: pressure_units = pressure['units'][0] except AttributeError: pressure_units = 'no units attribute for pressure' if pressure_mean: if 'SF' in node: pressure_compare = int(round(pressure_max)) else: pressure_compare = int(round(pressure_mean)) if pressure_units == '0.001 dbar': pressure_max = round((pressure_max / 1000), 2) pressure_mean = round((pressure_mean / 1000), 2) pressure_compare = round((pressure_compare / 1000), 2) notes.append('Pressure converted from 0.001 dbar to dbar for pressure comparison') elif pressure_units == 'daPa': pressure_max = round((pressure_max / 1000), 2) pressure_mean = round((pressure_mean / 1000), 2) pressure_compare = round((pressure_compare / 1000), 2) notes.append('Pressure converted from daPa to dbar for pressure comparison') else: pressure_compare = None if (not deploy_depth) or (not pressure_mean): pressure_diff = None else: pressure_diff = pressure_compare - deploy_depth except KeyError: press = 'no seawater pressure in file' pressure_diff = None pressure_mean = None pressure_max = None pressure_compare = None press_outliers = None pressure_units = None # Add files and info to dictionary filenames = data['deployments'][deployment]['method'][method]['stream'][data_stream][ 'file'].keys() if fname not in filenames: data['deployments'][deployment]['method'][method]['stream'][data_stream]['file'][ fname] = OrderedDict( file_downloaded=pd.to_datetime(splitter[0][0:15]).strftime('%Y-%m-%dT%H:%M:%S'), file_coordinates=list(ds.coords.keys()), sampling_rate_seconds=sampling_rt_sec, sampling_rate_details=rates, data_start=data_start, data_stop=data_stop, time_gaps=gap_list, unique_timestamps=time_test, n_timestamps=len(sci_vars_dict['time']['values']), n_days=n_days, notes=notes, ascending_timestamps=time_ascending, pressure_comparison=dict(pressure_mean=pressure_mean, units=pressure_units, num_outliers=press_outliers, diff=pressure_diff, pressure_max=pressure_max, variable=press, pressure_compare=pressure_compare), vars_in_file=ds_variables, vars_not_in_file=[x for x in unmatch1 if 'time' not in x], vars_not_in_db=unmatch2, sci_var_stats=OrderedDict()) # calculate statistics for science variables, excluding outliers +/- 5 SD for sv in sci_vars_dict.keys(): if sv != 't_max': # for ADCP if sv != 'time': print(sv) var = sci_vars_dict[sv] vD = var['values'] var_units = var['units'] #if 'timedelta' not in str(vD.dtype): vnum_dims = len(np.shape(vD)) # for OPTAA wavelengths, print the array if sv == 'wavelength_a' or sv == 'wavelength_c': [g_min, g_max] = cf.get_global_ranges(r, sv) n_all = len(var) mean = list(vD) num_outliers = None vmin = None vmax = None sd = None n_stats = 'not calculated' n_nan = None n_fv = None n_grange = 'no global ranges' fv = var['fv'][0] else: if vnum_dims > 2: print('variable has more than 2 dimensions') num_outliers = None mean = None vmin = None vmax = None sd = None n_stats = 'variable has more than 2 dimensions' n_nan = None n_fv = None n_grange = None fv = None n_all = None else: if vnum_dims > 1: n_all = [len(vD), len(vD.flatten())] else: n_all = len(vD) n_nan = int(np.sum(np.isnan(vD))) fv = var['fv'][0] vD[vD == fv] = np.nan # turn fill values to nans n_fv = int(np.sum(np.isnan(vD))) - n_nan [g_min, g_max] = cf.get_global_ranges(r, sv) if list(np.unique(np.isnan(vD))) != [True]: # reject data outside of global ranges if g_min is not None and g_max is not None: # turn data outside of global ranges to nans #var_gr = var_nofv.where((var_nofv >= g_min) & (var_nofv <= g_max)) vD[vD < g_min] = np.nan vD[vD > g_max] = np.nan n_grange = int(np.sum(np.isnan(vD)) - n_fv - n_nan) else: n_grange = 'no global ranges' if list(np.unique(np.isnan(vD))) != [True]: if sv == 'spkir_abj_cspp_downwelling_vector': # don't remove outliers from dataset [num_outliers, mean, vmin, vmax, sd, n_stats] = cf.variable_statistics_spkir(vD) else: if vnum_dims > 1: var_gr = vD.flatten() else: var_gr = vD # drop nans before calculating stats var_gr = var_gr[~np.isnan(var_gr)] [num_outliers, mean, vmin, vmax, sd, n_stats] = cf.variable_statistics(var_gr, 5) else: num_outliers = None mean = None vmin = None vmax = None sd = None n_stats = 0 n_grange = None else: num_outliers = None mean = None vmin = None vmax = None sd = None n_stats = 0 n_grange = None if vnum_dims > 1: sv = '{} (dims: {})'.format(sv, list(np.shape(var['values']))) else: sv = sv #if 'timedelta' not in str(var.values.dtype): data['deployments'][deployment]['method'][method]['stream'][data_stream]['file'][ fname]['sci_var_stats'][sv] = dict(n_outliers=num_outliers, mean=mean, min=vmin, max=vmax, stdev=sd, n_stats=n_stats, units=var_units, n_nans=n_nan, n_fillvalues=n_fv, fill_value=str(fv), global_ranges=[g_min, g_max], n_grange=n_grange, n_all=n_all) sfile = os.path.join(save_dir, '{}-{}-file_analysis.json'.format(rev_dep, r)) with open(sfile, 'w') as outfile: json.dump(data, outfile) json_file_list.append(str(sfile)) depfile = os.path.join(save_dir, '{}-dependencies.txt'.format(r)) with open(depfile, 'w') as depf: depf.write(str(dependencies)) return json_file_list
def main(files, out, time_break, depth, start, end, interactive): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ fname, ext = os.path.splitext(files) if ext in '.nc': list_files = [files] elif ext in '.ncml': list_files = [files] else: list_files = read_file(files) stream_vars = pf.load_variable_dict(var='eng') # load engineering variables for nc in list_files: print nc with xr.open_dataset(nc, mask_and_scale=False) as ds: # change dimensions from 'obs' to 'time' ds = ds.swap_dims({'obs': 'time'}) ds_variables = ds.data_vars.keys() # List of dataset variables stream = ds.stream # List stream name associated with the data title_pre = mk_str(ds.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds.attrs, 's') # , var, tt0, tt1, 's') platform = ds.subsite node = ds.node sensor = ds.sensor # save_dir = os.path.join(out,'xsection_depth_profiles') save_dir = os.path.join(out, ds.subsite, ds.subsite + '-' + ds.node + '-' + ds.sensor, ds.stream, 'xsection_depth_profiles') cf.create_dir(save_dir) misc = ['quality', 'string', 'timestamp', 'deployment', 'id', 'provenance', 'qc', 'time', 'mission', 'obs', 'volt', 'ref', 'sig', 'amp', 'rph', 'calphase', 'phase', 'therm', 'light'] reg_ex = re.compile('|'.join(misc)) # keep variables that are not in the regular expression sci_vars = [s for s in ds_variables if not reg_ex.search(s)] if not time_break == None: times = np.unique(ds[time_break]) for t in times: time_ind = t == ds[time_break].data for var in sci_vars: x = dict(data=ds['time'].data[time_ind], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime(x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime(x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop('comment') # remove from the attributes sci = ds[var] # or else the variable won't load y = dict(data=ds[depth].data[time_ind], info=dict(label='Pressure', units='dbar', var=var, platform=platform, node=node, sensor=sensor)) try: z_lab = sci.long_name except AttributeError: z_lab = sci.standard_name z = dict(data=sci.data[time_ind], info=dict(label=z_lab, units=str(sci.units), var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.depth_glider_cross_section(x, y, z, title=title) if interactive == True: fig.canvas.mpl_connect('pick_event', lambda event: pf.onpick3(event, x['data'], y['data'], z['data'])) plt.show() else: pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') else: ds = ds.sel(time=slice(start, end)) for var in sci_vars: x = dict(data=ds['time'].data[:], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime(x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime(x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop('comment') # remove from the attributes sci = ds[var] # or else the variable won't load y = dict(data=ds[depth].data[:], info=dict(label='Pressure', units='dbar', var=var, platform=platform, node=node, sensor=sensor)) try: z_lab = sci.long_name except AttributeError: z_lab = sci.standard_name z = dict(data=sci.data[:], info=dict(label=z_lab, units=sci.units, var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.depth_glider_cross_section(x, y, z, title=title, interactive=interactive) if interactive == True: fig.canvas.mpl_connect('pick_event', lambda event: pf.onpick3(event, x['data'], y['data'], z['data'])) plt.show() else: pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all')
def main(url_list, sDir, plot_type, start_time, end_time, deployment_num, bfiles): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list: rd_list.append(rd) for r in rd_list: if 'ENG' not in r: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: if 'bottom_track_earth' not in splitter[-1]: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join((spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments(main_sensor, fdatasets) subsite = r.split('-')[0] array = subsite[0:2] save_dir = os.path.join(sDir, array, subsite, r, plot_type) cf.create_dir(save_dir) sname = '_'.join((r, plot_type)) sh = pd.DataFrame() deployments = [] for ii, d in enumerate(fdatasets_sel): print('\nDataset {} of {}: {}'.format(ii + 1, len(fdatasets_sel), d.split('/')[-1])) deploy = d.split('/')[-1].split('_')[0] if deployment_num: if int(deploy[-4:]) is not deployment_num: continue ds = xr.open_dataset(d, mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print('No data to plot for specified time range: ({} to {})'.format(start_time, end_time)) continue try: ds_lat = ds['lat'].values except KeyError: ds_lat = None print('No latitude variable in file') try: ds_lon = ds['lon'].values except KeyError: ds_lon = None print('No longitude variable in file') if ds_lat is not None and ds_lon is not None: data = {'lat': ds_lat, 'lon': ds_lon} new_r = pd.DataFrame(data, columns=['lat', 'lon'], index=ds['time'].values) sh = sh.append(new_r) # append the deployments that are actually plotted if int(deploy[-4:]) not in deployments: deployments.append(int(deploy[-4:])) # plot data by deployment sfile = '-'.join((deploy, sname)) if array == 'CE': ttl = 'Glider Track - ' + r + ' - ' + deploy + '\nx: Mooring Locations' else: ttl = 'Glider Track - ' + r + ' - ' + deploy + '\nx: Mooring Locations' + '\n blue box: Glider Sampling Area' #fig, ax = pf.plot_profiles(ds_lon, ds_lat, ds['time'].values, ylabel, xlabel, clabel, stdev=None) plot_map(save_dir, sfile, ttl, ds_lon, ds_lat, ds['time'].values, array, bfiles, plot_type) sh = sh.resample('H').median() # resample hourly xD = sh.lon.values yD = sh.lat.values tD = sh.index.values title = 'Glider Track - ' + r + '\nDeployments: ' + str(deployments) + ' x: Mooring Locations' + '\n blue box: Glider Sampling Area' save_dir_main = os.path.join(sDir, array, subsite, r) plot_map(save_dir_main, sname, title, xD, yD, tD, array, bfiles, plot_type, add_box='yes')
def main(files, out, time_break, depth): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ fname, ext = os.path.splitext(files) if ext in '.nc': list_files = [files] elif ext in '.ncml': list_files = [files] else: list_files = read_file(files) stream_vars = pf.load_variable_dict(var='eng') # load engineering variables for nc in list_files: print nc with xr.open_dataset(nc, mask_and_scale=False) as ds: # change dimensions from 'obs' to 'time' ds = ds.swap_dims({'obs': 'time'}) ds_variables = ds.data_vars.keys() # List of dataset variables stream = ds.stream # List stream name associated with the data title_pre = mk_str(ds.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds.attrs, 's') # , var, tt0, tt1, 's') platform = ds.subsite node = ds.node sensor = ds.sensor deployment = 'D0000{}'.format(str(np.unique(ds.deployment)[0])) stream = ds.stream save_dir = os.path.join(out, platform, deployment, node, sensor, stream, 'depth_profiles') cf.create_dir(save_dir) # try: # eng = stream_vars[stream] # select specific streams engineering variables # except KeyError: # eng = [''] misc = ['quality', 'string', 'timestamp', 'deployment', 'id', 'provenance', 'qc', 'time', 'mission', 'obs', 'volt', 'ref', 'sig', 'amp', 'rph', 'calphase', 'phase', 'therm'] # reg_ex = re.compile('|'.join(eng+misc)) # make regular expression reg_ex = re.compile('|'.join(misc)) # keep variables that are not in the regular expression sci_vars = [s for s in ds_variables if not reg_ex.search(s)] # t0, t1 = pf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = (pd.to_datetime(t0) + (pd.to_datetime(t1) - pd.to_datetime(t0)) / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] times = np.unique(ds[time_break]) for t in times: time_ind = t == ds[time_break].data for var in sci_vars: x = dict(data=ds['time'].data[time_ind], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime(x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime(x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop('comment') # remove from the attributes sci = ds[var] # or else the variable won't load y = dict(data=ds[depth].data[time_ind], info=dict(label='Pressure', units='dbar', var=var, platform=platform, node=node, sensor=sensor)) try: z_lab = sci.long_name except AttributeError: z_lab = sci.standard_name z = dict(data=sci.data[time_ind], info=dict(label=z_lab, units=sci.units, var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.depth_cross_section(z, y, x, title=title) pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') # try: # y_lab = sci.standard_name # except AttributeError: # y_lab = var # y = dict(data=sci.data, info=dict(label=y_lab, units=sci.units)) del x, y
def main(sDir, plotting_sDir, url_list, sd_calc): dr = pd.read_csv('https://datareview.marine.rutgers.edu/notes/export') drn = dr.loc[dr.type == 'exclusion'] rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) pms = [] for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) pms.append(row[ii]) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments( main_sensor, fdatasets) # find time ranges to exclude from analysis for data review database subsite = r.split('-')[0] subsite_node = '-'.join((subsite, r.split('-')[1])) drne = drn.loc[drn.reference_designator.isin( [subsite, subsite_node, r])] et = [] for i, row in drne.iterrows(): sdate = cf.format_dates(row.start_date) edate = cf.format_dates(row.end_date) et.append([sdate, edate]) # get science variable long names from the Data Review Database stream_sci_vars = cd.sci_var_long_names(r) # check if the science variable long names are the same for each stream sci_vars_dict = cd.sci_var_long_names_check(stream_sci_vars) # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) # build dictionary of science data from the preferred dataset for each deployment print('\nAppending data from files') sci_vars_dict, pressure_unit, pressure_name = cd.append_science_data( ps_df, n_streams, r, fdatasets_sel, sci_vars_dict, et) # analyze combined dataset print('\nAnalyzing combined dataset and writing summary file') array = subsite[0:2] save_dir = os.path.join(sDir, array, subsite) cf.create_dir(save_dir) rows = [] if ('FLM' in r) and ( 'CTDMO' in r ): # calculate Flanking Mooring CTDMO stats based on pressure headers = [ 'common_stream_name', 'preferred_methods_streams', 'deployments', 'long_name', 'units', 't0', 't1', 'fill_value', 'global_ranges', 'n_all', 'press_min_max', 'n_excluded_forpress', 'n_nans', 'n_fillvalues', 'n_grange', 'define_stdev', 'n_outliers', 'n_stats', 'mean', 'min', 'max', 'stdev', 'note' ] else: headers = [ 'common_stream_name', 'preferred_methods_streams', 'deployments', 'long_name', 'units', 't0', 't1', 'fill_value', 'global_ranges', 'n_all', 'n_nans', 'n_fillvalues', 'n_grange', 'define_stdev', 'n_outliers', 'n_stats', 'mean', 'min', 'max', 'stdev' ] for m, n in sci_vars_dict.items(): print('\nSTREAM: ', m) if m == 'common_stream_placeholder': m = 'science_data_stream' if m == 'metbk_hourly': # don't calculate ranges for metbk_hourly continue if ('FLM' in r) and ( 'CTDMO' in r ): # calculate Flanking Mooring CTDMO stats based on pressure # index the pressure variable to filter and calculate stats on the rest of the variables sv_press = 'Seawater Pressure' vinfo_press = n['vars'][sv_press] # first, index where data are nans, fill values, and outside of global ranges fv_press = list(np.unique(vinfo_press['fv']))[0] pdata = vinfo_press['values'] [pind, __, __, __, __, __] = index_dataset(r, vinfo_press['var_name'], pdata, fv_press) pdata_filtered = pdata[pind] [__, pmean, __, __, psd, __] = cf.variable_statistics(pdata_filtered, None) # index of pressure = average of all 'valid' pressure data +/- 1 SD ipress_min = pmean - psd ipress_max = pmean + psd ind_press = (pdata >= ipress_min) & (pdata <= ipress_max) # calculate stats for all variables print('\nPARAMETERS:') for sv, vinfo in n['vars'].items(): print(sv) fv_lst = np.unique(vinfo['fv']).tolist() if len(fv_lst) == 1: fill_value = fv_lst[0] else: print('No unique fill value for {}'.format(sv)) lunits = np.unique(vinfo['units']).tolist() n_all = len(vinfo['t']) # filter data based on pressure index t_filtered = vinfo['t'][ind_press] data_filtered = vinfo['values'][ind_press] deploy_filtered = vinfo['deployments'][ind_press] n_excluded = n_all - len(t_filtered) [dataind, g_min, g_max, n_nan, n_fv, n_grange] = index_dataset(r, vinfo['var_name'], data_filtered, fill_value) t_final = t_filtered[dataind] data_final = data_filtered[dataind] deploy_final = deploy_filtered[dataind] t0 = pd.to_datetime( min(t_final)).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime( max(t_final)).strftime('%Y-%m-%dT%H:%M:%S') deploy = list(np.unique(deploy_final)) deployments = [int(dd) for dd in deploy] if len(data_final) > 1: [num_outliers, mean, vmin, vmax, sd, n_stats ] = cf.variable_statistics(data_final, sd_calc) else: mean = None vmin = None vmax = None sd = None n_stats = None note = 'restricted stats calculation to data points where pressure is within defined ranges' \ ' (average of all pressure data +/- 1 SD)' rows.append([ m, list(np.unique(pms)), deployments, sv, lunits, t0, t1, fv_lst, [g_min, g_max], n_all, [round(ipress_min, 2), round(ipress_max, 2)], n_excluded, n_nan, n_fv, n_grange, sd_calc, num_outliers, n_stats, mean, vmin, vmax, sd, note ]) # plot CTDMO data used for stats psave_dir = os.path.join(plotting_sDir, array, subsite, r, 'timeseries_plots_stats') cf.create_dir(psave_dir) dr_data = cf.refdes_datareview_json(r) deployments = [] end_times = [] for index, row in ps_df.iterrows(): deploy = row['deployment'] deploy_info = cf.get_deployment_information( dr_data, int(deploy[-4:])) deployments.append(int(deploy[-4:])) end_times.append( pd.to_datetime(deploy_info['stop_date'])) sname = '-'.join((r, sv)) fig, ax = pf.plot_timeseries_all(t_final, data_final, sv, lunits[0], stdev=None) ax.set_title( (r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) if sd_calc: sname = '-'.join((r, sv, 'rmoutliers')) fig, ax = pf.plot_timeseries_all(t_final, data_final, sv, lunits[0], stdev=sd_calc) ax.set_title( (r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) else: if not sd_calc: sdcalc = None print('\nPARAMETERS: ') for sv, vinfo in n['vars'].items(): print(sv) fv_lst = np.unique(vinfo['fv']).tolist() if len(fv_lst) == 1: fill_value = fv_lst[0] else: print(fv_lst) print('No unique fill value for {}'.format(sv)) lunits = np.unique(vinfo['units']).tolist() t = vinfo['t'] if len(t) > 1: data = vinfo['values'] n_all = len(t) if 'SPKIR' in r or 'presf_abc_wave_burst' in m: if 'SPKIR' in r: [dd_data, g_min, g_max, n_nan, n_fv, n_grange] = index_dataset_2d( r, 'spkir_abj_cspp_downwelling_vector', data, fill_value) else: [dd_data, g_min, g_max, n_nan, n_fv, n_grange] = index_dataset_2d( r, 'presf_wave_burst_pressure', data, fill_value) t_final = t t0 = pd.to_datetime( min(t_final)).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime( max(t_final)).strftime('%Y-%m-%dT%H:%M:%S') deploy_final = vinfo['deployments'] deploy = list(np.unique(deploy_final)) deployments = [int(dd) for dd in deploy] num_outliers = [] mean = [] vmin = [] vmax = [] sd = [] n_stats = [] for i in range(len(dd_data)): dd = data[i] # drop nans before calculating stats dd = dd[~np.isnan(dd)] [ num_outliersi, meani, vmini, vmaxi, sdi, n_statsi ] = cf.variable_statistics(dd, sd_calc) num_outliers.append(num_outliersi) mean.append(meani) vmin.append(vmini) vmax.append(vmaxi) sd.append(sdi) n_stats.append(n_statsi) else: [dataind, g_min, g_max, n_nan, n_fv, n_grange] = index_dataset(r, vinfo['var_name'], data, fill_value) t_final = t[dataind] if len(t_final) > 0: t0 = pd.to_datetime( min(t_final)).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime( max(t_final)).strftime('%Y-%m-%dT%H:%M:%S') data_final = data[dataind] # if sv == 'Dissolved Oxygen Concentration': # xx = (data_final > 0) & (data_final < 400) # data_final = data_final[xx] # t_final = t_final[xx] # if sv == 'Seawater Conductivity': # xx = (data_final > 1) & (data_final < 400) # data_final = data_final[xx] # t_final = t_final[xx] deploy_final = vinfo['deployments'][dataind] deploy = list(np.unique(deploy_final)) deployments = [int(dd) for dd in deploy] if len(data_final) > 1: [ num_outliers, mean, vmin, vmax, sd, n_stats ] = cf.variable_statistics( data_final, sd_calc) else: sdcalc = None num_outliers = None mean = None vmin = None vmax = None sd = None n_stats = None else: sdcalc = None num_outliers = None mean = None vmin = None vmax = None sd = None n_stats = None deployments = None t0 = None t1 = None else: sdcalc = None num_outliers = None mean = None vmin = None vmax = None sd = None n_stats = None deployments = None t0 = None t1 = None t_final = [] if sd_calc: print_sd = sd_calc else: print_sd = sdcalc rows.append([ m, list(np.unique(pms)), deployments, sv, lunits, t0, t1, fv_lst, [g_min, g_max], n_all, n_nan, n_fv, n_grange, print_sd, num_outliers, n_stats, mean, vmin, vmax, sd ]) if len(t_final) > 0: # plot data used for stats psave_dir = os.path.join( plotting_sDir, array, subsite, r, 'timeseries_reviewed_datarange') cf.create_dir(psave_dir) dr_data = cf.refdes_datareview_json(r) deployments = [] end_times = [] for index, row in ps_df.iterrows(): deploy = row['deployment'] deploy_info = cf.get_deployment_information( dr_data, int(deploy[-4:])) deployments.append(int(deploy[-4:])) end_times.append( pd.to_datetime(deploy_info['stop_date'])) sname = '-'.join((r, sv)) # plot hourly averages for streaming data if 'streamed' in sci_vars_dict[list( sci_vars_dict.keys())[0]]['ms'][0]: sname = '-'.join((sname, 'hourlyavg')) df = pd.DataFrame({ 'dfx': t_final, 'dfy': data_final }) dfr = df.resample('H', on='dfx').mean() # Plot all data fig, ax = pf.plot_timeseries_all(dfr.index, dfr['dfy'], sv, lunits[0], stdev=None) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) if sd_calc: sname = '-'.join( (sname, 'hourlyavg_rmoutliers')) fig, ax = pf.plot_timeseries_all(dfr.index, dfr['dfy'], sv, lunits[0], stdev=sd_calc) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) elif 'SPKIR' in r: fig, ax = pf.plot_spkir(t_final, dd_data, sv, lunits[0]) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) # plot each wavelength wavelengths = [ '412nm', '443nm', '490nm', '510nm', '555nm', '620nm', '683nm' ] for wvi in range(len(dd_data)): fig, ax = pf.plot_spkir_wv( t_final, dd_data[wvi], sv, lunits[0], wvi) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) snamewvi = '-'.join((sname, wavelengths[wvi])) pf.save_fig(psave_dir, snamewvi) elif 'presf_abc_wave_burst' in m: fig, ax = pf.plot_presf_2d(t_final, dd_data, sv, lunits[0]) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) snamewave = '-'.join((sname, m)) pf.save_fig(psave_dir, snamewave) else: # plot all data if not streamed fig, ax = pf.plot_timeseries_all(t_final, data_final, sv, lunits[0], stdev=None) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) if sd_calc: sname = '-'.join((r, sv, 'rmoutliers')) fig, ax = pf.plot_timeseries_all(t_final, data_final, sv, lunits[0], stdev=sd_calc) ax.set_title((r + '\nDeployments: ' + str(sorted(deployments)) + '\n' + t0 + ' - ' + t1), fontsize=8) for etimes in end_times: ax.axvline(x=etimes, color='k', linestyle='--', linewidth=.6) pf.save_fig(psave_dir, sname) fsum = pd.DataFrame(rows, columns=headers) fsum.to_csv('{}/{}_data_ranges.csv'.format(save_dir, r), index=False)
def main(folder, out, time_break): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ with xr.open_mfdataset(folder, mask_and_scale=False) as ds: # change dimensions from 'obs' to 'time' ds = ds.swap_dims({'obs': 'time'}) ds_variables = ds.data_vars.keys() # List of dataset variables stream = ds.stream # List stream name associated with the data title_pre = mk_str(ds.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds.attrs, 's') # , var, tt0, tt1, 's') platform = ds.subsite node = ds.node sensor = ds.sensor save_dir = os.path.join(out, ds.subsite, ds.node, ds.stream, 'timeseries') cf.create_dir(save_dir) try: eng = stream_vars[stream] # select specific streams engineering variables except KeyError: eng = [''] misc = ['timestamp', 'provenance', 'qc', 'id', 'obs', 'deployment', 'volts', 'counts', 'quality_flag'] reg_ex = re.compile('|'.join(eng+misc)) # make regular expression # keep variables that are not in the regular expression sci_vars = [s for s in ds_variables if not reg_ex.search(s)] # t0, t1 = pf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = (pd.to_datetime(t0) + (pd.to_datetime(t1) - pd.to_datetime(t0)) / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] times = np.unique(ds[time_break]) for t in times: time_ind = t == ds[time_break].data for var in sci_vars: x = dict(data=ds['time'].data[time_ind], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime(x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime(x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop('comment') # remove from the attributes sci = ds[var] # or else the variable won't load # define possible pressure variables pressure_vars = ['seawater_pressure', 'sci_water_pressure_dbar', 'ctdgv_m_glider_instrument_recovered-sci_water_pressure_dbar', 'ctdgv_m_glider_instrument-sci_water_pressure_dbar'] rePressure = re.compile('|'.join(pressure_vars)) # define y as pressure variable pressure = [s for s in sci.variables if rePressure.search(s)] pressure = ''.join(pressure) y = sci.variables[pressure] yN = pressure y_units = sci.units try: y_lab = sci.long_name except AttributeError: y_lab = sci.standard_name y = dict(data=sci.data[time_ind], info=dict(label=y_lab, units=sci.units, var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.auto_plot(x, y, title, stdev=None, line_style='r-o', g_range=True) pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') # plot z variable each time fig, ax = pf.depth_cross_section(x, y, title, stdev=1, line_style='r-o', g_range=True) pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}_outliers_removed'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') del x, y
file = os.path.join(root,filename) f = xr.open_dataset(file) f = f.swap_dims({'obs':'time'}) fN = f.source platform = f.subsite node = f.node sensor = f.sensor title = platform + '-' + node + '-' + sensor global fName head, tail = os.path.split(filename) fName = tail.split('.', 1)[0] d = fName.split('_')[0] save_dir = os.path.join(rootdir, 'timeseries', d) cf.create_dir(save_dir) varList = [] for vars in f.variables: varList.append(str(vars)) yVars = [s for s in varList if not reg_ex.search(s)] for v in yVars: print v t = f['time'].data t_dict = dict(data = t, info = dict(label='Time', units='GMT')) y = f[v]
@usage: sDir: directory where outputs are saved username: OOI API username token: OOI API password """ import datetime as dt import functions.common as cf import scripts sDir = '/Users/lgarzio/Documents/OOI' username = '******' token = 'token' cf.create_dir(sDir) now = dt.datetime.now().strftime('%Y%m%dT%H%M') arrays = input( '\nPlease select arrays (CE, CP, GA, GI, GP, GS, RS). Must be comma separated (if choosing multiple) or press enter to select all: ' ) or '' array = scripts.data_request_tools.format_inputs(arrays) subsites = input( '\nPlease fully-qualified subsites (e.g. GI01SUMO, GI05MOAS). Must be comma separated (if choosing multiple) or press enter to select all: ' ) or '' subsite = scripts.data_request_tools.format_inputs(subsites) nodes = input( '\nPlease select fully-qualified nodes. (e.g. GL469, GL477). Must be comma separated (if choosing multiple) or press enter to select all: ' ) or ''
def main(url_list, sDir, deployment_num, start_time, end_time, preferred_only, n_std, surface_params, depth_params): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list and 'ENG' not in rd: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments( main_sensor, fdatasets) for fd in fdatasets_sel: part_d = fd.split('/')[-1] print('\n{}'.format(part_d)) ds = xr.open_dataset(fd, mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( fd) array = subsite[0:2] sci_vars = cf.return_science_vars(stream) if 'CE05MOAS' in r or 'CP05MOAS' in r: # for coastal gliders, get m_water_depth for bathymetry eng = '-'.join((r.split('-')[0], r.split('-')[1], '00-ENG000000', method, 'glider_eng')) eng_url = [s for s in url_list if eng in s] if len(eng_url) == 1: eng_datasets = cf.get_nc_urls(eng_url) # filter out collocated datasets eng_dataset = [ j for j in eng_datasets if (eng in j.split('/')[-1] and deployment in j.split('/')[-1]) ] if len(eng_dataset) > 0: ds_eng = xr.open_dataset(eng_dataset[0], mask_and_scale=False) t_eng = ds_eng['time'].values m_water_depth = ds_eng['m_water_depth'].values # m_altimeter_status = 0 means a good reading (not nan or -1) eng_ind = ds_eng['m_altimeter_status'].values == 0 m_water_depth = m_water_depth[eng_ind] t_eng = t_eng[eng_ind] else: print('No engineering file for deployment {}'.format( deployment)) m_water_depth = None t_eng = None else: m_water_depth = None t_eng = None else: m_water_depth = None t_eng = None if deployment_num is not None: if int(deployment.split('0')[-1]) is not deployment_num: print(type(int(deployment.split('0')[-1])), type(deployment_num)) continue if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print( 'No data to plot for specified time range: ({} to {})'. format(start_time, end_time)) continue stime = start_time.strftime('%Y-%m-%d') etime = end_time.strftime('%Y-%m-%d') ext = stime + 'to' + etime # .join((ds0_method, ds1_method save_dir_profile = os.path.join(sDir, array, subsite, refdes, 'profile_plots', deployment, ext) save_dir_xsection = os.path.join(sDir, array, subsite, refdes, 'xsection_plots', deployment, ext) save_dir_4d = os.path.join(sDir, array, subsite, refdes, 'xsection_plots_4d', deployment, ext) else: save_dir_profile = os.path.join(sDir, array, subsite, refdes, 'profile_plots', deployment) save_dir_xsection = os.path.join(sDir, array, subsite, refdes, 'xsection_plots', deployment) save_dir_4d = os.path.join(sDir, array, subsite, refdes, 'xsection_plots_4d', deployment) tm = ds['time'].values try: ds_lat = ds['lat'].values except KeyError: ds_lat = None print('No latitude variable in file') try: ds_lon = ds['lon'].values except KeyError: ds_lon = None print('No longitude variable in file') # get pressure variable y, y_units, press = cf.add_pressure_to_dictionary_of_sci_vars(ds) for sv in sci_vars: print(sv) if 'pressure' not in sv: z = ds[sv].values fv = ds[sv]._FillValue sv_units = ds[sv].units # Check if the array is all NaNs if sum(np.isnan(z)) == len(z): print('Array of all NaNs - skipping plot.') continue # Check if the array is all fill values elif len(z[z != fv]) == 0: print('Array of all fill values - skipping plot.') continue else: # reject erroneous data dtime, zpressure, ndata, lenfv, lennan, lenev, lengr, global_min, global_max, lat, lon = \ cf.reject_erroneous_data(r, sv, tm, y, z, fv, ds_lat, ds_lon) # get rid of 0.0 data if 'CTD' in r: ind = zpressure > 0.0 else: ind = ndata > 0.0 lenzero = np.sum(~ind) dtime = dtime[ind] zpressure = zpressure[ind] ndata = ndata[ind] if ds_lat is not None and ds_lon is not None: lat = lat[ind] lon = lon[ind] else: lat = None lon = None t0 = pd.to_datetime( dtime.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime( dtime.max()).strftime('%Y-%m-%dT%H:%M:%S') title = ' '.join((deployment, refdes, method)) + '\n' + t0 + ' to ' + t1 # reject time range from data portal file export t_portal, z_portal, y_portal, lat_portal, lon_portal = \ cf.reject_timestamps_dataportal(subsite, r, dtime, zpressure, ndata, lat, lon) print( 'removed {} data points using visual inspection of data' .format(len(ndata) - len(z_portal))) # create data groups columns = ['tsec', 'dbar', str(sv)] # min_r = int(round(min(y_portal) - zcell_size)) # max_r = int(round(max(y_portal) + zcell_size)) # ranges = list(range(min_r, max_r, zcell_size)) #ranges = [0, 10, 20, 30, 40, 50, 60, 70, 80, 200] range1 = list( range(surface_params[0], surface_params[1], surface_params[2])) range2 = list( range(depth_params[0], depth_params[1] + depth_params[2], depth_params[2])) ranges = range1 + range2 groups, d_groups = gt.group_by_depth_range( t_portal, y_portal, z_portal, columns, ranges) if 'scatter' in sv: n_std = None # to use percentile else: n_std = n_std # get percentile analysis for printing on the profile plot inpercentile = [surface_params[3]] * len( range1) + [depth_params[3]] * len(range2) n_std = [surface_params[3]] * len( range1) + [depth_params[3]] * len(range2) y_plt, n_med, n_min, n_max, n0_std, n1_std, l_arr, time_ex = reject_timestamps_in_groups( groups, d_groups, n_std, inpercentile) """ Plot all data """ if len(tm) > 0: cf.create_dir(save_dir_profile) cf.create_dir(save_dir_xsection) sname = '-'.join((r, method, sv)) sfileall = '_'.join(('all_data', sname)) ''' profile plot ''' xlabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" clabel = 'Time' fig, ax = pf.plot_profiles(z, y, tm, ylabel, xlabel, clabel, stdev=None) ax.set_title(title, fontsize=9) fig.tight_layout() pf.save_fig(save_dir_profile, sfileall) ''' xsection plot ''' clabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" fig, ax, bar = pf.plot_xsection(subsite, tm, y, z, clabel, ylabel, t_eng, m_water_depth, inpercentile=None, stdev=None) ax.set_title(title, fontsize=9) fig.tight_layout() pf.save_fig(save_dir_xsection, sfileall) """ Plot cleaned-up data """ if len(dtime) > 0: sfile = '_'.join(('rm_erroneous_data', sname)) ''' profile plot ''' xlabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" clabel = 'Time' fig, ax = pf.plot_profiles(z_portal, y_portal, t_portal, ylabel, xlabel, clabel, stdev=None) ax.set_title(title, fontsize=9) ax.plot(n_med, y_plt, '.k') ax.fill_betweenx(y_plt, n0_std, n1_std, color='m', alpha=0.2) leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} zeros'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nexcluded {} suspect data points when inspected visually' .format(len(ndata) - len(z_portal)) + '\n(black) data median in {} dbar segments (break at {} dbar)' .format([surface_params[2], depth_params[2]], depth_params[0]) + '\n(magenta) upper and lower {} percentile envelope in {} dbar segments' .format( [surface_params[3], depth_params[3]], [surface_params[2], depth_params[2]]), ) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) fig.tight_layout() pf.save_fig(save_dir_profile, sfile) ''' xsection plot ''' clabel = sv + " (" + sv_units + ")" ylabel = press[0] + " (" + y_units[0] + ")" # plot non-erroneous data fig, ax, bar = pf.plot_xsection(subsite, t_portal, y_portal, z_portal, clabel, ylabel, t_eng, m_water_depth, inpercentile=None, stdev=None) ax.set_title(title, fontsize=9) leg_text = ( 'removed {} fill values, {} NaNs, {} Extreme Values (1e7), {} Global ranges [{} - {}], ' '{} zeros'.format(lenfv, lennan, lenev, lengr, global_min, global_max, lenzero) + '\nexcluded {} suspect data points when inspected visually' .format(len(ndata) - len(z_portal)), ) ax.legend(leg_text, loc='upper center', bbox_to_anchor=(0.5, -0.17), fontsize=6) fig.tight_layout() pf.save_fig(save_dir_xsection, sfile) ''' 4D plot for gliders only ''' if 'MOAS' in r: if ds_lat is not None and ds_lon is not None: cf.create_dir(save_dir_4d) clabel = sv + " (" + sv_units + ")" zlabel = press[0] + " (" + y_units[0] + ")" fig = plt.figure() ax = fig.add_subplot(111, projection='3d') sct = ax.scatter(lon_portal, lat_portal, y_portal, c=z_portal, s=2) cbar = plt.colorbar(sct, label=clabel, extend='both') cbar.ax.tick_params(labelsize=8) ax.invert_zaxis() ax.view_init(25, 32) ax.invert_xaxis() ax.invert_yaxis() ax.set_zlabel(zlabel, fontsize=9) ax.set_ylabel('Latitude', fontsize=9) ax.set_xlabel('Longitude', fontsize=9) ax.set_title(title, fontsize=9) pf.save_fig(save_dir_4d, sfile)
def main(url_list, sDir, deployment_num, start_time, end_time, preferred_only, n_std, inpercentile, zcell_size, zdbar): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list and 'ENG' not in rd and 'ADCP' not in rd: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] deployments = [] for url in url_list: splitter = url.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) catalog_rms = '-'.join((r, splitter[-2], splitter[-1])) if rd_check == r: udatasets = cf.get_nc_urls([url]) for u in udatasets: # filter out collocated data files if catalog_rms == u.split('/')[-1].split('_20')[0][15:]: datasets.append(u) deployments.append( int(u.split('/')[-1].split('_')[0][-4:])) deployments = np.unique(deployments).tolist() fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets_sel = cf.filter_collocated_instruments( main_sensor, fdatasets) for dep in deployments: if deployment_num is not None: if dep is not deployment_num: print('\nskipping deployment {}'.format(dep)) continue rdatasets = [ s for s in fdatasets_sel if 'deployment%04d' % dep in s ] rdatasets.sort() if len(rdatasets) > 0: sci_vars_dict = {} # rdatasets = rdatasets[0:2] #### for testing for i in range(len(rdatasets)): ds = xr.open_dataset(rdatasets[i], mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) print('\nAppending data from {}: file {} of {}'.format( 'deployment%04d' % dep, i + 1, len(rdatasets))) array = r[0:2] subsite = r.split('-')[0] if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print( 'No data to plot for specified time range: ({} to {})' .format(start_time, end_time)) continue stime = start_time.strftime('%Y-%m-%d') etime = end_time.strftime('%Y-%m-%d') ext = stime + 'to' + etime # .join((ds0_method, ds1_method save_dir_profile = os.path.join( sDir, array, subsite, r, 'profile_plots', 'deployment%04d' % dep, ext) save_dir_xsection = os.path.join( sDir, array, subsite, r, 'xsection_plots', 'deployment%04d' % dep, ext) else: save_dir_profile = os.path.join( sDir, array, subsite, r, 'profile_plots', 'deployment%04d' % dep) save_dir_xsection = os.path.join( sDir, array, subsite, r, 'xsection_plots', 'deployment%04d' % dep) if len(sci_vars_dict) == 0: fname, subsite, refdes, method, stream, deployment = cf.nc_attributes( rdatasets[0]) sci_vars = cf.return_science_vars(stream) if 'CTDPF' not in r: sci_vars.append('int_ctd_pressure') sci_vars.append('time') sci_vars = list(np.unique(sci_vars)) # initialize the dictionary for sci_var in sci_vars: if sci_var == 'time': sci_vars_dict.update({ sci_var: dict(values=np.array([], dtype=np.datetime64), units=[], fv=[]) }) else: sci_vars_dict.update({ sci_var: dict(values=np.array([]), units=[], fv=[]) }) # append data for the deployment into the dictionary for s_v in sci_vars_dict.keys(): vv = ds[s_v] try: if vv.units not in sci_vars_dict[s_v]['units']: sci_vars_dict[s_v]['units'].append(vv.units) except AttributeError: print('') try: if vv._FillValue not in sci_vars_dict[s_v]['fv']: sci_vars_dict[s_v]['fv'].append(vv._FillValue) vv_data = vv.values try: vv_data[ vv_data == vv. _FillValue] = np.nan # turn fill values to nans except ValueError: print('') except AttributeError: print('') if len(vv.dims) > 1: print('Skipping plot: variable has >1 dimension') else: sci_vars_dict[s_v]['values'] = np.append( sci_vars_dict[s_v]['values'], vv.values) # plot after appending all data into one file data_start = pd.to_datetime( min(sci_vars_dict['time']['values'])).strftime( '%Y-%m-%dT%H:%M:%S') data_stop = pd.to_datetime(max( sci_vars_dict['time']['values'])).strftime( '%Y-%m-%dT%H:%M:%S') time1 = sci_vars_dict['time']['values'] ds_lat1 = np.empty(np.shape(time1)) ds_lon1 = np.empty(np.shape(time1)) # define pressure variable try: pname = 'seawater_pressure' press = sci_vars_dict[pname] except KeyError: pname = 'int_ctd_pressure' press = sci_vars_dict[pname] y1 = press['values'] try: y_units = press['units'][0] except IndexError: y_units = '' for sv in sci_vars_dict.keys(): print('') print(sv) if sv not in [ 'seawater_pressure', 'int_ctd_pressure', 'time' ]: z1 = sci_vars_dict[sv]['values'] fv = sci_vars_dict[sv]['fv'][0] sv_units = sci_vars_dict[sv]['units'][0] # Check if the array is all NaNs if sum(np.isnan(z1)) == len(z1): print('Array of all NaNs - skipping plot.') continue # Check if the array is all fill values elif len(z1[z1 != fv]) == 0: print('Array of all fill values - skipping plot.') continue else: # remove unreasonable pressure data (e.g. for surface piercing profilers) if zdbar: po_ind = (0 < y1) & (y1 < zdbar) tm = time1[po_ind] y = y1[po_ind] z = z1[po_ind] ds_lat = ds_lat1[po_ind] ds_lon = ds_lon1[po_ind] else: tm = time1 y = y1 z = z1 ds_lat = ds_lat1 ds_lon = ds_lon1 # reject erroneous data dtime, zpressure, ndata, lenfv, lennan, lenev, lengr, global_min, global_max, lat, lon = \ cf.reject_erroneous_data(r, sv, tm, y, z, fv, ds_lat, ds_lon) # get rid of 0.0 data # if sv == 'salinity': # ind = ndata > 20 # elif sv == 'density': # ind = ndata > 1010 # elif sv == 'conductivity': # ind = ndata > 2 # else: # ind = ndata > 0 # if sv == 'sci_flbbcd_chlor_units': # ind = ndata < 7.5 # elif sv == 'sci_flbbcd_cdom_units': # ind = ndata < 25 # else: # ind = ndata > 0.0 if 'CTD' in r: ind = zpressure > 0.0 else: ind = ndata > 0.0 lenzero = np.sum(~ind) dtime = dtime[ind] zpressure = zpressure[ind] ndata = ndata[ind] if ds_lat is not None and ds_lon is not None: lat = lat[ind] lon = lon[ind] else: lat = None lon = None if len(dtime) > 0: # reject time range from data portal file export t_portal, z_portal, y_portal, lat_portal, lon_portal = \ cf.reject_timestamps_dataportal(subsite, r, dtime, zpressure, ndata, lat, lon) print( 'removed {} data points using visual inspection of data' .format(len(ndata) - len(z_portal))) # create data groups # if len(y_portal) > 0: # columns = ['tsec', 'dbar', str(sv)] # min_r = int(round(np.nanmin(y_portal) - zcell_size)) # max_r = int(round(np.nanmax(y_portal) + zcell_size)) # ranges = list(range(min_r, max_r, zcell_size)) # # groups, d_groups = gt.group_by_depth_range(t_portal, y_portal, z_portal, columns, ranges) # # if 'scatter' in sv: # n_std = None # to use percentile # else: # n_std = n_std # # # get percentile analysis for printing on the profile plot # y_avg, n_avg, n_min, n_max, n0_std, n1_std, l_arr, time_ex = cf.reject_timestamps_in_groups( # groups, d_groups, n_std, inpercentile) """ Plot all data """ if len(time1) > 0: cf.create_dir(save_dir_profile) cf.create_dir(save_dir_xsection) sname = '-'.join((r, method, sv)) # sfileall = '_'.join(('all_data', sname, pd.to_datetime(time1.min()).strftime('%Y%m%d'))) # tm0 = pd.to_datetime(time1.min()).strftime('%Y-%m-%dT%H:%M:%S') # tm1 = pd.to_datetime(time1.max()).strftime('%Y-%m-%dT%H:%M:%S') sfileall = '_'.join( (sname, pd.to_datetime( t_portal.min()).strftime('%Y%m%d'))) tm0 = pd.to_datetime(t_portal.min()).strftime( '%Y-%m-%dT%H:%M:%S') tm1 = pd.to_datetime(t_portal.max()).strftime( '%Y-%m-%dT%H:%M:%S') title = ' '.join( (deployment, refdes, method)) + '\n' + tm0 + ' to ' + tm1 if 'SPKIR' in r: title = title + '\nWavelength = 510 nm' ''' profile plot ''' xlabel = sv + " (" + sv_units + ")" ylabel = pname + " (" + y_units + ")" clabel = 'Time' # fig, ax = pf.plot_profiles(z1, y1, time1, ylabel, xlabel, clabel, stdev=None) fig, ax = pf.plot_profiles(z_portal, y_portal, t_portal, ylabel, xlabel, clabel, stdev=None) ax.set_title(title, fontsize=9) fig.tight_layout() pf.save_fig(save_dir_profile, sfileall) ''' xsection plot ''' clabel = sv + " (" + sv_units + ")" ylabel = pname + " (" + y_units + ")" # fig, ax, bar = pf.plot_xsection(subsite, time1, y1, z1, clabel, ylabel, t_eng=None, # m_water_depth=None, inpercentile=None, stdev=None) fig, ax, bar = pf.plot_xsection( subsite, t_portal, y_portal, z_portal, clabel, ylabel, t_eng=None, m_water_depth=None, inpercentile=None, stdev=None) if fig: ax.set_title(title, fontsize=9) fig.tight_layout() pf.save_fig(save_dir_xsection, sfileall) """
def main(nc, directory, out, time_break, breakdown): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ list_files = directory + "/*.nc" # list_files = ['https://opendap.oceanobservatories.org/thredds/dodsC/ooi/friedrich-knuth-gmail/20170322T191659-RS03AXPS-PC03A-4A-CTDPFA303-streamed-ctdpf_optode_sample/deployment0003_RS03AXPS-PC03A-4A-CTDPFA303-streamed-ctdpf_optode_sample_20170312T000000.426102-20170322T190000.059973.nc', # 'https://opendap.oceanobservatories.org/thredds/dodsC/ooi/friedrich-knuth-gmail/20170322T191659-RS03AXPS-PC03A-4A-CTDPFA303-streamed-ctdpf_optode_sample/deployment0003_RS03AXPS-PC03A-4A-CTDPFA303-streamed-ctdpf_optode_sample_20161222T000000.132709-20170311T235959.426096.nc'] # print list_files stream_vars = pf.load_variable_dict(var='eng') # load engineering variables with xr.open_dataset(nc, mask_and_scale=False) as ds_ncfile: stream = ds_ncfile.stream # List stream name associated with the data title_pre = mk_str(ds_ncfile.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds_ncfile.attrs, 's') # , var, tt0, tt1, 's') platform = ds_ncfile.subsite node = ds_ncfile.node sensor = ds_ncfile.sensor # save_dir = os.path.join(out, platform, node, stream, 'xsection_depth_profiles') save_dir = os.path.join(out,'timeseries',breakdown) cf.create_dir(save_dir) with xr.open_mfdataset(list_files) as ds: # change dimensions from 'obs' to 'time' ds = ds.swap_dims({'obs': 'time'}) ds_variables = ds.data_vars.keys() # List of dataset variables # try: # eng = stream_vars[stream] # select specific streams engineering variables # except KeyError: # eng = [''] misc = ['quality', 'string', 'timestamp', 'deployment', 'id', 'provenance', 'qc', 'time', 'mission', 'obs', 'volt', 'ref', 'sig', 'amp', 'rph', 'calphase', 'phase', 'therm'] # reg_ex = re.compile('|'.join(eng+misc)) # make regular expression reg_ex = re.compile('|'.join(misc)) # keep variables that are not in the regular expression sci_vars = [s for s in ds_variables if not reg_ex.search(s)] # t0, t1 = pf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = (pd.to_datetime(t0) + (pd.to_datetime(t1) - pd.to_datetime(t0)) / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] times = np.unique(ds[time_break]) for t in times: time_ind = t == ds[time_break].data for var in sci_vars: x = dict(data=ds['time'].data[time_ind], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime(x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime(x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop('comment') # remove from the attributes sci = ds[var] # or else the variable won't load try: y_lab = sci.long_name except AttributeError: y_lab = sci.standard_name y = dict(data=sci.data[time_ind], info=dict(label=y_lab, units=str(sci.units), var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.auto_plot(x, y, title, stdev=None, line_style='.', g_range=True) pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') # try: # y_lab = sci.standard_name # except AttributeError: # y_lab = var # y = dict(data=sci.data, info=dict(label=y_lab, units=sci.units)) # plot timeseries with outliers removed # fig, ax = pf.auto_plot(x, y, title, stdev=1, line_style='.', g_range=True) # pf.resize(width=12, height=8.5) # Resize figure # save_name = '{}-{}-{}_{}_{}-{}_outliers_removed'.format(platform, node, sensor, var, t0, t1) # pf.save_fig(save_dir, save_name, res=150) # Save figure # plt.close('all') del x, y
def main(folder, out, time_break): """ files: url to an .nc/.ncml file or the path to a text file containing .nc/.ncml links. A # at the front will skip links in the text file. out: Directory to save plots """ with xr.open_mfdataset(folder, mask_and_scale=False) as ds: # change dimensions from 'obs' to 'time' ds = ds.swap_dims({'obs': 'time'}) ds_variables = ds.data_vars.keys() # List of dataset variables stream = ds.stream # List stream name associated with the data title_pre = mk_str(ds.attrs, 't') # , var, tt0, tt1, 't') save_pre = mk_str(ds.attrs, 's') # , var, tt0, tt1, 's') platform = ds.subsite node = ds.node sensor = ds.sensor save_dir = os.path.join(out, ds.subsite, ds.node, ds.stream, 'timeseries') cf.create_dir(save_dir) try: eng = stream_vars[ stream] # select specific streams engineering variables except KeyError: eng = [''] misc = [ 'timestamp', 'provenance', 'qc', 'id', 'obs', 'deployment', 'volts', 'counts', 'quality_flag' ] reg_ex = re.compile('|'.join(eng + misc)) # make regular expression # keep variables that are not in the regular expression sci_vars = [s for s in ds_variables if not reg_ex.search(s)] # t0, t1 = pf.get_rounded_start_and_end_times(ds_disk['time'].data) # tI = (pd.to_datetime(t0) + (pd.to_datetime(t1) - pd.to_datetime(t0)) / 2) # time_list = [[t0, t1], [t0, tI], [tI, t1]] times = np.unique(ds[time_break]) for t in times: time_ind = t == ds[time_break].data for var in sci_vars: x = dict(data=ds['time'].data[time_ind], info=dict(label='Time', units='GMT')) t0 = pd.to_datetime( x['data'].min()).strftime('%Y-%m-%dT%H%M%00') t1 = pd.to_datetime( x['data'].max()).strftime('%Y-%m-%dT%H%M%00') try: sci = ds[var] print var # sci = sub_ds[var] except UnicodeEncodeError: # some comments have latex characters ds[var].attrs.pop('comment') # remove from the attributes sci = ds[var] # or else the variable won't load # define possible pressure variables pressure_vars = [ 'seawater_pressure', 'sci_water_pressure_dbar', 'ctdgv_m_glider_instrument_recovered-sci_water_pressure_dbar', 'ctdgv_m_glider_instrument-sci_water_pressure_dbar' ] rePressure = re.compile('|'.join(pressure_vars)) # define y as pressure variable pressure = [s for s in sci.variables if rePressure.search(s)] pressure = ''.join(pressure) y = sci.variables[pressure] yN = pressure y_units = sci.units try: y_lab = sci.long_name except AttributeError: y_lab = sci.standard_name y = dict(data=sci.data[time_ind], info=dict(label=y_lab, units=sci.units, var=var, platform=platform, node=node, sensor=sensor)) title = title_pre + var # plot timeseries with outliers fig, ax = pf.auto_plot(x, y, title, stdev=None, line_style='r-o', g_range=True) pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}'.format(platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') # plot z variable each time fig, ax = pf.depth_cross_section(x, y, title, stdev=1, line_style='r-o', g_range=True) pf.resize(width=12, height=8.5) # Resize figure save_name = '{}-{}-{}_{}_{}-{}_outliers_removed'.format( platform, node, sensor, var, t0, t1) pf.save_fig(save_dir, save_name, res=150) # Save figure plt.close('all') del x, y
def main(sDir, url_list, preferred_only): rd_list = [] ms_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) ms = uu.split(rd + '-')[1].split('/')[0] if rd not in rd_list: rd_list.append(rd) if ms not in ms_list: ms_list.append(ms) for r in rd_list: print('\n{}'.format(r)) subsite = r.split('-')[0] array = subsite[0:2] # filter datasets datasets = [] for u in url_list: print(u) splitter = u.split('/')[-2].split('-') rd_check = '-'.join( (splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) datasets.append(udatasets) datasets = list(itertools.chain(*datasets)) fdatasets = [] if preferred_only == 'yes': # get the preferred stream information ps_df, n_streams = cf.get_preferred_stream_info(r) for index, row in ps_df.iterrows(): for ii in range(n_streams): try: rms = '-'.join((r, row[ii])) except TypeError: continue for dd in datasets: spl = dd.split('/')[-2].split('-') catalog_rms = '-'.join( (spl[1], spl[2], spl[3], spl[4], spl[5], spl[6])) fdeploy = dd.split('/')[-1].split('_')[0] if rms == catalog_rms and fdeploy == row['deployment']: fdatasets.append(dd) else: fdatasets = datasets main_sensor = r.split('-')[-1] fdatasets = cf.filter_collocated_instruments(main_sensor, fdatasets) # ps_df, n_streams = cf.get_preferred_stream_info(r) # get end times of deployments dr_data = cf.refdes_datareview_json(r) deployments = [] end_times = [] for index, row in ps_df.iterrows(): deploy = row['deployment'] deploy_info = get_deployment_information(dr_data, int(deploy[-4:])) deployments.append(int(deploy[-4:])) end_times.append(pd.to_datetime(deploy_info['stop_date'])) # # filter datasets # datasets = [] # for u in url_list: # print(u) # splitter = u.split('/')[-2].split('-') # rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) # if rd_check == r: # udatasets = cf.get_nc_urls([u]) # datasets.append(udatasets) # datasets = list(itertools.chain(*datasets)) # main_sensor = r.split('-')[-1] # fdatasets = cf.filter_collocated_instruments(main_sensor, datasets) # fdatasets = cf.filter_other_streams(r, ms_list, fdatasets) methodstream = [] for f in fdatasets: methodstream.append('-'.join((f.split('/')[-2].split('-')[-2], f.split('/')[-2].split('-')[-1]))) ms_dict = save_dir_path(ms_list) for ms in np.unique(methodstream): fdatasets_sel = [x for x in fdatasets if ms in x] check_ms = ms.split('-')[1] if 'recovered' in check_ms: check_ms = check_ms.split('_recovered')[0] if ms_dict['ms_count'][ms_dict['ms_unique'] == ms.split('-') [0]] == 1: save_dir = os.path.join(sDir, array, subsite, r, 'timeseries_yearly_plot', ms.split('-')[0]) else: save_dir = os.path.join(sDir, array, subsite, r, 'timeseries_yearly_plot', ms.split('-')[0], check_ms) cf.create_dir(save_dir) stream_sci_vars_dict = dict() for x in dr_data['instrument']['data_streams']: dr_ms = '-'.join((x['method'], x['stream_name'])) if ms == dr_ms: stream_sci_vars_dict[dr_ms] = dict(vars=dict()) sci_vars = dict() for y in x['stream']['parameters']: if y['data_product_type'] == 'Science Data': sci_vars.update( {y['name']: dict(db_units=y['unit'])}) if len(sci_vars) > 0: stream_sci_vars_dict[dr_ms]['vars'] = sci_vars sci_vars_dict = cd.initialize_empty_arrays(stream_sci_vars_dict, ms) print('\nAppending data from files: {}'.format(ms)) for fd in fdatasets_sel: ds = xr.open_dataset(fd, mask_and_scale=False) print(fd) for var in list(sci_vars_dict[ms]['vars'].keys()): sh = sci_vars_dict[ms]['vars'][var] try: ds[var] print(var) deployment_num = np.unique(ds['deployment'].values)[0] sh['deployments'] = np.append(sh['deployments'], deployment_num) if ds[var].units == sh['db_units']: if ds[var]._FillValue not in sh['fv']: sh['fv'].append(ds[var]._FillValue) if ds[var].units not in sh['units']: sh['units'].append(ds[var].units) tD = ds['time'].values varD = ds[var].values sh['t'] = np.append(sh['t'], tD) sh['values'] = np.append(sh['values'], varD) except KeyError: print('KeyError: ', var) print('\nPlotting data') for m, n in sci_vars_dict.items(): for sv, vinfo in n['vars'].items(): print(sv) if len(vinfo['t']) < 1: print('no variable data to plot') else: sv_units = vinfo['units'][0] deployments_num = vinfo['deployments'] fv = vinfo['fv'][0] t0 = pd.to_datetime(min( vinfo['t'])).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(max( vinfo['t'])).strftime('%Y-%m-%dT%H:%M:%S') x = vinfo['t'] y = vinfo['values'] # reject NaNs nan_ind = ~np.isnan(y) x_nonan = x[nan_ind] y_nonan = y[nan_ind] # reject fill values fv_ind = y_nonan != vinfo['fv'][0] x_nonan_nofv = x_nonan[fv_ind] y_nonan_nofv = y_nonan[fv_ind] # reject extreme values Ev_ind = cf.reject_extreme_values(y_nonan_nofv) y_nonan_nofv_nE = y_nonan_nofv[Ev_ind] x_nonan_nofv_nE = x_nonan_nofv[Ev_ind] # reject values outside global ranges: global_min, global_max = cf.get_global_ranges(r, sv) print('global ranges: ', global_min, global_max) if global_min and global_max: gr_ind = cf.reject_global_ranges( y_nonan_nofv_nE, global_min, global_max) y_nonan_nofv_nE_nogr = y_nonan_nofv_nE[gr_ind] x_nonan_nofv_nE_nogr = x_nonan_nofv_nE[gr_ind] else: y_nonan_nofv_nE_nogr = y_nonan_nofv_nE x_nonan_nofv_nE_nogr = x_nonan_nofv_nE # check array length if len(y_nonan_nofv_nE_nogr) > 0: if m == 'common_stream_placeholder': sname = '-'.join((r, sv)) print(var, 'empty array') else: sname = '-'.join((r, m, sv)) # group data by year groups, g_data = gt.group_by_time_range( x_nonan_nofv_nE_nogr, y_nonan_nofv_nE_nogr, 'A') # create bins # groups_min = min(groups.describe()['DO']['min']) # lower_bound = int(round(groups_min)) # groups_max = max(groups.describe()['DO']['max']) # if groups_max < 1: # upper_bound = 1 # step_bound = 1 # else: # upper_bound = int(round(groups_max + (groups_max / 50))) # step_bound = int(round((groups_max - groups_min) / 10)) # # if step_bound == 0: # step_bound += 1 # # if (upper_bound - lower_bound) == step_bound: # lower_bound -= 1 # upper_bound += 1 # if (upper_bound - lower_bound) < step_bound: # print('<') # step_bound = int(round(step_bound / 10)) # print(lower_bound, upper_bound, step_bound) # bin_range = list(range(lower_bound, upper_bound, step_bound)) # print(bin_range) # preparing color palette colors = color_names[:len(groups)] # colors = [color['color'] for color in # list(pyplot.rcParams['axes.prop_cycle'][:len(groups)])] fig0, ax0 = pyplot.subplots(nrows=2, ncols=1) # subplot for histogram and basic statistics table ax0[1].axis('off') ax0[1].axis('tight') the_table = ax0[1].table( cellText=groups.describe().round(2).values, rowLabels=groups.describe().index.year, rowColours=colors, colLabels=groups.describe().columns.levels[1], loc='center') the_table.set_fontsize(5) # subplot for data fig, ax = pyplot.subplots(nrows=len(groups), ncols=1, sharey=True) if len(groups) == 1: ax = [ax] t = 1 for ny in range(len(groups)): # prepare data for plotting y_data = g_data[ny + (t + 1)].dropna(axis=0) x_time = g_data[ny + t].dropna(axis=0) t += 1 if len(y_data) != 0 and len(x_time) != 0: n_year = x_time[0].year col_name = str(n_year) serie_n = pd.DataFrame(columns=[col_name], index=x_time) serie_n[col_name] = list(y_data[:]) # plot histogram # serie_n.plot.hist(ax=ax0[0], bins=bin_range, # histtype='bar', color=colors[ny], stacked=True) if len(serie_n) != 1: serie_n.plot.kde(ax=ax0[0], color=colors[ny]) ax0[0].legend(fontsize=8, bbox_to_anchor=(0., 1.12, 1., .102), loc=3, ncol=len(groups), mode="expand", borderaxespad=0.) # ax0[0].set_xticks(bin_range) ax0[0].set_xlabel('Observation Ranges', fontsize=8) ax0[0].set_ylabel( 'Density', fontsize=8 ) #'Number of Observations' ax0[0].set_title( ms.split('-')[0] + ' (' + sv + ', ' + sv_units + ')' + ' Kernel Density Estimates', fontsize=8) # plot data serie_n.plot(ax=ax[ny], linestyle='None', marker='.', markersize=0.5, color=colors[ny]) ax[ny].legend().set_visible(False) # plot Mean and Standard deviation ma = serie_n.rolling('86400s').mean() mstd = serie_n.rolling('86400s').std() ax[ny].plot(ma.index, ma[col_name].values, 'k', linewidth=0.15) ax[ny].fill_between( mstd.index, ma[col_name].values - 2 * mstd[col_name].values, ma[col_name].values + 2 * mstd[col_name].values, color='b', alpha=0.2) # prepare the time axis parameters datemin = datetime.date(n_year, 1, 1) datemax = datetime.date(n_year, 12, 31) ax[ny].set_xlim(datemin, datemax) xlocator = mdates.MonthLocator( ) # every month myFmt = mdates.DateFormatter('%m') ax[ny].xaxis.set_minor_locator( xlocator) ax[ny].xaxis.set_major_formatter(myFmt) # prepare the time axis parameters # ax[ny].set_yticks(bin_range) ylocator = MaxNLocator(prune='both', nbins=3) ax[ny].yaxis.set_major_locator( ylocator) # format figure ax[ny].tick_params(axis='both', color='r', labelsize=7, labelcolor='m') if ny < len(groups) - 1: ax[ny].tick_params( which='both', pad=0.1, length=1, labelbottom=False) ax[ny].set_xlabel(' ') else: ax[ny].tick_params(which='both', color='r', labelsize=7, labelcolor='m', pad=0.1, length=1, rotation=0) ax[ny].set_xlabel('Months', rotation=0, fontsize=8, color='b') ax[ny].set_ylabel(n_year, rotation=0, fontsize=8, color='b', labelpad=20) ax[ny].yaxis.set_label_position( "right") if ny == 0: if global_min and global_max: ax[ny].set_title( sv + '( ' + sv_units + ') -- Global Range: [' + str(int(global_min)) + ',' + str(int(global_max)) + '] \n' 'Plotted: Data, Mean and 2STD (Method: One day rolling window calculations) \n', fontsize=8) else: ax[ny].set_title( sv + '( ' + sv_units + ') -- Global Range: [] \n' 'Plotted: Data, Mean and 2STD (Method: One day rolling window calculations) \n', fontsize=8) # plot global ranges # ax[ny].axhline(y=global_min, color='r', linestyle='--', linewidth=.6) # ax[ny].axhline(y=global_max, color='r', linestyle='--', linewidth=.6) # mark deployment end times on figure ymin, ymax = ax[ny].get_ylim() #dep = 1 for etimes in range(len(end_times)): if end_times[ etimes].year == n_year: ax[ny].axvline( x=end_times[etimes], color='b', linestyle='--', linewidth=.6) ax[ny].text( end_times[etimes], ymin, 'End' + str(deployments_num[etimes] ), fontsize=6, style='italic', bbox=dict(boxstyle='round', ec=(0., 0.5, 0.5), fc=(1., 1., 1.))) # dep += 1 # ax[ny].set_ylim(5, 12) # save figure to a file sfile = '_'.join(('all', sname)) save_file = os.path.join(save_dir, sfile) fig.savefig(str(save_file), dpi=150) sfile = '_'.join(('Statistics', sname)) save_file = os.path.join(save_dir, sfile) fig0.savefig(str(save_file), dpi=150) pyplot.close()
def main(sDir, url_list): # get summary lists of reference designators and delivery methods rd_list = [] rdm_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) rdm = '-'.join((rd, elements[5])) if rd not in rd_list: rd_list.append(rd) if rdm not in rdm_list: rdm_list.append(rdm) json_file_list = [] for r in rd_list: rdm_filtered = [k for k in rdm_list if r in k] dinfo = {} save_dir = os.path.join(sDir, r.split('-')[0], r) cf.create_dir(save_dir) sfile = os.path.join(save_dir, '{}-method_comparison.json'.format(r)) if len(rdm_filtered) == 1: print('Only one delivery method provided - no comparison.') dinfo['note'] = 'no comparison - only one delivery method provided' with open(sfile, 'w') as outfile: json.dump(dinfo, outfile) json_file_list.append(str(sfile)) continue elif len(rdm_filtered) > 1 & len(rdm_filtered) <= 3: print('\nComparing data from different methods for: {}'.format(r)) for i in range(len(rdm_filtered)): urls = [x for x in url_list if rdm_filtered[i] in x] for u in urls: splitter = u.split('/')[-2].split('-') catalog_rms = '-'.join((r, splitter[-2], splitter[-1])) udatasets = cf.get_nc_urls([u]) idatasets = [] for dss in udatasets: # filter out collocated data files if catalog_rms == dss.split('/')[-1].split( '_20')[0][15:]: idatasets.append(dss) deployments = [ str(k.split('/')[-1][0:14]) for k in idatasets ] udeploy = np.unique(deployments).tolist() for ud in udeploy: rdatasets = [s for s in idatasets if ud in s] file_ms_lst = [] for dataset in rdatasets: splt = dataset.split('/')[-1].split( '_20')[0].split('-') file_ms_lst.append('-'.join((splt[-2], splt[-1]))) file_ms = np.unique(file_ms_lst).tolist()[0] try: dinfo[file_ms] except KeyError: dinfo[file_ms] = {} dinfo[file_ms].update({ud: rdatasets}) else: print( 'More than 3 methods provided. Please provide fewer datasets for analysis.' ) continue dinfo_df = pd.DataFrame(dinfo) umethods = [] ustreams = [] for k in dinfo.keys(): umethods.append(k.split('-')[0]) ustreams.append(k.split('-')[1]) if len(np.unique(ustreams)) > len( np.unique(umethods) ): # if there is more than 1 stream per delivery method mdict = dict() method_stream_df = cf.stream_word_check(dinfo) for cs in (np.unique( method_stream_df['stream_name_compare'])).tolist(): print('Common stream_name: {}'.format(cs)) method_stream_list = [] for row in method_stream_df.itertuples(): index, method, stream_name, stream_name_compare = row if stream_name_compare == cs: method_stream_list.append('-'.join( (method, stream_name))) dinfo_df_filtered = dinfo_df[method_stream_list] summary_dict = compare_data(dinfo_df_filtered) # merge dictionaries for all streams for one reference designator mdict = merge_two_dicts(mdict, summary_dict) with open(sfile, 'w') as outfile: json.dump(mdict, outfile) else: summary_dict = compare_data(dinfo_df) with open(sfile, 'w') as outfile: json.dump(summary_dict, outfile) json_file_list.append(str(sfile)) return json_file_list
file = os.path.join(root, filename) f = xr.open_dataset(file) f = f.swap_dims({'obs': 'time'}) fN = f.source platform = f.subsite node = f.node sensor = f.sensor title = platform + '-' + node + '-' + sensor global fName head, tail = os.path.split(filename) fName = tail.split('.', 1)[0] d = fName.split('_')[0] save_dir = os.path.join(rootdir, 'timeseries', d) cf.create_dir(save_dir) varList = [] for vars in f.variables: varList.append(str(vars)) yVars = [s for s in varList if not reg_ex.search(s)] for v in yVars: print v t = f['time'].data t_dict = dict(data=t, info=dict(label='Time', units='GMT')) y = f[v]
def main(sDir, url_list, start_time, end_time, deployment_num): rd_list = [] for uu in url_list: elements = uu.split('/')[-2].split('-') rd = '-'.join((elements[1], elements[2], elements[3], elements[4])) if rd not in rd_list and 'OPTAA' in rd: rd_list.append(rd) for r in rd_list: print('\n{}'.format(r)) datasets = [] deployments = [] for u in url_list: splitter = u.split('/')[-2].split('-') rd_check = '-'.join((splitter[1], splitter[2], splitter[3], splitter[4])) if rd_check == r: udatasets = cf.get_nc_urls([u]) for ud in udatasets: # filter out collocated data files if 'OPTAA' in ud.split('/')[-1]: datasets.append(ud) if ud.split('/')[-1].split('_')[0] not in deployments: deployments.append(ud.split('/')[-1].split('_')[0]) deployments.sort() fdatasets = np.unique(datasets).tolist() for deploy in deployments: if deployment_num is not None: if int(deploy[-4:]) is not deployment_num: print('\nskipping {}'.format(deploy)) continue rdatasets = [s for s in fdatasets if deploy in s] if len(rdatasets) > 0: sci_vars_dict = {'optical_absorption': dict(atts=dict(fv=[], units=[])), 'beam_attenuation': dict(atts=dict(fv=[], units=[]))} for i in range(len(rdatasets)): #for i in range(0, 2): ##### for testing ds = xr.open_dataset(rdatasets[i], mask_and_scale=False) ds = ds.swap_dims({'obs': 'time'}) if start_time is not None and end_time is not None: ds = ds.sel(time=slice(start_time, end_time)) if len(ds['time'].values) == 0: print('No data to plot for specified time range: ({} to {})'.format(start_time, end_time)) continue if i == 0: fname, subsite, refdes, method, stream, deployment = cf.nc_attributes(rdatasets[0]) array = subsite[0:2] filename = '_'.join(fname.split('_')[:-1]) save_dir = os.path.join(sDir, array, subsite, refdes, 'timeseries_plots', deployment) cf.create_dir(save_dir) for k in sci_vars_dict.keys(): print('\nAppending data from {}: {}'.format(deploy, k)) vv = ds[k] fv = vv._FillValue vvunits = vv.units if fv not in sci_vars_dict[k]['atts']['fv']: sci_vars_dict[k]['atts']['fv'].append(fv) if vvunits not in sci_vars_dict[k]['atts']['units']: sci_vars_dict[k]['atts']['units'].append(vvunits) if k == 'optical_absorption': wavelengths = ds['wavelength_a'].values elif k == 'beam_attenuation': wavelengths = ds['wavelength_c'].values for j in range(len(wavelengths)): if (wavelengths[j] > 671.) and (wavelengths[j] < 679.): wv = str(wavelengths[j]) try: sci_vars_dict[k][wv] except KeyError: sci_vars_dict[k].update({wv: dict(values=np.array([]), time=np.array([], dtype=np.datetime64))}) v = vv.sel(wavelength=j).values sci_vars_dict[k][wv]['values'] = np.append(sci_vars_dict[k][wv]['values'], v) sci_vars_dict[k][wv]['time'] = np.append(sci_vars_dict[k][wv]['time'], ds['time'].values) title = ' '.join((deployment, refdes, method)) colors = ['purple', 'green', 'orange'] t0_array = np.array([], dtype=np.datetime64) t1_array = np.array([], dtype=np.datetime64) for var in sci_vars_dict.keys(): print('Plotting {}'.format(var)) plotting = [] # keep track if anything is plotted fig1, ax1 = plt.subplots() fig2, ax2 = plt.subplots() [g_min, g_max] = cf.get_global_ranges(r, var) for idk, dk in enumerate(sci_vars_dict[var]): if dk != 'atts': v = sci_vars_dict[var][dk]['values'] n_all = len(sci_vars_dict[var][dk]['values']) n_nan = np.sum(np.isnan(v)) # convert fill values to nans v[v == sci_vars_dict[var]['atts']['fv'][0]] = np.nan n_fv = np.sum(np.isnan(v)) - n_nan if n_nan + n_fv < n_all: # plot before global ranges are removed plotting.append('yes') tm = sci_vars_dict[var][dk]['time'] t0_array = np.append(t0_array, tm.min()) t1_array = np.append(t1_array, tm.max()) ax1.scatter(tm, v, c=colors[idk - 1], label='{} nm'.format(dk), marker='.', s=1) # reject data outside of global ranges if g_min is not None and g_max is not None: v[v < g_min] = np.nan v[v > g_max] = np.nan n_grange = np.sum(np.isnan(v)) - n_fv - n_nan else: n_grange = 'no global ranges' # plot after global ranges are removed ax2.scatter(tm, v, c=colors[idk - 1], label='{} nm: rm {} GR'.format(dk, n_grange), marker='.', s=1) if len(plotting) > 0: t0 = pd.to_datetime(t0_array.min()).strftime('%Y-%m-%dT%H:%M:%S') t1 = pd.to_datetime(t1_array.max()).strftime('%Y-%m-%dT%H:%M:%S') ax1.grid() pf.format_date_axis(ax1, fig1) ax1.legend(loc='best', fontsize=7) ax1.set_ylabel((var + " (" + sci_vars_dict[var]['atts']['units'][0] + ")"), fontsize=9) ax1.set_title((title + '\n' + t0 + ' - ' + t1), fontsize=9) sfile = '-'.join((filename, var, t0[:10])) save_file = os.path.join(save_dir, sfile) fig1.savefig(str(save_file), dpi=150) ax2.grid() pf.format_date_axis(ax2, fig2) ax2.legend(loc='best', fontsize=7) ax2.set_ylabel((var + " (" + vv.units + ")"), fontsize=9) title_gr = 'GR: global ranges' ax2.set_title((title + '\n' + t0 + ' - ' + t1 + '\n' + title_gr), fontsize=9) sfile2 = '-'.join((filename, var, t0[:10], 'rmgr')) save_file2 = os.path.join(save_dir, sfile2) fig2.savefig(str(save_file2), dpi=150) plt.close('all')