In numpy one can create a matrix and use the handy slice notation
arr=np.array([[1,2,3], [4,5,6], [7, 8, 9], [10,11,12]])
print (arr[2, :])
print (arr[1:2, 2])
And this can be extended up to N dimensions.
But what now if one I wish to have the same thing, but one axis is instead of being a numeric axis, it is a string-based axis? So indexing an element would be like:
print(arr["cylinder", :, :]) #prints all cylinders
print(arr["sphere", 4, 100]) #prints sphere of 4 radius, 100 bar
print(arr[:, 4, 100]) #prints every shape with 4 radius 100 bar
I could make for each "combination" (all shapes, specific radius, specific pressure ... all shapes, all radii, specific pressure ... specific shape, specific radius, specific pressure). A unique function but that is infeasible, so how can I create this?
Currently everything is stored as dictionaries of dictionaries (especially because only values for radius and pressure are used). If the underlying storage could be kept as dictionaries of dictionaries - but adding the slice/index operators that woudl be golden!
current code (and yes I do have the idea to look into kwargs to make the current codebase better for adding new points) - this is just added to prevent the "NP" problem issue:
class all_measurements(object):
def __init__(self):
self.measurements = {}
def add_measurement(self, measurement):
shape = measurement.shape
size = measurement.size
pressure = measurement.pressure
fname = measurement.filename
if shape in self.measurements:
shape_dict = self.measurements[shape]
else:
shape_dict = {}
self.measurements[shape] = shape_dict
if size in shape_dict:
size_dict = shape_dict[size]
else:
size_dict ={}
shape_dict[size] = size_dict
if pressure in size_dict:
pressure_dict = size_dict[pressure]
else:
pressure_dict = {}
size_dict[pressure] = pressure_dict
if fname in pressure_dict:
print("adding same file twice!")
pressure_dict[fname] = measurement
def get_measurements(self, shape = None, size = None, pressure = None, fname = None):
current_dict = self.measurements
if shape is None:
return current_dict
if shape in current_dict:
current_dict = current_dict[shape]
else:
return None
if size is None:
return current_dict
if size in current_dict:
current_dict = current_dict[size]
else:
return None
if pressure is None:
return current_dict
if pressure in current_dict:
current_dict = current_dict[pressure]
else:
return None
if fname is None:
return current_dict
if fname in current_dict:
return current_dict[fname]
else:
return None
__getitem__
and__getslice__
methods to your class to get indexing syntax. Of course it's your responsibility to interpret the index or slice, and return the correct item. – hpaulj Mar 24 '15 at 2:57