2

I make points everyday and make it into a polygon and merge it to the previous polygon I have already made

enter image description here

The format of the points are in yyyy-mm-dd_Points and the polygon format is yyyymmdd_progress which is stored in my folder.

My code primarily generates polygon (variable polygon) by buffer (but I'm also open to suggestions better way to generate polygon from points), then I will manually paste the directory to the variable lay1, then it will get merged.

How can I get the directory of the layer I want to merge with the polygon I just created?

So this is my code:

  from qgis import processing
from datetime import datetime, timedelta

path_file = f'C:/Users/CMCA/Downloads'

date = datetime.strftime(datetime.now() - timedelta(2), "%Y%m%d") lay1 = path_file +'/'+f'{date}'+'_progress'+'.gpkg'

#lay1 = 'C:/Users/CMCA/OneDrive - Boskalis/Documents/20230323_PVDprogress.gpkg' inlayDir = iface.activeLayer()

print("Start Polygon Process...") print("Generating polygon") polygon = processing.runAndLoadResults("native:buffer", {'INPUT':inlayDir, 'DISTANCE':1.5, 'SEGMENTS':2, 'END_CAP_STYLE':0, 'JOIN_STYLE':0, 'MITER_LIMIT':2, 'DISSOLVE':True, 'OUTPUT':'TEMPORARY_OUTPUT'})

polygon = polygon['OUTPUT'] columns_to_delete_indx = polygon.attributeList() polygon.startEditing() polygon.dataProvider().deleteAttributes(columns_to_delete_indx) polygon.commitChanges()

print("merging...") merge = processing.runAndLoadResults("native:mergevectorlayers",{'LAYERS':[lay1,polygon], 'CRS':QgsCoordinateReferenceSystem('USER:100000'), 'OUTPUT':'TEMPORARY_OUTPUT'})

Error:

  Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 31, in <module>
AttributeError: 'str' object has no attribute 'attributeList'

This is the whole code I've done so far but I am having trouble with the errors :

    from qgis import processing
    from datetime import datetime, timedelta
path_file = f'C:/Users/CMCA/Downloads'

date = datetime.strftime(datetime.now() - timedelta(2), &quot;%Y%m%d&quot;) # or &quot;%Y%m%d_%H%M%S&quot;
lay1 = path_file +'/'+f'{date}'+'_progress'+'.gpkg'

#lay1 = 'C:/Users/CMCA/OneDrive - Boskalis/Documents/20230327_PVDprogress.gpkg'
inlayDir = iface.activeLayer()
P3_boundary = 'D:/QGIS/General/PhaseRev3_BoundariesOutside_v2.gpkg'

clustering = processing.runAndLoadResults(&quot;native:dbscanclustering&quot;,
                                          {'INPUT':inlayDir,
                                          'MIN_SIZE':5,
                                          'EPS':2,
                                          'DBSCAN*':False,
                                          'FIELD_NAME':'CLUSTER_ID',
                                          'SIZE_FIELD_NAME':'CLUSTER_SIZE',
                                          'OUTPUT':'TEMPORARY_OUTPUT'})

concave_Hull = processing.runAndLoadResults(&quot;qgis:concavehull&quot;,
                                            {'INPUT':clustering['OUTPUT'],
                                            'ALPHA':0.01,
                                            'HOLES':True,
                                            'NO_MULTIGEOMETRY':True,
                                            'OUTPUT':'TEMPORARY_OUTPUT'})
print(&quot;Generating polygon&quot;)

buffer = processing.run(&quot;native:buffer&quot;,
              {'INPUT':concave_Hull['OUTPUT'],
               'DISTANCE':1,
               'SEGMENTS':5,
               'END_CAP_STYLE':2,
               'JOIN_STYLE':0,
               'MITER_LIMIT':2,
               'DISSOLVE':True,
               'OUTPUT':'TEMPORARY_OUTPUT'})


polygon = buffer['OUTPUT']
columns_to_delete_indx = polygon.attributeList()
polygon.startEditing()
polygon.dataProvider().deleteAttributes(columns_to_delete_indx)
polygon.commitChanges()
polygon = iface.activeLayer()

print(&quot;merging...&quot;)

merge = processing.runAndLoadResults(&quot;native:mergevectorlayers&quot;,{'LAYERS':[lay1,polygon],
                                         'CRS':QgsCoordinateReferenceSystem('USER:100000'),
                                         'OUTPUT':'TEMPORARY_OUTPUT'})



Error: Generating polygon merging... Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "<string>", line 53, in <module> File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python/plugins\processing\tools\general.py", line 151, in runAndLoadResults return Processing.runAlgorithm(alg, parameters=parameters, onFinish=handleAlgorithmResults, feedback=feedback, File "C:\PROGRA~1/QGIS32~1.0/apps/qgis/./python/plugins\processing\core\Processing.py", line 181, in runAlgorithm raise QgsProcessingException(msg) _core.QgsProcessingException: Unable to execute algorithm Incorrect parameter value for LAYERS

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
charliey
  • 163
  • 7
  • 1
    I'm not clear from the current version of your question what your process is, or what specifically you are asking for help with. Can you clarify? – Tom Brennan Mar 26 '23 at 07:23
  • i edited my statement above , I hope this is clear – charliey Mar 26 '23 at 13:43
  • 1
    The error you get is because dir is a reserved keyword in Python. Hence the built-in function or method part of the error. Having said that, you can't have defined your dir variable because if you had, it would have overwritten the built-in function. – Matt Mar 26 '23 at 13:55
  • I edited it again .. the path_file , date is concatenated in lay1 variable. and it suppose to fine the layer with that file name . but i still get an error – charliey Mar 26 '23 at 14:01
  • 2
    Does the error correspond to the new code? According to the code in your question you are no longer trying to add a built-in function or method and a string. Please include all relevant code, otherwise it is difficult to help you. You also miss the f from the beginning of your f string (the string with the curly braces {}). – Matt Mar 26 '23 at 15:15
  • I edited my script, with what you have noticed, but it gave me new error. – charliey Mar 27 '23 at 09:43
  • polygon['OUTPUT'] is just a string, the path to the file where the temporary output is stored. You need to use processing.run (not runAndLoadResults) - the OUTPUT from that is a QgsVectorLayer, which will allow you to use .attributeList() – Tom Brennan Mar 27 '23 at 10:01
  • 2
    This thread is becoming very muddled with the error reported being changed, reframing of the question, and now two different scripts at once. There are already 2 valid answers to the problem previously stated. I would recommend rolling back your edits and opening a new question for your new problem. – Matt Mar 29 '23 at 08:55

2 Answers2

6

In the last version of your question, use processing.run instead of processing.runAndLoadResults. Because runAndLoadResults methods returns {'OUTPUT': 'buffer_0ae....'}. So polygon['OUTPUT'] gives you a string. That's why you're getting the error.

Instead, use processing.run. It returns {'OUTPUT': <qgis._core.QgsVectorLayer object at 0x00...>}. In this case, polygon["OUTPUT"] gives you the layer reference in memory and you don't get that error.

Please review this answer for more detailed information.

In a nutshell, use this:

polygon = processing.run("native:buffer", ... 
polygon = polygon['OUTPUT']

If you need to add the buffer layer to the project, use also:

QgsProject.instance().addMapLayer(polygon)
Kadir Şahbaz
  • 76,800
  • 56
  • 247
  • 389
4

Calling 'OUTPUT' on the result of processing.runAndLoadResults returns a Map Layer ID (a string), not a QgsMapLayer.

Add this to get a reference to the layer:

polygon = polygon['OUTPUT']

add this line

polygon = QgsProject.instance().mapLayer(polygon)

should now work

columns_to_delete_indx = polygon.attributeList()

Matt
  • 16,843
  • 3
  • 21
  • 52
  • I have added the whole script i made so far here, if you could please check what is wrong ? – charliey Mar 29 '23 at 05:29
  • I got another Error: Traceback (most recent call last): File "C:\PROGRA~1\QGIS32~1.0\apps\Python39\lib\code.py", line 90, in runcode exec(code, self.locals) File "", line 1, in File "", line 45, in TypeError: QgsProject.mapLayer(): argument 1 has unexpected type 'QgsVectorLayer' – charliey Mar 29 '23 at 09:09