How to use the xarray.DataArray.from_dict function in xarray

To help you get started, we’ve selected a few xarray examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github MPAS-Dev / MPAS-Analysis / mpas_analysis / ocean / remap_depth_slices_subtask.py View on Github external
verticalIndices[depthIndex, :] = 0
                mask[depthIndex, :] = self.maxLevelCell.values >= 0
            elif depth == 'bot':
                # switch to zero-based index
                verticalIndices[depthIndex, :] = self.maxLevelCell.values
                mask[depthIndex, :] = self.maxLevelCell.values >= 0
            else:

                verticalIndex = np.argmin(np.abs(zMid - depth), axis=1)

                verticalIndices[depthIndex, :] = verticalIndex.values
                mask[depthIndex, :] = np.logical_and(depth <= zTop,
                                                     depth >= zBot).values

        self.verticalIndices = \
            xr.DataArray.from_dict({'dims': ('depthSlice', 'nCells'),
                                    'coords': {'depthSlice':
                                               {'dims': ('depthSlice',),
                                                'data': depthNames}},
                                    'data': verticalIndices})
        self.verticalIndexMask = \
            xr.DataArray.from_dict({'dims': ('depthSlice', 'nCells'),
                                    'coords': {'depthSlice':
                                               {'dims': ('depthSlice',),
                                                'data': depthNames}},
                                    'data': mask})

        # then, call run from the base class (RemapMpasClimatologySubtask),
        # which will perform the main function of the task
        super(RemapDepthSlicesSubtask, self).run_task()
