Return the digital elevation map projected to the lat lon matrix coordenates.

    Keyword arguments:
    filename -- the name of a netcdf file.
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)
1121223
def _map_from_binaries(self, eopatch, dst_shape, request_data):
        
        if self.feature_name in eopatch[self.feature_type]:
            raster = eopatch[self.feature_type][self.feature_name].squeeze()
        else:
            raster = np.ones(dst_shape, dtype=self.raster_dtype) * self.no_data_val

        new_raster = self._reproject(eopatch, self._to_binary_mask(request_data))

        # update raster
        raster[new_raster != 0] = new_raster[new_raster != 0]

        return raster
749907
def _decode_filename(base_filename, problem_name, decode_hp):
  
  if decode_hp.shards > 1:
    base_filename = _add_shard_to_filename(base_filename, decode_hp)
  if ("beam{beam}.alpha{alpha}.decodes".format(
      beam=str(decode_hp.beam_size), alpha=str(decode_hp.alpha))
      in base_filename):
    return base_filename
  else:
    return (
        "{base}.{model}.{hp}.{problem}.beam{beam}.alpha{alpha}.decodes".format(
            base=base_filename,
            model=FLAGS.model,
            hp=FLAGS.hparams_set,
            problem=problem_name,
            beam=str(decode_hp.beam_size),
            alpha=str(decode_hp.alpha)))
1274922
def write_reg(self, filename):
        
        with open(filename, 'w') as out:
            for d in range(1, self.maxdepth+1):
                for p in self.pixeldict[d]:
                    line = "fk5; polygon("
                    # the following int() gets around some problems with np.int64 that exist prior to numpy v 1.8.1
                    vectors = list(zip(*hp.boundaries(2**d, int(p), step=1, nest=True)))
                    positions = []
                    for sky in self.vec2sky(np.array(vectors), degrees=True):
                        ra, dec = sky
                        pos = SkyCoord(ra/15, dec, unit=(u.degree, u.degree))
                        positions.append(pos.ra.to_string(sep=':', precision=2))
                        positions.append(pos.dec.to_string(sep=':', precision=2))
                    line += ','.join(positions)
                    line += ")"
                    print(line, file=out)
        return
347911
def get_map_matrix(inputfile, sheet_name):
    
    matrix = read_excel_file(inputfile, sheet_name)
    output = [['Locus', 'Group', 'Position']]
    for row in matrix:
        if row[0] and not re.match(r'c\d+\.loc[\d\.]+', row[0]):
            output.append([row[0], row[1], row[2]])
    return output
419663
def persist(filename):
    
    dem_projected = obtain_to(filename)
    with nc.loader(filename) as root:
        data = nc.getvar(root, 'data')
        dem = nc.getvar(root, 'dem', 'f4', source=data)
        stack = [dim for dim in dem.shape if dim not in dem_projected.shape]
        stack = stack[0] if stack else 1
        dem[:] = np.vstack(map(lambda x: [dem_projected], range(stack)))
171796
def read_locations(filename):
    
    data = ConfigParser()
    if filename == '-':
        data.read_file(sys.stdin)
    else:
        data.read(filename)
    if not data.sections():
        logging.debug('Config file is empty')

    locations = {}
    for name in data.sections():
        if data.has_option(name, 'locator'):
            latitude, longitude = utils.from_grid_locator(data.get(name,
                                                                   'locator'))
        else:
            latitude = data.getfloat(name, 'latitude')
            longitude = data.getfloat(name, 'longitude')
        locations[name] = (latitude, longitude)
    return locations
1213300
def get_lon_variable(nc):
    '''
    
    '''
    if 'longitude' in nc.variables:
        return 'longitude'
    longitudes = nc.get_variables_by_attributes(standard_name="longitude")
    if longitudes:
        return longitudes[0].name
    return None
1143289
def _format_name_map(self, lon, lat):
        '''  '''

        if self.ppd in [4, 16, 64, 128]:
            lolaname = '_'.join(['LDEM', str(self.ppd)])
        elif self.ppd in [512]:
            lolaname = '_'.join(
                ['LDEM', str(self.ppd), lat[0], lat[1], lon[0], lon[1]])
        return lolaname
15461
def _format_name_map(self, lonc, latc):
        '''  '''

        return '_'.join(['WAC', 'GLOBAL'] +
                        ['E' + latc + lonc, "{0:0>3}".format(self.ppd) + 'P'])
40778
def _load(self, filename):
        """"""
        filename = pathlib.Path(filename)
        with filename.open() as fd:
            data = fd.readlines()

        # Get the strings that correspond to self.fileid
        bool_head = [l.strip().startswith("[") for l in data]

        int_head = np.squeeze(np.where(bool_head))
        int_head = np.atleast_1d(int_head)

        start = int_head[self.fileid]+1

        if len(int_head) > self.fileid+1:
            end = int_head[self.fileid+1]
        else:
            end = len(data)

        subdata = data[start:end]

        # separate all elements and strip them
        subdata = [[it.strip() for it in l.split("=")] for l in subdata]

        points = []

        for var, val in subdata:
            if var.lower() == "x axis":
                xaxis = val.lower()
            elif var.lower() == "y axis":
                yaxis = val.lower()
            elif var.lower() == "name":
                self.name = val
            elif var.lower() == "inverted":
                if val == "True":
                    self.inverted = True
            elif var.lower().startswith("point"):
                val = np.array(val.strip("[]").split(), dtype=float)
                points.append([int(var[5:]), val])
            else:
                raise KeyError("Unknown variable: {} = {}".
                               format(var, val))
        self.axes = (xaxis, yaxis)
        # sort points
        points.sort()
        # get only coordinates from points
        self.points = np.array([p[1] for p in points])

        # overwrite unique id
        unique_id = int(data[start-1].strip().strip("Polygon []"))
        self._set_unique_id(unique_id)
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)
1037823
def nearest_loc_obs(self, lat, lon):
        
        sitelist = self.loc_observations(SITELIST)
        sites = parse_sitelist(sitelist)
        site = get_nearest_site(sites, lat, lon)
        return self.loc_observations(site)
552193
def _get_url(self, filename):
        
        return self.cdn_url.format(self.mver, self.relnum, filename)
608779
def get_filepath(self, filename):
        
        return os.path.join(self.parent_folder, '{},{},{}'.format(self.tile_name, self.date, self.aws_index),
                            self.add_file_extension(filename)).replace(':', '.')
441785
def load_codebook(self, filename):
        
        self.codebook = np.loadtxt(filename, comments='%')
        if self.n_dim == 0:
            self.n_dim = self.codebook.shape[1]
        if self.codebook.shape != (self._n_rows * self._n_columns,
                                   self.n_dim):
            raise Exception("The dimensions of the codebook do not "
                            "match that of the map")
        self.codebook.shape = (self._n_rows, self._n_columns, self.n_dim)
758026
def __get_output_filenames(self):
        
        # if there is only one file, use the normal filename with nothing appended.
        if len(self.noaa_data_sorted["Data"]) == 1:
            self.output_filenames.append(self.filename_txt)

        # if there are multiple files that need to be written out, (multiple data table pairs), then append numbers
        elif len(self.noaa_data_sorted["Data"]) > 1:
            for i in range(0, self.output_file_ct):
                tmp_name = "{}-{}.txt".format(self.dsn, i+1)
                self.output_filenames.append(tmp_name)
        return