Utilities¶
Plugin utilities
CustomJsonEncoder ¶
FileUtils ¶
Provides functionality for commonly used file-related operations.
copy_file
staticmethod
¶
Copies file to the target directory
Source code in src/cplus_plugin/utils.py
create_comparison_reports_dir
staticmethod
¶
Creates a comparison reports subdirectory under the base directory. Skips creation of the subdirectory if it already exists.
Source code in src/cplus_plugin/utils.py
create_ncs_carbon_dir
staticmethod
¶
Creates an NCS subdirectory for carbon layers under BASE_DIR. Skips creation of the subdirectory if it already exists.
Source code in src/cplus_plugin/utils.py
create_ncs_pathways_dir
staticmethod
¶
Creates an NCS subdirectory under BASE_DIR. Skips creation of the subdirectory if it already exists.
Source code in src/cplus_plugin/utils.py
create_new_dir
staticmethod
¶
Creates new file directory if it doesn't exist
Source code in src/cplus_plugin/utils.py
create_new_file
staticmethod
¶
Creates new file
create_npv_pwls_dir
staticmethod
¶
Creates an NPV PWL subdirectory under PWL child directory in the base directory. Skips creation of the subdirectory if it already exists.
Source code in src/cplus_plugin/utils.py
create_pwls_dir ¶
Creates priority weighting layers subdirectory under BASE_DIR. Skips creation of the subdirectory if it already exists.
Source code in src/cplus_plugin/utils.py
get_fonts_dir
staticmethod
¶
Returns the fonts directory in the plugin.
Returns:
| Type | Description |
|---|---|
str
|
Fonts directory. |
get_icon
staticmethod
¶
Creates an icon based on the icon name in the 'icons' folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name |
str
|
File name which should include the extension. |
required |
Returns:
| Type | Description |
|---|---|
QtGui.QIcon
|
Icon object matching the file name. |
Source code in src/cplus_plugin/utils.py
get_icon_path
staticmethod
¶
Gets the full path of the icon with the given name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name |
str
|
File name which should include the extension. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The full path to the icon in the plugin. |
Source code in src/cplus_plugin/utils.py
get_pixmap
staticmethod
¶
Creates a pixmap based on the file name in the 'icons' folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name |
str
|
File name which should include the extension. |
required |
Returns:
| Type | Description |
|---|---|
QtGui.QPixmap
|
Pixmap object matching the file name. |
Source code in src/cplus_plugin/utils.py
plugin_dir
staticmethod
¶
Returns the root directory of the plugin.
Returns:
| Type | Description |
|---|---|
str
|
Root directory of the plugin. |
report_template_path
staticmethod
¶
Get the absolute path to the template file with the given name. Caller needs to verify that the file actually exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_name |
str
|
Template file name including the extension. If none is specified then it will use |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The absolute path to the template file with the given name. |
Source code in src/cplus_plugin/utils.py
align_rasters ¶
align_rasters(input_raster_source, reference_raster_source, extent=None, output_dir=None, rescale_values=False, resample_method=0)
Based from work on https://github.com/inasafe/inasafe/pull/2070 Aligns the passed raster files source and save the results into new files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_raster_source |
str
|
Input layer source |
required |
reference_raster_source |
str
|
Reference layer source |
required |
extent |
list
|
Clip extent |
None
|
output_dir |
str
|
Absolute path of the output directory for the snapped layers |
None
|
rescale_values |
bool
|
Whether to rescale pixel values |
False
|
resample_method |
ResampleAlg
|
Method to use when resampling |
0
|
Source code in src/cplus_plugin/utils.py
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 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
array_from_raster ¶
Read a raster and return the pixel values as numpy array
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_layer |
QgsRasterLayer
|
Input raster layer |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Pixel values as numpy array |
Source code in src/cplus_plugin/utils.py
calculate_raster_area ¶
Calculates the area of value pixels for the given band in a raster layer.
This varies from 'calculate_raster_area_by_pixel_value' in that it gives the total area instead of grouping by pixel value.
Please note that this function will run in the main application thread hence for best results, it is recommended to execute it in a background process if part of a bigger workflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer |
QgsRasterLayer
|
Input layer whose area for value pixels is to be calculated. |
required |
band_number |
int
|
Band number to compute area, default is band one. |
1
|
feedback |
QgsProcessingFeedback
|
Feedback object for progress during area calculation. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
The total area of value pixels of the raster else -1 if the raster is invalid or if it is empty. Pixels with NoData value are not included in the computation. |
Source code in src/cplus_plugin/utils.py
calculate_raster_area_by_pixel_value ¶
Calculates the area of value pixels in hectares for the given band in a raster layer and groups the area by the pixel value.
Please note that this function will run in the main application thread hence for best results, it is recommended to execute it in a background process if part of a bigger workflow.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
layer |
QgsRasterLayer
|
Input layer whose area for value pixels is to be calculated. |
required |
band_number |
int
|
Band number to compute area, default is band one. |
1
|
feedback |
QgsProcessingFeedback
|
Feedback object for progress during area calculation. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
A dictionary containing the pixel value as the key and the corresponding area in hectares as the value for all the pixels in the raster otherwise returns a empty dictionary if the raster is invalid or if it is empty. |
Source code in src/cplus_plugin/utils.py
clean_filename ¶
Creates a safe filename by removing operating system invalid filename characters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename |
str
|
File name |
required |
Source code in src/cplus_plugin/utils.py
compress_raster ¶
compress_raster(input_path, output_path=None, compression_type='DEFLATE', compress_level=6, nodata_value=None, output_format='GTiff', create_options=None, additional_options=None)
Compresses a raster file using GDAL and optionally replace old NoData pixel values with a new one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path |
str
|
Path to the input raster file |
required |
output_path |
str
|
Path to the input raster file. If none the ouput will saved to a temporary file |
None
|
compression_type |
str
|
Compression algorithm (e.g., 'DEFLATE', 'LZW', 'PACKBITS', 'JPEG', 'NONE') |
'DEFLATE'
|
compress_level |
int
|
Compression level (1-9 for DEFLATE/LZW, 1-100 for JPEG) |
6
|
nodata_value |
float
|
Value to set as nodata (default: None). If None, retain the input nodatavalue |
None
|
output_format |
str
|
Output format (default: 'GTiff' for GeoTIFF) |
'GTiff'
|
create_options |
list
|
Additional GDAL creation options as a list |
None
|
additional_options |
list
|
dditional GDAL options as a list |
None
|
Returns:
| Type | Description |
|---|---|
str | None
|
Path to the temporary file if successful, None if failed |
Source code in src/cplus_plugin/utils.py
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 | |
contains_font_family ¶
Checks if the specified font family exists in the font database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
font_family |
str
|
Name of the font family to check. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the font family exists, else False. |
Source code in src/cplus_plugin/utils.py
convert_size ¶
Convert byte size to human readable text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size_bytes |
int
|
byte sizse |
required |
Returns:
| Type | Description |
|---|---|
str
|
human readable text |
Source code in src/cplus_plugin/utils.py
create_connectivity_raster ¶
create_connectivity_raster(input_raster_path, output_raster_path, connectivity_type=8, min_patch_area=None, area_unit='ha')
Computes the pixel connectivity of a given binary raster
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_raster_path |
str
|
Input layer path |
required |
output_raster_path |
str
|
Output layer path |
required |
connectivity_type |
int
|
Number of pixels reachable from the specified pixel in 4- or 8-directional adjacency For 4-directional connectivity → N, S, E, W adjacency For 8-directional connectivity → N, S, E, W, NE, NW, SE, SW adjacency Default to 8 |
8
|
min_patch_area |
float
|
Minimum patch size, default to None |
None
|
area_unit |
str
|
Unit of the patch size i.e ha or m2, defaulto to ha |
'ha'
|
Source code in src/cplus_plugin/utils.py
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 | |
format_value_with_unit ¶
Format a value with an appropriate unit suffix for filename.
The unit is determined based on the metadata_id. Common patterns: - Years/experience: "5years", "10years" - Percentage: "25pct", "50pct" - Weight: "10kg", "25kg" - Default: "12p50" (12.50 with decimal point as 'p')
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value |
float
|
The numeric value |
required |
metadata_id |
str
|
Metadata ID to determine the appropriate unit |
required |
Returns:
| Type | Description |
|---|---|
str
|
Formatted string like "5years", "10pct", "25kg" |
Source code in src/cplus_plugin/utils.py
function_help_to_html ¶
Creates a HTML string containing the detailed help of an expression function.
The specific HTML formatting is deduced from the code here: https://github.com/qgis/QGIS/blob/master/src/core/expression/qgsexpression.cpp#L565
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
function_name |
str
|
Name of the expression function. |
required |
description |
str
|
Detailed description of the function. |
required |
arguments |
List[tuple]
|
List containing the arguments. Each argument should consist of a tuple containing three elements i.e. argument name, description and bool where True will indicate the argument is optional. Take note of the order as mandatory arguments should be first in the list. |
None
|
examples |
List[tuple]
|
Examples of using the function. Each item in the list should be a tuple containing an example expression and the corresponding return value. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The expression function's help in HTML for use in, for example, an expression builder. |
Source code in src/cplus_plugin/utils.py
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 | |
generate_constant_raster_filename ¶
Generate a descriptive filename for a constant raster.
Follows the pattern: {sanitized_component_name}_{value_with_unit}.tif
Example outputs: - "agroforestry_5years.tif" - "corn_production_25pct.tif" - "animal_management_10kg.tif"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component_name |
str
|
Name of the pathway/activity |
required |
value |
float
|
The constant value for this raster |
required |
metadata_id |
str
|
Metadata ID to determine the value unit |
required |
Returns:
| Type | Description |
|---|---|
str
|
Safe filename with extension |
Source code in src/cplus_plugin/utils.py
generate_random_color ¶
Generate a random color object using a system-seeded deterministic approach.
Returns:
| Type | Description |
|---|---|
QColor
|
A random generated color. |
Source code in src/cplus_plugin/utils.py
get_constant_raster_dir ¶
Get the directory path for constant rasters.
Creates a hierarchical directory structure: {base_dir}/{component_type}/{raster_type}/
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_dir |
str
|
Base directory (e.g., "BASE_DIR/constant_rasters") |
required |
component_type |
ModelComponentType
|
Type of model component (NCS_PATHWAY or ACTIVITY) |
required |
metadata_id |
str
|
Raster type ID (e.g., "years_experience_pathway") |
required |
Returns:
| Type | Description |
|---|---|
str
|
Full path to the constant raster directory |
Source code in src/cplus_plugin/utils.py
get_layer_type ¶
Get layer type code from file path
Source code in src/cplus_plugin/utils.py
get_plugin_version ¶
Returns the current plugin version as saved in the metadata.txt plugin file.
Returns:
| Type | Description |
|---|---|
str
|
Plugin version |
Source code in src/cplus_plugin/utils.py
get_report_font ¶
Uses the default font family name to create a font for use in the report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
size |
float
|
The font point size, default is 11. |
11.0
|
bold |
bool
|
True for bold font else False which is the default. |
False
|
italic |
bool
|
True for font to be in italics else False which is the default. |
False
|
Returns:
| Type | Description |
|---|---|
QtGui.QFont
|
Font to use in a report. |
Source code in src/cplus_plugin/utils.py
install_font ¶
Installs the font families in the specified folder name under the plugin's 'fonts' folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dir_name |
str
|
Directory name, under the 'fonts' folder, which contains the font families to be installed. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the font(s) were successfully installed, else False if the directory name does not exist or if the given font families already exist in the application's font database. |
Source code in src/cplus_plugin/utils.py
log ¶
Logs the message into QGIS logs using qgis_cplus as the default log instance. If notify_user is True, user will be notified about the log.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message |
str
|
The log message |
required |
name |
str
|
Name of te log instance, qgis_cplus is the default |
'qgis_cplus'
|
info |
bool
|
Whether the message is about info or a warning |
True
|
notify |
bool
|
Whether to notify user about the log |
True
|
Source code in src/cplus_plugin/utils.py
md5 ¶
Get md5 checksum off a file
normalize_raster ¶
Create a normalized input raster
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_raster_path |
str
|
Input layer path |
required |
output_raster_path |
str
|
Output layer path |
required |
processing_context |
QgsProcessingContext
|
Qgis processing context |
None
|
feedback |
QgsProcessingFeedback
|
Qgis processing feedback |
None
|
Source code in src/cplus_plugin/utils.py
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 | |
open_documentation ¶
Opens documentation website in the default browser
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url |
str
|
URL link to documentation site (e.g. gh pages site) |
None
|
Source code in src/cplus_plugin/utils.py
raster_from_array ¶
Create a QGIS raster layer from a numpy array
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array |
ndarray
|
Input numpy array (2D or 3D) |
required |
extent |
QgsRectangle
|
QgsRectangle with the extent in CRS coordinates |
required |
crs |
QgsCoordinateReferenceSystem
|
Coordinate system |
required |
output_path |
str
|
Optional path to save as GeoTIFF (if None, creates temporary layer) |
None
|
layer_name |
str Returns: QgsRasterLayer
|
Optional name for the layer |
'Numpy Raster'
|
Source code in src/cplus_plugin/utils.py
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 | |
save_constant_raster_metadata ¶
Save metadata for a constant raster to a text file.
Creates a .meta.txt file alongside the raster with information about how it was created.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata |
ConstantRasterFileMetadata
|
ConstantRasterFileMetadata with all metadata information |
required |
raster_dir |
str
|
Directory where the raster file is located |
required |
Returns:
| Type | Description |
|---|---|
str
|
Path to the metadata file |
Source code in src/cplus_plugin/utils.py
todict ¶
Convert any object to dictionary
Source code in src/cplus_plugin/utils.py
tr ¶
Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message |
(str, QString)
|
String for translation. |
required |
Returns:
| Type | Description |
|---|---|
QString
|
Translated version of message. |
Source code in src/cplus_plugin/utils.py
transform_extent ¶
Transforms the passed extent into the destination crs
:param extent: Target extent
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_crs |
QgsCoordinateReferenceSystem
|
Source CRS of the passed extent |
required |
dest_crs |
QgsCoordinateReferenceSystem
|
Destination CRS |
required |
Source code in src/cplus_plugin/utils.py
write_constant_raster_metadata_file ¶
Write constant raster metadata to a text file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata |
ConstantRasterFileMetadata
|
ConstantRasterFileMetadata instance with all metadata information |
required |
file_path |
str
|
Path where the metadata file should be written |
required |
Returns:
| Type | Description |
|---|---|
str
|
Path to the metadata file that was written |
Source code in src/cplus_plugin/utils.py
zip_shapefile ¶
Zip shapefile to an object with same name.
For example, the .shp filename is test_file.shp, then the zip file
name would be test_file.zip
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shapefile_path |
str
|
Path of the shapefile |
required |
Returns:
| Type | Description |
|---|---|
str
|
Zip file path if the specified |