Ejemplo n.º 1
0
def StandaloneStyle(cfg):
    """
    Construct a OWS style object that stands alone, independent of a complete OWS configuration environment.

    :param cfg: A valid OWS Style definition configuration dictionary.

        Refer to the documentation for the valid syntax:

        https://datacube-ows.readthedocs.io/en/latest/cfg_styling.html

    :return: A OWS Style Definition object, prepared to work in standalone mode.
    """
    style = StyleDefBase(StandaloneProductProxy(), cfg, stand_alone=True)
    style.make_ready(None)
    return style
Ejemplo n.º 2
0
def prelegend_style():
    style = StyleDefBase.__new__(StyleDefBase)
    return style
Ejemplo n.º 3
0
        d = self.apply_index(data)
        return self.color_ramp.apply(d)

    def single_date_legend(self, bytesio):
        colour_ramp_legend(bytesio, self.legend_cfg, self.color_ramp,
                           self.product.name, self.title)

    class MultiDateHandler(StyleDefBase.MultiDateHandler):
        auto_legend = True

        def __init__(self, style, cfg):
            super().__init__(style, cfg)
            self.feature_info_label = cfg.get("feature_info_label", None)

            self.color_ramp = ColorRamp(style, cfg)

        def transform_data(self, data):
            xformed_data = self.style.apply_index(data)
            agg = self.aggregator(xformed_data)
            return self.color_ramp.apply(agg)

        def legend(self, bytesio):
            title = self.legend_cfg.get("title", self.range_str() + " Dates")
            name = self.style.product.name + f"_{self.min_count}"
            colour_ramp_legend(bytesio, self.legend_cfg, self.color_ramp, name,
                               title)
            return True


StyleDefBase.register_subclass(ColorRampDef, ("range", "color_ramp"))
Ejemplo n.º 4
0
        d = data['index_function']
        for band, intensity in self.rgb_components.items():
            rampdata = self.color_ramp.get_value(d, band)
            component_band_data = None
            if band in self.rgb_components:
                for c_band, c_intensity in self.rgb_components[band].items():
                    if callable(c_intensity):
                        imgband_component_data = c_intensity(
                            data[c_band], c_band, band)
                    else:
                        imgband_component_data = data[c_band] * c_intensity
                    if component_band_data is not None:
                        component_band_data += imgband_component_data
                    else:
                        component_band_data = imgband_component_data
                    if band != "alpha":
                        component_band_data = self.compress_band(
                            band, component_band_data)
                img_band_data = (rampdata * 255.0 *
                                 (1.0 - self.component_ratio) +
                                 self.component_ratio * component_band_data)
            else:
                img_band_data = rampdata * 255.0
            imgdata[band] = (d.dims, img_band_data.astype("uint8"))

        return imgdata


StyleDefBase.register_subclass(HybridStyleDef,
                               "component_ratio",
                               priority=True)
def prelegend_style():
    style = StyleDefBase.__new__(StyleDefBase)
    style._unready_attributes = []
    return style
Ejemplo n.º 6
0
                [imgdata, band_data])

        imgdata *= 255
        return imgdata.astype('uint8')

    def single_date_legend(self, bytesio):
        patches = []
        for band in self.value_map.keys():
            for rule in reversed(self.value_map[band]):
                # only include values that are not transparent (and that have a non-blank title or abstract)
                if rule.alpha > 0.001 and rule.label:
                    try:
                        patch = mpatches.Patch(color=rule.rgb.hex_l,
                                               label=rule.label)
                    # pylint: disable=broad-except
                    except Exception as e:
                        print("Error creating patch?", e)
                    patches.append(patch)
        cfg = self.legend_cfg
        plt.rcdefaults()
        if cfg.get("rcParams", None) is not None:
            plt.rcParams.update(cfg.get("rcParams"))
        figure = plt.figure(figsize=(cfg.get("width", 3),
                                     cfg.get("height", 1.25)))
        plt.axis('off')
        legend = plt.legend(handles=patches, loc='center', frameon=False)
        plt.savefig(bytesio, format='png')


