Loads lat-lon coordinates from a netCDF file.
540525
def load_coordinates(self):
        
        coord_file = Dataset(self.coordinate_file)
        if "lon" in coord_file.variables.keys():
            self.coordinates["lon"] = coord_file.variables["lon"][:]
            self.coordinates["lat"] = coord_file.variables["lat"][:]
        else:
            self.coordinates["lon"] = coord_file.variables["XLONG"][0]
            self.coordinates["lat"] = coord_file.variables["XLAT"][0]
        coord_file.close()
588273
def from_array(array):
        
        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")

        data = {}
        data['longitude'] = float(array.get('longitude'))
        data['latitude'] = float(array.get('latitude'))
        data['_raw'] = array
        return Location(**data)
526422
def loadnetcdf(filename, copy=True):
    
    filename = str(Path(filename).expanduser())

    if copy:
        dataarray = xr.open_dataarray(filename).copy()
    else:
        dataarray = xr.open_dataarray(filename, chunks={})

    if dataarray.name is None:
        dataarray.name = filename.rstrip('.nc')

    for key, val in dataarray.coords.items():
        if val.dtype.kind == 'S':
            dataarray[key] = val.astype('U')
        elif val.dtype == np.int32:
            dataarray[key] = val.astype('i8')

    return dataarray
616931
def load_tiff(file):
    
    ndv, xsize, ysize, geot, projection, datatype = get_geo_info(file)
    data = gdalnumeric.LoadFile(file)
    data = np.ma.masked_array(data, mask=data == ndv, fill_value=ndv)
    return data
456340
def _write_lat_lon(data_out_nc, rivid_lat_lon_z_file):
        
        # only add if user adds
        if rivid_lat_lon_z_file and os.path.exists(rivid_lat_lon_z_file):
            # get list of COMIDS
            lookup_table = np.loadtxt(
                rivid_lat_lon_z_file,
                delimiter=",",
                usecols=(0, 1, 2),
                skiprows=1,
                dtype={
                    'names': ('rivid', 'lat', 'lon'),
                    'formats': ('i8', 'f8', 'f8'),
                },
            )

            # Get relevant arrays while we update them
            nc_rivids = data_out_nc.variables['rivid'][:]
            lats = data_out_nc.variables['lat'][:]
            lons = data_out_nc.variables['lon'][:]

            lat_min = None
            lat_max = None
            lon_min = None
            lon_max = None

            # Process each row in the lookup table
            for nc_index, nc_rivid in enumerate(nc_rivids):
                try:
                    lookup_index = \
                        np.where(lookup_table['rivid'] == nc_rivid)[0][0]
                except Exception:
                    raise Exception('rivid {0} misssing in '
                                    'comid_lat_lon_z file'.format(nc_rivid))

                lat = float(lookup_table['lat'][lookup_index])
                lats[nc_index] = lat
                if lat_min is None or lat < lat_min:
                    lat_min = lat
                if lat_max is None or lat > lat_max:
                    lat_max = lat

                lon = float(lookup_table['lon'][lookup_index])
                lons[nc_index] = lon
                if lon_min is None or lon < lon_min:
                    lon_min = lon
                if lon_max is None or lon > lon_max:
                    lon_max = lon

            # Overwrite netCDF variable values
            data_out_nc.variables['lat'][:] = lats
            data_out_nc.variables['lon'][:] = lons

            # Update metadata
            if lat_min is not None:
                data_out_nc.geospatial_lat_min = lat_min
            if lat_max is not None:
                data_out_nc.geospatial_lat_max = lat_max
            if lon_min is not None:
                data_out_nc.geospatial_lon_min = lon_min
            if lon_max is not None:
                data_out_nc.geospatial_lon_max = lon_max
        else:
            print('No comid_lat_lon_z file. Not adding values ...')
173362
def lonlat2xyz(lon, lat):
    

    lons = np.array(lon)
    lats = np.array(lat)

    xs = np.cos(lats) * np.cos(lons)
    ys = np.cos(lats) * np.sin(lons)
    zs = np.sin(lats)

    return xs, ys, zs
