Skip to content

Commit 91ba94f

Browse files
Add BHoMObject class to python (#233)
2 parents 32437f9 + 941979c commit 91ba94f

10 files changed

Lines changed: 545 additions & 3 deletions

File tree

‎Python_Engine/Python/Dockerfile‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,22 @@
11
FROM python:3.10-slim
2-
32
COPY . /Python_Toolkit
43

4+
#requires build argument --build-context bhom-assemblies C:/ProgramData/BHoM/Assemblies
5+
COPY --from=bhom-assemblies . /bin/BHoM/Assemblies
6+
7+
#install .net core 8.0, and set the pythonnet runtime to the .net core CLR
8+
RUN apt-get update \
9+
&& apt-get install -y wget
10+
11+
RUN wget https://packages.microsoft.com/config/debian/13/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
12+
RUN dpkg -i packages-microsoft-prod.deb
13+
RUN rm packages-microsoft-prod.deb
14+
15+
RUN apt-get update \
16+
&& apt-get install -y aspnetcore-runtime-10.0
17+
18+
ENV PYTHONNET_RUNTIME="coreclr"
19+
520
RUN pip3 install ./Python_Toolkit
621

722
RUN rm ./Python_Toolkit -rf

‎Python_Engine/Python/src/python_toolkit/bhom/analytics.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def decorator(function: Callable):
154154
@wraps(function)
155155
def wrapper(*args, **kwargs) -> Any:
156156
"""A wrapper around the function that captures usage analytics."""
157-
157+
158158
if disable:
159159
CONSOLE_LOGGER.debug("bhom_analytics is curently disabled.")
160160
return function(*args, **kwargs)
Lines changed: 312 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,312 @@
1+
from base64 import decode
2+
import copy
3+
from ctypes import ArgumentError
4+
from datetime import datetime
5+
from json import encoder
6+
from pathlib import Path
7+
import uuid
8+
import re
9+
from typing import Any, List, Dict, Union
10+
import json
11+
from json import JSONEncoder, JSONDecoder
12+
from .logging import CONSOLE_LOGGER
13+
from . import BHOM_VERSION
14+
from .util import bson_unix_ticks, bson_unix_ticks_to_datetime
15+
import pandas as pd
16+
import numpy as np
17+
18+
BHOM_SHORT_VERSION = ".".join(BHOM_VERSION.split(".")[0:2])
19+
20+
def convert_pascal_to_camel(s: str):
21+
"""Converts a string to camel_case."""
22+
sections = re.split("(?<=.)(?=[A-Z])", s) #zero-length match before capitals, skipping capital at the 0th index
23+
parts = []
24+
for sec in sections:
25+
parts.append(sec.lower())
26+
27+
return "_".join(parts)
28+
29+
def convert_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+
for sec in sections: #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 _)
35+
if sec == "":
36+
parts.append("_")
37+
continue
38+
elif sec.startswith("_"):
39+
parts.append(sec)
40+
continue
41+
42+
parts.append(sec.capitalize())
43+
44+
return ''.join(parts)
45+
46+
class BHoMJSONDecoder(JSONDecoder):
47+
def __init__(self, *args, **kwargs):
48+
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
49+
50+
def object_hook(self, d):
51+
if "$date" in d:
52+
CONSOLE_LOGGER.debug(f"deserialising timestamp {d}")
53+
return bson_unix_ticks_to_datetime(d["$date"])
54+
55+
if "_t" not in d:
56+
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}")
57+
return self.deserialise_unknown(d)
58+
59+
props = {
60+
"_t": d.pop("_t"),
61+
"_bhom_version": d.pop("_bhomVersion", BHOM_SHORT_VERSION)
62+
}
63+
64+
if (props["_bhom_version"] is not None) 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+
if d.get("BHoM_Guid", None) is not None:
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
78+
for prop_name in d:
79+
props[convert_pascal_to_camel(prop_name)] = d[prop_name]
80+
81+
return self.deserialise_unknown(BHoMObject(**props))
82+
else:
83+
if props["_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.
84+
return d["_v"]
85+
86+
#deserialise as IObject
87+
for prop_name in d:
88+
props[convert_pascal_to_camel(prop_name)] = d[prop_name]
89+
90+
return self.deserialise_unknown(IObject(**props))
91+
92+
def deserialise_unknown(self, obj: Union['IObject', 'BHoMObject', dict]):
93+
"""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+
return obj
95+
96+
class BHoMJSONEncoder(JSONEncoder):
97+
def default(self, o):
98+
if isinstance(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+
if len(o.tags) > 0:
108+
props["Tags"] = o.tags
109+
110+
if len(o.fragments) > 0:
111+
props["Fragments"] = o.fragments
112+
113+
if len(o.custom_data) > 0:
114+
props["CustomData"] = o.custom_data
115+
116+
if o._bhom_version is not None:
117+
props["_bhomVersion"] = o._bhom_version
118+
119+
#get property names with reflection and convert all properties to PascalCase as the BHoM serialiser expects
120+
for prop_name, value in vars(o).copy().items():
121+
if prop_name in ["name", "bhom_guid", "tags", "fragments", "custom_data", "_t", "_bhom_version"]:
122+
continue
123+
124+
props[convert_camel_to_pascal(prop_name)] = value
125+
126+
return props
127+
elif isinstance(o, IObject):
128+
props = {
129+
"_t": o._t
130+
}
131+
132+
if o._bhom_version is not None:
133+
props["_bhomVersion"] = o._bhom_version
134+
135+
for prop_name, value in vars(o).copy().items():
136+
if prop_name in ["_t", "_bhom_version"]:
137+
continue
138+
139+
props[convert_camel_to_pascal(prop_name)] = value
140+
141+
return props
142+
#handle common non-serialisable types
143+
elif isinstance(o, uuid.UUID): #UUID object is not json serialisable by default
144+
return str(o)
145+
elif isinstance(o, pd.DatetimeIndex):
146+
return [date.isoformat() for date in o]
147+
elif isinstance(o, np.ndarray):
148+
return o.tolist()
149+
elif isinstance(o, pd.Timestamp):
150+
return {"$date": bson_unix_ticks(o.to_pydatetime(), True)}
151+
elif isinstance(o, datetime):
152+
return {"$date": bson_unix_ticks(o, True)}
153+
elif isinstance(o, pd.Series):
154+
return dict(zip(o.index.astype(str), o))
155+
elif isinstance(o, Path):
156+
return { "FileName": str(o.name), "Directory": str(o.parent), "_t": "BH.oM.Adapter.FileSettings", "BHoM_Guid": str(uuid.uuid4()) }
157+
158+
return self.serialise_unknown(o) #if the object is unknown at this point, call serialise_unknown to allow subclasses to add their own serialisation logic.
159+
160+
def serialise_unknown(self, obj: Any) -> Union[Dict[str, str], str, List[str], Any]:
161+
"""
162+
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+
return super(type(self), self).default(obj) #fallback to default json decoder (ValueError) if object is not a BHoMObject or common serialisable type.
168+
169+
class IObject:
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+
for kwarg in kwargs:
185+
setattr(self, kwarg, kwargs[kwarg])
186+
187+
def __repr__(self) -> str:
188+
return f"{type(self).__name__} of type {self._t}, version: '{getattr(self, '_bhom_version', 'Unknown')}'"
189+
190+
def __eq__(self, other) -> bool:
191+
if not isinstance(other, IObject):
192+
return False
193+
194+
if self._t != other._t:
195+
return False
196+
197+
vself = vars(self).copy()
198+
vother = vars(other).copy()
199+
200+
#ignore these properties when comparing by property.
201+
ignore = ["_bhom_version"]
202+
_ = [(vself.pop(p, None), vother.pop(p, None)) for p in ignore]
203+
204+
return vself == vother
205+
206+
@classmethod
207+
def from_json(cls, j: str, decoder_class: type = BHoMJSONDecoder) -> 'IObject':
208+
obj = json.loads(j, cls=decoder_class)
209+
210+
if not isinstance(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+
raise TypeError("The object provided does not deserialise to a valid BHoM object.")
212+
213+
return obj
214+
215+
def to_json(self, encoder_class: type = BHoMJSONEncoder) -> str:
216+
return json.dumps(self, cls=encoder_class)
217+
218+
@classmethod
219+
def from_dict(cls, d: dict) -> 'IObject':
220+
try:
221+
return cls(**d) #should be valid as long as the dictionary has all necessary entries.
222+
except ArgumentError as ae:
223+
raise ArgumentError("Input dictionary was missing some required arguments, see traceback for more information.") from ae
224+
225+
def to_dict(self, encoder_class: type = BHoMJSONEncoder) -> dict:
226+
"""Convert this IObject to a dictionary via deep copying vars(self)."""
227+
return copy.deepcopy(vars(self))
228+
229+
class BHoMObject(IObject):
230+
name: str
231+
bhom_guid: uuid.UUID
232+
tags: List[str]
233+
fragments: List[Dict[str, object]]
234+
custom_data: Dict[str, object]
235+
236+
def __init__(
237+
self,
238+
_t: str, #don't make default, as subclasses of this class should set this with super().__init__
239+
name: str = "",
240+
bhom_guid: uuid.UUID = uuid.uuid4(),
241+
tags: List[str] = [],
242+
fragments: List[Dict[str, object]] = [],
243+
custom_data: Dict[str, object] = {},
244+
_bhom_version: str = None,
245+
**kwargs
246+
) -> 'BHoMObject':
247+
self._t = _t
248+
self.name = name
249+
self.bhom_guid = bhom_guid
250+
self.fragments = fragments
251+
self.tags = tags
252+
self.custom_data = custom_data
253+
self._bhom_version = _bhom_version
254+
255+
#set non-CustomData properties with reflection.
256+
for kwarg in kwargs:
257+
setattr(self, kwarg, kwargs[kwarg])
258+
259+
def __repr__(self) -> str:
260+
return f"{type(self).__name__} of type {self._t}, name: '{self.name}', version: '{getattr(self, '_bhom_version', 'Unknown')}', id: '{self.bhom_guid}'"
261+
262+
def __eq__(self, other) -> bool:
263+
if not isinstance(other, BHoMObject):
264+
return False
265+
266+
if self._t != other._t:
267+
return False
268+
269+
vself = vars(self).copy()
270+
vother = vars(other).copy()
271+
272+
#ignore these properties when comparing by property.
273+
ignore = ["bhom_guid", "_bhom_version"]
274+
_ = [(vself.pop(p, None), vother.pop(p, None)) for p in ignore]
275+
276+
return vself == vother
277+
278+
@classmethod
279+
def from_json(cls, j: str, decoder_class: type = BHoMJSONDecoder):
280+
obj = json.loads(j, cls=decoder_class)
281+
282+
if isinstance(obj, list):
283+
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+
if issubclass(cls, BHoMObject) and cls != BHoMObject:
287+
obj = cls._from_bhom_object(obj)
288+
289+
if not isinstance(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+
raise TypeError("The object provided does not deserialise to a valid BHoM object.")
291+
292+
return obj
293+
294+
@classmethod
295+
def from_json_array(cls, j: str, decoder_class: type = BHoMJSONDecoder):
296+
objs = json.loads(j, cls=decoder_class)
297+
298+
if not isinstance(objs, list):
299+
raise TypeError("The root element of the JSON provided was not a JSON array. Perhaps you intended to use `<cls>.from_json(j)` instead?")
300+
301+
out = []
302+
for obj in objs:
303+
if issubclass(cls, BHoMObject) and cls != BHoMObject:
304+
out.append(cls._from_bhom_object(obj))
305+
continue
306+
out.append(obj)
307+
308+
return out
309+
310+
@classmethod
311+
def _from_bhom_object(cls, o: 'BHoMObject'):
312+
return cls(**vars(o).copy()) #assuming that the sub class is correctly set up, then this should work
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
from ._bhom_callable_decorator import bhom_wrapper

0 commit comments

Comments
 (0)