github MPAS-Dev / MPAS-Analysis / preprocess_observations / compute_woce_transects.py View on Github external
z = numpy.ma.masked_all(pressure.shape)
    z[validMask] = gsw.z_from_p(pressure[validMask], Lat[validMask])
    SA = gsw.SA_from_SP(salinity[validMask], pressure[validMask],
                        Lon[validMask], Lat[validMask])

    CT = gsw.CT_from_t(SA, temperature[validMask], pressure[validMask])

    potDensity = numpy.ma.masked_all(pressure.shape)
    potDensity[validMask] = gsw.rho(SA, CT, 0.)

    potTemp = numpy.ma.masked_all(pressure.shape)

    potTemp[validMask] = gsw.pt0_from_t(SA, temperature[validMask],
                                        pressure[validMask])

    longitude = xarray.DataArray.from_dict({'dims': ('nPoints',),
                                            'data': longitude,
                                            'attrs': {'long_name': 'longitude',
                                                      'units': 'degrees'}})
    latitude = xarray.DataArray.from_dict({'dims': ('nPoints',),
                                           'data': latitude,
                                           'attrs': {'long_name': 'latitude',
                                                     'units': 'degrees'}})

    pressure = xarray.DataArray.from_dict({'dims': ('nPoints',
                                                    'nz'),
                                           'data': pressure,
                                           'attrs':
                                               {'long_name': 'pressure',
                                                'units': 'dbar'}})

    z = xarray.DataArray.from_dict({'dims': ('nPoints', 'nz'),
github MPAS-Dev / MPAS-Analysis / preprocess_observations / preprocess_SOSE_data.py View on Github external
remapper.build_mapping_file(method='bilinear')

    remapper.remap_file(inFileName=tempFileName1,
                        outFileName=tempFileName2,
                        overwrite=True,
                        renormalize=0.01)

    ds = xarray.open_dataset(tempFileName2)
    if 'z' in ds:
        print('  transposing back...')
        ds = ds.chunk({'Time': 4})
        ds = ds.transpose('Time', 'x', 'y', 'z', 'nvertices')
    ds.attrs['meshName'] = outDescriptor.meshName

    for coord in ['x', 'y']:
        ds.coords[coord] = xarray.DataArray.from_dict(
            outDescriptor.coords[coord])

    ds = ds.set_coords(names=['month', 'year'])

    write_netcdf(ds, outFileName)
    ds.close()
github MPAS-Dev / MPAS-Analysis / preprocess_observations / compute_woce_transects.py View on Github external
potTemp = numpy.ma.masked_all(pressure.shape)

    potTemp[validMask] = gsw.pt0_from_t(SA, temperature[validMask],
                                        pressure[validMask])

    longitude = xarray.DataArray.from_dict({'dims': ('nPoints',),
                                            'data': longitude,
                                            'attrs': {'long_name': 'longitude',
                                                      'units': 'degrees'}})
    latitude = xarray.DataArray.from_dict({'dims': ('nPoints',),
                                           'data': latitude,
                                           'attrs': {'long_name': 'latitude',
                                                     'units': 'degrees'}})

    pressure = xarray.DataArray.from_dict({'dims': ('nPoints',
                                                    'nz'),
                                           'data': pressure,
                                           'attrs':
                                               {'long_name': 'pressure',
                                                'units': 'dbar'}})

    z = xarray.DataArray.from_dict({'dims': ('nPoints', 'nz'),
                                    'data': z,
                                    'attrs':
                                        {'long_name': 'height',
                                         'units': 'm'}})

    potTemp = xarray.DataArray.from_dict({'dims': ('nPoints',
                                                   'nz'),
                                          'data': potTemp,
                                          'attrs':
github MPAS-Dev / MPAS-Analysis / mpas_analysis / ocean / compute_transects_subtask.py View on Github external
lats = []
        lons = []
        x = []
        obsDatasets = self.obsDatasets.get_observations()
        datasets = list(obsDatasets.values())
        for transectIndex, ds in enumerate(datasets):
            localLats = list(ds.lat.values)
            localLons = list(ds.lon.values)
            localX = list(ds.x.values)
            localIndices = [transectIndex for lat in localLats]
            lats.extend(localLats)
            lons.extend(localLons)
            x.extend(localX)
            transectNumber.extend(localIndices)

        self.transectNumber = xr.DataArray.from_dict(
            {'dims': ('nPoints'),
             'data': transectNumber})

        self.x = xr.DataArray.from_dict(
            {'dims': ('nPoints'),
             'data': x})

        self.collectionDescriptor = PointCollectionDescriptor(
            lats, lons, collectionName=self.transectCollectionName,
            units='degrees', outDimension='nPoints')

        self.add_comparison_grid_descriptor(self.transectCollectionName,
                                            self.collectionDescriptor)

        # then, call setup_and_check from the base class
        # (RemapMpasClimatologySubtask)
github UCLA-Plasma-Simulation-Group / pyVisOS / osh5def.py View on Github external
for ax in data.axes:
                ax_data = {'dims': ax.name, 'data': ax.ax.copy(), 'attrs': {'units': str(ax.units)}}
                for k, v in ax.attrs.items():
                    ax_data['attrs'].setdefault(k, v)
                dim_dict[ax.name] = ax_data

            # self.units will be converted to str by xarray, no special treatment needed
            data_attrs_dict = {}
            data_attrs_dict.update(data.run_attrs)
            data_attrs_dict.update(data.data_attrs)

            dims_name = tuple(k for k, v in dim_dict.items())

            data_dict = {'coords': dim_dict, 'attrs': data_attrs_dict,
                         'dims': dims_name, 'data': data.view(np.ndarray), 'name': data.name}
            return xr.DataArray.from_dict(data_dict)
github lmb-freiburg / demon / python / depthmotionnet / evaluation / evaluate_to_xarray.py View on Github external
def read_xarray_json(in_file):
    """Reads xarray from a json file"""
    with open(in_file, 'r') as f:
        return xarray.DataArray.from_dict(json.load(f))
github MPAS-Dev / MPAS-Analysis / mpas_analysis / ocean / climatology_map_ohc_anomaly.py View on Github external
dsRestart = xarray.open_dataset(self.restartFileName)
        dsRestart = dsRestart.isel(Time=0)

        # specific heat [J/(kg*degC)]
        cp = self.namelist.getfloat('config_specific_heat_sea_water')
        # [kg/m3]
        rho = self.namelist.getfloat('config_density0')

        unitsScalefactor = 1e-9

        nVertLevels = dsRestart.sizes['nVertLevels']

        zMid = compute_zmid(dsRestart.bottomDepth, dsRestart.maxLevelCell,
                            dsRestart.layerThickness)

        vertIndex = xarray.DataArray.from_dict(
            {'dims': ('nVertLevels',), 'data': numpy.arange(nVertLevels)})

        temperature = climatology['timeMonthly_avg_activeTracers_temperature']
        layerThickness = climatology['timeMonthly_avg_layerThickness']

        masks = [vertIndex < dsRestart.maxLevelCell,
                 zMid <= self.minDepth,
                 zMid >= self.maxDepth]
        for mask in masks:
            temperature = temperature.where(mask)
            layerThickness = layerThickness.where(mask)

        ohc = unitsScalefactor * rho * cp * layerThickness * temperature
        ohc = ohc.sum(dim='nVertLevels')
        return ohc  # }}}
github calliope-project / calliope / calliope / core / preprocess / lookup.py View on Github external
for carrier_tier_idx, carrier_tier in enumerate(carrier_tiers):
            # create a list of carriers for the given technology that fits
            # the current carrier_tier.
            relevant_carriers = model_run.techs[_tech].essentials.get(
                'carrier_' + carrier_tier, None)

            if relevant_carriers and isinstance(relevant_carriers, list):
                loc_tech_carriers = ','.join([loc_tech + "::" + i
                                              for i in relevant_carriers])
            elif relevant_carriers:
                loc_tech_carriers = loc_tech + "::" + relevant_carriers
            else:
                continue
            loc_techs_conversion_plus_array[loc_tech_idx, carrier_tier_idx] = loc_tech_carriers
    for k, v in primary_carrier_data.items():
        primary_carrier_data_array = xr.DataArray.from_dict({
            'data': v, 'dims': ['loc_techs_conversion_plus']
        })
        dataset['lookup_primary_loc_tech_carriers' + k] = primary_carrier_data_array

    dataset['lookup_loc_techs_conversion_plus'] = xr.DataArray(
        data=loc_techs_conversion_plus_array,
        dims=['loc_techs_conversion_plus', 'carrier_tiers'],
        coords={
            'loc_techs_conversion_plus': loc_techs_conversion_plus,
            'carrier_tiers': carrier_tiers
        }
    )

    return dataset
github MPAS-Dev / MPAS-Analysis / preprocess_observations / compute_woce_transects.py View on Github external
z = xarray.DataArray.from_dict({'dims': ('nPoints', 'nz'),
                                    'data': z,
                                    'attrs':
                                        {'long_name': 'height',
                                         'units': 'm'}})

    potTemp = xarray.DataArray.from_dict({'dims': ('nPoints',
                                                   'nz'),
                                          'data': potTemp,
                                          'attrs':
                                              {'long_name':
                                                  'potential temperature',
                                               'units': 'deg C'}})

    salinity = xarray.DataArray.from_dict({'dims': ('nPoints',
                                                    'nz'),
                                           'data': salinity,
                                           'attrs':
                                               {'long_name': 'salinity',
                                                'units': 'PSU'}})

    potDensity = xarray.DataArray.from_dict(
        {'dims': ('nPoints', 'nz'),
         'data': potDensity,
         'attrs': {'long_name': 'potential denisty',
                   'units': 'kg m^{-3}'}})

    dsTransect = xarray.Dataset({'lon': longitude,
                                 'lat': latitude,
                                 'pressure': pressure,
                                 'z': z,