1154967
def load(self, dataset_keys, previous_datasets=None):
        """"""
        all_datasets = previous_datasets or DatasetDict()
        datasets = DatasetDict()

        # Include coordinates in the list of datasets to load
        dsids = [self.get_dataset_key(ds_key) for ds_key in dataset_keys]
        coordinates = self._get_coordinates_for_dataset_keys(dsids)
        all_dsids = list(set().union(*coordinates.values())) + dsids

        for dsid in all_dsids:
            if dsid in all_datasets:
                continue
            coords = [all_datasets.get(cid, None)
                      for cid in coordinates.get(dsid, [])]
            ds = self._load_dataset_with_area(dsid, coords)
            if ds is not None:
                all_datasets[dsid] = ds
                if dsid in dsids:
                    datasets[dsid] = ds
        self._load_ancillary_variables(all_datasets)

        return datasets
1151333
def __create_coordinates(self, lat, lon, elev):
        
        # Sort lat an lon in numerical order
        lat.sort()
        lon.sort()
        geo_dict = {}
        # 4 coordinate values
        if len(lat) == 2 and len(lon) == 2:
            # Matching coordinate pairs. Not 4 unique values.
            if lat[0] == lat[1] and lon[0] == lon[1]:
                logger_noaa_lpd.info("coordinates found: {}".format("2"))
                lat.pop()
                lon.pop()
                geo_dict = self.__geo_point(lat, lon, elev)
            # 4 unique coordinates
            else:
                logger_noaa_lpd.info("coordinates found: {}".format("4"))
                geo_dict = self.__geo_multipoint(lat, lon, elev)
        # 2 coordinate values
        elif len(lat) == 1 and len(lon) == 1:
            logger_noaa_lpd.info("coordinates found: {}".format("2"))
            geo_dict = self.__geo_point(lat, lon, elev)
        # 0 coordinate values
        elif not lat and not lon:
            logger_noaa_lpd.info("coordinates found: {}".format("0"))
        else:
            geo_dict = {}
            logger_noaa_lpd.info("coordinates found: {}".format("too many"))
        return geo_dict
674073
def make_lat_lons(cvects):
    
    lats = np.degrees(np.arcsin(cvects[2]))
    lons = np.degrees(np.arctan2(cvects[0], cvects[1]))
    return np.hstack([lats, lons])
1319657
def lonlat2xyz(lons, lats):
    """"""
    R = 6370997.0
    x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons))
    y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons))
    z_coords = R * da.sin(da.deg2rad(lats))
    return x_coords, y_coords, z_coords
704955
def load_data(self, path, *args, **kwargs):
        """"""
        self.df = self._load(path,*args, **kwargs)
        self.series = self.df.iloc[:,0]
        print ("Success! file length: " +str(self.df.shape[0]))
168165
function(points, callback, fromIndex, toIndex) {
	var newPoints = [], i, len;
	try {
		for (i = 0, len = points.length; i < len; i++) {
			if (!points[i].lat || !points[i].lng) {
				continue;
			}
			newPoints.push(points[i]);
		}
		calculateFromGPX(newPoints, callback, fromIndex, toIndex);
	} catch(e) {
		callback(e, null);
	}
}
54260
def coordinate_dimension_matrix(nc):
    '''
    
    '''
    retval = {}
    x = get_lon_variable(nc)
    if x:
        retval['x'] = nc.variables[x].dimensions
    y = get_lat_variable(nc)
    if y:
        retval['y'] = nc.variables[y].dimensions

    z = get_z_variable(nc)
    if z:
        retval['z'] = nc.variables[z].dimensions

    t = get_time_variable(nc)
    if t:
        retval['t'] = nc.variables[t].dimensions
    return retval
