Beispiel #1
0
class execute_pep_process(Component):
    """ API for pep processing
    """
    implements(ProcessInterface)

    identifier = "execute_pep_interpolation"
    title = "Execute interpolation process of the PEP Library"
    metadata = {"test-metadata": "http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]

    inputs = [
        ("collection",
         LiteralData(
             'collection',
             str,
             optional=False,
             abstract="CoverageID to search in wcs server",
         )),
    ]

    outputs = [
        ("output", LiteralData('output', str,
                               abstract="pep Processing result")),
    ]

    def execute(self, collection, **kwarg):

        outputs = {}

        cmd_args = ['python', pep_path, '-c', collection]

        Popen(cmd_args)
        outputs['output'] = "Interpolation process started"

        return outputs
Beispiel #2
0
class Test07RequestParameterTest(Component):
    """ RequestParameters WPS test. """
    implements(ProcessInterface)

    identifier = "TC07:request-parameter"
    title = "Test Case 07: Request parameter."
    description = (
        "This test process demonstrates use of the RequestParameters "
        "input. The request parameter is a special input which passes "
        "meta-data extracted from the Django HTTPRequest object to the "
        "executed process.")

    inputs = [
        ("test_header", RequestParameter(get_header('X-Test-Header'))),
        ("input",
         LiteralData(
             'TC07:input01',
             str,
             optional=True,
             abstract="Optional simple string input.",
         )),
    ]

    outputs = [
        ("output",
         LiteralData(
             'TC07:output01',
             str,
             abstract="Simple string input.",
         )),
    ]

    @staticmethod
    def execute(test_header, **kwarg):
        return test_header or ""
Beispiel #3
0
class TestProcess04(Component):
    """ Test processes testing time-zone aware date-time input data-type
    with automatic time-zone conversion.
    """
    implements(ProcessInterface)

    identifier = "TC04:identity:literal:datetime"
    title = "Test Case 04: Literal input date-time time-zone test."
    profiles = ["test_profile"]

    TZ_DEFAULT = DateTime.TZOffset(+90)
    TZ_TARGET = DateTime.TZOffset(-120)
    #TIME_ZONE_UTC = DateTime.UTC

    inputs = [
        ('datetime',
         LiteralData(
             "TC04:datetime",
             DateTimeTZAware(TZ_DEFAULT, TZ_TARGET),
             title="Date-time input.",
         )),
    ]

    outputs = [
        ('datetime',
         LiteralData(
             "TC04:datetime",
             DateTime,
             title="Date-time output.",
         )),
    ]

    def execute(self, **inputs):
        return inputs['datetime']
Beispiel #4
0
    def process_inputs(self, process, decoder):
        """ Iterates over all input options stated in the process and parses 
            all given inputs. This also includes resolving references
        """
        input_params = process.inputs
        inputs = decoder.inputs

        kwargs = {}
        for key, parameter in input_params.items():

            if is_literal_type(parameter):
                parameter = LiteralData(key, parameter)

            try:
                # get the "raw" input value
                raw_value = inputs.pop(key)

                if isinstance(raw_value, Reference):
                    value = self.resolve_reference(raw_value, request)
                else:
                    value = parameter.parse_value(raw_value)

            except KeyError:
                if parameter.default is None:  # TODO: maybe an extra optional flag to allow None as a default value?
                    raise Exception("Parameter '%s' is required." % key)
                value = parameter.default

            kwargs[key] = value

        return kwargs
Beispiel #5
0
class TestProcess05(Component):
    """ Test processes testing time-zone aware date-time input data-type
    with automatic time-zone conversion.
    """
    implements(ProcessInterface)

    identifier = "TC05:identity:literal:datetime"
    title = "Test Case 05: Literal output date-time time-zone test."
    profiles = ["test_profile"]

    TZ_DEFAULT = DateTime.TZOffset(+90)
    TZ_TARGET = DateTime.TZOffset(-120)
    #TIME_ZONE_UTC = DateTime.UTC

    inputs = [
        ('datetime',
         LiteralData(
             "TC05:datetime",
             DateTime,
             title="Date-time input.",
         )),
    ]

    outputs = [
        ('datetime_original',
         LiteralData(
             "TC05:datetime",
             DateTime,
             title="Date-time output without modification.",
         )),
        ('datetime_aware',
         LiteralData(
             "TC05:datetime_aware",
             DateTimeTZAware(TZ_DEFAULT),
             title="Date-time output with default time-zone.",
         )),
        ('datetime_converted',
         LiteralData(
             "TC05:datetime_converted",
             DateTimeTZAware(TZ_DEFAULT, TZ_TARGET),
             title="Date-time output with default time-zone.",
         )),
    ]

    def execute(self, **inputs):
        return {
            'datetime_original': inputs['datetime'],
            'datetime_aware': inputs['datetime'],
            'datetime_converted': inputs['datetime'],
        }
Beispiel #6
0
class GetTimeDataProcess(Component):
    """ GetTimeDataProcess defines a WPS process needed by the EOxClient
        time-slider componenet """

    implements(ProcessInterface)

    identifier = "getTimeData"
    title = "Get times of collection coverages."
    decription = ("Query collection and get list of coverages and their times "
                  "and spatial extents. The process is used by the "
                  "time-slider of the EOxClient (web client).")

    metadata = {}
    profiles = ['EOxServer:GetTimeData']

    inputs = {
        "collection":
        LiteralData(
            "collection",
            title="Collection name (a.k.a. dataset-series identifier)."),
        "begin_time":
        LiteralData("begin_time",
                    datetime,
                    optional=True,
                    title="Optional start of the time interval."),
        "end_time":
        LiteralData("end_time",
                    datetime,
                    optional=True,
                    title="Optional end of the time interval."),
    }

    outputs = {
        "times":
        ComplexData("times",
                    formats=(FormatText('text/csv'), FormatText('text/plain')),
                    title=("Comma separated list of collection's coverages, "
                           "their extents and times."),
                    abstract=("NOTE: The use of the 'text/plain' format is "
                              "deprecated! This format will be removed!'"))
    }

    @staticmethod
    def execute(collection, begin_time, end_time, **kwarg):
        """ The main execution function for the process.
        """

        # get the dataset series matching the requested ID
        try:
            model = models.EOObject.objects.filter(
                identifier=collection).select_subclasses().get()
        except models.EOObject.DoesNotExist:
            raise InvalidInputValueError(
                "collection", "Invalid collection name '%s'!" % collection)

        if isinstance(model, (models.Collection, models.Mosaic)):
            if isinstance(model, models.Collection):
                qs = models.EOObject.objects.filter(
                    Q(  # coverages
                        coverage__isnull=False,
                        coverage__collections=model,
                    ) | Q(  # products
                        product__isnull=False,
                        product__collections=model,
                    ))
            else:
                qs = model.coverages

            # prepare coverage query set
            if end_time is not None:
                qs = qs.filter(begin_time__lte=end_time)
            if begin_time is not None:
                qs = qs.filter(end_time__gte=begin_time)
            qs = qs.order_by('begin_time', 'end_time').annotate(
                envelope=Envelope('footprint')).values_list(
                    "begin_time", "end_time", "identifier", "envelope")

        else:
            qs = [(model.begin_time, model.end_time, model.identifier,
                   model.footprint)]

        # create the output
        output = CDAsciiTextBuffer()
        writer = csv.writer(output, quoting=csv.QUOTE_ALL)
        header = ["starttime", "endtime", "bbox", "identifier"]
        writer.writerow(header)

        for starttime, endtime, identifier, bbox in qs:
            writer.writerow([
                isoformat(starttime),
                isoformat(endtime), bbox.extent if not bbox.empty else '()',
                identifier
            ])

        return output
Beispiel #7
0
class TestProcess03(Component):
    """ Test process generating binary complex data output. """
    implements(ProcessInterface)

    identifier = "TC03:image_generator:complex"
    title = "Test Case 03: Complex data binary output with format selection."
    description = (
        "Test process generating binary complex data output (an image)."
    )
    metadata = {"test-metadata": "http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]

    inputs = [
        ("method", LiteralData(
            'TC03:method', str, optional=True,
            title="Complex data output passing method.",
            abstract=(
                "This option controls the method how the complex data output "
                "payload is passed from process code."
            ),
            allowed_values=('in-memory-buffer', 'file'), default='file',
        )),
        ("seed", LiteralData(
            'TC03:seed', int, optional=True, title="Random generator seed.",
            abstract=(
                "Optional random generator seed that can be used to obtain "
                "reproducible random-generated result."
            ),
            allowed_values=AllowedRange(0, None, dtype=int),
        )),
    ]

    outputs = [
        ("output", ComplexData(
            'TC03:output00', title="Test case #02: Complex output #00",
            abstract="Binary complex data output (random-generated image).",
            formats=(
                FormatBinaryRaw('image/png'),
                FormatBinaryBase64('image/png'),
                FormatBinaryRaw('image/jpeg'),
                FormatBinaryBase64('image/jpeg'),
                FormatBinaryRaw('image/tiff'),
                FormatBinaryBase64('image/tiff'),
            )
        )),
    ]

    # NOTE:
    #   The output complex data format has to be handled by the processes
    #   itself and the format selection has to be passed to the 'execute'
    #   subroutine.  The output complex data format selection is passed
    #   to the process as an additional input argument - a simple dictionary
    #   with the 'mime_type', 'encoding', 'schema', and 'as_reference' keywords.
    #   In case no format being selected by the user this format selection
    #   is set to the default format.  The name of the input argument holding
    #   the is controlled by the process output definition.

    @staticmethod
    def execute(method, seed, output):
        # size of the output image
        size_x, size_y = (768, 512)

        # output format selection
        if output['mime_type'] == "image/png":
            extension = ".png"
            driver = gdal.GetDriverByName("PNG")
            options = []
        elif output['mime_type'] == "image/jpeg":
            extension = ".jpg"
            driver = gdal.GetDriverByName("JPEG")
            options = []
        elif output['mime_type'] == "image/tiff":
            extension = ".tif"
            driver = gdal.GetDriverByName("GTiff")
            options = ["TILED=YES", "COMPRESS=DEFLATE", "PHOTOMETRIC=RGB"]
        else:
            ExecuteError("Unexpected output format received! %r" % output)

        # generate a random in-memory GDAL dataset
        mem_driver = gdal.GetDriverByName("MEM")
        mem_ds = mem_driver.Create("", size_x, size_y, 3, gdal.GDT_Byte)
        random_state = RandomState(seed)
        for i in xrange(3):
            mem_ds.GetRasterBand(i+1).WriteArray(
                (256.0 * random_state.rand(size_y, size_x)).astype('uint8')
            )

        # convert in-memory dataset to the desired output
        tmp_filename = os.path.join("/tmp", str(uuid.uuid4()) + extension)
        output_filename = "test03_binary_complex" + extension

        try:
            driver.CreateCopy(tmp_filename, mem_ds, 0, options)
            del mem_ds

            if method == 'file':
                # Return object as a temporary Complex Data File.
                # None that the object holds the format attributes!
                # The 'filename' parameter sets the raw output
                # 'Content-Disposition: filename=' HTTP header.
                return CDFile(tmp_filename, filename=output_filename, **output)

            elif method == 'in-memory-buffer':
                # Return object as an in-memory Complex Data Buffer.
                # None that the object holds the format attributes!
                # The 'filename' parameter sets the raw output
                # 'Content-Disposition: filename=' HTTP header.
                with open(tmp_filename, 'rb') as fid:
                    _output = CDByteBuffer(
                        fid.read(), filename=output_filename, **output
                    )
                os.remove(tmp_filename)
                return _output
        except:
            # make sure no temporary file is left in case of an exception
            if os.path.isfile(tmp_filename):
                os.remove(tmp_filename)
            raise
Beispiel #8
0
class execute_pep_process(Component):
    """ Process to calcuate coverage spatial average
    """
    implements(ProcessInterface)

    identifier = "execute_pep_process"
    title = "Execute process of the PEP Library"
    metadata = {"test-metadata": "http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]

    inputs = [
        ("coverage",
         LiteralData(
             'coverage',
             str,
             optional=False,
             abstract="ID of coverage to be used in processing",
         )),
        ("process",
         LiteralData(
             'process',
             str,
             optional=False,
             abstract="PEP Process to be called by request",
         )),
        ("begin_time",
         LiteralData(
             'begin_time',
             str,
             optional=False,
             abstract="Start of the time interval",
         )),
        ("end_time",
         LiteralData(
             'end_time',
             str,
             optional=True,
             default=None,
             abstract="End of the time interval",
         )),
        ("bbox",
         BoundingBoxData(
             "bbox",
             crss=CRSS,
             optional=False,
             abstract="Bounding Box used for computation",
         )),
        ("o_coverage",
         LiteralData(
             'o_coverage',
             str,
             optional=True,
             default=None,
             abstract="ID for coverage to be used in band combination",
         )),
        ("gain",
         LiteralData(
             'gain',
             str,
             optional=True,
             default=None,
             abstract="Gain factor for unit conversion",
         )),
        ("offset",
         LiteralData(
             'offset',
             str,
             optional=True,
             default=None,
             abstract="Offset factor for unit conversion",
         )),
    ]

    outputs = [
        ("output", LiteralData('output', str, abstract="Average of coverage")),
    ]

    #outputs = [
    #    ("output",
    #        ComplexData('output',
    #            title="PEP Process result",
    #            abstract="Returns the PEP process call results",
    #            formats=FormatText('text/plain')
    #        )
    #    ),
    #]

    def execute(self, coverage, process, begin_time, end_time, bbox,
                o_coverage, gain, offset, **kwarg):

        outputs = {}

        cmd_args = [
            'python', pep_path, process, '-c',
            'ALARO_Surface_pressure_surface_4326_0059882', '-u',
            str(bbox.upper[1]), '-d',
            str(bbox.lower[1]), '-l',
            str(bbox.lower[0]), '-r',
            str(bbox.upper[0]), '-s',
            str(1368576000)
        ]

        if end_time:
            cmd_args.extend(['-e', str(end_time)])

        if o_coverage:
            cmd_args.extend(['-o', o_coverage])

        if gain:
            cmd_args.extend(['--gain', str(gain)])

        if offset:
            cmd_args.extend(['--offset', offset])

        result = check_output(cmd_args)
        outputs['output'] = result

        return outputs
Beispiel #9
0
class execute_pep_process(Component):
    """ API for pep processing
    """
    implements(ProcessInterface)

    identifier = "execute_assessment"
    title = "Execute assessment process of the PEP Library"
    metadata = {"test-metadata": "http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]

    # usage: tampDataAssessmentUtility.py [-h] -c COVERAGE [-g GROUND_PRODUCT] -u
    #                                     UR_LAT -d LL_LAT -l LL_LON -r UR_LON -s
    #                                     T_S [-e T_E] [--spatialtolerance degree]
    #                                     [--temporaltolerance mins]
    #                                     FUNCTION

    # Utility used to provide results "on-the-fly" between wcs data and ground db
    # data

    # optional arguments:
    #   -h, --help            show this help message and exit

    # Required function:
    #   FUNCTION              Available functions are: correlation

    # Coverage required options:
    #   -c COVERAGE           CoverageID to search in wcs server
    #   -g GROUND_PRODUCT     Ground product to search in DB, used in correlation
    #                         function
    #   -u UR_LAT             Upper latitude
    #   -d LL_LAT             Lower latitude
    #   -l LL_LON             Far west latitude
    #   -r UR_LON             Far east latitude
    #   -s T_S                Start time/date expressed in Unix Timestamp
    #   -e T_E                End time/date expressed in Unix Timestamp

    # Function 'correlation' optional arguments:
    #   --spatialtolerance degree
    #                         Apply the spatialtolerance in correlation function,
    #                         default 1 degree
    #   --temporaltolerance mins
    #                         Apply the temporaltolerance in correlation function,
    #                         default 60 mins

    inputs = [
        ("process",
         LiteralData(
             'process',
             str,
             optional=False,
             abstract=
             "Assesment functions; Available functions are: correlation",
         )),
        ("collection",
         LiteralData(
             'collection',
             str,
             optional=False,
             abstract="CoverageID to search in wcs server",
         )),
        ("o_collection",
         LiteralData(
             'o_collection',
             str,
             optional=True,
             abstract=
             "(collection name, to be used in case of combination functions",
         )),
        ("ground_product",
         LiteralData(
             'ground_product',
             str,
             optional=True,
             abstract="Ground product to search in DB",
         )),
        ("bbox",
         BoundingBoxData(
             "bbox",
             crss=CRSS,
             optional=False,
             abstract="Bounding Box used for computation",
         )),
        ("start_time",
         LiteralData(
             'start_time',
             str,
             optional=False,
             abstract="Start time/date expressed in Unix Timestamp",
         )),
        ("end_time",
         LiteralData(
             'end_time',
             str,
             optional=True,
             default=None,
             abstract="End time/date expressed in Unix Timestamp",
         )),
        ("spatialtolerance",
         LiteralData(
             'spatialtolerance',
             str,
             optional=True,
             default=None,
             abstract=
             "Apply the spatialtolerance in correlation function, default 1 degree",
         )),
        ("temporaltolerance",
         LiteralData(
             'temporaltolerance',
             str,
             optional=True,
             default=None,
             abstract=
             "Apply the temporaltolerance in correlation function, default 60 mins",
         )),
    ]

    outputs = [
        ("output", LiteralData('output', str,
                               abstract="pep Processing result")),
    ]

    def execute(self, process, collection, o_collection, ground_product, bbox,
                start_time, end_time, spatialtolerance, temporaltolerance,
                **kwarg):

        outputs = {}

        cmd_args = [
            'python', pep_path, process, '-c', collection, '-u',
            str(bbox.upper[1]), '-d',
            str(bbox.lower[1]), '-l',
            str(bbox.lower[0]), '-r',
            str(bbox.upper[0]), '-s', start_time, '-e',
            str(end_time)
        ]

        if o_collection:
            cmd_args.extend(['-o', o_collection])

        if ground_product:
            cmd_args.extend(['-g', ('"%s"' % ground_product)])

        if spatialtolerance:
            cmd_args.extend(['--spatialtolerance', spatialtolerance])

        if temporaltolerance:
            cmd_args.extend(['--temporaltolerance', temporaltolerance])

        result = check_output(cmd_args)
        outputs['output'] = result

        return outputs
Beispiel #10
0
class GetTimeDataProcess(Component):
    """ GetTimeDataProcess defines a WPS process needed by the EOxClient
        time-slider componenet """

    implements(ProcessInterface)

    identifier = "getTimeData"
    title = "Get times of collection coverages."
    decription = ("Query collection and get list of coverages and their times "
                  "and spatial extents. The process is used by the time-slider "
                  "of the EOxClient (web client).")

    metadata = {}
    profiles = ['EOxServer:GetTimeData']

    inputs = {
        "collection": LiteralData("collection",
            title="Collection name (a.k.a. dataset-series identifier)."),
        "begin_time": LiteralData("begin_time", datetime, optional=True,
            title="Optional start of the time interval."),
        "end_time": LiteralData("end_time", datetime, optional=True,
            title="Optional end of the time interval."),
    }

    outputs = {
        "times": ComplexData("times",
                    formats=(FormatText('text/csv'), FormatText('text/plain')),
                    title="Comma separated list of collection's coverages, "
                          "their extents and times.",
                    abstract="NOTE: The use of the 'text/plain' format is "
                             "deprecated! This format will be removed!'"
                )
    }

    @staticmethod
    def execute(collection, begin_time, end_time, **kwarg):
        """ The main execution function for the process.
        """

        # get the dataset series matching the requested ID
        try:
            model = models.EOObject.objects.get(identifier=collection)
        except models.EOObject.DoesNotExist:
            raise InvalidInputValueError(
                "collection", "Invalid collection name '%s'!" % collection
            )

        if models.iscollection(model):
            model = model.cast()

            # recursive dataset series lookup
            def _get_children_ids(ds):
                ds_rct = ds.real_content_type
                id_list = [ds.id]
                for child in model.eo_objects.filter(real_content_type=ds_rct):
                    id_list.extend(_get_children_ids(child))
                return id_list

            collection_ids = _get_children_ids(model)

            # prepare coverage query set
            coverages_qs = models.Coverage.objects.filter(
                collections__id__in=collection_ids
            )
            if end_time is not None:
                coverages_qs = coverages_qs.filter(begin_time__lte=end_time)
            if begin_time is not None:
                coverages_qs = coverages_qs.filter(end_time__gte=begin_time)
            coverages_qs = coverages_qs.order_by('begin_time', 'end_time')
            coverages_qs = coverages_qs.envelope()
            coverages_qs = coverages_qs.values_list("begin_time", "end_time", "identifier", "envelope")

        else:
            coverages_qs = ((model.begin_time, model.end_time, model.identifier, model.footprint),)

        # create the output
        output = CDAsciiTextBuffer()
        writer = csv.writer(output, quoting=csv.QUOTE_ALL)
        header = ["starttime", "endtime", "bbox", "identifier"]
        writer.writerow(header)

        for starttime, endtime, identifier, bbox in coverages_qs:
            writer.writerow([isoformat(starttime), isoformat(endtime), bbox.extent, identifier])

        return output
Beispiel #11
0
class execute_file_system(Component):
    """ API for pep file system processing
    """
    implements(ProcessInterface)

    identifier = "execute_file_system"
    title = "Execute process of the file system PEP Library"
    metadata = {"test-metadata":"http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]


# Usage, in folder "/home/tamp/pep.lib/scripts":

# usage: FilesystemData.py [-h] [--standalone] -f func -l label [-c coverage]
#                          [-n name] -u value [-i dir] [-o dir] [--gain val]
#                          [--offset val]

# Utility used to reprocess entire collections on filesystem

# optional arguments:
#   -h, --help    show this help message and exit
#   --standalone  Execute the module stand-alone, without going through ingester in das_ing

# Required Arguments:
#   -f func       available functions are: verticalIntegration, convert
#   -l label      new label to attach to new filename

# Required Arguments if NOT executed stand-alone:
#   -c coverage   Coverage_ID in data_ingestion_collectiontable
#   -n name       New name for data_ingestion_collectiontable
#   -u value      measurement unit for new collection

# Required Arguments if executed stand-alone:
#   -i dir        directory where search tif recoursively
#   -o dir        directory where put results, Created if not exists

# function 'convert' optional arguments (Result = (coverage_ID+offset)*gain) :
#   --gain val    apply the gain in conversion function, default 1

#   --offset val  apply the offset in conversion function, default 0


    inputs = [
        ("process", LiteralData('process', str, optional=False,
            abstract="available functions are: verticalIntegration, convert",
        )),
        ("label", LiteralData('label', str, optional=False,
            abstract="new label to attach to new filename",
        )),
        ("collection", LiteralData('collection', str, optional=False,
            abstract="collection name",
        )),
        ("name", LiteralData('name', str, optional=False,
            abstract="New name for data_ingestion_collectiontable",
        )),
        ("value", LiteralData('value', str, optional=False,
            abstract="measurement unit for new collection",
        )),
        ("gain", LiteralData('gain', str, optional=True,
            default=None, abstract="The gain factor (needed only for conversion unit function) (--gain)",
        )),
        ("offset", LiteralData('offset', str, optional=True,
            default=None, abstract="The offset factor (needed only for conversion unit function) (--offset)",
        ))
    ]


    outputs = [
        ("output", LiteralData('output', str,
            abstract="pep Processing result"
        )),
    ]
    

    def execute(self, process, label, collection, name, value, gain,
                offset, **kwarg):

        outputs = {}

        cmd_args = ['python', pep_path,
                    '-f', process,
                    '-l', label,
                    '-c', collection,
                    '-n', name,
                    '-u', value ]

        if gain:
            cmd_args.extend(['--gain',str(gain)])

        if offset:
            cmd_args.extend(['--offset', str(offset)])


        result = check_output(cmd_args)
        outputs['output'] = result


        return outputs
Beispiel #12
0
class TestProcess00(Component):
    """ Test identity process (the outputs are copies of the inputs)
    demonstrating various features of the literal data inputs and outputs.
    """
    implements(ProcessInterface)

    identifier = "TC00:identity:literal"
    title = "Test Case 00: Literal data identity."
    metadata = {"test-metadata": "http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]

    inputs = [
        ("input00", str),  # mandatory minimal string input
        ("input01",
         LiteralData(
             'TC00:input01',
             String,
             optional=True,
             abstract="Optional simple string input.",
         )),
        ("input02",
         LiteralData(
             'TC00:input02',
             str,
             optional=True,
             abstract="Optional enumerated string input with default value.",
             allowed_values=('low', 'medium', 'high'),
             default='medium',
         )),
        ("input03",
         LiteralData(
             'TC00:input03',
             float,
             optional=True,
             title="Distance",
             abstract=
             ("Optional restricted float input with default value and simple "
              "UOM conversion."),
             allowed_values=AllowedRange(0, 2, dtype=float),
             default=0,
             uoms=[
                 ('m', 1.0),
                 ('mm', 1e-3),
                 ('cm', 1e-2),
                 ('dm', 1e-1),
                 ('yd', 0.9144),
                 ('ft', 0.3048),
                 ('in', 0.0254),
                 ('km', 1000.0),
                 ('mi', 1609.344),
                 ('NM', 1852.0),
             ],
         )),
        ("input04",
         LiteralData(
             'TC00:input04',
             float,
             optional=True,
             title="Temperature",
             abstract=(
                 "Optional restricted float input with default value and "
                 "advanced UOM conversion."),
             allowed_values=AllowedRange(0, None, dtype=float),
             default=298.15,
             uoms=(('K', 1.0), UnitLinear('C', 1.0, 273.15),
                   UnitLinear('F', 5.0 / 9.0, 459.67 * 5.0 / 9.0)),
         )),
    ]

    outputs = [
        ("output00", str),  # minimal string output
        (
            "output01",
            LiteralData(
                # NOTE: Outputs can be optional and have default value too.
                'TC00:output01',
                String,
                optional=True,
                default='n/a',
                abstract="Simple string output.",
            )),
        ("output02",
         LiteralData(
             'TC00:output02',
             str,
             abstract="Enumerated string output.",
             allowed_values=('low', 'medium', 'high'),
             default='medium',
         )),
        ("output03",
         LiteralData(
             'TC00:output03',
             float,
             title="Distance",
             abstract="Restricted float output with UOM conversion.",
             allowed_values=AllowedRange(0, 1, dtype=float),
             uoms=[
                 ('m', 1.0),
                 ('mm', 1e-3),
                 ('cm', 1e-2),
                 ('dm', 1e-1),
                 ('yd', 0.9144),
                 ('ft', 0.3048),
                 ('in', 0.0254),
                 ('km', 1000.0),
                 ('mi', 1609.344),
                 ('NM', 1852.0),
             ],
         )),
        ("output04",
         LiteralData(
             'TC00:output04',
             float,
             title="Temperature",
             abstract="Restricted float output advanced UOM conversion.",
             allowed_values=AllowedRange(0, None, dtype=float),
             uoms=(
                 ('K', 1.0),
                 UnitLinear('C', 1.0, 273.15),
                 UnitLinear('F', 5.0 / 9.0, 459.67 * 5.0 / 9.0),
             ),
         )),
    ]

    def execute(self, **inputs):
        """ WPS Process execute handler. """
        return {
            'output00': inputs['input00'],
            'output01': inputs.get('input01'),
            'output02': inputs['input02'],
            'output03': inputs['input03'],
            'output04': inputs['input04'],
        }
Beispiel #13
0
class execute_pep_process(Component):
    """ API for pep processing
    """
    implements(ProcessInterface)

    identifier = "execute"
    title = "Execute process of the PEP Library"
    metadata = {"test-metadata":"http://www.metadata.com/test-metadata"}
    profiles = ["test_profile"]


# Required function:
#   FUNCTION            Available functions are: spatialAverage, temporalAverage, conversion, add, subtract

# Coverage required options:
#   -c COVERAGE         CoverageID to search in wcs server
#   -o SECOND_COVERAGE  Second coverageID to search in wcs server, used in band
#                       combination function (add, subtract)
#   -u UR_LAT           Upper latitude
#   -d LL_LAT           Lower latitude
#   -l LL_LON           Far west latitude
#   -r UR_LON           Far east latitude
#   -s T_S              Start time/date expressed in Unix Timestamp
#   -e T_E              End time/date expressed in Unix Timestamp

# Function 'convert' optional arguments. (Result = (coverage_ID+offset)*gain):
#   --gain val          Apply the gain in conversion function, default 1
#   --offset val        Apply the offset in conversion function, default 0

    inputs = [
        ("process", LiteralData('process', str, optional=False,
            abstract="PEP Process to be called by request; Available functions are: spatialAverage, temporalAverage, conversion, add, subtract",
        )),
        ("collection", LiteralData('collection', str, optional=False,
            abstract="CoverageID to search in wcs server",
        )),
        ("o_collection", LiteralData('o_collection', str, optional=True,
            abstract="(collection name, to be used in case of bandCombination2D function",
        )),
        ("bbox", BoundingBoxData("bbox", crss=CRSS, optional=False,
            abstract="Bounding Box used for computation",
        )),
        ("start_time", LiteralData('start_time', str, optional=False,
            abstract="Start time/date expressed in Unix Timestamp",
        )),
        ("end_time", LiteralData('end_time', str, optional=False,
            default=None, abstract="End time/date expressed in Unix Timestamp",
        )),
        ("gain", LiteralData('gain', str, optional=True,
            default=None, abstract="The gain factor (needed only for conversion unit function) (--gain)",
        )),
        ("offset", LiteralData('offset', str, optional=True,
            default=None, abstract="The offset factor (needed only for conversion unit function) (--offset)",
        )),
    ]


    outputs = [
        ("output", ComplexData(
            "output", title="The processing result", formats=(
                FormatBinaryRaw("image/tiff"),
            )
        )),
    ]
    

    def execute(self, process, collection, o_collection, bbox, start_time,
                end_time, gain, offset, **kwarg):

        outputs = {}

        cmd_args = [
            'python', pep_path, process,
            '-c', collection,
            '-u', str(bbox.upper[1]), '-d', str(bbox.lower[1]),
            '-l', str(bbox.lower[0]), '-r', str(bbox.upper[0]),
            '-s', str(start_time),
            '-e', str(end_time),
        ]

        if o_collection:
            cmd_args.extend(['-o', o_collection])

        if gain:
            cmd_args.extend(['--gain', str(gain)])

        if offset:
            cmd_args.extend(['--offset', str(offset)])

        result = check_output(cmd_args).strip()

        if os.path.isfile(result):
            # open file
            with open(result, "rb") as fid:
                filedata = fid.read()

            outputs['output'] = filedata
        else:
            outputs['output'] = result

        return outputs