|
1 | 1 | # fork of https://github.com/encode/starlette/blob/master/starlette/middleware/gzip.py |
2 | 2 | import gzip |
3 | 3 | import io |
| 4 | +import logging |
| 5 | +import json |
4 | 6 |
|
5 | | -from typing import Annotated, NoReturn, Any |
6 | | -import numpy as np |
| 7 | +from typing import NoReturn, Tuple |
7 | 8 |
|
8 | | -from pydantic import PlainSerializer |
| 9 | +from rocketpy import Function |
| 10 | +from rocketpy._encoders import RocketPyEncoder |
9 | 11 | from starlette.datastructures import Headers, MutableHeaders |
10 | 12 | from starlette.types import ASGIApp, Message, Receive, Scope, Send |
11 | 13 |
|
| 14 | +logger = logging.getLogger(__name__) |
12 | 15 |
|
13 | | -def to_python_primitive(v: Any) -> Any: |
| 16 | + |
| 17 | +class DiscretizeConfig: |
14 | 18 | """ |
15 | | - Convert complex types to Python primitives. |
| 19 | + Configuration class for RocketPy function discretization. |
16 | 20 |
|
17 | | - Args: |
18 | | - v: Any value, particularly those with a 'source' attribute |
19 | | - containing numpy arrays or generic types. |
| 21 | + This class allows easy configuration of discretization parameters |
| 22 | + for different types of RocketPy objects and their callable attributes. |
| 23 | + """ |
20 | 24 |
|
21 | | - Returns: |
22 | | - The primitive representation of the input value. |
| 25 | + def __init__( |
| 26 | + self, bounds: Tuple[float, float] = (0, 10), samples: int = 200 |
| 27 | + ): |
| 28 | + self.bounds = bounds |
| 29 | + self.samples = samples |
| 30 | + |
| 31 | + @classmethod |
| 32 | + def for_environment(cls) -> 'DiscretizeConfig': |
| 33 | + return cls(bounds=(0, 50000), samples=100) |
| 34 | + |
| 35 | + @classmethod |
| 36 | + def for_motor(cls) -> 'DiscretizeConfig': |
| 37 | + return cls(bounds=(0, 10), samples=150) |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def for_rocket(cls) -> 'DiscretizeConfig': |
| 41 | + return cls(bounds=(0, 1), samples=100) |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def for_flight(cls) -> 'DiscretizeConfig': |
| 45 | + return cls(bounds=(0, 30), samples=200) |
| 46 | + |
| 47 | + |
| 48 | +def rocketpy_encoder(obj, config: DiscretizeConfig = DiscretizeConfig()): |
23 | 49 | """ |
24 | | - if hasattr(v, "source"): |
25 | | - if isinstance(v.source, np.ndarray): |
26 | | - return v.source.tolist() |
| 50 | + Encode a RocketPy object using official RocketPy encoders. |
27 | 51 |
|
28 | | - if isinstance(v.source, (np.generic,)): |
29 | | - return v.source.item() |
| 52 | + This function discretizes callable Function attributes and then uses |
| 53 | + RocketPy's official RocketPyEncoder for complete object serialization. |
30 | 54 |
|
31 | | - return str(v.source) |
| 55 | + Args: |
| 56 | + obj: RocketPy object (Environment, Motor, Rocket, Flight) |
| 57 | + config: DiscretizeConfig object with discretization parameters (optional) |
32 | 58 |
|
33 | | - if isinstance(v, (np.generic,)): |
34 | | - return v.item() |
| 59 | + Returns: |
| 60 | + Dictionary of encoded attributes |
| 61 | + """ |
35 | 62 |
|
36 | | - if isinstance(v, (np.ndarray,)): |
37 | | - return v.tolist() |
| 63 | + for attr_name in dir(obj): |
| 64 | + if attr_name.startswith('_'): |
| 65 | + continue |
| 66 | + |
| 67 | + try: |
| 68 | + attr_value = getattr(obj, attr_name) |
| 69 | + except Exception: |
| 70 | + continue |
| 71 | + |
| 72 | + if callable(attr_value) and isinstance(attr_value, Function): |
| 73 | + try: |
| 74 | + # Create a new Function from the source to avoid mutating the original object. |
| 75 | + # This is important because: |
| 76 | + # 1. The original RocketPy object should remain unchanged for reusability |
| 77 | + # 2. Multiple simulations might need different discretization parameters |
| 78 | + # 3. Other parts of the system might depend on the original continuous function |
| 79 | + discretized_func = Function(attr_value.source) |
| 80 | + discretized_func.set_discrete( |
| 81 | + lower=config.bounds[0], |
| 82 | + upper=config.bounds[1], |
| 83 | + samples=config.samples, |
| 84 | + mutate_self=True, |
| 85 | + ) |
38 | 86 |
|
39 | | - return str(v) |
| 87 | + setattr(obj, attr_name, discretized_func) |
40 | 88 |
|
| 89 | + except Exception as e: |
| 90 | + logger.warning(f"Failed to discretize {attr_name}: {e}") |
41 | 91 |
|
42 | | -AnyToPrimitive = Annotated[ |
43 | | - Any, |
44 | | - PlainSerializer(to_python_primitive), |
45 | | -] |
| 92 | + try: |
| 93 | + json_str = json.dumps( |
| 94 | + obj, |
| 95 | + cls=RocketPyEncoder, |
| 96 | + include_outputs=True, |
| 97 | + include_function_data=True, |
| 98 | + ) |
| 99 | + return json.loads(json_str) |
| 100 | + except Exception as e: |
| 101 | + logger.warning(f"Failed to encode with RocketPyEncoder: {e}") |
| 102 | + attributes = {} |
| 103 | + for attr_name in dir(obj): |
| 104 | + if not attr_name.startswith('_'): |
| 105 | + try: |
| 106 | + attr_value = getattr(obj, attr_name) |
| 107 | + if not callable(attr_value): |
| 108 | + attributes[attr_name] = str(attr_value) |
| 109 | + except Exception: |
| 110 | + continue |
| 111 | + return attributes |
46 | 112 |
|
47 | 113 |
|
48 | 114 | class RocketPyGZipMiddleware: |
|
0 commit comments