Skip to content

Qgis algorithms

Import
from pyqgis_wrapper.processing.base import QgisAlgorithm, InPlaceAlgorithm,VectorAlgorithm, RasterAlgorithm, PointCloudAlgorithm

QgisAlgorithm(context=QgsProcessingContext(), feedback=QgsProcessingFeedback(), is_child_algorithm=True)

Wrapper for a QGIS processing algorithm.

Attributes:

Name Type Description
algorithm_id str

Algorithm ID.

name str

Name of the algorithm.

Parameters:

Name Type Description Default
context qgis.core.QgsProcessingContext

Processing context.

qgis.core.QgsProcessingContext()
feedback qgis.core.QgsProcessingFeedback

Processing feedback.

qgis.core.QgsProcessingFeedback()
is_child_algorithm bool

If True the outputs will be added to the provided context. Giving the ownership of the outputs to the caller.

True
Source code in pyqgis_wrapper/processing/base.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    context: QgsProcessingContext = QgsProcessingContext(),
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    is_child_algorithm: bool = True,
):
    """
    :param context: Processing context.
    :type context: QgsProcessingContext, optional
    :param feedback: Processing feedback.
    :type feedback: QgsProcessingFeedback, optional
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool
    """

    self._load_algorithm()
    self.available_parameters = self.get_available_params()
    self.required_parameters = self.get_required_parameters()
    self.optional_parameters = self.get_optionnal_parameters()
    self.context = context
    self.feedback = feedback
    self.is_child_algorithm = is_child_algorithm

get_available_params()

Return all parameters for the algorithm.

Returns:

Type Description
List[str]

List of parameter names.

Source code in pyqgis_wrapper/processing/base.py
132
133
134
135
136
137
138
139
def get_available_params(self) -> List[str]:
    """
    Return all parameters for the algorithm.

    :returns: List of parameter names.
    :rtype: List[str]
    """
    return [p for p in self.algorithm.parameterDefinitions()]

get_required_parameters()

Return required parameters for algorithm.

Returns:

Type Description
List[str]

Required parameters names.

Source code in pyqgis_wrapper/processing/base.py
141
142
143
144
145
146
147
148
149
150
151
152
def get_required_parameters(self) -> List[str]:
    """
    Return required parameters for algorithm.

    :returns: Required parameters names.
    :rtype: List[str]
    """
    return [
        p.name()
        for p in self.available_parameters
        if not (p.flags() & QgsProcessingParameterDefinition.FlagOptional)
    ]

validate_parameters(parameters)

Match the case of input parameters to algorithm parameters.

Parameters:

Name Type Description Default
parameters typing.Dict[str, typing.Any]

Input parameters

required

Returns:

Type Description
Dict[str, Any]

Validated parameters

Source code in pyqgis_wrapper/processing/base.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def validate_parameters(
    self,
    parameters: Dict[str, Any],
) -> Dict[str, Any]:
    """
    Match the case of input parameters to algorithm parameters.

    :param parameters: Input parameters
    :type parameters: Dict[str, Any]

    :return: Validated parameters
    :rtype: Dict[str, Any]
    """
    alg_parameters = self._build_parameters(True)
    valid_parameters = {}
    for name, value in parameters.items():
        if name.upper() in alg_parameters:
            valid_parameters[name.upper()] = value
        elif name.lower() in alg_parameters:
            valid_parameters[name.lower()] = value
        else:
            raise KeyError(f"Invalid parameter(s) for {self.algorithm_id}: {name}")

        if value == "**REQUIRED**":
            raise ValueError(
                f"Missing required parameters for {self.algorithm_id}: {name}"
            )

    return valid_parameters

get_optionnal_parameters()

Return optionnal parameters for algorithm.

Returns:

Type Description
List[str]

Optionnal parameters names.

Source code in pyqgis_wrapper/processing/base.py
184
185
186
187
188
189
190
191
192
193
194
195
def get_optionnal_parameters(self) -> List[str]:
    """
    Return optionnal parameters for algorithm.

    :returns: Optionnal parameters names.
    :rtype: List[str]
    """
    return [
        p.name()
        for p in self.available_parameters
        if p.flags() & QgsProcessingParameterDefinition.FlagOptional
    ]

run_algorithm(parameters)

Run the processing algorithm.

Parameters:

Name Type Description Default
parameters typing.Dict[str, typing.Any]