354994
def load(cls, filename, **kwargs):
        
        
        if not os.path.exists(filename):
            raise IOError("filename {0} does not exist" .format(filename))
        
        if filename.lower().endswith(".fits") \
        or filename.lower().endswith(".fits.gz"):
            image = fits.open(filename, **kwargs)
            
            header = image[0].header
            
            # Check for a tabular data structure
            if len(image) > 1 and image[0].data is None:

                names = [name.lower() for name in image[1].data.names]
                dispersion_key = 'wave' if 'wave' in names else 'disp'
                
                disp, flux = image[1].data[dispersion_key], image[1].data['flux']

                if 'error' in names or 'variance' in names:
                    variance_key = 'error' if 'error' in names else 'variance'
                    variance = image[1].data[variance_key]

            else:

                # According to http://iraf.net/irafdocs/specwcs.php ....
                #li = a.headers['LTM1_1'] * np.arange(a.headers['NAXIS1']) + a.headers['LTV1']
                #a.headers['CRVAL1'] + a.headers['CD1_1'] * (li - a.headers['CRPIX1'])

                if np.all([key in header.keys() for key in ('CDELT1', 'NAXIS1', 'CRVAL1')]):
                    disp = header['CRVAL1'] + (np.arange(header['NAXIS1']) \
                        - header.get("CRPIX1", 0)) * header['CDELT1']
            
                if "LTV1" in header.keys():
                    disp -= header['LTV1'] * header['CDELT1']

                #disp -= header['LTV1'] if header.has_key('LTV1') else 0
                flux = image[0].data

                # Check for an input_variance array
                extnames = [ext.header.get("EXTNAME", None) for ext in image[1:]]
                if "input_variance" in extnames:
                    index = 1 + extnames.index("input_variance")
                    variance = image[index].data
                    
                else:
                    variance = None
            
                # Check for logarithmic dispersion
                if "CTYPE1" in header.keys() and header["CTYPE1"] == "AWAV-LOG":
                    disp = np.exp(disp)

            # Add the headers in
            headers = {}
            for row in header.items():
                key, value = row
                
                # Check the value is valid
                try:
                    str(value)

                except TypeError:
                    logger.debug("Skipping header key {0}".format(key))
                    continue

                if len(key) == 0 or len(str(value)) == 0: continue
    
                if key in headers.keys():
                    if not isinstance(headers[key], list):
                        headers[key] = [headers[key]]
                    
                    headers[key].append(value)

                else:
                    headers[key] = value

            for key, value in headers.iteritems():
                if isinstance(value, list):
                    headers[key] = "\n".join(map(str, value))

        else:
            headers = {}
            try:
                disp, flux, variance = np.loadtxt(filename, unpack=True, **kwargs)
            except:
                disp, flux = np.loadtxt(filename, unpack=True, **kwargs)
            
        return cls(disp, flux, variance=variance, headers=headers)
438512
def obtain_to(filename):
    
    root, _ = nc.open(filename)
    lat, lon = nc.getvar(root, 'lat')[0,:], nc.getvar(root, 'lon')[0,:]
    nc.close(root)
    return obtain(lat, lon)
1119480
def _load_GeoTransform(self):
        """"""
        def load_lon():
            return arange(ds.RasterXSize)*b[1]+b[0]

        def load_lat():
            return arange(ds.RasterYSize)*b[5]+b[3]
        ds = self.ds
        b = self.ds.GetGeoTransform()  # bbox, interval
        if with_dask:
            lat = Array(
                {('lat', 0): (load_lat,)}, 'lat', (self.ds.RasterYSize,),
                shape=(self.ds.RasterYSize,), dtype=float)
            lon = Array(
                {('lon', 0): (load_lon,)}, 'lon', (self.ds.RasterXSize,),
                shape=(self.ds.RasterXSize,), dtype=float)
        else:
            lat = load_lat()
            lon = load_lon()
        return Variable(('lat',), lat), Variable(('lon',), lon)
421691
def _get_lat_lon_indices(lsm_lat_array, lsm_lon_array, lat, lon):
    
    if lsm_lat_array.ndim == 2 and lsm_lon_array.ndim == 2:
        lsm_lat_indices_from_lat, lsm_lon_indices_from_lat = \
            np.where((lsm_lat_array == lat))
        lsm_lat_indices_from_lon, lsm_lon_indices_from_lon = \
            np.where((lsm_lon_array == lon))

        index_lsm_grid_lat = np.intersect1d(lsm_lat_indices_from_lat,
                                            lsm_lat_indices_from_lon)[0]
        index_lsm_grid_lon = np.intersect1d(lsm_lon_indices_from_lat,
                                            lsm_lon_indices_from_lon)[0]

    elif lsm_lat_array.ndim == 1 and lsm_lon_array.ndim == 1:
        index_lsm_grid_lon = np.where(lsm_lon_array == lon)[0][0]
        index_lsm_grid_lat = np.where(lsm_lat_array == lat)[0][0]
    else:
        raise IndexError("Lat/Lon lists have invalid dimensions. "
                         "Only 1D or 2D arrays allowed ...")

    return index_lsm_grid_lat, index_lsm_grid_lon