Genreate a Band object given band metadata

        Args:
            band (dict): dictionary containing metadata for a given band

        Return:
            Band : the loaded Band onject
173581
def GenerateBand(self, band, meta_only=False, cast=False):
        """"""

        # Read the band data and add it to dictionary
        if not meta_only:
            fname = band.get('file_name')
            data = self.ReadTif('%s/%s' % (os.path.dirname(self.filename), fname))
            # band['data'] = data # TODO: data is not a properties object so do not set yet

        def FixBitmap(d):
            p = d.get('bitmap_description')
            if p:
                lis = p.get('bit')
                bm = dict()
                # Fix bitmap_description from list of dicts to one dict
                for i in lis:
                    key = i['num']
                    value = i['text']
                    bm[key] = value
                del d['bitmap_description']
                d['bitmap_description'] = bm
            return d

        band = SetProperties(Band, FixBitmap(self.CleanDict(band)))
        if not meta_only:
            if cast:
                # cast as floats and fill bad values with nans
                data = data.astype(np.float32)
                data[data==band.fill_value] = -9999
                if band.valid_range is not None:
                    data[data<band.valid_range.min] = -9999
                    data[data>band.valid_range.max] = -9999
                data[data==-9999] = np.nan
            else:
                data = np.ma.masked_where(data==band.fill_value, data)
                if band.valid_range is not None:
                    data = np.ma.masked_where(data<band.valid_range.min, data)
                    data = np.ma.masked_where(data>band.valid_range.max, data)
            # Flip y axis if requested
            if self.yflip:
                data = np.flip(data, 0)
            band.data = data

        if not meta_only:
            band.validate()

        return band
904043
def set_metadata(self, key: str, value: str):
        
        if not isinstance(key, str) or not isinstance(value, str):
            raise TypeError("'key' and 'value' of metadata MUST be strings")
        self.metadata[key] = value
647980
def scan_band(self, band, **kwargs):
        

        kal_run_line = fn.build_kal_scan_band_string(self.kal_bin,
                                                     band, kwargs)
        raw_output = subprocess.check_output(kal_run_line.split(' '),
                                             stderr=subprocess.STDOUT)
        kal_normalized = fn.parse_kal_scan(raw_output)
        return kal_normalized
880503
def set_metadata(self, queue, metadata, clear=False):
        
        return self._manager.set_metadata(queue, metadata, clear=clear)
1258266
def composer(self, type, **meta):
        
        def decorator(f):
            self.register_composer(type, f)
            if meta:
                self.register_meta(type, **meta)
            return f
        return decorator
1082671
def from_metadata(cls, metadata: Dict[str, Any]) -> 'LogFields':
        
        return cls(fields=json.loads(metadata.get(LOG_FIELDS_KEY_META, '{}')))
385256
def get(self, telescope, band):
        """"""

        klass = self._bpass_classes.get(telescope)
        if klass is None:
            raise NotDefinedError('bandpass data for %s not defined', telescope)

        bp = klass()
        bp.registry = self
        bp.telescope = telescope
        bp.band = band
        return bp
1029329
def _parse_metadata(self, meta):
        
        output = {}
        for name, value in meta.items():
            name = name.lower()
            if name == "summary":
                value = textile(value)
            output[name] = self.process_metadata(name, value)
        return output
347679
def set_genre(self, genre):
        
        self._set_attr(TCON(encoding=3, text=str(genre)))
919966
def _load_data(self, band):
        
        d = bandpass_data_fits('sw' + self._band_map[band] + '_20041120v106.arf')[1].data

        # note:
        #   data.WAVE_MIN[i] < data.WAVE_MIN[i+1], but
        #   data.WAVE_MIN[i] > data.WAVE_MAX[i] (!)
        #   data.WAVE_MIN[i] = data.WAVE_MAX[i+1] (!)

        wmid = 0.5 * (d.WAVE_MIN + d.WAVE_MAX) # in Ångström
        df = pd.DataFrame({'wlen': wmid, 'resp': d.SPECRESP,
                           'wlo': d.WAVE_MAX, 'whi': d.WAVE_MIN})
        return df
623595
def dmag(self,band):
        
        mag2 = self.stars['{}_mag_B'.format(band)]
        mag1 = self.stars['{}_mag_A'.format(band)]
        return mag2-mag1
1022633
def _parse_bands(lines, n_start):
        """"""
        kpoints = []
        labels = []
        bands_s1 = []
        bands_s2 = []
        known_kpoints = {}
        pattern = re.compile(".*?Nr.*?Spin.*?K-Point.*?", re.DOTALL)

        selected_lines = lines[n_start:]
        for current_line, line in enumerate(selected_lines):
            splitted = line.split()
            if "KPOINTS| Special K-Point" in line:
                kpoint = tuple(map(float, splitted[-3:]))
                if " ".join(splitted[-5:-3]) != "not specified":
                    label = splitted[-4]
                    known_kpoints[kpoint] = label
            elif pattern.match(line):
                spin = int(splitted[3])
                kpoint = tuple(map(float, splitted[-3:]))
                kpoint_n_lines = int(math.ceil(int(selected_lines[current_line + 1]) / 4.))
                band = list(
                    map(float, ' '.join(selected_lines[current_line + 2:current_line + 2 + kpoint_n_lines]).split()))
                if spin == 1:
                    if kpoint in known_kpoints:
                        labels.append((len(kpoints), known_kpoints[kpoint]))
                    kpoints.append(kpoint)
                    bands_s1.append(band)
                elif spin == 2:
                    bands_s2.append(band)
        if bands_s2:
            bands = [bands_s1, bands_s2]
        else:
            bands = bands_s1
        return np.array(kpoints), labels, np.array(bands)
