Source code for compas.datastructures.datastructure
from__future__importprint_functionfrom__future__importabsolute_importfrom__future__importdivisionimportjsonfromcopyimportdeepcopyfromcompas.utilitiesimportDataEncoderfromcompas.utilitiesimportDataDecoderfromcompas.baseimportBase__all__=['Datastructure']classDatastructure(Base):def__init__(self):super(Datastructure,self).__init__()def__str__(self):"""Generate a readable representation of the data of the datastructure."""returnjson.dumps(self.data,sort_keys=True,indent=4)@classmethoddeffrom_data(cls,data):"""Construct a datastructure from structured data. Parameters ---------- data : dict The data dictionary. Returns ------- :class:`compas.datastructures.Datastructure` An object of the type of ``cls``. Notes ----- This constructor method is meant to be used in conjunction with the corresponding *to_data* method. """datastructure=cls()datastructure.data=datareturndatastructuredefto_data(self):"""Returns a dictionary of structured data representing the data structure. Returns ------- dict The structured data. Notes ---- This method produces the data that can be used in conjunction with the corresponding *from_data* class method. """returnself.data@classmethoddeffrom_json(cls,filepath):"""Construct a datastructure from structured data contained in a json file. Parameters ---------- filepath : str The path to the json file. Returns ------- :class:`compas.datastructures.Datastructure` An object of the type of ``cls``. Notes ----- This constructor method is meant to be used in conjunction with the corresponding *to_json* method. """withopen(filepath,'r')asfp:data=json.load(fp,cls=DataDecoder)datastructure=cls()datastructure.data=datareturndatastructuredefto_json(self,filepath,pretty=False):"""Serialise the structured data representing the datastructure to json. Parameters ---------- filepath : str The path to the json file. """withopen(filepath,'w+')asf:ifpretty:json.dump(self.data,f,sort_keys=True,indent=4,cls=DataEncoder)else:json.dump(self.data,f,cls=DataEncoder)defcopy(self,cls=None):"""Make an independent copy of the datastructure object. Parameters ---------- cls : :class:`compas.datastructure.Datastructure`, optional The type of datastructure to return. Defaults to the type of the current datastructure. Returns ------- :class:`compas.datastructure.Datastructure` A separate, but identical datastructure object. """ifnotcls:cls=type(self)returncls.from_data(deepcopy(self.data))# ==============================================================================## ==============================================================================if__name__=='__main__':pass