Dictionary of parameters.

required

Returns:

Type Description
Union[None, Dict[str, Any]]

Output of the processing algorithm.

Source code in pyqgis_wrapper/processing/base.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def run_algorithm(self, parameters: Dict[str, Any]) -> Union[None, Dict[str, Any]]:
    """
    Run the processing algorithm.

    :param parameters: Dictionary of parameters.
    :type parameters: Dict[str, Any]

    :returns: Output of the processing algorithm.
    :rtype: Union[None, Dict[str, Any]]
    """
    return processing.run(
        self.algorithm_id,
        parameters,
        feedback=self.feedback,
        context=self.context,
        is_child_algorithm=self.is_child_algorithm,
    )

is_path_valid(parameters)

Check validity of the output path if it is provided.

Parameters:

Name Type Description Default
parameters typing.Union[None, typing.Dict[str, typing.Any]]

Processing algorithm parameters.

required
Source code in pyqgis_wrapper/processing/base.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def is_path_valid(self, parameters: Union[None, Dict[str, Any]]):
    """
    Check validity of the output path if it is provided.

    :param parameters: Processing algorithm parameters.
    :type parameters: Union[None, Dict[str, Any]]
    """
    if parameters is not None:
        for param in self.algorithm.outputDefinitions():
            if (
                self.algorithm_id in OutputType.override_output_param()
                and param.name().upper()
                in OutputType.override_output_param()[self.algorithm_id]
            ):
                continue
            if parameters[param.name()] not in OutputType.values():
                if not Path(parameters[param.name()]).parents[0].exists():
                    raise FileNotFoundError(
                        f"Provided path for {param.name()} does not exists."
                    )

            else:
                if any(
                    name in self.algorithm_id
                    for name in OutputType.override_algorithm()
                ):
                    parameters[param.name()] = OutputType.override_output(
                        self.algorithm_id, self.context
                    )

preprocess(parameters)

Preprocess algorithm parameters.

Parameters:

Name Type Description Default
parameters typing.Union[None, typing.Dict[str, typing.Any]]

Processing algorithm parameters.

required

Returns:

Type Description
Any

Preprocessed parameters.

Source code in pyqgis_wrapper/processing/base.py
245
246
247
248
249
250
251
252
253
254
255
256
def preprocess(self, parameters: Union[None, Dict[str, Any]]) -> Any:
    """
    Preprocess algorithm parameters.

    :param parameters: Processing algorithm parameters.
    :type parameters: Union[None, Dict[str, Any]]

    :returns: Preprocessed parameters.
    :rtype: Any
    """
    self.is_path_valid(parameters)
    return parameters

postprocess(output)

Post-process algorithm output.

Parameters:

Name Type Description Default
output typing.Union[None, typing.Dict[str, typing.Any]]

Output of the processing algorithm.

required

Returns:

Type Description
Any

Post-processed outputs.

Source code in pyqgis_wrapper/processing/base.py
258
259
260
261
262
263
264
265
266
267
268
def postprocess(self, output: Union[None, Dict[str, Any]]) -> Any:
    """
    Post-process algorithm output.

    :param output: Output of the processing algorithm.
    :type output: Union[None, Dict[str, Any]]

    :returns: Post-processed outputs.
    :rtype: Any
    """
    return output

run(parameters)

Run algorithm and post process results.

Parameters:

Name Type Description Default
parameters typing.Dict[str, typing.Any]

Parameters of algorithm.

required

Returns:

Type Description
Union[None, Dict[str, Any]]

Outputs after post process.

Source code in pyqgis_wrapper/processing/base.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
def run(self, parameters: Dict[str, Any]) -> Union[None, Dict[str, Any]]:
    """
    Run algorithm and post process results.

    :param parameters: Parameters of algorithm.
    :type parameters: Dict[str, Any]

    :returns: Outputs after post process.
    :rtype: Union[None, Dict[str, Any]]
    """
    parameters = self.validate_parameters(parameters)
    parameters = self.preprocess(parameters)
    output = self.run_algorithm(parameters)
    output = self.postprocess(output)
    return output

build_parameters(build_opt=False, output_type=OutputType.TEMP) classmethod

Build the parameters dict with defaultValue and return it to the caller for completion or modification.

Allows the users to not build each parameters himself. Fetching the parameters name can be tedious.

Parameters:

Name Type Description Default
build_opt bool