StyleDefBase.register_subclass(ColorMapStyleDef, "value_map")
Ejemplo n.º 7
0
        imgdata = Dataset()
        for imgband, components in self.rgb_components.items():
            if callable(components):
                imgband_data = components(data)
                dims = imgband_data.dims
                imgband_data = imgband_data.astype('uint8')
                imgdata[imgband] = (dims, imgband_data)
            else:
                imgband_data = None
                for band, intensity in components.items():
                    if callable(intensity):
                        imgband_component = intensity(data[band], band, imgband)
                    else:
                        imgband_component = data[band] * intensity

                    if imgband_data is not None:
                        imgband_data += imgband_component
                    else:
                        imgband_data = imgband_component
                if imgband_data is None:
                    imgband_data = np.zeros(list(data.dims.values()), 'uint8')
                    imgband_data = DataArray(imgband_data, data.coords, data.dims.keys())
                if imgband != "alpha":
                    imgband_data = self.compress_band(imgband, imgband_data)
                imgdata[imgband] = (imgband_data.dims,
                                    imgband_data.astype("uint8"))
        return imgdata


StyleDefBase.register_subclass(ComponentStyleDef, "components")
Ejemplo n.º 8
0
def test_multidate_handler():
    # TODO: Consolidate these into a fixture
    class FakeData:
        def __init__(self):
            self.nodata = np.nan

        def item(self):
            return np.nan

    class FakeDataset:
        def __getitem__(self, key):
            return FakeData()

    class FakeMdhStyle:
        include_in_feature_info = True

        def __init__(self):
            self.product = "test"
            self.needed_bands = ["test"]
            self.index_function = lambda x: FakeData()

    data = np.random.randint(0, 255, size=(4, 3), dtype=np.uint8)
    locs = ["IA", "IL", "IN"]
    times = pd.date_range("2000-01-01", periods=4)
    fake_mask = xr.DataArray(data,
                             coords=[times, locs],
                             dims=["time", "space"])

    fake_cfg = {
        "allowed_count_range": [0, 10],
        "aggregator_function": "datacube_ows.band_utils.multi_date_delta",
    }

    fake_cfg_equal = {
        "allowed_count_range": [1, 1],
        "aggregator_function": "datacube_ows.band_utils.multi_date_delta",
    }

    mdh = StyleDefBase.MultiDateHandler(FakeMdhStyle(), fake_cfg)
    assert mdh is not None
    assert not mdh.legend(None)
    assert mdh.collapse_mask(fake_mask) is not None
    assert isinstance(mdh.range_str(), str)
    assert mdh.applies_to(2)
    assert not mdh.applies_to(11)

    mdh_equal = StyleDefBase.MultiDateHandler(FakeMdhStyle(), fake_cfg_equal)
    assert isinstance(mdh_equal.range_str(), str)

    with pytest.raises(ConfigException) as excinfo:
        bad_mdh = StyleDefBase.MultiDateHandler(FakeMdhStyle(), {})

    assert "must have an allowed_count_range" in str(excinfo.value)

    with pytest.raises(ConfigException) as excinfo:
        bad_mdh = StyleDefBase.MultiDateHandler(FakeMdhStyle(), {
            "allowed_count_range": [0, 5, 10],
        })

    assert "allowed_count_range must have 2" in str(excinfo.value)

    with pytest.raises(ConfigException) as excinfo:
        bad_mdh = StyleDefBase.MultiDateHandler(FakeMdhStyle(), {
            "allowed_count_range": [10, 5],
        })

    assert "minimum must be less than equal to maximum" in str(excinfo.value)

    with pytest.raises(ConfigException) as excinfo:
        bad_mdh = StyleDefBase.MultiDateHandler(FakeMdhStyle(), {
            "allowed_count_range": [0, 10],
        })

    assert "Aggregator function is required" in str(excinfo.value)

    with pytest.raises(NotImplementedError) as excinfo:
        mdh.transform_data(None)

    assert str(excinfo) == "<ExceptionInfo NotImplementedError() tblen=2>"