You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 91ba94f
Browse filesBrowse the repository at this point in the historyBrowse files
sections=re.split("(?<=.)(?=[A-Z])", s) #zero-length match before capitals, skipping capital at the 0th index
23
+
parts= []
24
+
forsecinsections:
25
+
parts.append(sec.lower())
26
+
27
+
return"_".join(parts)
28
+
29
+
defconvert_camel_to_pascal(s: str):
30
+
"""Converts a string to PascalCase, ignoring _ if it is the first character."""
31
+
sections=re.split(r'(?<=.)_', s) #match all `_` except if it is the first character.
32
+
33
+
parts= []
34
+
forsecinsections: #capitalise each section unless the section is empty (in which case, append an underscore) or the section starts with an underscore (first section can begin with _)
CONSOLE_LOGGER.debug(f"BHoMJSONDecoder could not convert the following dictionary into a BHoMObject due to a missing '_t' property. Falling back to dictionary: {d}")
if (props["_bhom_version"] isnotNone) and (props["_bhom_version"] !=BHOM_SHORT_VERSION):
65
+
CONSOLE_LOGGER.warning(f"The bhom version specified in the encoded json ({props['_bhom_version']}) is different from the BHoM version that python_toolkit was installed with ({BHOM_SHORT_VERSION}). There may be versioning issues with this object. Consider deserialising and then serialising again with the BHoM serialiser to get the correct version, or update BHoM to the correct version.")
66
+
67
+
ifd.get("BHoM_Guid", None) isnotNone:
68
+
#deserialise as BHoM Object
69
+
70
+
#get default BHoMObject properties and replace with defaults if not present
71
+
props["name"] =d.pop("Name", "")
72
+
props["bhom_guid"] =uuid.UUID(d.pop("BHoM_Guid"))
73
+
props["tags"] =d.pop("Tags", [])
74
+
props["fragments"] =d.pop("Fragments", [])
75
+
props["custom_data"] =d.pop("CustomData", {})
76
+
77
+
#convert all other properties to camel_case as python users expect
ifprops["_t"].startswith("System.Collections.Generic.List"): #this handles when the BHoM serialiser makes generic lists from CustomObject list properties, which get converted to a dictionary. The BHoM serialiser does recognise lists if it can find the object definition via reflection.
"""Override this method in a subclass to add extra object hook on top of the existing method. If the object is an object serialised by the BHoM serialiser, the output object will be a BHoMObject or IObject, so use isinstance() to select."""
94
+
returnobj
95
+
96
+
classBHoMJSONEncoder(JSONEncoder):
97
+
defdefault(self, o):
98
+
ifisinstance(o, BHoMObject):
99
+
#initialise special BHoMObject properties
100
+
101
+
props= {
102
+
"Name": o.name,
103
+
"BHoM_Guid": str(o.bhom_guid),
104
+
"_t": o._t
105
+
}
106
+
107
+
iflen(o.tags) >0:
108
+
props["Tags"] =o.tags
109
+
110
+
iflen(o.fragments) >0:
111
+
props["Fragments"] =o.fragments
112
+
113
+
iflen(o.custom_data) >0:
114
+
props["CustomData"] =o.custom_data
115
+
116
+
ifo._bhom_versionisnotNone:
117
+
props["_bhomVersion"] =o._bhom_version
118
+
119
+
#get property names with reflection and convert all properties to PascalCase as the BHoM serialiser expects
returnself.serialise_unknown(o) #if the object is unknown at this point, call serialise_unknown to allow subclasses to add their own serialisation logic.
This is called by the BHoMJSONEncoder to serialise unknown objects so that the BHoM can handle them if they exist as BHoM Objects in c# but not in python (i.e. an object from an external library).
163
+
164
+
Override this method in a sub class with its own logic, and call super().serialise_unknown(obj) for objects that are unknown, or do not wish to serialise.
165
+
The following objects won't be passed to this method: BHoMObject, IObject, uuid.UUID, pandas.DatetimeIndex, numpy.ndarray, pandas.Timestamp, pandas.Series, pathlib.Path
166
+
"""
167
+
returnsuper(type(self), self).default(obj) #fallback to default json decoder (ValueError) if object is not a BHoMObject or common serialisable type.
168
+
169
+
classIObject:
170
+
"""More generic version of BHoMObject, for non-native objects serialised by the BHoM serialiser, but do not inherit from BHoMObject."""
171
+
_t: str
172
+
_bhom_version: str
173
+
174
+
def__init__(
175
+
self,
176
+
_t: str,
177
+
_bhom_version: str=None,
178
+
**kwargs
179
+
) ->'IObject':
180
+
self._t=_t
181
+
self._bhom_version=_bhom_version
182
+
183
+
#set properties with reflection.
184
+
forkwarginkwargs:
185
+
setattr(self, kwarg, kwargs[kwarg])
186
+
187
+
def__repr__(self) ->str:
188
+
returnf"{type(self).__name__} of type {self._t}, version: '{getattr(self, '_bhom_version', 'Unknown')}'"
189
+
190
+
def__eq__(self, other) ->bool:
191
+
ifnotisinstance(other, IObject):
192
+
returnFalse
193
+
194
+
ifself._t!=other._t:
195
+
returnFalse
196
+
197
+
vself=vars(self).copy()
198
+
vother=vars(other).copy()
199
+
200
+
#ignore these properties when comparing by property.
ifnotisinstance(obj, cls): #this only tests that the top level object was deserialised correctly, if there are problems with deep properties, change the CONSOLE_LOGGER log level to debug.
211
+
raiseTypeError("The object provided does not deserialise to a valid BHoM object.")
CONSOLE_LOGGER.warning("The root element of the JSON provided was a list, assuming that the first item is the desired object. If you intended to deserialise a list, please use the `<cls>.from_json_array(j)` method instead.")
284
+
obj=obj[0]
285
+
286
+
ifissubclass(cls, BHoMObject) andcls!=BHoMObject:
287
+
obj=cls._from_bhom_object(obj)
288
+
289
+
ifnotisinstance(obj, cls): #this only tests that the top level object was deserialised correctly, if there are problems with deep properties, change the CONSOLE_LOGGER log level to debug.
290
+
raiseTypeError("The object provided does not deserialise to a valid BHoM object.")
0 commit comments