Build with optional parameters or not, defaults to False

False
output_type typing.Optional[typing.Union[str, pyqgis_wrapper.processing.base.OutputType]]

Define the type of output to build algorithm outputs. Either memory: or TEMPORARY_OUTPUT. If the output is memory you can name your layer with "memory:layer_name" Outputs parameters can then be updated manually in the returned dict. By default it'll us the class output_type

pyqgis_wrapper.processing.base.OutputType.TEMP

Returns:

Type Description
Dict[str:Any]

Dictionnary of parameters for the QgsProcessingAlgorithm

Source code in pyqgis_wrapper/processing/base.py
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@classmethod
def build_parameters(
    cls,
    build_opt: bool = False,
    output_type: Optional[Union[str, OutputType]] = OutputType.TEMP,
) -> Dict[str, Any]:
    """
    Build the parameters dict with defaultValue and return
    it to the caller for completion or modification.

    Allows the users to not build each parameters himself.
    Fetching the parameters name can be tedious.

    :param build_opt: Build with optional parameters or not, defaults to False
    :type build_opt: bool, optional
    :param output_type: Define the type of output to build algorithm outputs. Either memory: or TEMPORARY_OUTPUT.
    If the output is memory you can name your layer with "memory:layer_name"
    Outputs parameters can then be updated manually in the returned dict.
    By default it'll us the class output_type
    :type output_type: Optional[Union[str, OutputType]]

    :return: Dictionnary of parameters for the QgsProcessingAlgorithm
    :rtype: Dict[str:Any]
    """
    return cls()._build_parameters(build_opt=build_opt, output_type=output_type)

help() classmethod

Call the full algorithm description.

Source code in pyqgis_wrapper/processing/base.py
435
436
437
438
439
440
@classmethod
def help(cls):
    """
    Call the full algorithm description.
    """
    processing.algorithmHelp(cls.algorithm_id)

apply(parameters, feedback=QgsProcessingFeedback(), context=QgsProcessingContext(), is_child_algorithm=True) classmethod

Build QGIS Algorithm and run it.

Parameters:

Name Type Description Default
parameters typing.Dict[str, typing.Any]

Dict of parameters.

required
feedback qgis.core.QgsProcessingFeedback

QgsProcessingFeedback to use for algorithm.

qgis.core.QgsProcessingFeedback()
context qgis.core.QgsProcessingContext

QgsProcessing context.

qgis.core.QgsProcessingContext()
is_child_algorithm bool

If True the outputs will be added to the provided context. Giving the ownership of the outputs to the caller.

True

Returns:

Type Description
Union[None, Any, Tuple[Any, ...]]

Return.

Source code in pyqgis_wrapper/processing/base.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
@classmethod
def apply(
    cls,
    parameters: Dict[str, Any],
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    context: QgsProcessingContext = QgsProcessingContext(),
    is_child_algorithm: bool = True,
) -> Union[None, Dict[str, Any]]:
    """
    Build QGIS Algorithm and run it.

    :param parameters: Dict of parameters.
    :type parameters: Dict[str, Any]
    :param feedback: QgsProcessingFeedback to use for algorithm.
    :type feedback: QgsProcessingFeedback
    :param context: QgsProcessing context.
    :type context: QgsProcessingContext
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool

    :returns: Return.
    :rtype: Union[None, Any, Tuple[Any, ...]]
    """

    return cls(
        feedback=feedback, context=context, is_child_algorithm=is_child_algorithm
    ).run(parameters)

build_and_run(build_opt=False, output_type=OutputType.TEMP, feedback=QgsProcessingFeedback(), context=QgsProcessingContext(), is_child_algorithm=True, parameters=None, **kwargs) classmethod

Convenience method to automatically build parameters, update them and run the algorithm.

It accepts a dict of parameters through parameters or named arguments through kwargs It'll raise an error if the key is not avaialable in the parameetrs dict. It'll raise an error if it's missing required parameters.

Parameters:

Name Type Description Default
build_opt bool

Build with optional parameters or not, defaults to False

False
output_type typing.Optional[typing.Union[str, pyqgis_wrapper.processing.base.OutputType]]

Define the type of output to build algorithm outputs. Either memory: or TEMPORARY_OUTPUT. If the output is memory you can name your layer with "memory:layer_name" Outputs parameters can then be updated manually in the returned dict. By default it'll us the class output_type

