0

I am trying to create a data structure that will be used for geospatial decomposition - basically take a top 10x10 grid and be able to decompose each grid within it. I am using namedtuples for the structure. And to replicate the structure for the lower level I am using an "object" type in a cell so it can contain a lower-layer grid.

The code is below, and I am getting an error below when I assign the nestedGrid to the object type. How can I achieve my desired outcome?

Traceback (most recent call last): File "/Users/bryon/git_repo/SIT719/Task_9_1HD/main.py", line 53, in adaptivegrid.adaptivegrid(working_dataset, bounds, task_lat, task_long, "adaptive0.html") File "/Users/bryon/git_repo/SIT719/Task_9_1HD/adaptivegrid.py", line 47, in adaptivegrid c1.lowerGrid = nestedGrid AttributeError: can't set attribute

from collections import namedtuple
import pandas as pd
import numpy as np

Point = namedtuple('Point', 'x y')
pt1 = Point(1.0, 5.0)
pt2 = Point(2.5, 1.5)
print(pt1, pt2)

Coord = namedtuple('Coord', 'lat long')
Bounds = namedtuple('Bounds', 'llCoord urCoord')
Cell = namedtuple('Cell', 'Bounds noisyCount lowerGrid')

# Calculate the grid and store in a data structure. Structure should have:
# 
pt1 = Coord(1.0, 2.0)
pt2 = Coord(5.0, 6.0)
b = Bounds(pt1, pt2)
cell = Cell(b, 7.2, object)

# Create a 10x10 grid of Cells and set [0][0] to some test data
grid = np.empty(shape=(10,10), dtype=object)
grid[0][0] = cell

# Now create a nested grid in in grid[0][0]
c1 = grid[0][0]

# Create a 2x2 grid to nest
nestedGrid = np.empty(shape=(2,2), dtype=object)
# Assign the nested grid to [0][0]
c1.lowerGrid = nestedGrid

# Create some test data for thenested grid and store in [1][1] of the nested grid
c2 = Cell(b, 3.14, object)
nestedGrid[1][1] = c2

# Print the  cell in the nested grid
print(grid[0][0].lowerGrid[1][1])  
Bryon
  • 939
  • 13
  • 25

1 Answers1

0

Namedtuples are immutable like normal tuples. So you can not change a value. But there is the _replace method which replaces a value by creating a new instance.

Instead of

# Assign the nested grid to [0][0]
c1.lowerGrid = nestedGrid

do

# Assign the nested grid to [0][0]
grid[0][0] = grid[0][0]._replace(lowerGrid=nestedGrid)

(You cannot assign this here to c1, because this will change only the variable c1, not the value in the grid)

Sven Eberth
  • 3,057
  • 12
  • 24
  • 29