528712
def metadata_to_dict(metadata):
    

    tree = etree.parse(metadata)
    root = tree.getroot()

    meta = OrderedDict()

    keys = [
        'SPACECRAFT_NAME',
        'PRODUCT_STOP_TIME',
        'Cloud_Coverage_Assessment',
        'PROCESSING_LEVEL',
        'PRODUCT_TYPE',
        'PROCESSING_BASELINE',
        'SENSING_ORBIT_NUMBER',
        'SENSING_ORBIT_DIRECTION',
        'PRODUCT_FORMAT',
    ]

    # grab important keys from the file
    for key in keys:
        try:
            meta[key.lower()] = root.findall('.//' + key)[0].text
        except IndexError:
            meta[key.lower()] = None

    meta['product_cloud_coverage_assessment'] = float(meta.pop('cloud_coverage_assessment'))

    meta['sensing_orbit_number'] = int(meta['sensing_orbit_number'])

    # get tile list
    meta['tiles'] = get_tiles_list(root.findall('.//Product_Organisation')[0])

    # get available bands
    if root.findall('.//Band_List'):
        bands = root.findall('.//Band_List')[0]
        meta['band_list'] = []
        for b in bands:
            band = b.text.replace('B', '')
            if len(band) == 1:
                band = 'B' + pad(band, 2)
            else:
                band = b.text
            meta['band_list'].append(band)
    else:
        bands = root.findall('.//Spectral_Information_List')[0]
        meta['band_list'] = []
        for b in bands:
            band = b.attrib['physicalBand'].replace('B', '')
            if len(band) == 1:
                band = 'B' + pad(band, 2)
            else:
                band = b.attrib['physicalBand']
            meta['band_list'].append(band)

    return meta
645641
def _load(self, scale=1.0):
        

        LOG.debug("File: %s", str(self.requested_band_filename))

        data = np.genfromtxt(self.requested_band_filename,
                             unpack=True,
                             names=['wavelength',
                                    'wavenumber',
                                    'response'],
                             skip_header=2)

        wvl = data['wavelength'] * scale
        resp = data['response']

        self.rsr = {'wavelength': wvl, 'response': resp}
229351
def A_brighter(self, band='g'):
        
        mA = self.stars['{}_mag_A'.format(band)]
        mBC = addmags(self.stars['{}_mag_B'.format(band)],
                     self.stars['{}_mag_C'.format(band)])
        return mA < mBC
1120698
def bandWave(self):
        
        if self.binset.startswith('('):
            return self._computeBandwave(self.binset)
        else:
            return self._getBandwaveFomFile(self.binset)
1050839
def band_path(self, band_id, for_gdal=False, absolute=False):
        """"""
        band_id = str(band_id).zfill(2)
        if not isinstance(band_id, str) or band_id not in BAND_IDS:
            raise ValueError("band ID not valid: %s" % band_id)
        if self.dataset.is_zip and for_gdal:
            zip_prefix = "/vsizip/"
            if absolute:
                granule_basepath = zip_prefix + os.path.dirname(os.path.join(
                    self.dataset.path,
                    self.dataset.product_metadata_path
                ))
            else:
                granule_basepath = zip_prefix + os.path.dirname(
                    self.dataset.product_metadata_path
                )
        else:
            if absolute:
                granule_basepath = os.path.dirname(os.path.join(
                    self.dataset.path,
                    self.dataset.product_metadata_path
                ))
            else:
                granule_basepath = os.path.dirname(
                    self.dataset.product_metadata_path
                )
        product_org = self.dataset._product_metadata.iter(
            "Product_Organisation").next()
        granule_item = [
            g
            for g in chain(*[gl for gl in product_org.iter("Granule_List")])
            if self.granule_identifier == g.attrib["granuleIdentifier"]
        ]
        if len(granule_item) != 1:
            raise S2ReaderMetadataError(
                "Granule ID cannot be found in product metadata."
            )
        rel_path = [
            f.text for f in granule_item[0].iter() if f.text[-2:] == band_id
        ]
        if len(rel_path) != 1:
            # Apparently some SAFE files don't contain all bands. In such a
            # case, raise a warning and return None.
            warnings.warn(
                "%s: image path to band %s could not be extracted" % (
                    self.dataset.path, band_id
                )
            )
            return
        img_path = os.path.join(granule_basepath, rel_path[0]) + ".jp2"
        # Above solution still fails on the "safe" test dataset. Therefore,
        # the path gets checked if it contains the IMG_DATA folder and if not,
        # try to guess the path from the old schema. Not happy with this but
        # couldn't find a better way yet.
        if "IMG_DATA" in img_path:
            return img_path
        else:
            if self.dataset.is_zip:
                zip_prefix = "/vsizip/"
                granule_basepath = zip_prefix + os.path.join(
                    self.dataset.path, self.granule_path)
            else:
                granule_basepath = self.granule_path
            return os.path.join(
                os.path.join(granule_basepath, "IMG_DATA"),
                "".join([
                    "_".join((self.granule_identifier).split("_")[:-1]),
                    "_B",
                    band_id,
                    ".jp2"
                ])
            )