pyqgis_wrapper.processing.base.OutputType.TEMP
feedback qgis.core.QgsProcessingFeedback

QgsProcessingFeedback to use for algortihm., defaults to None

qgis.core.QgsProcessingFeedback()
context qgis.core.QgsProcessingContext

Context where the algorithm is executed, defaults to None

qgis.core.QgsProcessingContext()
is_child_algorithm bool

If True the outputs will be added to the provided context. Giving the ownership of the outputs to the caller.

True
parameters typing.Optional[typing.Dict[str, typing.Any]]

Dict of parameters, defaults to None

None

Returns:

Type Description
Union[None, Dict[str, Any]]

Results of the processing algorithm

Source code in pyqgis_wrapper/processing/base.py
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
@classmethod
def build_and_run(
    cls,
    build_opt: bool = False,
    output_type: Optional[Union[str, OutputType]] = OutputType.TEMP,
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    context: QgsProcessingContext = QgsProcessingContext(),
    is_child_algorithm: bool = True,
    parameters: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Union[None, Dict[str, Any]]:
    """
    Convenience method to automatically build parameters, update them
    and run the algorithm.

    It accepts a dict of parameters through parameters or named arguments through kwargs
    It'll raise an error if the key is not avaialable in the parameetrs dict.
    It'll raise an error if it's missing required parameters.

    :param build_opt: Build with optional parameters or not, defaults to False
    :type build_opt: bool, optional
    :param output_type: Define the type of output to build algorithm outputs. Either memory: or TEMPORARY_OUTPUT.
    If the output is memory you can name your layer with "memory:layer_name"
    Outputs parameters can then be updated manually in the returned dict.
    By default it'll us the class output_type
    :type output_type: Optional[Union[str, OutputType]], optional
    :param feedback: QgsProcessingFeedback to use for algortihm., defaults to None
    :type feedback: Optional[QgsProcessingFeedback], optional
    :param context: Context where the algorithm is executed, defaults to None
    :type context: Optional[QgsProcessingContext], optional
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool
    :param parameters: Dict of parameters, defaults to None
    :type parameters: Optional[Dict[str, Any]], optional

    :return: Results of the processing algorithm
    :rtype: Union[None, Dict[str, Any]]
    """
    instance = cls(
        feedback=feedback, context=context, is_child_algorithm=is_child_algorithm
    )
    params = instance._build_parameters(
        build_opt=build_opt, output_type=output_type
    )

    if parameters is not None:
        parameters.update(kwargs)
    elif kwargs is not None:
        parameters = kwargs
    else:
        raise ValueError(
            "You must give either a parameters arguments or keyword arguments."
        )

    # We check the input parameters and then update with the constrcuted params.
    # It just match the case needed for parameter but does not check if
    # the provided parameters include all the REQUIRED parameters
    # Later a second function call will check the updated parameters too see
    # if all REQUIRED parameters are effectively provided.
    parameters = instance.validate_parameters(parameters)
    params.update(parameters)

    return instance.run(params)

InPlaceAlgorithm(context=QgsProcessingContext(), feedback=QgsProcessingFeedback(), is_child_algorithm=True)

Bases: pyqgis_wrapper.processing.base.QgisAlgorithm

Wrapper for processing algorithms for algorithms which does in place modifications on inputs.

Source code in pyqgis_wrapper/processing/base.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    context: QgsProcessingContext = QgsProcessingContext(),
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    is_child_algorithm: bool = True,
):
    """
    :param context: Processing context.
    :type context: QgsProcessingContext, optional
    :param feedback: Processing feedback.
    :type feedback: QgsProcessingFeedback, optional
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool
    """

    self._load_algorithm()
    self.available_parameters = self.get_available_params()
    self.required_parameters = self.get_required_parameters()
    self.optional_parameters = self.get_optionnal_parameters()
    self.context = context
    self.feedback = feedback
    self.is_child_algorithm = is_child_algorithm

VectorAlgorithm(spatial_index=True, *args, **kwargs)

Bases: pyqgis_wrapper.processing.base.QgisAlgorithm

Wrapper for processing algorithms which does vector layers processing.

Parameters:

Name Type Description Default
spatial_index bool

To create a spatial index on output vector layers. Defaults to True.

True
Source code in pyqgis_wrapper/processing/base.py
551
552
553
554
555
556
557
558
559
560
561
562
def __init__(
    self,
    spatial_index: bool = True,
    *args,
    **kwargs,
):
    """
    :param spatial_index: To create a spatial index on output vector layers. Defaults to True.
    :type spatial_index: bool, optional
    """
    self.spatial_index = spatial_index
    super().__init__(*args, **kwargs)

create_spatial_index(layer)

Create spatial index on layer.

Parameters:

Name Type Description Default
layer qgis.core.QgsVectorLayer

Layer to produce spatial index on.

required
Source code in pyqgis_wrapper/processing/base.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def create_spatial_index(self, layer: QgsVectorLayer):
    """
    Create spatial index on layer.

    :param layer: Layer to produce spatial index on.
    :type layer: QgsVectorLayer
    """
    processing.run(
        "native:createspatialindex",
        {"INPUT": layer},
        feedback=self.feedback,
        context=self.context,
        is_child_algorithm=self.is_child_algorithm,
    )

postprocess(outputs)

Post process outputs. Add spatial index to output vector layer.

Parameters:

Name Type Description Default
output typing.Dict[str, typing.Any]

Dict of algorithm outputs.

required

Returns:

Type Description
Dict[str, Any]

Algorithm's output.

Source code in pyqgis_wrapper/processing/base.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def postprocess(self, outputs: Dict[str, Any]) -> Dict[str, Any]:
    """
    Post process outputs. Add spatial index to output vector layer.

    :param output: Dict of algorithm outputs.
    :type output: Dict[str, Any]

    :returns: Algorithm's output.
    :rtype: Dict[str, Any]
    """

    outputs = self._load_layers(outputs)
    # Je laisserais en dict perso pour pas filtrer des sorties secondaires.
    # La structure si dessous évite une double itératon sur les outputs
    if self.spatial_index:
        for k, output in outputs.items():
            if isinstance(output, QgsVectorLayer):
                self.create_spatial_index(output)
    # outputs = outputs[0] if len(outputs) == 1 else tuple(outputs)

    return outputs

apply(parameters, spatial_index=True, feedback=QgsProcessingFeedback(), context=QgsProcessingContext(), is_child_algorithm=True) classmethod

Build QGIS Algorithm and run it.

Parameters:

Name Type Description Default
parameters typing.Dict[str, typing.Any]

Dict of parameters.

required
spatial_index bool

To create a spatial index on output vector layers. Defaults to True.

True
feedback qgis.core.QgsProcessingFeedback

QgsProcessingFeedback to use for algorithm.

qgis.core.QgsProcessingFeedback()
context qgis.core.QgsProcessingContext

QgsProcessing context.

qgis.core.QgsProcessingContext()
is_child_algorithm bool

If True the outputs will be added to the provided context. Giving the ownership of the outputs to the caller.

True

Returns:

Type Description
Union[None, Dict[str, Any]]

Return.

Source code in pyqgis_wrapper/processing/base.py
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
@classmethod
def apply(
    cls,
    parameters: Dict[str, Any],
    spatial_index: bool = True,
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    context: QgsProcessingContext = QgsProcessingContext(),
    is_child_algorithm: bool = True,
) -> Union[None, Dict[str, Any]]:
    """
    Build QGIS Algorithm and run it.

    :param parameters: Dict of parameters.
    :type parameters: Dict[str, Any]
    :param spatial_index: To create a spatial index on output vector layers. Defaults to True.
    :type spatial_index: bool, optional
    :param feedback: QgsProcessingFeedback to use for algorithm.
    :type feedback: QgsProcessingFeedback
    :param context: QgsProcessing context.
    :type context: QgsProcessingContext
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool

    :returns: Return.
    :rtype: Union[None, Dict[str, Any]]
    """
    return cls(
        feedback=feedback,
        context=context,
        is_child_algorithm=is_child_algorithm,
        spatial_index=spatial_index,
    ).run(parameters)

build_and_run(build_opt=False, output_type=OutputType.TEMP, feedback=QgsProcessingFeedback(), context=QgsProcessingContext(), is_child_algorithm=True, spatial_index=True, parameters=None, **kwargs) classmethod

Convenience method to automatically build parameters, update them and run the algorithm.

It accepts a dict of parameters through parameters or named arguments through kwargs It'll raise an error if the key is not avaialable in the parameetrs dict. It'll raise an error if it's missing required parameters.

Parameters:

Name Type Description Default
build_opt bool

Build with optional parameters or not, defaults to False

False
output_type typing.Optional[typing.Union[str, pyqgis_wrapper.processing.base.OutputType]]

Define the type of output to build algorithm outputs. Either memory: or TEMPORARY_OUTPUT. If the output is memory you can name your layer with "memory:layer_name" Outputs parameters can then be updated manually in the returned dict. By default it'll us the class output_type

pyqgis_wrapper.processing.base.OutputType.TEMP
feedback qgis.core.QgsProcessingFeedback

QgsProcessingFeedback to use for algortihm., defaults to None

qgis.core.QgsProcessingFeedback()
context qgis.core.QgsProcessingContext

Context where the algorithm is executed, defaults to None

qgis.core.QgsProcessingContext()
is_child_algorithm bool

If True the outputs will be added to the provided context. Giving the ownership of the outputs to the caller.

True
spatial_index bool

To create a spatial index on output vector layers. Defaults to True.

True
parameters typing.Optional[typing.Dict[str, typing.Any]]

Dict of parameters, defaults to None

None

Returns:

Type Description
Union[None, Dict[str, Any]]

Results of the processing algorithm

Source code in pyqgis_wrapper/processing/base.py
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
@classmethod
def build_and_run(
    cls,
    build_opt: bool = False,
    output_type: Optional[Union[str, OutputType]] = OutputType.TEMP,
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    context: QgsProcessingContext = QgsProcessingContext(),
    is_child_algorithm: bool = True,
    spatial_index: bool = True,
    parameters: Optional[Dict[str, Any]] = None,
    **kwargs: Any,
) -> Union[None, Dict[str, Any]]:
    """
    Convenience method to automatically build parameters, update them
    and run the algorithm.

    It accepts a dict of parameters through parameters or named arguments through kwargs
    It'll raise an error if the key is not avaialable in the parameetrs dict.
    It'll raise an error if it's missing required parameters.

    :param build_opt: Build with optional parameters or not, defaults to False
    :type build_opt: bool, optional
    :param output_type: Define the type of output to build algorithm outputs. Either memory: or TEMPORARY_OUTPUT.
    If the output is memory you can name your layer with "memory:layer_name"
    Outputs parameters can then be updated manually in the returned dict.
    By default it'll us the class output_type
    :type output_type: Optional[Union[str, OutputType]], optional
    :param feedback: QgsProcessingFeedback to use for algortihm., defaults to None
    :type feedback: Optional[QgsProcessingFeedback], optional
    :param context: Context where the algorithm is executed, defaults to None
    :type context: Optional[QgsProcessingContext], optional
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool
    :param spatial_index: To create a spatial index on output vector layers. Defaults to True.
    :type spatial_index: bool, optional
    :param parameters: Dict of parameters, defaults to None
    :type parameters: Optional[Dict[str, Any]], optional

    :return: Results of the processing algorithm
    :rtype: Union[None, Dict[str, Any]]
    """
    instance = cls(
        feedback=feedback,
        context=context,
        is_child_algorithm=is_child_algorithm,
        spatial_index=spatial_index,
    )
    params = instance._build_parameters(
        build_opt=build_opt, output_type=output_type
    )

    if parameters is not None:
        parameters.update(kwargs)
    elif kwargs is not None:
        parameters = kwargs
    else:
        raise ValueError(
            "You must give either a parameters arguments or keyword arguments."
        )

    # We check the input parameters and then update with the constrcuted params.
    # It just match the case needed for parameter but does not check if
    # the provided parameters include all the REQUIRED parameters
    # Later a second function call will check the updated parameters too see
    # if all REQUIRED parameters are effectively provided.
    parameters = instance.validate_parameters(parameters)
    params.update(parameters)

    return instance.run(params)

RasterAlgorithm(context=QgsProcessingContext(), feedback=QgsProcessingFeedback(), is_child_algorithm=True)

Bases: pyqgis_wrapper.processing.base.QgisAlgorithm

Wrapper for processing algorithms which does raster layers processing.

Source code in pyqgis_wrapper/processing/base.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    context: QgsProcessingContext = QgsProcessingContext(),
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    is_child_algorithm: bool = True,
):
    """
    :param context: Processing context.
    :type context: QgsProcessingContext, optional
    :param feedback: Processing feedback.
    :type feedback: QgsProcessingFeedback, optional
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool
    """

    self._load_algorithm()
    self.available_parameters = self.get_available_params()
    self.required_parameters = self.get_required_parameters()
    self.optional_parameters = self.get_optionnal_parameters()
    self.context = context
    self.feedback = feedback
    self.is_child_algorithm = is_child_algorithm

postprocess(outputs)

Post process outputs. Add spatial index to output vector layer.

Parameters:

Name Type Description Default
output typing.Dict[str, typing.Any]

Dict of algorithm outputs.

required

Returns:

Type Description
Dict[str, Any]

Algorithm's output.

Source code in pyqgis_wrapper/processing/base.py
783
784
785
786
787
788
789
790
791
792
793
794
795
def postprocess(self, outputs: Dict[str, Any]) -> Dict[str, Any]:
    """
    Post process outputs. Add spatial index to output vector layer.

    :param output: Dict of algorithm outputs.
    :type output: Dict[str, Any]

    :returns: Algorithm's output.
    :rtype: Dict[str, Any]
    """
    outputs = self._load_layers(outputs)

    return outputs

PointCloudAlgorithm(context=QgsProcessingContext(), feedback=QgsProcessingFeedback(), is_child_algorithm=True)

Bases: pyqgis_wrapper.processing.base.QgisAlgorithm

Wrapper for processing algortihms which does raster layers processing.

Source code in pyqgis_wrapper/processing/base.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    context: QgsProcessingContext = QgsProcessingContext(),
    feedback: QgsProcessingFeedback = QgsProcessingFeedback(),
    is_child_algorithm: bool = True,
):
    """
    :param context: Processing context.
    :type context: QgsProcessingContext, optional
    :param feedback: Processing feedback.
    :type feedback: QgsProcessingFeedback, optional
    :param is_child_algorithm: If True the outputs will be added to the provided context.
    Giving the ownership of the outputs to the caller.
    :type is_child_algorithm: bool
    """

    self._load_algorithm()
    self.available_parameters = self.get_available_params()
    self.required_parameters = self.get_required_parameters()
    self.optional_parameters = self.get_optionnal_parameters()
    self.context = context
    self.feedback = feedback
    self.is_child_algorithm = is_child_algorithm

OutputType

Bases: str, enum.Enum

Class to store output type

override_algorithm() classmethod

Dict to check if the algorithm doesn't handle TEMP or memory output

Returns:

Type Description
Dict[str, str]

Dict with algorithm id as keys and extension as values

Source code in pyqgis_wrapper/processing/base.py
51
52
53
54
55
56
57
58
59
@classmethod
def override_algorithm(cls) -> Dict[str, str]:
    """
    Dict to check if the algorithm doesn't handle TEMP or memory output

    :return: Dict with algorithm id as keys and extension as values
    :rtype: Dict[str, str]
    """
    return {"grass:v.net.distance": ".gpkg", "grass:v.net": ".gpkg"}

override_output(algorithm_id, context=QgsProcessingContext()) classmethod

Some algorithms (grass or saga) doesn't handle TEMPORARY OUTPUT outside qgis. This functions allows an override check and create a temp file in temp directory if a path is not provided. The list should be expanded as needed.

Parameters:

Name Type Description Default
algorithm_id str

algorithm_id

required
context qgis.core.QgsProcessingContext

Processing context.

qgis.core.QgsProcessingContext()

Returns:

Type Description
Dict[str, str]

Dict of "incorrect behavior algorithm" id as keys and tempfile name as values

Source code in pyqgis_wrapper/processing/base.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@classmethod
def override_output(
    cls, algorithm_id: str, context: QgsProcessingContext = QgsProcessingContext()
) -> Dict[str, str]:
    """
    Some algorithms (grass or saga) doesn't handle TEMPORARY OUTPUT outside qgis.
    This functions allows an override check and create a
    temp file in temp directory if a path is not provided. The list should be expanded as needed.

    :param algorithm_id: algorithm_id
    :type algorithm_id: str
    :param context: Processing context.
    :type context: QgsProcessingContext, optional
    :return: Dict of "incorrect behavior algorithm" id as keys and tempfile name as values
    :rtype: Dict[str, str]
    """
    file_name = str(uuid.uuid4()) + cls.override_algorithm()[algorithm_id]
    return QgsProcessingUtils.generateTempFilename(file_name, context=context)